claude-code-session-manager 0.40.3 → 0.41.1

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 (54) hide show
  1. package/dist/assets/{TiptapBody-DweEtHks.js → TiptapBody-Cr-O75Yg.js} +1 -1
  2. package/dist/assets/{index-BxVBtmjA.css → index-CKY3mHgV.css} +1 -1
  3. package/dist/assets/{index-QRU8uTeq.js → index-CV9TNjxX.js} +631 -624
  4. package/dist/index.html +2 -2
  5. package/package.json +3 -1
  6. package/plugins/session-manager-dev/skills/develop/SKILL.md +5 -5
  7. package/plugins/session-manager-dev/skills/develop/standards.md +1 -1
  8. package/plugins/session-manager-dev/skills/explain-to-me/SKILL.md +2 -2
  9. package/plugins/session-manager-dev/skills/find-opportunity/SKILL.md +1 -1
  10. package/plugins/session-manager-dev/skills/project-status/SKILL.md +20 -34
  11. package/plugins/session-manager-dev/skills/propose-epic/SKILL.md +68 -0
  12. package/scripts/lib/watchdogHelpers.cjs +5 -5
  13. package/scripts/mint-epic.cjs +28 -0
  14. package/scripts/propose-epic.cjs +55 -0
  15. package/src/main/__tests__/epicMint.test.cjs +85 -0
  16. package/src/main/__tests__/opsErrorLog.test.cjs +87 -0
  17. package/src/main/__tests__/prdCreate.test.cjs +124 -2
  18. package/src/main/__tests__/promptSessionEvents.test.cjs +56 -2
  19. package/src/main/__tests__/promptSessionTranscript.test.cjs +0 -0
  20. package/src/main/__tests__/rcaFeedbackHook.test.cjs +43 -211
  21. package/src/main/__tests__/scheduler-archived-twin-guard.test.cjs +63 -0
  22. package/src/main/__tests__/scheduler-notify-originating-tab-transcript.test.cjs +86 -0
  23. package/src/main/__tests__/scheduler-notify-originating-tab.test.cjs +21 -0
  24. package/src/main/__tests__/scheduler-writeprd-epic-rollback.test.cjs +78 -0
  25. package/src/main/browserView.cjs +1 -1
  26. package/src/main/chatRunner.cjs +24 -47
  27. package/src/main/config.cjs +12 -6
  28. package/src/main/docEdit.cjs +3 -4
  29. package/src/main/index.cjs +12 -0
  30. package/src/main/ipcSchemas.cjs +59 -11
  31. package/src/main/lib/__tests__/opsOwnership.test.cjs +92 -0
  32. package/src/main/lib/__tests__/projectBriefCore.test.cjs +74 -0
  33. package/src/main/lib/epicMint.cjs +133 -59
  34. package/src/main/lib/opsErrorLog.cjs +96 -0
  35. package/src/main/lib/opsOwnership.cjs +169 -0
  36. package/src/main/lib/prdCreate.cjs +39 -1
  37. package/src/main/lib/prdLocations.cjs +21 -0
  38. package/src/main/lib/projectBriefCore.cjs +70 -4
  39. package/src/main/lib/queueStore.cjs +3 -0
  40. package/src/main/lib/rcaFeedbackHook.cjs +41 -55
  41. package/src/main/logs.cjs +19 -1
  42. package/src/main/projectBrief.cjs +36 -2
  43. package/src/main/promptSessionEvents.cjs +24 -2
  44. package/src/main/promptSessionTranscript.cjs +0 -0
  45. package/src/main/pty.cjs +15 -0
  46. package/src/main/queueOps.cjs +1 -1
  47. package/src/main/scheduler/prdParser.cjs +8 -0
  48. package/src/main/scheduler.cjs +158 -62
  49. package/src/main/templates/PRD_AUTHORING.md +1 -1
  50. package/src/preload/api.d.ts +83 -4
  51. package/src/preload/index.cjs +26 -5
  52. package/plugins/session-manager-dev/skills/my-feedback/SKILL.md +0 -140
  53. package/plugins/session-manager-dev/skills/optimize-kpi/SKILL.md +0 -290
  54. package/plugins/session-manager-dev/skills/process-feedback/SKILL.md +0 -265
@@ -226,8 +226,22 @@ async function gatherSrcTree(cwd) {
226
226
 
227
227
  const inFlight = new Set();
228
228
 
229
+ /**
230
+ * Register the project root as an allowed WRITE root before persisting
231
+ * brief.json. config.cjs only grants project-root writes to roots added via
232
+ * addAllowedRoot, and until now the sole caller was pty.cjs's spawn — so a
233
+ * project whose tab had no live PTY (dormant/hydrated tab, chat-only Epic)
234
+ * failed the write with "Write outside allowed write boundaries" *after*
235
+ * paying for a full synthesis. The read-side validatePath above has already
236
+ * proven the cwd is inside allowedRoots, so this widens nothing.
237
+ */
238
+ function allowBriefWrites(realCwd) {
239
+ config.addAllowedRoot(realCwd);
240
+ }
241
+
229
242
  async function refresh({ cwd }) {
230
243
  const realCwd = config.validatePath(cwd);
244
+ allowBriefWrites(realCwd);
231
245
 
232
246
  if (inFlight.has(realCwd)) {
233
247
  return { ok: false, error: 'refresh already running' };
@@ -279,9 +293,10 @@ async function refresh({ cwd }) {
279
293
  priorPinned,
280
294
  model: BRIEF_MODEL,
281
295
  nowIso: new Date().toISOString(),
296
+ priorEditedAt: priorBrief ? priorBrief.editedAt : null,
282
297
  });
283
298
 
284
- await config.writeJson(briefPath(realCwd), persisted);
299
+ await config.writeJson(briefPath(realCwd), persisted, { writer: 'project-home' });
285
300
  return { ok: true, brief: persisted };
286
301
  } finally {
287
302
  if (token) sessionSlots.release(token);
@@ -289,12 +304,29 @@ async function refresh({ cwd }) {
289
304
  }
290
305
  }
291
306
 
307
+ /**
308
+ * Hand-edit brief.json in place — the "maintain" half of the generate-and-
309
+ * maintain loop, and the reason the brief is a real file rather than a cache.
310
+ * Zero LLM cost. Edited pinnable blocks are auto-pinned by computeUpdate so
311
+ * the next refresh feeds them back in instead of rewriting them.
312
+ */
313
+ async function update({ cwd, patch }) {
314
+ const realCwd = config.validatePath(cwd);
315
+ allowBriefWrites(realCwd);
316
+ const currentBrief = await readBrief(realCwd);
317
+ const result = core.computeUpdate(currentBrief, patch, new Date().toISOString());
318
+ if (!result.ok) return result;
319
+ await config.writeJson(briefPath(realCwd), result.brief, { writer: 'project-home' });
320
+ return { ok: true, brief: result.brief };
321
+ }
322
+
292
323
  async function setPin({ cwd, block, pinned }) {
293
324
  const realCwd = config.validatePath(cwd);
325
+ allowBriefWrites(realCwd);
294
326
  const currentBrief = await readBrief(realCwd);
295
327
  const result = core.computeSetPin(currentBrief, block, pinned);
296
328
  if (!result.ok) return result;
297
- await config.writeJson(briefPath(realCwd), result.brief);
329
+ await config.writeJson(briefPath(realCwd), result.brief, { writer: 'project-home' });
298
330
  return { ok: true, brief: result.brief };
299
331
  }
300
332
 
@@ -303,6 +335,7 @@ function registerProjectBriefIpc() {
303
335
  ipcMain.handle('project-brief:get', v(s.projectBriefCwd, get));
304
336
  ipcMain.handle('project-brief:refresh', v(s.projectBriefCwd, refresh));
305
337
  ipcMain.handle('project-brief:set-pin', v(s.projectBriefSetPin, setPin));
338
+ ipcMain.handle('project-brief:update', v(s.projectBriefUpdate, update));
306
339
  }
307
340
 
308
341
  module.exports = {
@@ -310,4 +343,5 @@ module.exports = {
310
343
  get,
311
344
  refresh,
312
345
  setPin,
346
+ update,
313
347
  };
@@ -18,6 +18,22 @@ function promptSessionActiveIndexPath(cwd) {
18
18
  return `${String(cwd).replace(/\/+$/, '')}/session-manager-operations/prompt-sessions/active-index.json`;
19
19
  }
20
20
 
21
+ // IPC channel broadcast whenever an event is appended to a PromptSession's
22
+ // chain from the main process (currently only the scheduler's response-event
23
+ // append below). Mirrors chatRunner.cjs's attachWindow/broadcast pattern.
24
+ const EVENT_APPENDED_CHANNEL = 'promptSession:event-appended';
25
+
26
+ let mainWindow = null;
27
+ function attachWindow(win) { mainWindow = win; }
28
+
29
+ function broadcast(channel, payload) {
30
+ try {
31
+ if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents && !mainWindow.webContents.isDestroyed()) {
32
+ mainWindow.webContents.send(channel, payload);
33
+ }
34
+ } catch { /* render frame may be gone */ }
35
+ }
36
+
21
37
  let seq = 0;
22
38
  function mintEventId() {
23
39
  seq += 1;
@@ -75,7 +91,8 @@ async function appendResponseEventIfKnown(cwd, sourcePromptId, text) {
75
91
  text,
76
92
  };
77
93
  data.events[sourcePromptId] = [...events, event];
78
- await config.writeJson(path, data);
94
+ await config.writeJson(path, data, { writer: 'scheduler' });
95
+ broadcast(EVENT_APPENDED_CHANNEL, { cwd, promptSessionId: sourcePromptId, event });
79
96
  return true;
80
97
  });
81
98
  } catch (e) {
@@ -84,4 +101,9 @@ async function appendResponseEventIfKnown(cwd, sourcePromptId, text) {
84
101
  }
85
102
  }
86
103
 
87
- module.exports = { appendResponseEventIfKnown, promptSessionActiveIndexPath };
104
+ module.exports = {
105
+ appendResponseEventIfKnown,
106
+ promptSessionActiveIndexPath,
107
+ attachWindow,
108
+ EVENT_APPENDED_CHANNEL,
109
+ };
package/src/main/pty.cjs CHANGED
@@ -20,6 +20,7 @@ const { addAllowedRoot } = require('./config.cjs');
20
20
  const { cleanChildEnv, pathWithUserBins } = require('./lib/cleanEnv.cjs');
21
21
  const { checkInsideHome } = require('./lib/insideHome.cjs');
22
22
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
23
+ const opsErrorLog = require('./lib/opsErrorLog.cjs');
23
24
 
24
25
  // Absolute path to the installed package root (src/main/ -> ../../), shown in
25
26
  // the remediation message so the user can cd there and rebuild.
@@ -162,6 +163,13 @@ class PtyManager {
162
163
  });
163
164
  } catch (err) {
164
165
  console.error('[pty] pty.spawn threw:', err);
166
+ opsErrorLog.appendError({
167
+ cwd,
168
+ scope: 'pty',
169
+ tabId,
170
+ tags: ['spawn-failed'],
171
+ message: `pty.spawn threw: ${err?.message ?? String(err)}`,
172
+ });
165
173
  // Surface the cause in the tab + report a clean exit rather than throwing
166
174
  // an opaque IPC error (covers a missing/invalid cwd or a native fault).
167
175
  sendIfAlive(this.window, `pty:data:${tabId}`, nativeModuleHelp(`pty.spawn failed: ${err?.message ?? String(err)}`));
@@ -196,6 +204,13 @@ class PtyManager {
196
204
  // real interactive shell (which prints a prompt immediately) is exempt.
197
205
  if (!gotData && exitCode !== 0 && Date.now() - spawnedAt < 1200) {
198
206
  sendIfAlive(this.window, `pty:data:${tabId}`, nativeModuleHelp(`The shell exited immediately (code ${exitCode}).`));
207
+ opsErrorLog.appendError({
208
+ cwd,
209
+ scope: 'pty',
210
+ tabId,
211
+ tags: ['immediate-exit'],
212
+ message: `shell exited immediately (code ${exitCode}, signal ${signal ?? 'none'}) after ${Date.now() - spawnedAt}ms with no output`,
213
+ });
199
214
  }
200
215
  sendIfAlive(this.window, `pty:exit:${tabId}`, { exitCode, signal });
201
216
  this.sessions.delete(tabId);
@@ -519,7 +519,7 @@ async function retagOne({ slug, parallelGroup, estimateMinutes }) {
519
519
  // Atomic write via shared helper. If slug changed, write at the new path
520
520
  // and unlink the old slug.
521
521
  try {
522
- await config.writeTextAtomic(dst, newRaw);
522
+ await config.writeTextAtomic(dst, newRaw, { writer: 'scheduler' });
523
523
  if (dst !== src) {
524
524
  try { await fsp.unlink(src); } catch { /* if src is already same as dst (race), fine */ }
525
525
  }
@@ -73,6 +73,14 @@ async function parsePrdRaw(filePath) {
73
73
  // dropped straight into an Epic's prds/ dir still get real linkage
74
74
  // instead of null.
75
75
  sourcePromptId: fm.sourcePromptId || deriveEpicIdFromPrdPath(filePath) || null,
76
+ // The Epic this PRD actually belongs to, derived purely from its location
77
+ // (epic dir name == epic id, 1:1 by design — prdLocations.deriveEpicIdFromPrdPath).
78
+ // Deliberately separate from sourcePromptId: that field is *intent* and
79
+ // can be stale or hand-written wrong in frontmatter (real rows in
80
+ // queue.json exist where sourcePromptId and sourceTabId disagree), while
81
+ // this one is *fact* on disk. Every surface that shows "which Epic is this
82
+ // from" reads this, so Scheduler and Epics can't drift apart.
83
+ epicId: deriveEpicIdFromPrdPath(filePath),
76
84
  // Optional traceability back to the chat tab that queued this PRD (PRD
77
85
  // 761) — read back at job completion to route a status prompt via
78
86
  // enqueueExternalPrompt (PRD 753). Additive — absent on every PRD
@@ -63,6 +63,7 @@ const prdParser = require('./scheduler/prdParser.cjs');
63
63
  const sessionsStore = require('./sessionsStore.cjs');
64
64
  const { enqueueExternalPrompt } = require('./chatRunner.cjs');
65
65
  const { appendResponseEventIfKnown } = require('./promptSessionEvents.cjs');
66
+ const promptSessionTranscript = require('./promptSessionTranscript.cjs');
66
67
  const { verifyRun } = require('./runVerify.cjs');
67
68
  const { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS } = require('./lib/terminalRunOutcome.cjs');
68
69
  const logs = require('./logs.cjs');
@@ -84,9 +85,8 @@ const queueOps = require('./queueOps.cjs');
84
85
  // Plain Node module, no Electron dependency; queuePath/prdsDir defaults already
85
86
  // match ROOT/QUEUE_PATH below since both resolve the same ~/.claude/session-manager
86
87
  // home-dir layout.
87
- const { sweep: sweepFeedback } = require('../../scripts/lib/watchdogHelpers.cjs');
88
- const { resolvePrdsDirs, resolvePrdWriteDir, listEpicPrdDirs } = require('./lib/prdLocations.cjs');
89
- const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/epicMint.cjs');
88
+ const { resolvePrdsDirs, resolvePrdWriteDir, listEpicPrdDirs, listArchivedPrdDirs } = require('./lib/prdLocations.cjs');
89
+ const { ensureEpic, appendPrdCreatedEvent, removeEpic, readActiveIndex } = require('./lib/epicMint.cjs');
90
90
 
91
91
  // ---------- origin session resolution (PRD 832) ----------
92
92
  // An Epic IS a tagged claude session — job rows carry the originating
@@ -144,6 +144,10 @@ const POST_RESULT_GRACE_MS = 90_000;
144
144
  const POST_RESULT_KILL_MS = 30_000;
145
145
  const RESULT_TAIL_POLL_MS = 5_000;
146
146
  const RESULT_TAIL_BYTES = 8 * 1024;
147
+ // Wider than RESULT_TAIL_BYTES (which only needs the subtype near the
148
+ // boundary) — a real `result` string can be a full paragraph, so
149
+ // extractResultTextFromLog scans more of the tail to find it whole.
150
+ const RESULT_TEXT_TAIL_BYTES = 64 * 1024;
147
151
 
148
152
  // Idle-output watchdog: if the log file mtime stops advancing for this long
149
153
  // while the process is still alive, the agent is hung mid-work (network
@@ -492,23 +496,43 @@ function prdPathForJob(job) {
492
496
  return path.join(prdDirForCwd(job && job.cwd), `${job && job.slug}.md`);
493
497
  }
494
498
 
495
- /** Absolute path to the sibling `prds-archived/<slug>.md` twin of a job's PRD. */
499
+ /**
500
+ * Absolute path to a job's archived-twin `<slug>.md`. Resolves to the first
501
+ * archive dir (across the flat legacy layout and every Epic's own sibling
502
+ * archive — see listArchivedPrdDirs) that actually contains the slug, falling
503
+ * back to the flat `prds-archived/<slug>.md` path when none do (this fallback
504
+ * is only ever used for its string value — logging/note text in
505
+ * prdArchivedSkipResult — never as an existence check).
506
+ */
496
507
  function archivedPrdPathForJob(job) {
497
- return path.join(prdDirForCwd(job && job.cwd), '..', 'prds-archived', `${job && job.slug}.md`);
508
+ const slug = job && job.slug;
509
+ const flatPath = path.join(prdDirForCwd(job && job.cwd), '..', 'prds-archived', `${slug}.md`);
510
+ for (const dir of listArchivedPrdDirs((job && job.cwd) || DEFAULT_PROJECT_CWD)) {
511
+ const candidate = safeSlugPathIn(dir, slug);
512
+ if (candidate && fs.existsSync(candidate)) return candidate;
513
+ }
514
+ return flatPath;
498
515
  }
499
516
 
500
517
  /**
501
- * True if a job's PRD has already been archived (sibling `prds-archived/<slug>.md`
502
- * exists). A queue entry whose PRD moved there is stale — the work already shipped
503
- * — not a genuine missing-PRD failure.
518
+ * True if a job's PRD has already been archived — in the flat legacy
519
+ * `prds-archived/` dir OR in the Epic-scoped sibling archive dir every new
520
+ * PRD actually lands in (archiveCompletedPrd archives into the source PRD's
521
+ * OWN parent's prds-archived/, which for an Epic PRD is inside that Epic).
522
+ * A queue entry whose PRD moved to either is stale — the work already
523
+ * shipped — not a genuine missing-PRD failure.
504
524
  */
505
525
  async function archivedTwinExists(job) {
506
- try {
507
- await fsp.access(archivedPrdPathForJob(job));
508
- return true;
509
- } catch {
510
- return false;
526
+ const slug = job && job.slug;
527
+ for (const dir of listArchivedPrdDirs((job && job.cwd) || DEFAULT_PROJECT_CWD)) {
528
+ const candidate = safeSlugPathIn(dir, slug);
529
+ if (!candidate) continue;
530
+ try {
531
+ await fsp.access(candidate);
532
+ return true;
533
+ } catch { /* not here — try the next archive dir */ }
511
534
  }
535
+ return false;
512
536
  }
513
537
 
514
538
  /**
@@ -1106,9 +1130,13 @@ async function reconcile(state) {
1106
1130
  estimateMinutes: p.estimateMinutes,
1107
1131
  sourcePromptId: reconcileSourcePromptId(job, p.sourcePromptId),
1108
1132
  sourceTabId: p.sourceTabId,
1133
+ // Unlike sourcePromptId (frozen once a row leaves 'pending'), epicId is
1134
+ // refreshed from disk every pass: the PRD's directory IS its Epic
1135
+ // membership, so moving the file between Epic dirs must re-point the row.
1136
+ epicId: p.epicId ?? job.epicId ?? null,
1109
1137
  dependsOn: p.dependsOn,
1110
1138
  originSessionId: job.originSessionId
1111
- ?? resolveOriginSessionId(p.cwd, reconcileSourcePromptId(job, p.sourcePromptId)),
1139
+ ?? resolveOriginSessionId(p.cwd, p.epicId ?? reconcileSourcePromptId(job, p.sourcePromptId)),
1112
1140
  bodyPreview: p.body.split('\n').slice(0, 6).join('\n'),
1113
1141
  });
1114
1142
  }
@@ -1167,8 +1195,9 @@ async function reconcile(state) {
1167
1195
  estimateMinutes: p.estimateMinutes,
1168
1196
  sourcePromptId: p.sourcePromptId,
1169
1197
  sourceTabId: p.sourceTabId,
1198
+ epicId: p.epicId ?? null,
1170
1199
  dependsOn: p.dependsOn,
1171
- originSessionId: resolveOriginSessionId(p.cwd, p.sourcePromptId),
1200
+ originSessionId: resolveOriginSessionId(p.cwd, p.epicId ?? p.sourcePromptId),
1172
1201
  bodyPreview: p.body.split('\n').slice(0, 6).join('\n'),
1173
1202
  status: 'pending',
1174
1203
  runId: null,
@@ -1267,17 +1296,11 @@ let resumeTimer = null;
1267
1296
  let pollLoopTimer = null;
1268
1297
  let rescheduleInterval = null;
1269
1298
  let heartbeatInterval = null;
1270
- // Feedback sweep piggybacks on the 60s heartbeat tick but runs far less often —
1271
- // every Nth tick — since it's a readdir-per-active-project scan, not free.
1272
- // 5 ticks = 5 minutes; well inside sweep()/activeProjectCwds()'s 90-minute
1273
- // active-session window, so no active project can be missed between sweeps.
1274
- const FEEDBACK_SWEEP_TICK_INTERVAL = 5;
1275
- let feedbackSweepTickCount = 0;
1276
- /** Pure gate for the tick counter above — exported so the wiring is testable
1277
- * without waiting on real setInterval timers. */
1278
- function feedbackSweepDue(tickCount, interval = FEEDBACK_SWEEP_TICK_INTERVAL) {
1279
- return tickCount >= interval;
1280
- }
1299
+ // (The 5-minute feedback sweep that used to piggyback on this heartbeat is
1300
+ // gone: it scanned each active project's session-manager-operations/feedback/
1301
+ // and auto-queued a /process-feedback PRD. Both the folder and that skill are
1302
+ // retired — agents now file a `proposed` Epic that waits for human approval,
1303
+ // so there is nothing to sweep for. See lib/rcaFeedbackHook.cjs.)
1281
1304
  // In-memory set of slugs currently spawned in this process. Prevents
1282
1305
  // double-spawn when runDueJobs() is called while jobs are in flight.
1283
1306
  const runningSet = new Set();
@@ -1623,6 +1646,34 @@ function isNotifiableTerminalStatus(effectiveStatus) {
1623
1646
  return effectiveStatus === 'completed' || effectiveStatus === 'failed';
1624
1647
  }
1625
1648
 
1649
+ /**
1650
+ * Scans a run log's tail for the last `{"type":"result",...}` JSONL event
1651
+ * (the claude harness's final message) and returns its `result` string, or
1652
+ * null if the log is missing, unreadable, or has no parseable result line.
1653
+ * Never throws — a missing/torn log must not break notifyOriginatingTab.
1654
+ */
1655
+ function extractResultTextFromLog(logPath) {
1656
+ if (!logPath) return null;
1657
+ try {
1658
+ const tail = readTail(logPath, RESULT_TEXT_TAIL_BYTES);
1659
+ if (!tail) return null;
1660
+ const lines = tail.split('\n');
1661
+ for (let i = lines.length - 1; i >= 0; i--) {
1662
+ const line = lines[i].trim();
1663
+ if (!line || !line.includes('"type":"result"')) continue;
1664
+ try {
1665
+ const parsed = JSON.parse(line);
1666
+ if (parsed && typeof parsed.result === 'string') return parsed.result;
1667
+ } catch {
1668
+ // torn/partial line — keep scanning backward
1669
+ }
1670
+ }
1671
+ return null;
1672
+ } catch {
1673
+ return null;
1674
+ }
1675
+ }
1676
+
1626
1677
  /**
1627
1678
  * notifyOriginatingTab(job) → void
1628
1679
  *
@@ -1630,31 +1681,62 @@ function isNotifiableTerminalStatus(effectiveStatus) {
1630
1681
  * rateLimited auto-pause, which resets the job to pending instead), publish
1631
1682
  * a short status notification for the PRD that queued this job.
1632
1683
  *
1633
- * Resolution order (PRD 814): (1) if the PRD's `sourcePromptId` resolves to
1634
- * a known, still-active PromptSession (minted for a dev-work dispatch, PRD
1635
- * 813) under the job's cwd, append a 'response' PromptSessionEvent to THAT
1636
- * session's own event chain — its own scoped PromptSessionConversation, not
1637
- * whatever tab happens to be active — and stop; (2) otherwise, fall back to
1638
- * today's behavior: push a short status prompt into the chat tab that queued
1639
- * this PRD via enqueueExternalPrompt (PRD 753), resolved via the PRD's own
1640
- * `sourceTabId` frontmatter, then the first open tab (per sessionsStore's
1641
- * persisted tabs.json) whose cwd matches the job's cwd — first match only,
1642
- * no fan-out to multiple matching tabs; (3) no-op. Never throws to the
1643
- * caller (fire-and-forget from spawnJob). Deps are injectable (mirrors
1644
- * partitionBootOrphans's isAlive param) so unit tests can exercise the
1645
- * resolution logic without touching disk/electron.
1684
+ * Resolution order (PRD 814, extended by PRD 854): (1) if the PRD's
1685
+ * `sourcePromptId` resolves to a known, still-active PromptSession (minted
1686
+ * for a dev-work dispatch, PRD 813) under the job's cwd, append a 'response'
1687
+ * PromptSessionEvent to THAT session's own event chain — its own scoped Epic
1688
+ * conversation (EpicDetail.tsx), not whatever tab happens to be active — and
1689
+ * stop; (2) otherwise, fall back to pushing a short status prompt via
1690
+ * enqueueExternalPrompt (PRD 753) at a target id resolved from, in order,
1691
+ * the PRD's own `sourceTabId` frontmatter, then `sourcePromptId` again (a PRD
1692
+ * dispatched straight from an Epic's composer, dispatchPromptSessionToPrd,
1693
+ * never sets sourceTabId — sourcePromptId IS the Epic id and is a valid
1694
+ * chat:external-send target too, which the renderer now resolves against
1695
+ * both open tabs and known Epics, refusing a completed one), then the first
1696
+ * open tab (per sessionsStore's persisted tabs.json) whose cwd matches the
1697
+ * job's cwd — first match only, no fan-out to multiple matching tabs; (3)
1698
+ * no-op. The cwd-match step only runs when NEITHER sourceTabId nor
1699
+ * sourcePromptId is present in frontmatter at all — `sendPrompt` (
1700
+ * enqueueExternalPrompt) is fire-and-forget IPC with no ack, so once step
1701
+ * (2) picks either id it is not retried even if the renderer can't resolve
1702
+ * it either (e.g. a stale/garbage id) — same non-guaranteed-delivery
1703
+ * tradeoff this function already accepted for sourceTabId pre-PRD-854.
1704
+ * Never throws to the caller (fire-and-forget from spawnJob). Deps are
1705
+ * injectable (mirrors partitionBootOrphans's isAlive param) so unit tests
1706
+ * can exercise the resolution logic without touching disk/electron.
1646
1707
  */
1647
1708
  async function notifyOriginatingTab(job, {
1648
1709
  parsePrdRaw = prdParser.parsePrdRaw,
1649
1710
  loadSessions = sessionsStore.load,
1650
1711
  sendPrompt = enqueueExternalPrompt,
1651
1712
  appendResponseEvent = appendResponseEventIfKnown,
1713
+ appendTranscriptTurn = promptSessionTranscript.appendTurn,
1714
+ readResultFromLog = extractResultTextFromLog,
1652
1715
  } = {}) {
1653
1716
  try {
1654
1717
  const prdPath = prdPathForJob(job);
1655
1718
  const prd = await parsePrdRaw(prdPath).catch(() => null);
1656
1719
  const message = `PRD ${job.slug} finished: ${job.status}. Check Scheduler for details.`;
1657
1720
 
1721
+ // Persist the job's real result text (not just the short status chip
1722
+ // above) to the durable per-Epic transcript, keyed off whichever id
1723
+ // notifyOriginatingTab would otherwise notify. Best-effort: a missing
1724
+ // cwd/epic id, an unreadable run log, or an IPC error here must never
1725
+ // block the notification below.
1726
+ const epicIdForTranscript = prd?.sourcePromptId || prd?.sourceTabId || null;
1727
+ if (epicIdForTranscript && job.cwd) {
1728
+ try {
1729
+ const logPath = job.runId ? path.join(RUNS_DIR, job.runId, `${job.slug}.log`) : null;
1730
+ const resultText = readResultFromLog(logPath);
1731
+ await appendTranscriptTurn(job.cwd, epicIdForTranscript, {
1732
+ role: 'assistant',
1733
+ text: resultText || message,
1734
+ });
1735
+ } catch (e) {
1736
+ console.error('[scheduler] notifyOriginatingTab transcript append error', job?.slug, e);
1737
+ }
1738
+ }
1739
+
1658
1740
  if (prd?.sourcePromptId) {
1659
1741
  const routed = await appendResponseEvent(job.cwd || null, prd.sourcePromptId, message).catch((e) => {
1660
1742
  console.error('[scheduler] notifyOriginatingTab appendResponseEvent error', job?.slug, e);
@@ -1663,7 +1745,13 @@ async function notifyOriginatingTab(job, {
1663
1745
  if (routed) return;
1664
1746
  }
1665
1747
 
1666
- let targetTabId = prd?.sourceTabId || null;
1748
+ // appendResponseEvent already refused above (unknown id, completed
1749
+ // Epic, or disk error) — the sourcePromptId fallback below re-sends to
1750
+ // the SAME id via chat:external-send, which the renderer independently
1751
+ // re-checks against its own live PromptSession store. Deliberate
1752
+ // defense-in-depth (main's disk-backed check vs. the renderer's
1753
+ // in-memory one can disagree/race), not a redundant duplicate to prune.
1754
+ let targetTabId = prd?.sourceTabId || prd?.sourcePromptId || null;
1667
1755
  if (!targetTabId) {
1668
1756
  const jobCwd = job.cwd || null;
1669
1757
  if (jobCwd) {
@@ -1673,7 +1761,7 @@ async function notifyOriginatingTab(job, {
1673
1761
  }
1674
1762
  }
1675
1763
  if (!targetTabId) {
1676
- console.log(`[scheduler] notifyOriginatingTab: no target tab for ${job.slug}, skipping`);
1764
+ console.log(`[scheduler] notifyOriginatingTab: no open tab and no Epic for ${job.slug}, skipping`);
1677
1765
  return;
1678
1766
  }
1679
1767
 
@@ -1838,8 +1926,13 @@ async function executeJob(job, runDir, defaultCwd, onPid) {
1838
1926
  }
1839
1927
 
1840
1928
  // Read full PRD body fresh from disk (queue stored only the preview).
1929
+ // Resolve through findPrdDir's full candidate search (legacy flat dir +
1930
+ // every project's Epic-scoped dirs) first, so the common case — a live
1931
+ // Epic-scoped PRD — is a first-try hit instead of probing the retired flat
1932
+ // dir and only then falling back.
1841
1933
  let prompt;
1842
- let prdPath = prdPathForJob(job);
1934
+ const resolvedDir = await findPrdDir(job.slug);
1935
+ let prdPath = resolvedDir ? path.join(resolvedDir, `${job.slug}.md`) : prdPathForJob(job);
1843
1936
  try {
1844
1937
  const parsed = await parsePrd(prdPath);
1845
1938
  // Centrally enforce the review → security-review → verify → commit finish
@@ -3757,7 +3850,7 @@ function registerScheduleHandlers() {
3757
3850
  const resolved = safeSlugPathIn(dir, data.slug);
3758
3851
  if (!resolved) return { ok: false, error: 'invalid slug' };
3759
3852
  try {
3760
- await config.writeTextAtomic(resolved, data.body);
3853
+ await config.writeTextAtomic(resolved, data.body, { writer: 'scheduler' });
3761
3854
  } catch (e) {
3762
3855
  return { ok: false, error: e?.message ?? 'write failed' };
3763
3856
  }
@@ -3795,6 +3888,7 @@ function registerScheduleHandlers() {
3795
3888
  cwd: parsed.cwd || '',
3796
3889
  estimateMinutes: parsed.estimateMinutes,
3797
3890
  sourcePromptId: parsed.sourcePromptId,
3891
+ epicId: parsed.epicId ?? null,
3798
3892
  mtimeMs: stat.mtimeMs,
3799
3893
  });
3800
3894
  } catch (e) {
@@ -4006,16 +4100,6 @@ async function init() {
4006
4100
  utilization: cachedUtilization,
4007
4101
  consecutiveFailures,
4008
4102
  });
4009
-
4010
- feedbackSweepTickCount++;
4011
- if (feedbackSweepDue(feedbackSweepTickCount, FEEDBACK_SWEEP_TICK_INTERVAL)) {
4012
- feedbackSweepTickCount = 0;
4013
- try {
4014
- sweepFeedback();
4015
- } catch (e) {
4016
- console.warn('[scheduler] feedback sweep failed', e?.message);
4017
- }
4018
- }
4019
4103
  }, 60_000);
4020
4104
  if (heartbeatInterval.unref) heartbeatInterval.unref();
4021
4105
 
@@ -4125,10 +4209,16 @@ const remote = {
4125
4209
  if (!dir) {
4126
4210
  try {
4127
4211
  const { fm } = splitFrontmatter(body);
4128
- const epic = ensureEpic(cwd, {
4212
+ const epic = await ensureEpic(cwd, {
4129
4213
  goalText: fm.title || slug,
4130
4214
  tag: fm.tag,
4131
4215
  // An Epic-conversation dispatch already has its Epic — join it.
4216
+ // fm.sourcePromptId must be an existing Epic's promptSessionId
4217
+ // (== its active-index.json sessions key), NOT a
4218
+ // PromptTicket.id — epicMint.cjs's ensureEpic looks it up via
4219
+ // `index.sessions[explicitEpicId]` (see epicMint.cjs ~line 73),
4220
+ // a literal-equality join. Any other id (e.g. a PromptTicket.id)
4221
+ // simply won't match and mints a sibling Epic instead of joining.
4132
4222
  epicId: fm.sourcePromptId,
4133
4223
  });
4134
4224
  dir = epic.prdDir;
@@ -4151,16 +4241,22 @@ const remote = {
4151
4241
  // PRD 825: if this call minted a brand-new Epic (ensureEpic's `created`)
4152
4242
  // and the write below never lands, don't strand an empty Epic dir —
4153
4243
  // best-effort remove `<epic>/prds` then `<epic>` itself, only when empty.
4244
+ // PRD 851: also drop the Epic's active-index.json entry (sessions/events)
4245
+ // so an orphaned seed-prompt-only Epic doesn't linger in the Epics nav.
4246
+ // Gated on epicCreated (never fires when ensureEpic joined an existing
4247
+ // Epic) so a pre-existing Epic's history is never touched.
4154
4248
  const cleanupEmptyMintedEpic = async () => {
4155
4249
  if (!epicCreated || !epicId) return;
4156
4250
  try {
4157
4251
  const entries = await fsp.readdir(dir);
4158
- if (entries.length > 0) return;
4159
- await fsp.rmdir(dir);
4160
- const epicRootDir = path.dirname(dir);
4161
- const epicRootEntries = await fsp.readdir(epicRootDir);
4162
- if (epicRootEntries.length === 0) await fsp.rmdir(epicRootDir);
4252
+ if (entries.length === 0) {
4253
+ await fsp.rmdir(dir);
4254
+ const epicRootDir = path.dirname(dir);
4255
+ const epicRootEntries = await fsp.readdir(epicRootDir);
4256
+ if (epicRootEntries.length === 0) await fsp.rmdir(epicRootDir);
4257
+ }
4163
4258
  } catch { /* best-effort only */ }
4259
+ try { removeEpic(cwd, epicId); } catch { /* best-effort only */ }
4164
4260
  };
4165
4261
 
4166
4262
  const resolved = safeSlugPathIn(dir, slug);
@@ -4185,11 +4281,11 @@ const remote = {
4185
4281
  await cleanupEmptyMintedEpic();
4186
4282
  return { ok: false, error: 'invalid slug' };
4187
4283
  }
4188
- await config.writeTextAtomic(resolved, body);
4284
+ await config.writeTextAtomic(resolved, body, { writer: 'scheduler' });
4189
4285
  const stat = await fsp.stat(resolved);
4190
4286
  if (epicTrace) {
4191
4287
  // Best-effort: record the dispatch on the minted Epic's event chain.
4192
- try { appendPrdCreatedEvent(cwd, epicTrace, slug); } catch { /* trace only */ }
4288
+ try { await appendPrdCreatedEvent(cwd, epicTrace, slug); } catch { /* trace only */ }
4193
4289
  }
4194
4290
  return { ok: true, bytesWritten: stat.size };
4195
4291
  } catch (e) {
@@ -4288,4 +4384,4 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
4288
4384
  });
4289
4385
  }
4290
4386
 
4291
- module.exports = { registerScheduleHandlers, attachWindow, init, ROOT, PRDS_DIR, writeQueue, reconcile, reconcileSourcePromptId, allocateParallelGroup, selectHistoryJobs, parsePorcelain, FINISH_PROTOCOL, remote, pickNextBatch, pickForProject, reapDeadRunningJobs, pollRecoveryClearSource, memoryLimitedBatchSize, availableForJobs, reverifyNeedsReview, isRescanCandidate, isPromotableOriginal, selectAutoFixTargets, isEligibleForImmediateAutoFix, resolveRunId, isUnresolvableNeedsReview, healTargetForFix, buildInvestigationPrompt, committedInWindow, computeCommittedDuringRun, classifySigtermWithCommit, isFixPlanSlug, isFixPlanBeyondDepthCap, MAX_INVESTIGATION_DEPTH, forceTickOutcome, applyPauseCleared, detectNetworkErrorInLog, detectRateLimitInLog, classifyFailureOutcome, commitGuardVerdict, TRANSIENT_RETRY_CAP, buildScheduleStatePayload, partitionBootOrphans, applyOrphanOutcome, BOOT_ORPHAN_KILL_GRACE_MS, feedbackSweepDue, FEEDBACK_SWEEP_TICK_INTERVAL, sweepFeedback, registerAdminRoutes, notifyOriginatingTab, isNotifiableTerminalStatus, candidatePrdsDirs, prdDirForCwd, prdPathForJob, archivedPrdPathForJob, archivedTwinExists, findPrdDir, runPrdMigration, shouldSkipInvestigationForCleanRun, archiveCompletedPrd, retireCompletedSlugs, SCHEDULER_BOOTED_AT, SCHEDULER_CODE_SHA, resetJobFields };
4387
+ module.exports = { registerScheduleHandlers, attachWindow, init, ROOT, PRDS_DIR, writeQueue, reconcile, reconcileSourcePromptId, allocateParallelGroup, selectHistoryJobs, parsePorcelain, FINISH_PROTOCOL, remote, pickNextBatch, pickForProject, reapDeadRunningJobs, pollRecoveryClearSource, memoryLimitedBatchSize, availableForJobs, reverifyNeedsReview, isRescanCandidate, isPromotableOriginal, selectAutoFixTargets, isEligibleForImmediateAutoFix, resolveRunId, isUnresolvableNeedsReview, healTargetForFix, buildInvestigationPrompt, committedInWindow, computeCommittedDuringRun, classifySigtermWithCommit, isFixPlanSlug, isFixPlanBeyondDepthCap, MAX_INVESTIGATION_DEPTH, forceTickOutcome, applyPauseCleared, detectNetworkErrorInLog, detectRateLimitInLog, classifyFailureOutcome, commitGuardVerdict, TRANSIENT_RETRY_CAP, buildScheduleStatePayload, partitionBootOrphans, applyOrphanOutcome, BOOT_ORPHAN_KILL_GRACE_MS, registerAdminRoutes, notifyOriginatingTab, isNotifiableTerminalStatus, extractResultTextFromLog, candidatePrdsDirs, prdDirForCwd, prdPathForJob, archivedPrdPathForJob, archivedTwinExists, findPrdDir, runPrdMigration, shouldSkipInvestigationForCleanRun, archiveCompletedPrd, retireCompletedSlugs, SCHEDULER_BOOTED_AT, SCHEDULER_CODE_SHA, resetJobFields };
@@ -437,7 +437,7 @@ not be re-proposed:
437
437
 
438
438
  ### Reference implementation of this exact loop
439
439
 
440
- `/process-feedback`'s step 0b (source → triage → `/develop` → queue) is a working example of this
440
+ The proposal → approve → `/develop` → queue path is a working example of this
441
441
  shape, landed 2026-07-14 (`feat(process-feedback): sync open GitHub issues into the feedback
442
442
  intake`, commit `352b89c`). It syncs open GitHub issues into `session-manager-operations/feedback/`
443
443
  (deduped on a `gh-issue-<N>` token), then processes each item through the same triage → `/develop`