-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher.js
More file actions
415 lines (353 loc) · 14.9 KB
/
Copy pathwatcher.js
File metadata and controls
415 lines (353 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// ============================================================
// watcher.js — Codex SPU Path & Status Watcher
// ============================================================
require("dotenv").config();
const chokidar = require("chokidar");
const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");
const { globSync } = require("glob");
const config = require("./config");
const github = require("./github");
// ─── Verificación crítica de CODEX_ROOT ───────────────────────
// dotenvx a veces inyecta comillas literales en el valor
const CODEX_ROOT = (config.CODEX_ROOT || "").replace(/^["']|["']$/g, "").trim();
if (!CODEX_ROOT) {
console.error("❌ CODEX_ROOT no está definido en .env");
process.exit(1);
}
try {
const stat = fs.statSync(CODEX_ROOT);
if (!stat.isDirectory()) throw new Error("No es un directorio");
} catch (e) {
console.error(`❌ No se puede acceder a CODEX_ROOT: ${CODEX_ROOT}`);
console.error(` Error: ${e.message}`);
process.exit(1);
}
// ─── Utilidades ───────────────────────────────────────────────
function toRelativePath(absolutePath) {
return "/" + path.relative(CODEX_ROOT, absolutePath).replace(/\\/g, "/");
}
function readMarkdown(filePath) {
const raw = fs.readFileSync(filePath, "utf8");
const parsed = matter(raw);
return { data: parsed.data, content: parsed.content, raw };
}
function writeMarkdown(filePath, data, content) {
fs.writeFileSync(filePath, matter.stringify(content, data), "utf8");
}
function getAllMarkdownFiles() {
const ignore = config.IGNORED_FOLDERS.map(f => `**/${f}/**`);
return globSync("**/*.md", { cwd: CODEX_ROOT, absolute: true, ignore });
}
function toWatchRelative(inputPath) {
const relativePath = path.isAbsolute(inputPath)
? path.relative(CODEX_ROOT, inputPath)
: inputPath;
return relativePath.replace(/\\/g, "/");
}
function isIgnoredFolderPath(inputPath) {
const rel = toWatchRelative(inputPath);
return config.IGNORED_FOLDERS.some(folder => (
rel === folder ||
rel.startsWith(`${folder}/`) ||
rel.includes(`/${folder}/`)
));
}
function isMarkdownPath(inputPath) {
return toWatchRelative(inputPath).toLowerCase().endsWith(".md");
}
function getStageFromPath(absolutePath) {
const rel = path.relative(CODEX_ROOT, absolutePath).replace(/\\/g, "/");
const parts = rel.split("/");
if (parts[0] === config.PIPELINE_ROOT && parts.length >= 3) {
return parts[1].replace(/^\d+_/, "");
}
return null;
}
function getFilename(absolutePath) {
return path.basename(absolutePath, ".md");
}
// ─── Sesión ───────────────────────────────────────────────────
const session = {
startTime: new Date(),
moves: [],
created: [],
errors: [],
};
function logMove(file, from, to, refsUpdated, githubAction) {
session.moves.push({ file, from, to, refsUpdated, githubAction, timestamp: new Date() });
}
function logCreated(file, stage, issueUrl) {
session.created.push({ file, stage, issueUrl, timestamp: new Date() });
}
function logError(msg) {
session.errors.push({ msg, timestamp: new Date() });
console.warn(` ⚠️ ${msg}`);
}
function printSessionReport() {
const end = new Date();
const mins = Math.round((end - session.startTime) / 60000);
const duration = mins < 1 ? "menos de 1 min" : `${mins} min`;
console.log("\n" + "═".repeat(58));
console.log("📊 REPORTE DE SESIÓN — Codex SPU");
console.log("═".repeat(58));
console.log(` 🕐 Inicio: ${session.startTime.toLocaleTimeString("es-ES")}`);
console.log(` 🕐 Fin: ${end.toLocaleTimeString("es-ES")}`);
console.log(` ⏱️ Duración: ${duration}`);
console.log("─".repeat(58));
if (session.created.length > 0) {
console.log(`\n 🆕 Archivos añadidos al pipeline: ${session.created.length}`);
for (const c of session.created) {
const t = c.timestamp.toLocaleTimeString("es-ES");
console.log(`\n [${t}] 📄 ${c.file} → ${c.stage}`);
if (c.issueUrl) console.log(` 🐙 ${c.issueUrl}`);
}
}
if (session.moves.length > 0) {
console.log(`\n 🔄 Archivos movidos: ${session.moves.length}`);
for (const m of session.moves) {
const t = m.timestamp.toLocaleTimeString("es-ES");
console.log(`\n [${t}] 📄 ${m.file}`);
console.log(` ${m.from}`);
console.log(` → ${m.to}`);
if (m.refsUpdated > 0) console.log(` 📝 ${m.refsUpdated} referencia(s) actualizada(s)`);
if (m.githubAction) console.log(` 🐙 ${m.githubAction}`);
}
}
if (session.created.length === 0 && session.moves.length === 0) {
console.log("\n ℹ️ No se movió ni creó ningún archivo durante esta sesión.");
}
if (session.errors.length > 0) {
console.log(`\n ❌ Errores (${session.errors.length}):`);
for (const e of session.errors) {
const t = e.timestamp.toLocaleTimeString("es-ES");
console.log(` [${t}] ${e.msg}`);
}
}
console.log("\n" + "═".repeat(58));
console.log(" Systema Vivens — Semper Plus Ultra");
console.log("═".repeat(58) + "\n");
}
// ─── Lógica de actualización ──────────────────────────────────
function updateFrontmatter(absolutePath, newStage) {
const { data, content } = readMarkdown(absolutePath);
const newRelative = toRelativePath(absolutePath);
let changed = false;
if (data[config.PATH_FIELD] !== newRelative) {
console.log(` 📝 Path: ${data[config.PATH_FIELD]} → ${newRelative}`);
data[config.PATH_FIELD] = newRelative;
changed = true;
}
if (newStage) {
const cleanStage = newStage.replace(/^\d+_/, "");
if (data[config.STATUS_FIELD] !== cleanStage) {
console.log(` 📝 Status: ${data[config.STATUS_FIELD]} → ${cleanStage}`);
data[config.STATUS_FIELD] = cleanStage;
changed = true;
}
}
if (changed) {
writeMarkdown(absolutePath, data, content);
console.log(` 💾 Guardado.`);
} else {
console.log(` ℹ️ Sin cambios en frontmatter.`);
}
return data;
}
function setGithubUrl(absolutePath, url) {
const { data, content } = readMarkdown(absolutePath);
data[config.GITHUB_URL_FIELD] = url;
writeMarkdown(absolutePath, data, content);
}
function updateReferencesInAllFiles(oldRelative, newRelative, skipPath) {
if (!oldRelative) return 0;
const allFiles = getAllMarkdownFiles();
let count = 0;
for (const filePath of allFiles) {
if (filePath === skipPath) continue;
try {
const raw = fs.readFileSync(filePath, "utf8");
const escaped = oldRelative.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
if (!new RegExp(escaped).test(raw)) continue;
fs.writeFileSync(filePath, raw.replace(new RegExp(escaped, "g"), newRelative), "utf8");
console.log(` ✅ Ref actualizada en: ${toRelativePath(filePath)}`);
count++;
} catch (err) {
logError(`Ref update failed en ${filePath}: ${err.message}`);
}
}
return count;
}
// ─── Watcher ──────────────────────────────────────────────────
console.log("🧠 Codex SPU Watcher arrancando...");
console.log(`📂 Vigilando: ${CODEX_ROOT}`);
console.log(`🔄 Modo: polling (compatible con Windows)`);
console.log("─".repeat(50));
const knownPaths = new Map();
const MOVE_WINDOW_MS = 8000;
const recentlyDeleted = new Map();
const recentlyAdded = new Map();
const watcher = chokidar.watch(".", {
cwd: CODEX_ROOT,
ignored: (watchPath, stats) => {
if (isIgnoredFolderPath(watchPath)) return true;
return stats?.isFile() ? !isMarkdownPath(watchPath) : false;
},
persistent: true,
ignoreInitial: false,
// usePolling es necesario en Windows para detectar moves del Explorador
usePolling: true,
interval: 800,
awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 },
});
// Mantener el proceso vivo explícitamente (necesario en Windows con polling)
const keepAlive = setInterval(() => {}, 60000);
// ── Arranque: registra archivos existentes ────────────────────
watcher.on("add", (relativePath) => {
if (watcher._codexReady) return;
const absolutePath = path.join(CODEX_ROOT, relativePath);
try {
const { data } = readMarkdown(absolutePath);
const rel = toRelativePath(absolutePath);
const stage = getStageFromPath(absolutePath);
knownPaths.set(absolutePath, { relativePath: data[config.PATH_FIELD] || rel, stage });
if (config.VERBOSE) console.log(` 👁️ ${rel}`);
} catch { /* ignorar */ }
});
// ── Procesador central de MOVE ────────────────────────────────
async function processMoveEvent(addedAbs, addedInfo, deletedAbs, deletedInfo) {
const { newRelative, newStage, filename } = addedInfo;
const { oldRelativePath } = deletedInfo;
console.log(`\n🔄 Movido: ${filename}`);
console.log(` DE: ${oldRelativePath}`);
console.log(` A: ${newRelative}`);
const data = updateFrontmatter(addedAbs, newStage);
console.log(` ✅ path + status actualizados${newStage ? ` → ${newStage}` : ""}`);
const refs = updateReferencesInAllFiles(oldRelativePath, newRelative, addedAbs);
if (refs === 0) console.log(" ℹ️ Sin referencias en otros archivos");
let githubAction = null;
if (newStage) {
try {
if (data[config.GITHUB_URL_FIELD]) {
await github.moveItemByFilename(filename, newStage);
githubAction = `columna "${newStage}" actualizada en GitHub`;
} else {
console.log(` 🚀 Importando a GitHub: creando nueva Issue...`);
const { issueUrl } = await github.createIssueAndAddToProject(filename, newStage);
setGithubUrl(addedAbs, issueUrl);
githubAction = `Issue creada e importada a "${newStage}"`;
}
console.log(` ✅ 🐙 ${githubAction}`);
} catch (err) {
logError(`GitHub sync fallido para "${filename}": ${err.message}`);
}
}
logMove(filename, oldRelativePath, newRelative, refs, githubAction);
knownPaths.set(addedAbs, { relativePath: newRelative, stage: newStage });
console.log("─".repeat(50));
}
// ── Procesador de archivo nuevo real ─────────────────────────
async function processNewFile(absolutePath, newRelative, newStage, filename) {
knownPaths.set(absolutePath, { relativePath: newRelative, stage: newStage });
if (!newStage) return;
console.log(`\n📥 Detectado en pipeline: ${filename} [${newStage}]`);
const { data } = readMarkdown(absolutePath);
updateFrontmatter(absolutePath, newStage);
if (data[config.GITHUB_URL_FIELD]) {
console.log(` ℹ️ Ya tiene Issue: ${data[config.GITHUB_URL_FIELD]}`);
try {
await github.moveItemByFilename(filename, newStage);
console.log(` ✅ 🐙 Posición actualizada en GitHub Projects`);
} catch (err) {
logError(`No se pudo sincronizar: ${err.message}`);
}
} else {
console.log(` 🚀 Creando Issue en GitHub...`);
try {
const { issueUrl } = await github.createIssueAndAddToProject(filename, newStage);
setGithubUrl(absolutePath, issueUrl);
console.log(` ✅ 🐙 Issue creada: ${issueUrl}`);
logCreated(filename, newStage, issueUrl);
} catch (err) {
logError(`GitHub issue fallida para "${filename}": ${err.message}`);
}
}
console.log("─".repeat(50));
}
// ── Evento: archivo eliminado ─────────────────────────────────
watcher.on("unlink", async (relativePath) => {
const absolutePath = path.join(CODEX_ROOT, relativePath);
const known = knownPaths.get(absolutePath);
const basename = path.basename(absolutePath);
const deletedInfo = {
oldRelativePath: known?.relativePath || toRelativePath(absolutePath),
oldStage: known?.stage || null,
timestamp: Date.now(),
};
knownPaths.delete(absolutePath);
// ¿Ya llegó el add antes? (chokidar con polling puede invertir el orden)
let matchedAdd = null;
for (const [addedAbs, info] of recentlyAdded.entries()) {
if (path.basename(addedAbs) === basename && (Date.now() - info.timestamp) < MOVE_WINDOW_MS) {
matchedAdd = { addedAbs, ...info };
recentlyAdded.delete(addedAbs);
break;
}
}
if (matchedAdd) {
await processMoveEvent(matchedAdd.addedAbs, matchedAdd, absolutePath, deletedInfo);
} else {
recentlyDeleted.set(absolutePath, deletedInfo);
setTimeout(() => recentlyDeleted.delete(absolutePath), MOVE_WINDOW_MS + 500);
}
});
// ── Evento: archivo nuevo (post-arranque) ─────────────────────
watcher.on("add", async (relativePath) => {
if (!watcher._codexReady) return;
const absolutePath = path.join(CODEX_ROOT, relativePath);
const newRelative = toRelativePath(absolutePath);
const newStage = getStageFromPath(absolutePath);
const filename = getFilename(absolutePath);
const basename = path.basename(absolutePath);
// ¿Ya llegó el unlink antes? (orden normal)
let matchedOld = null;
for (const [oldAbs, info] of recentlyDeleted.entries()) {
if (path.basename(oldAbs) === basename && (Date.now() - info.timestamp) < MOVE_WINDOW_MS) {
matchedOld = { oldAbsolute: oldAbs, ...info };
recentlyDeleted.delete(oldAbs);
break;
}
}
if (matchedOld) {
await processMoveEvent(
absolutePath,
{ newRelative, newStage, filename, timestamp: Date.now() },
matchedOld.oldAbsolute,
matchedOld
);
return;
}
// Guardamos y esperamos si llega el unlink
const addedInfo = { newRelative, newStage, filename, timestamp: Date.now() };
recentlyAdded.set(absolutePath, addedInfo);
setTimeout(async () => {
if (!recentlyAdded.has(absolutePath)) return;
recentlyAdded.delete(absolutePath);
await processNewFile(absolutePath, newRelative, newStage, filename);
}, MOVE_WINDOW_MS);
});
// ── Listo ─────────────────────────────────────────────────────
watcher.on("ready", () => {
watcher._codexReady = true;
console.log(`\n✅ Watcher listo. ${knownPaths.size} archivos registrados.`);
console.log("👂 Escuchando cambios... (Ctrl+C para ver reporte y salir)\n");
});
watcher.on("error", err => console.error("❌ Error en watcher:", err));
// ── Ctrl+C → reporte ──────────────────────────────────────────
process.on("SIGINT", () => {
clearInterval(keepAlive);
watcher.close();
printSessionReport();
process.exit(0);
});