claude-code-session-manager 0.140.0 → 0.142.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 (204) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -9,7 +9,12 @@
9
9
  *
10
10
  * Layout (all paths via opsPath(cwd, 'tasks', ...)):
11
11
  * tasks/<YYYY-MM-DD>.jsonl summary lines, local date of the Task's startedAt.
12
- * kind 'start' | 'end' | 'imported'. Hashes + byte
12
+ * Event-log shaped {domain}.{action} kinds:
13
+ * 'task.started' (from null → to 'running') and
14
+ * 'task.status_changed' (from → to; an end, or a
15
+ * whole imported Task with importId, from null).
16
+ * Legacy 'start' | 'end' | 'imported' lines still
17
+ * on disk are read as those two kinds. Hashes + byte
13
18
  * counts only — never prompt/output text. Every
14
19
  * line carries sessionId (claude session id or
15
20
  * null) and persisted (true when the run kept its
@@ -18,6 +23,16 @@
18
23
  * promptTruncated/outputTruncated), stderrTail,
19
24
  * envelope. Written via atomicFs.writeJsonAtomic.
20
25
  *
26
+ * Status legality: every status line goes through transitionTask(from, to)
27
+ * against TASK_LEGAL_TRANSITIONS — refuse-plus-audit, like
28
+ * scheduler/scheduleJobTransitions.cjs. An illegal edge throws under vitest
29
+ * and, in prod, is refused (no line written, the call resolves null) with a
30
+ * `task_transition_refused` audit record. The read-side timeout derivation
31
+ * (running → interrupted) goes through the same table: a Task with no end
32
+ * reads 'interrupted' only once now > startedAt + (slotWaitSec + timeoutSec)
33
+ * * 1000 + INTERRUPT_GRACE_MS — startedAt is stamped before the slot wait, so
34
+ * the window counts it (a missing/non-numeric slotWaitSec counts as 0).
35
+ *
21
36
  * Retention: opsRetentionSettings.read().tasksDays (default 30). pruneOld runs
22
37
  * once per local day per project, on the first append of that day.
23
38
  *
@@ -41,7 +56,66 @@ const MAX_LIMIT = 200;
41
56
  const DAY_MS = 86400000;
42
57
  const DAY_FILE_RE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/;
43
58
  const TASK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
44
- const KINDS = new Set(['start', 'end', 'imported']);
59
+ const KIND_STARTED = 'task.started';
60
+ const KIND_STATUS_CHANGED = 'task.status_changed';
61
+ const KINDS = new Set([KIND_STARTED, KIND_STATUS_CHANGED]);
62
+ /** Pre-event-log kinds still on disk (≤ tasksDays old) → their current kind. */
63
+ const LEGACY_KINDS = { start: KIND_STARTED, end: KIND_STATUS_CHANGED, imported: KIND_STATUS_CHANGED };
64
+
65
+ /** Terminal Task statuses (taskRun.cjs + taskAdminRoutes.cjs + read-side 'interrupted'). */
66
+ const TERMINAL_STATUSES = Object.freeze([
67
+ 'ok', 'error', 'rate_limited', 'timeout', 'spawn_failed', 'caller_gone', 'slot_timeout',
68
+ 'too_many_waiting', 'interrupted',
69
+ ]);
70
+
71
+ /**
72
+ * Explicit from → to edges. The key 'null' is "no prior status": a Task's
73
+ * start (→ running), an imported whole Task, or an end whose start body is
74
+ * gone (→ any terminal). running → any terminal, including the timeout-derived
75
+ * 'interrupted'. Terminal statuses have no exits — a second end is refused.
76
+ */
77
+ const TASK_LEGAL_TRANSITIONS = {
78
+ null: ['running', ...TERMINAL_STATUSES],
79
+ running: [...TERMINAL_STATUSES],
80
+ };
81
+ for (const s of TERMINAL_STATUSES) TASK_LEGAL_TRANSITIONS[s] = [];
82
+
83
+ let refusedTransitionCount = 0;
84
+
85
+ function isUnderTest() {
86
+ return !!process.env.VITEST;
87
+ }
88
+
89
+ /**
90
+ * transitionTask(from, to, { taskId, cwd, source, reason }) → boolean.
91
+ * true when `from → to` is in TASK_LEGAL_TRANSITIONS. An illegal edge throws
92
+ * under vitest; in prod it logs, counts, writes a `task_transition_refused`
93
+ * audit record and returns false (the caller then refuses the write).
94
+ */
95
+ function transitionTask(from, to, ctx = {}) {
96
+ const key = from == null ? 'null' : String(from);
97
+ const edges = Object.prototype.hasOwnProperty.call(TASK_LEGAL_TRANSITIONS, key) ? TASK_LEGAL_TRANSITIONS[key] : null;
98
+ if (Array.isArray(edges) && edges.includes(to)) return true;
99
+ const detail = {
100
+ taskId: ctx.taskId ?? null,
101
+ from: from ?? null,
102
+ to: to ?? null,
103
+ source: ctx.source ?? null,
104
+ reason: ctx.reason ?? null,
105
+ cwd: ctx.cwd ?? null,
106
+ };
107
+ if (isUnderTest()) {
108
+ throw new Error(`taskLedger: illegal task transition ${detail.from} -> ${detail.to} (taskId=${detail.taskId})`);
109
+ }
110
+ refusedTransitionCount += 1;
111
+ console.error(`[taskLedger] illegal transition refused: taskId=${detail.taskId} from=${detail.from} to=${detail.to} source=${detail.source}`);
112
+ try {
113
+ require('../telemetry/auditLog.cjs').appendAuditEvent('task_transition_refused', detail);
114
+ } catch { /* auditing must never be the thing that fails */ }
115
+ return false;
116
+ }
117
+
118
+ function getRefusedTransitionCount() { return refusedTransitionCount; }
45
119
  // Text-bearing input fields: they go to the body file, never the summary line.
46
120
  const TEXT_FIELDS = ['prompt', 'output', 'stderrTail', 'envelope'];
47
121
  const USAGE_KEYS = ['input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'];
@@ -158,12 +232,14 @@ function startedMsOf(row) {
158
232
  async function appendTaskStart(cwd, row) {
159
233
  assertTaskId(row && row.taskId);
160
234
  const startedMs = startedMsOf(row);
235
+ if (!transitionTask(null, 'running', { taskId: row.taskId, cwd, source: 'appendTaskStart' })) return null;
161
236
  await maybePrune(cwd);
162
237
  const p = capText(row.prompt);
163
238
  await writeBody(cwd, row.taskId, {
164
239
  v: 1,
165
240
  taskId: row.taskId,
166
241
  startedAt: row.startedAt,
242
+ status: 'running',
167
243
  prompt: p.text,
168
244
  promptTruncated: p.truncated,
169
245
  });
@@ -171,7 +247,9 @@ async function appendTaskStart(cwd, row) {
171
247
  ...stripText(row),
172
248
  ...sessionFields(row),
173
249
  v: 1,
174
- kind: 'start',
250
+ kind: KIND_STARTED,
251
+ from: null,
252
+ to: 'running',
175
253
  source: 'sm',
176
254
  promptSha256: p.sha256,
177
255
  promptBytes: p.bytes,
@@ -183,12 +261,17 @@ async function appendTaskStart(cwd, row) {
183
261
  /**
184
262
  * appendTaskEnd(cwd, { ...endRow, output, stderrTail, envelope }) — rewrites
185
263
  * the body adding output fields and appends a kind 'end' line to the day file
186
- * of the Task's startedAt (taken from the row, else from the body).
264
+ * of the Task's startedAt (taken from the row, else from the body). The edge
265
+ * is body.status (a body without one = 'running'; no body = null) → row.status;
266
+ * an illegal edge (e.g. a second end) is refused and resolves null.
187
267
  */
188
268
  async function appendTaskEnd(cwd, row) {
189
269
  assertTaskId(row && row.taskId);
270
+ const body = await readBody(cwd, row.taskId);
271
+ const from = body ? (typeof body.status === 'string' && body.status ? body.status : 'running') : null;
272
+ if (!transitionTask(from, row.status, { taskId: row.taskId, cwd, source: 'appendTaskEnd' })) return null;
190
273
  await maybePrune(cwd);
191
- const prior = (await readBody(cwd, row.taskId)) || { v: 1, taskId: row.taskId };
274
+ const prior = body || { v: 1, taskId: row.taskId };
192
275
  const startedAt = row.startedAt || prior.startedAt || row.endedAt || new Date().toISOString();
193
276
  const startedMs = toMs(startedAt) ?? Date.now();
194
277
  const o = capText(row.output);
@@ -196,6 +279,7 @@ async function appendTaskEnd(cwd, row) {
196
279
  await writeBody(cwd, row.taskId, {
197
280
  ...prior,
198
281
  startedAt,
282
+ status: row.status,
199
283
  output: o.text,
200
284
  outputTruncated: o.truncated,
201
285
  stderrTail: stderr.text,
@@ -205,7 +289,9 @@ async function appendTaskEnd(cwd, row) {
205
289
  ...stripText(row),
206
290
  ...sessionFields(row),
207
291
  v: 1,
208
- kind: 'end',
292
+ kind: KIND_STATUS_CHANGED,
293
+ from,
294
+ to: row.status,
209
295
  startedAt,
210
296
  outputSha256: o.sha256,
211
297
  outputBytes: o.bytes,
@@ -222,6 +308,7 @@ async function appendImported(cwd, row) {
222
308
  assertTaskId(row && row.taskId);
223
309
  if (typeof row.importId !== 'string' || !row.importId) throw new Error('taskLedger: importId is required');
224
310
  const startedMs = startedMsOf(row);
311
+ if (!transitionTask(null, row.status, { taskId: row.taskId, cwd, source: 'appendImported' })) return null;
225
312
  await maybePrune(cwd);
226
313
  const p = capText(row.prompt);
227
314
  const o = capText(row.output);
@@ -230,6 +317,7 @@ async function appendImported(cwd, row) {
230
317
  v: 1,
231
318
  taskId: row.taskId,
232
319
  startedAt: row.startedAt,
320
+ status: row.status,
233
321
  prompt: p.text,
234
322
  promptTruncated: p.truncated,
235
323
  output: o.text,
@@ -241,7 +329,9 @@ async function appendImported(cwd, row) {
241
329
  ...stripText(row),
242
330
  ...sessionFields(row),
243
331
  v: 1,
244
- kind: 'imported',
332
+ kind: KIND_STATUS_CHANGED,
333
+ from: null,
334
+ to: row.status,
245
335
  source: 'direct',
246
336
  promptSha256: p.sha256,
247
337
  promptBytes: p.bytes,
@@ -289,6 +379,10 @@ async function readRows(cwd, range) {
289
379
  if (!line.trim()) continue;
290
380
  let row;
291
381
  try { row = JSON.parse(line); } catch { skippedLines += 1; continue; }
382
+ if (row && typeof row === 'object' && !Array.isArray(row)
383
+ && Object.prototype.hasOwnProperty.call(LEGACY_KINDS, row.kind)) {
384
+ row = { ...row, kind: LEGACY_KINDS[row.kind] };
385
+ }
292
386
  if (!row || typeof row !== 'object' || Array.isArray(row)
293
387
  || !KINDS.has(row.kind) || typeof row.taskId !== 'string' || !row.taskId) {
294
388
  skippedLines += 1;
@@ -300,21 +394,37 @@ async function readRows(cwd, range) {
300
394
  return { rows, skippedLines };
301
395
  }
302
396
 
303
- function foldedStatus(t, now) {
397
+ /**
398
+ * A Task's status: its end/imported status, else 'running' — or, once
399
+ * now > startedAt + (slotWaitSec + timeoutSec) * 1000 + INTERRUPT_GRACE_MS,
400
+ * the timeout-derived 'interrupted', taken only when TASK_LEGAL_TRANSITIONS
401
+ * allows running → it. startedAt is stamped before the slot wait, so the
402
+ * window includes it; a missing/non-numeric slotWaitSec counts as 0.
403
+ * A Task in `live` (taskIds this app is still running) with no end status
404
+ * reads 'running', never the timeout-derived 'interrupted'.
405
+ */
406
+ function foldedStatus(t, now, live) {
304
407
  if (t.status) return t.status;
408
+ if (live && live.has(t.taskId)) return 'running';
305
409
  const startedMs = toMs(t.startedAt);
410
+ const slotWaitMs = (Number(t.slotWaitSec) || 0) * 1000;
306
411
  const timeoutMs = (Number(t.timeoutSec) || 0) * 1000;
307
- if (startedMs != null && now > startedMs + timeoutMs + INTERRUPT_GRACE_MS) return 'interrupted';
412
+ if (startedMs != null && now > startedMs + slotWaitMs + timeoutMs + INTERRUPT_GRACE_MS
413
+ && transitionTask('running', 'interrupted', { taskId: t.taskId, source: 'foldedStatus:timeout' })) {
414
+ return 'interrupted';
415
+ }
308
416
  return 'running';
309
417
  }
310
418
 
311
- /** taskId → folded Task (start ⊕ end, or the imported line). */
312
- function fold(rows, now) {
419
+ /** taskId → folded Task (start ⊕ end, or the imported line). `live`: optional Set of running taskIds. */
420
+ function fold(rows, now, live) {
313
421
  const byId = new Map();
314
422
  for (const row of rows) {
315
- const { kind, ...fields } = row;
423
+ const { kind, from: _from, to: _to, ...fields } = row;
316
424
  const cur = byId.get(row.taskId);
317
- if (kind === 'end') {
425
+ if (kind === KIND_STATUS_CHANGED && typeof fields.importId === 'string' && fields.importId) {
426
+ byId.set(row.taskId, { ...(cur || {}), ...fields });
427
+ } else if (kind === KIND_STATUS_CHANGED) {
318
428
  // An end never erases start fields it doesn't carry — nor the start's
319
429
  // sessionId/persisted with its own null/false defaults.
320
430
  byId.set(row.taskId, {
@@ -324,20 +434,24 @@ function fold(rows, now) {
324
434
  sessionId: fields.sessionId || (cur && cur.sessionId) || null,
325
435
  persisted: fields.persisted === true || (cur && cur.persisted === true) || false,
326
436
  });
327
- } else if (kind === 'start') {
328
- byId.set(row.taskId, cur ? { ...fields, ...cur } : { ...fields });
329
437
  } else {
330
- byId.set(row.taskId, { ...(cur || {}), ...fields });
438
+ byId.set(row.taskId, cur ? { ...fields, ...cur } : { ...fields });
331
439
  }
332
440
  }
333
441
  const tasks = [];
334
442
  for (const t of byId.values()) {
335
- tasks.push({ ...t, ...sessionFields(t), status: foldedStatus(t, now) });
443
+ tasks.push({ ...t, ...sessionFields(t), status: foldedStatus(t, now, live) });
336
444
  }
337
445
  tasks.sort((a, b) => (toMs(b.startedAt) ?? 0) - (toMs(a.startedAt) ?? 0));
338
446
  return tasks;
339
447
  }
340
448
 
449
+ /** @param {unknown} ids iterable of taskIds (or nothing) → Set or null. */
450
+ function liveSet(ids) {
451
+ if (ids == null || typeof ids === 'string' || typeof (/** @type {any} */ (ids))[Symbol.iterator] !== 'function') return null;
452
+ return new Set(/** @type {Iterable<string>} */ (ids));
453
+ }
454
+
341
455
  function matches(t, f) {
342
456
  const caller = t.caller || {};
343
457
  if (f.pipeline != null && caller.pipeline !== f.pipeline) return false;
@@ -354,8 +468,10 @@ function matches(t, f) {
354
468
 
355
469
  /**
356
470
  * listTasks(cwd, { since, until, pipeline, runId, step, agent, status, source,
357
- * limit = 50 (max 200), offset = 0, now }) → { tasks, total, hasMore, skippedLines }.
471
+ * limit = 50 (max 200), offset = 0, now, liveTaskIds }) → { tasks, total, hasMore, skippedLines }.
358
472
  * Newest first by startedAt. `since`/`until` are ISO timestamps (inclusive).
473
+ * `liveTaskIds` (iterable of taskIds this app is still running) folds those
474
+ * Tasks as 'running' before the status filter, total and paging.
359
475
  */
360
476
  async function listTasks(cwd, opts = {}) {
361
477
  const o = opts || {};
@@ -367,7 +483,7 @@ async function listTasks(cwd, opts = {}) {
367
483
  untilDate: untilMs != null ? localDate(untilMs) : undefined,
368
484
  };
369
485
  const { rows, skippedLines } = await readRows(cwd, range);
370
- const all = fold(rows, now).filter((t) => matches(t, { ...o, sinceMs, untilMs }));
486
+ const all = fold(rows, now, liveSet(o.liveTaskIds)).filter((t) => matches(t, { ...o, sinceMs, untilMs }));
371
487
  const limitRaw = Number.isFinite(Number(o.limit)) && o.limit != null ? Math.floor(Number(o.limit)) : DEFAULT_LIMIT;
372
488
  const limit = Math.min(MAX_LIMIT, Math.max(1, limitRaw));
373
489
  const offset = Math.max(0, Math.floor(Number(o.offset) || 0));
@@ -375,14 +491,14 @@ async function listTasks(cwd, opts = {}) {
375
491
  return { tasks, total: all.length, hasMore: offset + tasks.length < all.length, skippedLines };
376
492
  }
377
493
 
378
- /** getTask(cwd, taskId, { now }) → folded Task with `body` (or body:null), or null. */
494
+ /** getTask(cwd, taskId, { now, liveTaskIds }) → folded Task with `body` (or body:null), or null. */
379
495
  async function getTask(cwd, taskId, opts = {}) {
380
496
  if (typeof taskId !== 'string' || !TASK_ID_RE.test(taskId)) return null;
381
497
  const now = typeof (opts && opts.now) === 'number' ? opts.now : Date.now();
382
498
  const { rows } = await readRows(cwd);
383
499
  const mine = rows.filter((r) => r.taskId === taskId);
384
500
  if (mine.length === 0) return null;
385
- const [task] = fold(mine, now);
501
+ const [task] = fold(mine, now, liveSet(opts && opts.liveTaskIds));
386
502
  return { ...task, body: await readBody(cwd, taskId) };
387
503
  }
388
504
 
@@ -390,7 +506,7 @@ async function getTask(cwd, taskId, opts = {}) {
390
506
  async function hasImport(cwd, importId) {
391
507
  if (typeof importId !== 'string' || !importId) return false;
392
508
  const { rows } = await readRows(cwd);
393
- return rows.some((r) => r.kind === 'imported' && r.importId === importId);
509
+ return rows.some((r) => r.kind === KIND_STATUS_CHANGED && r.importId === importId);
394
510
  }
395
511
 
396
512
  /**
@@ -430,8 +546,8 @@ async function readTaskUsageDays(cwd, { sinceDate, untilDate } = {}) {
430
546
  }
431
547
 
432
548
  /**
433
- * listPersistedSessionIds(cwd) → Set of sessionId from every retained 'start'
434
- * or 'imported' line with persisted === true. A start line is written before
549
+ * listPersistedSessionIds(cwd) → Set of sessionId from every retained
550
+ * 'task.started' line or imported (importId-carrying) 'task.status_changed' line with persisted === true. A start line is written before
435
551
  * the claude process spawns, so its id is here before its transcript exists.
436
552
  * Malformed lines are skipped; a missing tasks/ folder yields an empty Set.
437
553
  */
@@ -439,7 +555,8 @@ async function listPersistedSessionIds(cwd) {
439
555
  const { rows } = await readRows(cwd);
440
556
  const ids = new Set();
441
557
  for (const r of rows) {
442
- if ((r.kind === 'start' || r.kind === 'imported') && r.persisted === true
558
+ const isImport = r.kind === KIND_STATUS_CHANGED && typeof r.importId === 'string' && r.importId;
559
+ if ((r.kind === KIND_STARTED || isImport) && r.persisted === true
443
560
  && typeof r.sessionId === 'string' && r.sessionId) ids.add(r.sessionId);
444
561
  }
445
562
  return ids;
@@ -485,6 +602,7 @@ async function pruneOld(cwd, { now = Date.now(), maxAgeDays } = {}) {
485
602
  function _resetForTests() {
486
603
  chains.clear();
487
604
  prunedOn.clear();
605
+ refusedTransitionCount = 0;
488
606
  }
489
607
 
490
608
  module.exports = {
@@ -497,6 +615,10 @@ module.exports = {
497
615
  readTaskUsageDays,
498
616
  listPersistedSessionIds,
499
617
  pruneOld,
618
+ transitionTask,
619
+ getRefusedTransitionCount,
620
+ TASK_LEGAL_TRANSITIONS,
621
+ TERMINAL_STATUSES,
500
622
  BODY_CAP_BYTES,
501
623
  _resetForTests,
502
624
  };