claude-code-session-manager 0.142.0 → 0.143.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +20 -107
  3. package/dist/assets/{AppSettings-BcZgIvvY.js → AppSettings-BO4jDVGO.js} +1 -1
  4. package/dist/assets/{History-DpZuJXi1.js → History-DTttbvPb.js} +1 -1
  5. package/dist/assets/{HomeClaudeConfig-D32ZJtU-.js → HomeClaudeConfig-DADP5bfn.js} +2 -2
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-B_D4Bg7L.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BTClYV6i.js → ProjectClaudeConfig-DPnDJKcr.js} +1 -1
  8. package/dist/assets/{Scheduler-DPobKx1Z.js → Scheduler-CNLjn90m.js} +8 -8
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-cfV7sgk6.js} +1 -1
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-DVXtEIVy.js} +1 -1
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-CYajnSdx.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-DJ4gGRuE.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-D3MoHY2U.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-CdTppjKR.js} +436 -436
  16. package/dist/index.html +1 -1
  17. package/dist-web/app.js +356 -356
  18. package/package.json +3 -3
  19. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  20. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  21. package/plugins/session-manager-dev/skills/develop/SKILL.md +9 -3
  22. package/scripts/README.md +1 -0
  23. package/scripts/scheduler-mcp-server.cjs +304 -6
  24. package/src/main/adminRouteRegistry.cjs +10 -0
  25. package/src/main/build-info.json +4 -4
  26. package/src/main/chatRunner.cjs +105 -7
  27. package/src/main/config.cjs +5 -1
  28. package/src/main/health.cjs +38 -2
  29. package/src/main/index.cjs +12 -4
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/cast.md +10 -1
  32. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  33. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  34. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  35. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  36. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  37. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  38. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  39. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  40. package/src/main/lib/epic/artifactStore.cjs +78 -35
  41. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  42. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  43. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  44. package/src/main/lib/epic/epicValidationHook.cjs +13 -2
  45. package/src/main/lib/externalContract.cjs +12 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  47. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  48. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +30 -0
  49. package/src/main/lib/feedback-remote/pendingReplies.cjs +18 -0
  50. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  51. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  52. package/src/main/lib/git/gitWorktree.cjs +8 -0
  53. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  54. package/src/main/lib/git/worktreeDeps.cjs +113 -10
  55. package/src/main/lib/mcpToolCatalog.cjs +102 -8
  56. package/src/main/lib/opsOwnership.cjs +113 -28
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  58. package/src/main/lib/prd/prdCreate.cjs +350 -227
  59. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  60. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  61. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  62. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  63. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  64. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  65. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  66. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  67. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  68. package/src/main/lib/scheduler/planRecordHarvest.cjs +120 -52
  69. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  70. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  71. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  72. package/src/main/lib/scheduler/scheduleJobSchema.cjs +13 -0
  73. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  74. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  75. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  76. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +16 -5
  77. package/src/main/lib/tasks/memoryConsolidation.cjs +14 -2
  78. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  79. package/src/main/lib/tasks/taskAdminRoutes.cjs +78 -3
  80. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  81. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  82. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  83. package/src/main/lib/util/atomicFs.cjs +2 -2
  84. package/src/main/promptSessionEvents.cjs +16 -1
  85. package/src/main/pty.cjs +11 -2
  86. package/src/main/queueOps.cjs +1 -1
  87. package/src/main/runVerify.cjs +1 -1
  88. package/src/main/scheduler/utilizationHold.cjs +96 -6
  89. package/src/main/scheduler.cjs +533 -39
  90. package/src/main/templates/PRD_AUTHORING.md +7 -2
  91. package/src/preload/api.d.ts +47 -1
  92. package/src/preload/apiSurface.json +14 -0
  93. package/src/preload/index.cjs +2 -0
  94. package/src/seed/agents/demo-video-builder.md +15 -8
  95. package/src/seed/agents/validator.md +20 -19
@@ -5,7 +5,18 @@
5
5
  * pruneArtifacts({ projectRoot, epicStatus, now, days, tasksDays, dryRun, fsImpl, sizeCapBytes })
6
6
  * → { removed: string[] (owner ids whose folder was deleted), trimmed: string[] (owner
7
7
  * ids that lost some files but keep pinned/fresh ones), removedFiles, kept,
8
- * totalBytes (store size left after the sweep), overCap }. Never throws.
8
+ * totalBytes (store size left after the sweep), overCap,
9
+ * missingRows: string[] ('<owner-id>/<name>' ledger rows dropped because their file
10
+ * is gone), compacted: string[] (owner ids whose ledger was rewritten only to drop
11
+ * such rows), uncheckedRows: number (ledger rows kept because their file's state is
12
+ * unknown — an lstat error other than ENOENT/ENOTDIR; logged once per sweep) }. Never throws.
13
+ *
14
+ * Missing-file compaction runs for EVERY owner, whatever its lifecycle: a ledger row whose
15
+ * stored file artifacts/<owner>/<name> no longer exists (deleted from the OS file manager)
16
+ * is dropped — pinned rows included, since nothing is left to keep. Only a definite 'gone'
17
+ * (artifactStore.storedFileState: ENOENT/ENOTDIR, or not a regular file) counts as missing;
18
+ * an 'unknown' state (EACCES, EIO, …) keeps the row. The rewrite is asserted as writer 'artifacts'; dryRun reports
19
+ * the rows without writing.
9
20
  *
10
21
  * Epic folders artifacts/<epic-id>/ are eligible when:
11
22
  * - epicStatus(id) → { status: 'completed' | 'archived', completedAt | archivedAt }
@@ -40,6 +51,7 @@ const nodeFs = require('node:fs');
40
51
  const path = require('node:path');
41
52
  const opsOwnership = require('../opsOwnership.cjs');
42
53
  const atomicFs = require('../util/atomicFs.cjs');
54
+ const { storedFileState } = require('./artifactStore.cjs');
43
55
 
44
56
  const WRITER = 'artifacts';
45
57
  const NS = 'artifacts';
@@ -114,6 +126,30 @@ function childFiles(fsImpl, dir) {
114
126
  return entries.filter((e) => e.name !== LEDGER && !e.isSymbolicLink()).map((e) => e.name);
115
127
  }
116
128
 
129
+ /**
130
+ * Ledger entries not definitely gone (storedFileState !== 'gone'); records the dropped rows on
131
+ * ctx.result.missingRows and counts kept 'unknown' rows on ctx.result.uncheckedRows.
132
+ */
133
+ function presentEntries(ctx, ownerId, dir, entries) {
134
+ const live = [];
135
+ for (const e of entries) {
136
+ const state = storedFileState(path.join(dir, e.name), ctx.fsImpl);
137
+ if (state === 'gone') { ctx.result.missingRows.push(`${ownerId}/${e.name}`); continue; }
138
+ if (state === 'unknown') ctx.result.uncheckedRows += 1;
139
+ live.push(e);
140
+ }
141
+ return live;
142
+ }
143
+
144
+ /** Rewrite a kept owner's ledger without its missing-file rows → 'compacted' | null. */
145
+ function compactOwner(ctx, dir, entries, live, raw) {
146
+ if (live.length === entries.length) return null;
147
+ const ledgerFile = path.join(dir, LEDGER);
148
+ opsOwnership.assertOpsWrite(ledgerFile, WRITER);
149
+ if (!ctx.dryRun) atomicFs.writeJsonAtomicSync(ledgerFile, { ...raw, entries: live });
150
+ return 'compacted';
151
+ }
152
+
117
153
  function isEpicEligible(id, dir, epicStatus, cutoffMs, fsImpl) {
118
154
  let st;
119
155
  try { st = epicStatus(id); } catch { return false; }
@@ -128,7 +164,8 @@ function isEpicEligible(id, dir, epicStatus, cutoffMs, fsImpl) {
128
164
 
129
165
  /**
130
166
  * Remove `names` from owner folder `dir`, keeping `keepEntries` in its ledger. Deletes the
131
- * whole folder when nothing would remain. Returns 'removed' | 'trimmed' | null.
167
+ * whole folder when nothing would remain. Returns 'removed' | 'trimmed' | 'compacted'
168
+ * (only missing-file rows left the ledger) | null.
132
169
  */
133
170
  function applyOwner({ dir, names, keepEntries, entries, raw, dryRun, fsImpl, result }) {
134
171
  const remaining = childFiles(fsImpl, dir).filter((n) => !names.includes(n));
@@ -148,24 +185,26 @@ function applyOwner({ dir, names, keepEntries, entries, raw, dryRun, fsImpl, res
148
185
  const ledgerFile = path.join(dir, LEDGER);
149
186
  opsOwnership.assertOpsWrite(ledgerFile, WRITER);
150
187
  if (!dryRun) atomicFs.writeJsonAtomicSync(ledgerFile, { ...raw, entries: keepEntries });
151
- return 'trimmed';
188
+ return names.length === 0 ? 'compacted' : 'trimmed';
152
189
  }
153
190
 
154
191
  function pruneEpicOwner(ctx, id, dir) {
155
- if (!isEpicEligible(id, dir, ctx.epicStatus, ctx.cutoffMs, ctx.fsImpl)) return null;
156
192
  const { entries, raw } = readLedger(ctx.fsImpl, path.join(dir, LEDGER));
157
- const keepEntries = entries.filter((e) => e.pinned === true);
193
+ const live = presentEntries(ctx, id, dir, entries);
194
+ if (!isEpicEligible(id, dir, ctx.epicStatus, ctx.cutoffMs, ctx.fsImpl)) return compactOwner(ctx, dir, entries, live, raw);
195
+ const keepEntries = live.filter((e) => e.pinned === true);
158
196
  const keepNames = new Set(keepEntries.map((e) => e.name));
159
197
  const names = childFiles(ctx.fsImpl, dir).filter((n) => !keepNames.has(n));
160
198
  return applyOwner({ dir, names, keepEntries, entries, raw, dryRun: ctx.dryRun, fsImpl: ctx.fsImpl, result: ctx.result });
161
199
  }
162
200
 
163
- function pruneTaskOwner(ctx, dir) {
201
+ function pruneTaskOwner(ctx, ownerId, dir) {
164
202
  const { fsImpl, tasksCutoffMs } = ctx;
165
203
  const { entries, raw } = readLedger(fsImpl, path.join(dir, LEDGER));
204
+ const live = presentEntries(ctx, ownerId, dir, entries);
166
205
  const mtime = (n) => { try { return fsImpl.lstatSync(path.join(dir, n)).mtimeMs; } catch { return null; } };
167
206
  const old = (ms) => ms !== null && ms < tasksCutoffMs;
168
- const keepEntries = entries.filter((e) => e.pinned === true || !old(toMs(e.createdAt) ?? mtime(e.name)));
207
+ const keepEntries = live.filter((e) => e.pinned === true || !old(toMs(e.createdAt) ?? mtime(e.name)));
169
208
  const tracked = new Set(entries.map((e) => e.name));
170
209
  const keepNames = new Set(keepEntries.map((e) => e.name));
171
210
  const names = childFiles(fsImpl, dir).filter((n) => (tracked.has(n) ? !keepNames.has(n) : old(mtime(n))));
@@ -183,7 +222,9 @@ function safeDirs(fsImpl, dir) {
183
222
  }
184
223
 
185
224
  function pruneArtifacts(opts) {
186
- const result = { removed: [], trimmed: [], removedFiles: 0, kept: 0, totalBytes: 0, overCap: false };
225
+ const result = {
226
+ removed: [], trimmed: [], removedFiles: 0, kept: 0, totalBytes: 0, overCap: false, missingRows: [], compacted: [], uncheckedRows: 0,
227
+ };
187
228
  try {
188
229
  const o = opts || {};
189
230
  const fsImpl = o.fsImpl || nodeFs;
@@ -206,6 +247,7 @@ function pruneArtifacts(opts) {
206
247
  const size = scan(fsImpl, dir).bytes;
207
248
  const out = fn();
208
249
  if (out === 'removed') { result.removed.push(ownerId); freed += size; return; }
250
+ if (out === 'compacted') result.compacted.push(ownerId);
209
251
  if (out === 'trimmed') {
210
252
  result.trimmed.push(ownerId);
211
253
  if (!ctx.dryRun) freed += size - scan(fsImpl, dir).bytes;
@@ -223,7 +265,11 @@ function pruneArtifacts(opts) {
223
265
  }
224
266
  for (const t of safeDirs(fsImpl, path.join(root, TASKS_DIR))) {
225
267
  const dir = opsOwnership.opsPath(o.projectRoot, NS, TASKS_DIR, t);
226
- visit(`${TASKS_DIR}/${t}`, dir, () => pruneTaskOwner(ctx, dir));
268
+ const ownerId = `${TASKS_DIR}/${t}`;
269
+ visit(ownerId, dir, () => pruneTaskOwner(ctx, ownerId, dir));
270
+ }
271
+ if (result.uncheckedRows > 0) {
272
+ console.warn(`[artifactRetention] kept ${result.uncheckedRows} unchecked ledger row(s): file state unknown (lstat error other than ENOENT/ENOTDIR) (${root})`);
227
273
  }
228
274
  result.totalBytes = ctx.dryRun ? Math.max(0, before - freed) : scan(fsImpl, root).bytes;
229
275
  if (result.totalBytes > cap) {
@@ -3,7 +3,10 @@
3
3
  /**
4
4
  * artifactStore.cjs — the per-project Artifacts store. THE ONLY WRITER of a
5
5
  * project's `session-manager-operations/artifacts/` namespace (writer id
6
- * 'artifacts' in lib/opsOwnership.cjs; runtime, self-ignored).
6
+ * 'artifacts' in lib/opsOwnership.cjs; runtime). The store writes its own
7
+ * artifacts/.gitignore ('*') on every write, inside the owner lock and before
8
+ * any byte is copied (publishArtifact fails closed if it cannot) — it never
9
+ * relies on the scheduler's periodic ensureRuntimeIgnores sweep.
7
10
  *
8
11
  * Files an agent makes for human review (videos, images, docs, data) are
9
12
  * copied out of the job/Epic worktree into the MAIN project's ops root so they
@@ -21,6 +24,9 @@
21
24
  * by an in-process promise lock. publishArtifact/ingestDir never throw — every
22
25
  * refusal is a returned { ok:false, error } / skipped reason.
23
26
  *
27
+ * fs seam: reads are injectable (listArtifacts/readLedger take fsImpl); writes
28
+ * (publishArtifact/ingestDir) always use the real fs.
29
+ *
24
30
  * Retention: artifactsDays after the owning Epic completes (pruning lives in a
25
31
  * sibling module).
26
32
  */
@@ -28,7 +34,7 @@
28
34
  const fs = require('node:fs');
29
35
  const path = require('node:path');
30
36
  const crypto = require('node:crypto');
31
- const { opsPath, checkOpsWrite, assertOpsWrite } = require('../opsOwnership.cjs');
37
+ const { opsPath, checkOpsWrite, assertOpsWrite, ensureRuntimeIgnore } = require('../opsOwnership.cjs');
32
38
  const { writeJsonAtomic, readJsonOrSync } = require('../util/atomicFs.cjs');
33
39
 
34
40
  const NAMESPACE = 'artifacts';
@@ -77,13 +83,13 @@ function safeName(base) {
77
83
  }
78
84
 
79
85
  /** First free name in `dir`: name, name-2.ext, name-3.ext, ... (index.json is reserved). */
80
- function freeName(dir, name, fsImpl) {
86
+ function freeName(dir, name) {
81
87
  const ext = path.extname(name);
82
88
  const stem = ext ? name.slice(0, -ext.length) : name;
83
89
  for (let i = 1; i < 100000; i += 1) {
84
90
  const candidate = i === 1 ? name : `${stem}-${i}${ext}`;
85
91
  if (candidate === LEDGER) continue;
86
- if (!fsImpl.existsSync(path.join(dir, candidate))) return candidate;
92
+ if (!fs.existsSync(path.join(dir, candidate))) return candidate;
87
93
  }
88
94
  throw new Error('no free artifact name');
89
95
  }
@@ -93,10 +99,10 @@ function isUnder(child, root) {
93
99
  return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
94
100
  }
95
101
 
96
- function sha256File(file, fsImpl) {
102
+ function sha256File(file) {
97
103
  return new Promise((resolve, reject) => {
98
104
  const hash = crypto.createHash('sha256');
99
- const stream = (fsImpl.createReadStream || fs.createReadStream)(file);
105
+ const stream = fs.createReadStream(file);
100
106
  stream.on('error', reject);
101
107
  stream.on('data', (chunk) => hash.update(chunk));
102
108
  stream.on('end', () => resolve(hash.digest('hex')));
@@ -127,11 +133,10 @@ function ownerOf(epicId, taskId) {
127
133
  }
128
134
 
129
135
  /**
130
- * Read a ledger's entries; missing, empty, corrupt or entries-not-an-array → [].
131
- * Reads through readJsonOrSync (real fs), so it takes no fsImpl.
136
+ * Read a ledger's entries through fsImpl; missing, empty, corrupt or entries-not-an-array → [].
132
137
  */
133
- function readLedger(file) {
134
- const parsed = readJsonOrSync(file, null);
138
+ function readLedger(file, fsImpl) {
139
+ const parsed = readJsonOrSync(file, null, fsImpl);
135
140
  const entries = Array.isArray(parsed) ? parsed : parsed && Array.isArray(parsed.entries) ? parsed.entries : null;
136
141
  if (!entries) return [];
137
142
  return entries.filter((e) => e && typeof e === 'object' && typeof e.name === 'string');
@@ -150,13 +155,14 @@ function cleanProducer(producer, epicId, taskId) {
150
155
 
151
156
  /**
152
157
  * publishArtifact({ projectRoot, epicId, taskId, srcPath, title, kind, producer,
153
- * allowedRoots, fsImpl, appendEvent })
158
+ * allowedRoots, appendEvent })
154
159
  * → Promise<{ ok: true, storedPath, entry } | { ok: false, error }>
155
- * Never rejects.
160
+ * Never rejects. Every write step (lstat, realpath, mkdir, copy, hash,
161
+ * rename, unlink, ledger write) uses the real fs — there is no fsImpl seam.
156
162
  */
157
163
  async function publishArtifact({
158
164
  projectRoot, epicId, taskId, srcPath, title, kind, producer, allowedRoots,
159
- fsImpl = fs, appendEvent = null,
165
+ appendEvent = null,
160
166
  } = {}) {
161
167
  try {
162
168
  const owner = ownerOf(epicId, taskId);
@@ -172,16 +178,16 @@ async function publishArtifact({
172
178
  }
173
179
 
174
180
  let st;
175
- try { st = fsImpl.lstatSync(srcPath); } catch (e) { return { ok: false, error: `source unreadable: ${errMsg(e)}` }; }
181
+ try { st = fs.lstatSync(srcPath); } catch (e) { return { ok: false, error: `source unreadable: ${errMsg(e)}` }; }
176
182
  if (st.isSymbolicLink()) return { ok: false, error: 'source is a symlink' };
177
183
  if (!st.isFile()) return { ok: false, error: 'source is not a regular file' };
178
184
  if (st.size > MAX_BYTES) return { ok: false, error: `oversize (${st.size} > ${MAX_BYTES} bytes)` };
179
185
 
180
186
  let realSrc;
181
- try { realSrc = fsImpl.realpathSync(srcPath); } catch (e) { return { ok: false, error: `source unresolvable: ${errMsg(e)}` }; }
187
+ try { realSrc = fs.realpathSync(srcPath); } catch (e) { return { ok: false, error: `source unresolvable: ${errMsg(e)}` }; }
182
188
  const roots = (Array.isArray(allowedRoots) && allowedRoots.length ? allowedRoots : [projectRoot])
183
189
  .filter((r) => typeof r === 'string' && path.isAbsolute(r))
184
- .map((r) => { try { return fsImpl.realpathSync(r); } catch { return null; } })
190
+ .map((r) => { try { return fs.realpathSync(r); } catch { return null; } })
185
191
  .filter(Boolean);
186
192
  if (!roots.some((r) => isUnder(realSrc, /** @type {string} */ (r)))) {
187
193
  return { ok: false, error: 'source is outside every allowed root' };
@@ -200,8 +206,14 @@ async function publishArtifact({
200
206
  const ledgerFile = path.join(destDir, LEDGER);
201
207
 
202
208
  return await withLock(destDir, async () => {
203
- fsImpl.mkdirSync(destDir, { recursive: true });
204
- const name = freeName(destDir, safeName(path.basename(srcPath)), fsImpl);
209
+ fs.mkdirSync(destDir, { recursive: true });
210
+ // Self-ignore BEFORE any byte lands: never rely on a later sweep. Fail closed.
211
+ try {
212
+ ensureRuntimeIgnore(resolvedRoot, NAMESPACE);
213
+ } catch (e) {
214
+ return { ok: false, error: `could not write artifacts/.gitignore: ${errMsg(e)}` };
215
+ }
216
+ const name = freeName(destDir, safeName(path.basename(srcPath)));
205
217
  const dest = path.join(destDir, name);
206
218
  const verdict = checkOpsWrite(dest, WRITER);
207
219
  if (!verdict.ok) return { ok: false, error: `write refused: ${verdict.error}` };
@@ -212,14 +224,14 @@ async function publishArtifact({
212
224
  let sha256;
213
225
  let size;
214
226
  try {
215
- fsImpl.copyFileSync(realSrc, tmp, fs.constants.COPYFILE_FICLONE);
216
- size = fsImpl.statSync(tmp).size;
227
+ fs.copyFileSync(realSrc, tmp, fs.constants.COPYFILE_FICLONE);
228
+ size = fs.statSync(tmp).size;
217
229
  if (size > MAX_BYTES) throw new Error(`oversize after copy (${size} > ${MAX_BYTES} bytes)`);
218
- sha256 = await sha256File(tmp, fsImpl);
219
- if (fsImpl.existsSync(dest)) throw new Error('destination appeared during copy');
220
- fsImpl.renameSync(tmp, dest);
230
+ sha256 = await sha256File(tmp);
231
+ if (fs.existsSync(dest)) throw new Error('destination appeared during copy');
232
+ fs.renameSync(tmp, dest);
221
233
  } catch (e) {
222
- try { fsImpl.unlinkSync(tmp); } catch { /* never created or already gone */ }
234
+ try { fs.unlinkSync(tmp); } catch { /* never created or already gone */ }
223
235
  return { ok: false, error: `copy failed: ${errMsg(e)}` };
224
236
  }
225
237
 
@@ -233,11 +245,11 @@ async function publishArtifact({
233
245
  producer: cleanProducer(producer, epicId, taskId),
234
246
  };
235
247
  try {
236
- const entries = readLedger(ledgerFile);
248
+ const entries = readLedger(ledgerFile, fs);
237
249
  entries.push(entry);
238
250
  await writeJsonAtomic(ledgerFile, { version: 1, entries });
239
251
  } catch (e) {
240
- try { fsImpl.unlinkSync(dest); } catch { /* best effort: keep store and ledger in step */ }
252
+ try { fs.unlinkSync(dest); } catch { /* best effort: keep store and ledger in step */ }
241
253
  return { ok: false, error: `ledger write failed: ${errMsg(e)}` };
242
254
  }
243
255
 
@@ -264,15 +276,16 @@ async function publishArtifact({
264
276
  }
265
277
 
266
278
  /**
267
- * ingestDir({ projectRoot, epicId, taskId, srcDir, producer, allowedRoots, minAgeMs, fsImpl, appendEvent })
279
+ * ingestDir({ projectRoot, epicId, taskId, srcDir, producer, allowedRoots, minAgeMs, appendEvent })
268
280
  * → Promise<{ published: { srcPath, storedPath, entry }[], skipped: { path, reason }[] }>
269
281
  * Publishes every regular file directly in srcDir (non-recursive, max 200),
270
282
  * deleting each source only after its copy succeeded. Never rejects.
271
283
  * minAgeMs (default 0) skips any file modified within the last minAgeMs as
272
284
  * 'still being written', so a periodic sweep never moves a half-written file.
285
+ * Like publishArtifact, it uses the real fs for every step (no fsImpl seam).
273
286
  */
274
287
  async function ingestDir({
275
- projectRoot, epicId, taskId, srcDir, producer, allowedRoots, minAgeMs = 0, fsImpl = fs, appendEvent = null,
288
+ projectRoot, epicId, taskId, srcDir, producer, allowedRoots, minAgeMs = 0, appendEvent = null,
276
289
  } = {}) {
277
290
  /** @type {{ srcPath: string, storedPath: string, entry: object }[]} */
278
291
  const published = [];
@@ -285,12 +298,12 @@ async function ingestDir({
285
298
  }
286
299
  let names;
287
300
  try {
288
- const st = fsImpl.lstatSync(srcDir);
301
+ const st = fs.lstatSync(srcDir);
289
302
  if (!st.isDirectory()) {
290
303
  skipped.push({ path: srcDir, reason: 'srcDir is not a directory' });
291
304
  return { published, skipped };
292
305
  }
293
- names = fsImpl.readdirSync(srcDir).map(String).sort();
306
+ names = fs.readdirSync(srcDir).map(String).sort();
294
307
  } catch (e) {
295
308
  if (e && e.code === 'ENOENT') return { published, skipped };
296
309
  skipped.push({ path: srcDir, reason: `cannot list srcDir: ${errMsg(e)}` });
@@ -303,7 +316,7 @@ async function ingestDir({
303
316
  for (const name of names) {
304
317
  const src = path.join(srcDir, name);
305
318
  try {
306
- const st = fsImpl.lstatSync(src);
319
+ const st = fs.lstatSync(src);
307
320
  if (st.isSymbolicLink()) { skipped.push({ path: src, reason: 'symlink' }); continue; }
308
321
  if (st.isDirectory()) { skipped.push({ path: src, reason: 'directory' }); continue; }
309
322
  if (!st.isFile()) { skipped.push({ path: src, reason: 'not a regular file' }); continue; }
@@ -311,11 +324,11 @@ async function ingestDir({
311
324
  if (count >= MAX_INGEST_FILES) { skipped.push({ path: src, reason: `over the ${MAX_INGEST_FILES}-file limit` }); continue; }
312
325
  count += 1;
313
326
  const res = await publishArtifact({
314
- projectRoot, epicId, taskId, srcPath: src, producer, allowedRoots: roots, fsImpl, appendEvent,
327
+ projectRoot, epicId, taskId, srcPath: src, producer, allowedRoots: roots, appendEvent,
315
328
  });
316
329
  if (!res.ok) { skipped.push({ path: src, reason: res.error }); continue; }
317
330
  published.push({ srcPath: src, storedPath: res.storedPath, entry: res.entry });
318
- try { fsImpl.unlinkSync(src); } catch (e) {
331
+ try { fs.unlinkSync(src); } catch (e) {
319
332
  console.error('[artifactStore] could not delete ingested source', src, errMsg(e));
320
333
  }
321
334
  } catch (e) {
@@ -328,10 +341,36 @@ async function ingestDir({
328
341
  return { published, skipped };
329
342
  }
330
343
 
344
+ /**
345
+ * storedFileState(file, fsImpl) → 'file' | 'gone' | 'unknown', from lstat (no
346
+ * symlink following). 'file': a regular file. 'gone': lstat succeeded on
347
+ * something that is not a regular file (publish never stores a symlink, so a
348
+ * symlink — dangling or not — or a folder counts as gone), or lstat threw
349
+ * ENOENT/ENOTDIR. 'unknown': any other error (EACCES, EIO, …) — the file may
350
+ * still exist. The one rule shared by listArtifacts (shows only 'file') and the
351
+ * retention sweep (artifactRetention.cjs compacts only 'gone'). Never throws.
352
+ * @param {string} file
353
+ * @param {{ lstatSync: (p: string) => { isFile: () => boolean } }} [fsImpl]
354
+ * @returns {'file' | 'gone' | 'unknown'}
355
+ */
356
+ function storedFileState(file, fsImpl = fs) {
357
+ try {
358
+ const st = fsImpl.lstatSync(file);
359
+ return st.isFile() === true ? 'file' : 'gone';
360
+ } catch (e) {
361
+ const code = e && /** @type {{ code?: unknown }} */ (e).code;
362
+ return code === 'ENOENT' || code === 'ENOTDIR' ? 'gone' : 'unknown';
363
+ }
364
+ }
365
+
331
366
  /**
332
367
  * listArtifacts(projectRoot, { fsImpl }) → entries newest first, each with
333
368
  * `ownerId` (an Epic id, or `_tasks/<task-id>`). A missing or corrupt ledger
334
- * contributes [] for that owner. Never throws.
369
+ * contributes [] for that owner. An entry whose stored file
370
+ * (artifacts/<owner>/<name>) no longer exists — e.g. deleted from the OS file
371
+ * manager, or replaced by a symlink — or whose state is unknown (an lstat error other than
372
+ * ENOENT/ENOTDIR) is omitted (one lstat per entry through fsImpl, storedFileState); the daily sweep
373
+ * (artifactRetention.cjs) compacts such rows out of the ledger. Never throws.
335
374
  */
336
375
  function listArtifacts(projectRoot, { fsImpl = fs } = {}) {
337
376
  /** @type {object[]} */
@@ -355,7 +394,10 @@ function listArtifacts(projectRoot, { fsImpl = fs } = {}) {
355
394
  }
356
395
  }
357
396
  for (const { ownerId, dir } of owners) {
358
- for (const e of readLedger(path.join(dir, LEDGER))) out.push({ ...e, ownerId });
397
+ for (const e of readLedger(path.join(dir, LEDGER), fsImpl)) {
398
+ if (storedFileState(path.join(dir, e.name), fsImpl) !== 'file') continue;
399
+ out.push({ ...e, ownerId });
400
+ }
359
401
  }
360
402
  const t = (e) => { const v = Date.parse(e.createdAt); return Number.isFinite(v) ? v : 0; };
361
403
  out.sort((a, b) => t(b) - t(a));
@@ -381,6 +423,7 @@ module.exports = {
381
423
  publishArtifact,
382
424
  ingestDir,
383
425
  listArtifacts,
426
+ storedFileState,
384
427
  stagingDirFor,
385
428
  inferKind,
386
429
  MAX_BYTES,
@@ -457,6 +457,13 @@ function whichOnPath(name) {
457
457
  return null;
458
458
  }
459
459
 
460
+ /**
461
+ * Said with every missing-sandbox notice: sandboxed Bash cannot reach host
462
+ * loopback, so a live check is an http criterion the scheduler runs outside
463
+ * the sandbox (managed-agents-alignment.md#environments).
464
+ */
465
+ const SANDBOX_LOOPBACK_CLAUSE = "under the sandbox a job cannot reach services on this machine's loopback, so live checks run as http criteria";
466
+
460
467
  /** A local-timezone calendar date, e.g. "Nov 30, 2026". */
461
468
  function formatLocalDate(ms) {
462
469
  return new Date(ms).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
@@ -505,14 +512,14 @@ function checkJobSandbox({ sandboxDeps = null, platform = process.platform, mode
505
512
  : `Run Session Manager on Linux (bubblewrap + socat) or macOS (sandbox-exec)`;
506
513
  if (effectiveMode === 'report') {
507
514
  const detail = date
508
- ? `missing: ${missing.join(', ')} — report mode until ${date}: jobs fall back to tool rules now; from ${date} headless dev-lead and validator jobs will park with environment_unavailable until installed`
509
- : `missing: ${missing.join(', ')} — report mode: jobs fall back to tool rules`;
515
+ ? `missing: ${missing.join(', ')} — report mode until ${date}: jobs fall back to tool rules now; from ${date} headless dev-lead and validator jobs will park with environment_unavailable until installed; ${SANDBOX_LOOPBACK_CLAUSE}`
516
+ : `missing: ${missing.join(', ')} — report mode: jobs fall back to tool rules; ${SANDBOX_LOOPBACK_CLAUSE}`;
510
517
  return { ...base, ok: true, warn: true, detail, fix };
511
518
  }
512
519
  return {
513
520
  ...base,
514
521
  ok: false,
515
- detail: `missing: ${missing.join(', ')} — dev-lead and validator jobs park with environment_unavailable until installed`,
522
+ detail: `missing: ${missing.join(', ')} — dev-lead and validator jobs park with environment_unavailable until installed; ${SANDBOX_LOOPBACK_CLAUSE}`,
516
523
  fix,
517
524
  };
518
525
  }
@@ -53,6 +53,7 @@ const EVENT_KINDS = Object.freeze([
53
53
  'validator.verdict',
54
54
  'outcome.recorded',
55
55
  'artifact.published',
56
+ 'epic.state_changed',
56
57
  ]);
57
58
  const KIND_SET = new Set(EVENT_KINDS);
58
59
 
@@ -60,6 +61,34 @@ const KIND_SET = new Set(EVENT_KINDS);
60
61
  const chains = new Map();
61
62
  /** file path → last seq written. */
62
63
  const lastSeq = new Map();
64
+ /** Called with (cwd, record) after every successful append. */
65
+ const listeners = new Set();
66
+
67
+ /**
68
+ * onEpicEventAppended(fn) → unsubscribe. fn(cwd, record) runs after each
69
+ * record is on disk with one deep-frozen copy, parsed from the stored line, shared
70
+ * by all listeners (never the caller's object); a throwing listener is logged and never fails the append.
71
+ * @param {(cwd: string, record: Record<string, unknown>) => void} fn
72
+ */
73
+ function onEpicEventAppended(fn) {
74
+ if (typeof fn !== 'function') throw new Error('epicEventLog: listener must be a function');
75
+ listeners.add(fn);
76
+ return () => listeners.delete(fn);
77
+ }
78
+
79
+ /**
80
+ * deepFreeze(value) → value, with every nested object/array frozen.
81
+ * @template T
82
+ * @param {T} value
83
+ * @returns {T}
84
+ */
85
+ function deepFreeze(value) {
86
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
87
+ Object.freeze(value);
88
+ for (const v of Object.values(value)) deepFreeze(v);
89
+ }
90
+ return value;
91
+ }
63
92
 
64
93
  function assertEpicId(epicId) {
65
94
  if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) {
@@ -162,8 +191,21 @@ function appendEpicEvent(cwd, epicId, event) {
162
191
  }
163
192
  const seq = /** @type {number} */ (lastSeq.get(file)) + 1;
164
193
  const record = { seq, time: new Date().toISOString(), epicId, kind: event.kind, ...capped };
165
- await fsp.appendFile(file, `${prefix}${JSON.stringify(record)}\n`, 'utf8');
194
+ const line = JSON.stringify(record);
195
+ await fsp.appendFile(file, `${prefix}${line}\n`, 'utf8');
166
196
  lastSeq.set(file, seq);
197
+ // Listeners share one deep-frozen copy parsed from the stored line, so they
198
+ // see exactly the row on disk; a mutating listener throws (strict mode,
199
+ // logged below) instead of changing the caller's record or what a later
200
+ // listener sees.
201
+ const view = listeners.size ? deepFreeze(JSON.parse(line)) : null;
202
+ for (const fn of [...listeners]) {
203
+ try {
204
+ fn(cwd, /** @type {Record<string, unknown>} */ (view));
205
+ } catch (err) {
206
+ console.error('[epicEventLog] listener failed', err && err.message ? err.message : String(err));
207
+ }
208
+ }
167
209
  return record;
168
210
  });
169
211
  chains.set(file, next);
@@ -202,6 +244,7 @@ async function readEpicEvents(cwd, epicId, opts = {}) {
202
244
  function _resetForTests() {
203
245
  chains.clear();
204
246
  lastSeq.clear();
247
+ listeners.clear();
205
248
  }
206
249
 
207
250
  module.exports = {
@@ -210,5 +253,6 @@ module.exports = {
210
253
  WRITER,
211
254
  appendEpicEvent,
212
255
  readEpicEvents,
256
+ onEpicEventAppended,
213
257
  _resetForTests,
214
258
  };