claude-code-session-manager 0.139.0 → 0.141.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 (154) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-DExeJhqQ.js +2 -0
  3. package/dist/assets/History-DJMiuXyK.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-Bf1Cf8UL.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
  7. package/dist/assets/Scheduler-cyr61UAC.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-C1v91GEO.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-BrcWVpiW.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-DXhOWFG0.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-qivnDV6K.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-CMCPTKqC.js} +1 -1
  14. package/dist/assets/index-B2TQz3nd.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -19
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  33. package/scripts/README.md +1 -0
  34. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  35. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  36. package/scripts/ops-sweep.cjs +53 -23
  37. package/scripts/scheduler-mcp-server.cjs +205 -18
  38. package/src/main/build-info.json +4 -4
  39. package/src/main/config.cjs +112 -8
  40. package/src/main/docEdit.cjs +6 -1
  41. package/src/main/files.cjs +7 -27
  42. package/src/main/health.cjs +48 -15
  43. package/src/main/historyAggregator.cjs +88 -5
  44. package/src/main/historyDashboard.cjs +69 -4
  45. package/src/main/index.cjs +56 -2
  46. package/src/main/ipcSchemas.cjs +122 -16
  47. package/src/main/lib/AGENTS.md +54 -0
  48. package/src/main/lib/CLAUDE.md +1 -54
  49. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  50. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  51. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  52. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  53. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  54. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  55. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  56. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  57. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  58. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  59. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  60. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  61. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  62. package/src/main/lib/ephemeralCwd.cjs +37 -2
  63. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  64. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  65. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  66. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  67. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  68. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  69. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  70. package/src/main/lib/externalContract.cjs +31 -5
  71. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  72. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  73. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  74. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  75. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  76. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  77. package/src/main/lib/git/branchSweep.cjs +209 -4
  78. package/src/main/lib/git/gitWorktree.cjs +41 -5
  79. package/src/main/lib/guardShims.cjs +1 -1
  80. package/src/main/lib/historyRollup.cjs +26 -0
  81. package/src/main/lib/insideHome.cjs +27 -1
  82. package/src/main/lib/mcpToolCatalog.cjs +132 -13
  83. package/src/main/lib/mdDocCensus.cjs +59 -78
  84. package/src/main/lib/mdDocRefs.cjs +71 -93
  85. package/src/main/lib/mdNetworkScan.cjs +245 -250
  86. package/src/main/lib/mdReviewRecord.cjs +22 -9
  87. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  88. package/src/main/lib/opsOwnership.cjs +18 -2
  89. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  90. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  91. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  92. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  93. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  94. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  95. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  96. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  97. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  98. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  99. package/src/main/lib/prd/prdCreate.cjs +377 -23
  100. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  101. package/src/main/lib/prd/prdFrontmatter.cjs +121 -3
  102. package/src/main/lib/process/loginItem.cjs +171 -0
  103. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  104. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  105. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  106. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  107. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  108. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  109. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  110. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  111. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  112. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  113. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  114. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  115. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  116. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  117. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  118. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  119. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  120. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  121. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  122. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  123. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  124. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  125. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  126. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  127. package/src/main/lib/tasks/taskRun.cjs +313 -0
  128. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  129. package/src/main/loginItemIpc.cjs +35 -0
  130. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  131. package/src/main/projectPages.cjs +6 -15
  132. package/src/main/promptSessionEvents.cjs +9 -1
  133. package/src/main/queueOps.cjs +260 -3
  134. package/src/main/runVerify.cjs +53 -25
  135. package/src/main/scheduler/AGENTS.md +26 -0
  136. package/src/main/scheduler/CLAUDE.md +1 -26
  137. package/src/main/scheduler/budget.cjs +239 -9
  138. package/src/main/scheduler/cancelDependents.cjs +154 -0
  139. package/src/main/scheduler/prdParser.cjs +19 -1
  140. package/src/main/scheduler/reviewLadder.cjs +36 -3
  141. package/src/main/scheduler/starvation.cjs +89 -18
  142. package/src/main/scheduler.cjs +1080 -89
  143. package/src/main/supervisor.cjs +5 -1
  144. package/src/main/templates/PRD_AUTHORING.md +14 -1
  145. package/src/main/validationQualityHandlers.cjs +199 -0
  146. package/src/main/webRemote.cjs +10 -2
  147. package/src/preload/api.d.ts +364 -21
  148. package/src/preload/apiSurface.json +89 -10
  149. package/src/preload/index.cjs +23 -2
  150. package/src/seed/agents/validator.md +19 -8
  151. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  152. package/dist/assets/History-DDnqaLyw.js +0 -2
  153. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  154. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * taskIpc.cjs — renderer IPC for the Scheduler Tasks section.
5
+ *
6
+ * tasks:list { cwd, ...listTasks filters } → { ok, tasks, total, hasMore, skippedLines }
7
+ * tasks:get { cwd, id } → { ok, task } (task null when absent)
8
+ * tasks:get-switch { cwd } → { ok, enabled }
9
+ * tasks:set-switch { cwd, enabled } → { ok, enabled, changedAt }
10
+ *
11
+ * tasks:set-switch is the ONLY caller of taskSwitch.setTaskSwitch — the switch
12
+ * is a human decision made in the renderer (see taskSwitch.cjs). After every
13
+ * write, and once at registration, the held interactive slot in sessionSlots
14
+ * is set to anyTaskSwitchOn(), so it is held exactly while some project has
15
+ * Tasks on. Payloads are validated by strict zod schemas (ipcSchemas.cjs);
16
+ * an invalid payload rejects the invoke.
17
+ */
18
+
19
+ const { schemas, validated } = require('../../ipcSchemas.cjs');
20
+ const taskLedger = require('./taskLedger.cjs');
21
+ const taskSwitch = require('./taskSwitch.cjs');
22
+ const sessionSlots = require('../scheduler/sessionSlots.cjs');
23
+ const auditLog = require('../telemetry/auditLog.cjs');
24
+
25
+ function errMsg(err) {
26
+ return err && err.message ? err.message : String(err);
27
+ }
28
+
29
+ function syncInteractiveReserve() {
30
+ return sessionSlots.setInteractiveReserve(taskSwitch.anyTaskSwitchOn());
31
+ }
32
+
33
+ /**
34
+ * @param {{ ipcMain?: any }} [opts]
35
+ */
36
+ function registerTaskIpc(opts = {}) {
37
+ const ipcMain = opts.ipcMain || require('electron').ipcMain;
38
+
39
+ ipcMain.handle('tasks:list', validated(schemas.TaskListQuery, async ({ cwd, ...filters }) => {
40
+ try {
41
+ const res = await taskLedger.listTasks(cwd, filters);
42
+ return { ok: true, ...res };
43
+ } catch (err) {
44
+ return { ok: false, error: errMsg(err) };
45
+ }
46
+ }));
47
+
48
+ ipcMain.handle('tasks:get', validated(schemas.TaskGetQuery, async ({ cwd, id }) => {
49
+ try {
50
+ const task = await taskLedger.getTask(cwd, id);
51
+ return { ok: true, task };
52
+ } catch (err) {
53
+ return { ok: false, error: errMsg(err) };
54
+ }
55
+ }));
56
+
57
+ ipcMain.handle('tasks:get-switch', validated(schemas.TaskSwitchQuery, async ({ cwd }) => {
58
+ try {
59
+ return { ok: true, enabled: taskSwitch.isTaskSwitchOn(cwd) };
60
+ } catch (err) {
61
+ return { ok: false, error: errMsg(err) };
62
+ }
63
+ }));
64
+
65
+ ipcMain.handle('tasks:set-switch', validated(schemas.TaskSwitchSet, async ({ cwd, enabled }) => {
66
+ try {
67
+ const saved = taskSwitch.setTaskSwitch(cwd, enabled);
68
+ auditLog.appendAuditEvent('task_switch_changed', { cwd: saved.cwd, enabled: saved.enabled });
69
+ return { ok: true, enabled: saved.enabled, changedAt: saved.changedAt };
70
+ } catch (err) {
71
+ return { ok: false, error: errMsg(err) };
72
+ } finally {
73
+ syncInteractiveReserve();
74
+ }
75
+ }));
76
+
77
+ syncInteractiveReserve();
78
+ }
79
+
80
+ module.exports = { registerTaskIpc };
@@ -0,0 +1,502 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * taskLedger.cjs — the Task ledger: THE ONLY WRITER of a project's
5
+ * `session-manager-operations/tasks/` namespace (writer id 'tasks' in
6
+ * lib/opsOwnership.cjs) and the read model routes, IPC and history use.
7
+ *
8
+ * A Task is one headless `claude -p` run made for one project.
9
+ *
10
+ * Layout (all paths via opsPath(cwd, 'tasks', ...)):
11
+ * tasks/<YYYY-MM-DD>.jsonl summary lines, local date of the Task's startedAt.
12
+ * kind 'start' | 'end' | 'imported'. Hashes + byte
13
+ * counts only — never prompt/output text. Every
14
+ * line carries sessionId (claude session id or
15
+ * null) and persisted (true when the run kept its
16
+ * transcript; listPersistedSessionIds reads it).
17
+ * tasks/bodies/<taskId>.json prompt/output text (each capped at 1 MiB, with
18
+ * promptTruncated/outputTruncated), stderrTail,
19
+ * envelope. Written via atomicFs.writeJsonAtomic.
20
+ *
21
+ * Retention: opsRetentionSettings.read().tasksDays (default 30). pruneOld runs
22
+ * once per local day per project, on the first append of that day.
23
+ *
24
+ * Concurrency: appends to one day file are serialized by an in-process
25
+ * promise chain keyed by file path. Reads never throw on a bad line — the
26
+ * line is skipped and counted in `skippedLines`.
27
+ */
28
+
29
+ const fsp = require('node:fs/promises');
30
+ const path = require('node:path');
31
+ const crypto = require('node:crypto');
32
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
33
+ const atomicFs = require('../util/atomicFs.cjs');
34
+
35
+ const WRITER = 'tasks';
36
+ const NS = 'tasks';
37
+ const BODY_CAP_BYTES = 1024 * 1024;
38
+ const INTERRUPT_GRACE_MS = 120000;
39
+ const DEFAULT_LIMIT = 50;
40
+ const MAX_LIMIT = 200;
41
+ const DAY_MS = 86400000;
42
+ const DAY_FILE_RE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/;
43
+ const TASK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
44
+ const KINDS = new Set(['start', 'end', 'imported']);
45
+ // Text-bearing input fields: they go to the body file, never the summary line.
46
+ const TEXT_FIELDS = ['prompt', 'output', 'stderrTail', 'envelope'];
47
+ const USAGE_KEYS = ['input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'];
48
+
49
+ /** file path → tail of its append chain. */
50
+ const chains = new Map();
51
+ /** project ops dir → local date pruneOld last ran for it. */
52
+ const prunedOn = new Map();
53
+
54
+ function localDate(ms) {
55
+ const d = new Date(ms);
56
+ const p = (n) => String(n).padStart(2, '0');
57
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
58
+ }
59
+
60
+ function toMs(v) {
61
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
62
+ if (typeof v === 'string' && v) {
63
+ const ms = Date.parse(v);
64
+ if (Number.isFinite(ms)) return ms;
65
+ }
66
+ return null;
67
+ }
68
+
69
+ function sha256(text) {
70
+ return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
71
+ }
72
+
73
+ /** { text (≤ 1 MiB), truncated, bytes (full), sha256 (full) } for a string-ish value. */
74
+ function capText(value) {
75
+ const text = typeof value === 'string' ? value : value == null ? '' : String(value);
76
+ const buf = Buffer.from(text, 'utf8');
77
+ const truncated = buf.length > BODY_CAP_BYTES;
78
+ return {
79
+ text: truncated ? buf.subarray(0, BODY_CAP_BYTES).toString('utf8') : text,
80
+ truncated,
81
+ bytes: buf.length,
82
+ sha256: sha256(text),
83
+ };
84
+ }
85
+
86
+ function assertTaskId(taskId) {
87
+ if (typeof taskId !== 'string' || !TASK_ID_RE.test(taskId)) {
88
+ throw new Error(`taskLedger: invalid taskId "${taskId}"`);
89
+ }
90
+ }
91
+
92
+ function tasksDir(cwd) { return opsPath(cwd, NS); }
93
+ function dayFile(cwd, date) { return opsPath(cwd, NS, `${date}.jsonl`); }
94
+ function bodyFile(cwd, taskId) { return opsPath(cwd, NS, 'bodies', `${taskId}.json`); }
95
+
96
+ function stripText(row) {
97
+ const out = { ...row };
98
+ for (const k of TEXT_FIELDS) delete out[k];
99
+ return out;
100
+ }
101
+
102
+ /** sessionId (non-empty string, else null) + persisted (true only when === true). */
103
+ function sessionFields(row) {
104
+ return {
105
+ sessionId: typeof row.sessionId === 'string' && row.sessionId ? row.sessionId : null,
106
+ persisted: row.persisted === true,
107
+ };
108
+ }
109
+
110
+ function appendLine(file, obj) {
111
+ assertOpsWrite(file, WRITER);
112
+ const line = `${JSON.stringify(obj)}\n`;
113
+ const prev = chains.get(file) || Promise.resolve();
114
+ const next = prev.catch(() => {}).then(async () => {
115
+ await fsp.mkdir(path.dirname(file), { recursive: true });
116
+ await fsp.appendFile(file, line, 'utf8');
117
+ });
118
+ chains.set(file, next);
119
+ const cleanup = () => { if (chains.get(file) === next) chains.delete(file); };
120
+ next.then(cleanup, cleanup);
121
+ return next;
122
+ }
123
+
124
+ async function writeBody(cwd, taskId, body) {
125
+ const file = bodyFile(cwd, taskId);
126
+ assertOpsWrite(file, WRITER);
127
+ await atomicFs.writeJsonAtomic(file, body);
128
+ }
129
+
130
+ async function readBody(cwd, taskId) {
131
+ const body = await atomicFs.readJsonOr(bodyFile(cwd, taskId), null);
132
+ return body && typeof body === 'object' && !Array.isArray(body) ? body : null;
133
+ }
134
+
135
+ /** Once per local day per project, before the first append of that day. */
136
+ async function maybePrune(cwd) {
137
+ const key = tasksDir(cwd);
138
+ const today = localDate(Date.now());
139
+ if (prunedOn.get(key) === today) return;
140
+ prunedOn.set(key, today);
141
+ try {
142
+ await pruneOld(cwd, { now: Date.now() });
143
+ } catch (e) {
144
+ console.warn('[taskLedger] pruneOld failed:', e && e.message);
145
+ }
146
+ }
147
+
148
+ function startedMsOf(row) {
149
+ const ms = toMs(row.startedAt);
150
+ if (ms == null) throw new Error('taskLedger: startedAt (ISO) is required');
151
+ return ms;
152
+ }
153
+
154
+ /**
155
+ * appendTaskStart(cwd, { ...startRow, prompt }) — writes the body (prompt) and
156
+ * a kind 'start' summary line.
157
+ */
158
+ async function appendTaskStart(cwd, row) {
159
+ assertTaskId(row && row.taskId);
160
+ const startedMs = startedMsOf(row);
161
+ await maybePrune(cwd);
162
+ const p = capText(row.prompt);
163
+ await writeBody(cwd, row.taskId, {
164
+ v: 1,
165
+ taskId: row.taskId,
166
+ startedAt: row.startedAt,
167
+ prompt: p.text,
168
+ promptTruncated: p.truncated,
169
+ });
170
+ const line = {
171
+ ...stripText(row),
172
+ ...sessionFields(row),
173
+ v: 1,
174
+ kind: 'start',
175
+ source: 'sm',
176
+ promptSha256: p.sha256,
177
+ promptBytes: p.bytes,
178
+ };
179
+ await appendLine(dayFile(cwd, localDate(startedMs)), line);
180
+ return line;
181
+ }
182
+
183
+ /**
184
+ * appendTaskEnd(cwd, { ...endRow, output, stderrTail, envelope }) — rewrites
185
+ * 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).
187
+ */
188
+ async function appendTaskEnd(cwd, row) {
189
+ assertTaskId(row && row.taskId);
190
+ await maybePrune(cwd);
191
+ const prior = (await readBody(cwd, row.taskId)) || { v: 1, taskId: row.taskId };
192
+ const startedAt = row.startedAt || prior.startedAt || row.endedAt || new Date().toISOString();
193
+ const startedMs = toMs(startedAt) ?? Date.now();
194
+ const o = capText(row.output);
195
+ const stderr = capText(row.stderrTail);
196
+ await writeBody(cwd, row.taskId, {
197
+ ...prior,
198
+ startedAt,
199
+ output: o.text,
200
+ outputTruncated: o.truncated,
201
+ stderrTail: stderr.text,
202
+ envelope: row.envelope === undefined ? null : row.envelope,
203
+ });
204
+ const line = {
205
+ ...stripText(row),
206
+ ...sessionFields(row),
207
+ v: 1,
208
+ kind: 'end',
209
+ startedAt,
210
+ outputSha256: o.sha256,
211
+ outputBytes: o.bytes,
212
+ };
213
+ await appendLine(dayFile(cwd, localDate(startedMs)), line);
214
+ return line;
215
+ }
216
+
217
+ /**
218
+ * appendImported(cwd, { ...start+end fields, importId, prompt, output, ... }) —
219
+ * one kind 'imported' line (source 'direct') carrying the whole Task.
220
+ */
221
+ async function appendImported(cwd, row) {
222
+ assertTaskId(row && row.taskId);
223
+ if (typeof row.importId !== 'string' || !row.importId) throw new Error('taskLedger: importId is required');
224
+ const startedMs = startedMsOf(row);
225
+ await maybePrune(cwd);
226
+ const p = capText(row.prompt);
227
+ const o = capText(row.output);
228
+ const stderr = capText(row.stderrTail);
229
+ await writeBody(cwd, row.taskId, {
230
+ v: 1,
231
+ taskId: row.taskId,
232
+ startedAt: row.startedAt,
233
+ prompt: p.text,
234
+ promptTruncated: p.truncated,
235
+ output: o.text,
236
+ outputTruncated: o.truncated,
237
+ stderrTail: stderr.text,
238
+ envelope: row.envelope === undefined ? null : row.envelope,
239
+ });
240
+ const line = {
241
+ ...stripText(row),
242
+ ...sessionFields(row),
243
+ v: 1,
244
+ kind: 'imported',
245
+ source: 'direct',
246
+ promptSha256: p.sha256,
247
+ promptBytes: p.bytes,
248
+ outputSha256: o.sha256,
249
+ outputBytes: o.bytes,
250
+ };
251
+ await appendLine(dayFile(cwd, localDate(startedMs)), line);
252
+ return line;
253
+ }
254
+
255
+ // ─── Reads ────────────────────────────────────────────────────────────────
256
+
257
+ async function listDayFiles(cwd, { sinceDate, untilDate } = {}) {
258
+ let names;
259
+ try {
260
+ names = await fsp.readdir(tasksDir(cwd));
261
+ } catch (e) {
262
+ if (e.code === 'ENOENT') return [];
263
+ throw e;
264
+ }
265
+ const out = [];
266
+ for (const n of names) {
267
+ const m = DAY_FILE_RE.exec(n);
268
+ if (!m) continue;
269
+ if (sinceDate && m[1] < sinceDate) continue;
270
+ if (untilDate && m[1] > untilDate) continue;
271
+ out.push({ date: m[1], file: dayFile(cwd, m[1]) });
272
+ }
273
+ return out.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
274
+ }
275
+
276
+ /** Parsed, valid rows of the selected day files + the count of skipped lines. */
277
+ async function readRows(cwd, range) {
278
+ const rows = [];
279
+ let skippedLines = 0;
280
+ for (const { file } of await listDayFiles(cwd, range)) {
281
+ let text;
282
+ try {
283
+ text = await fsp.readFile(file, 'utf8');
284
+ } catch (e) {
285
+ if (e.code === 'ENOENT') continue;
286
+ throw e;
287
+ }
288
+ for (const line of text.split('\n')) {
289
+ if (!line.trim()) continue;
290
+ let row;
291
+ try { row = JSON.parse(line); } catch { skippedLines += 1; continue; }
292
+ if (!row || typeof row !== 'object' || Array.isArray(row)
293
+ || !KINDS.has(row.kind) || typeof row.taskId !== 'string' || !row.taskId) {
294
+ skippedLines += 1;
295
+ continue;
296
+ }
297
+ rows.push(row);
298
+ }
299
+ }
300
+ return { rows, skippedLines };
301
+ }
302
+
303
+ function foldedStatus(t, now) {
304
+ if (t.status) return t.status;
305
+ const startedMs = toMs(t.startedAt);
306
+ const timeoutMs = (Number(t.timeoutSec) || 0) * 1000;
307
+ if (startedMs != null && now > startedMs + timeoutMs + INTERRUPT_GRACE_MS) return 'interrupted';
308
+ return 'running';
309
+ }
310
+
311
+ /** taskId → folded Task (start ⊕ end, or the imported line). */
312
+ function fold(rows, now) {
313
+ const byId = new Map();
314
+ for (const row of rows) {
315
+ const { kind, ...fields } = row;
316
+ const cur = byId.get(row.taskId);
317
+ if (kind === 'end') {
318
+ // An end never erases start fields it doesn't carry — nor the start's
319
+ // sessionId/persisted with its own null/false defaults.
320
+ byId.set(row.taskId, {
321
+ ...(cur || {}),
322
+ ...fields,
323
+ startedAt: (cur && cur.startedAt) || fields.startedAt,
324
+ sessionId: fields.sessionId || (cur && cur.sessionId) || null,
325
+ persisted: fields.persisted === true || (cur && cur.persisted === true) || false,
326
+ });
327
+ } else if (kind === 'start') {
328
+ byId.set(row.taskId, cur ? { ...fields, ...cur } : { ...fields });
329
+ } else {
330
+ byId.set(row.taskId, { ...(cur || {}), ...fields });
331
+ }
332
+ }
333
+ const tasks = [];
334
+ for (const t of byId.values()) {
335
+ tasks.push({ ...t, ...sessionFields(t), status: foldedStatus(t, now) });
336
+ }
337
+ tasks.sort((a, b) => (toMs(b.startedAt) ?? 0) - (toMs(a.startedAt) ?? 0));
338
+ return tasks;
339
+ }
340
+
341
+ function matches(t, f) {
342
+ const caller = t.caller || {};
343
+ if (f.pipeline != null && caller.pipeline !== f.pipeline) return false;
344
+ if (f.runId != null && caller.runId !== f.runId) return false;
345
+ if (f.step != null && caller.step !== f.step) return false;
346
+ if (f.agent != null && t.agent !== f.agent) return false;
347
+ if (f.status != null && t.status !== f.status) return false;
348
+ if (f.source != null && t.source !== f.source) return false;
349
+ const ms = toMs(t.startedAt);
350
+ if (f.sinceMs != null && (ms == null || ms < f.sinceMs)) return false;
351
+ if (f.untilMs != null && (ms == null || ms > f.untilMs)) return false;
352
+ return true;
353
+ }
354
+
355
+ /**
356
+ * listTasks(cwd, { since, until, pipeline, runId, step, agent, status, source,
357
+ * limit = 50 (max 200), offset = 0, now }) → { tasks, total, hasMore, skippedLines }.
358
+ * Newest first by startedAt. `since`/`until` are ISO timestamps (inclusive).
359
+ */
360
+ async function listTasks(cwd, opts = {}) {
361
+ const o = opts || {};
362
+ const now = typeof o.now === 'number' ? o.now : Date.now();
363
+ const sinceMs = toMs(o.since);
364
+ const untilMs = toMs(o.until);
365
+ const range = {
366
+ sinceDate: sinceMs != null ? localDate(sinceMs) : undefined,
367
+ untilDate: untilMs != null ? localDate(untilMs) : undefined,
368
+ };
369
+ const { rows, skippedLines } = await readRows(cwd, range);
370
+ const all = fold(rows, now).filter((t) => matches(t, { ...o, sinceMs, untilMs }));
371
+ const limitRaw = Number.isFinite(Number(o.limit)) && o.limit != null ? Math.floor(Number(o.limit)) : DEFAULT_LIMIT;
372
+ const limit = Math.min(MAX_LIMIT, Math.max(1, limitRaw));
373
+ const offset = Math.max(0, Math.floor(Number(o.offset) || 0));
374
+ const tasks = all.slice(offset, offset + limit);
375
+ return { tasks, total: all.length, hasMore: offset + tasks.length < all.length, skippedLines };
376
+ }
377
+
378
+ /** getTask(cwd, taskId, { now }) → folded Task with `body` (or body:null), or null. */
379
+ async function getTask(cwd, taskId, opts = {}) {
380
+ if (typeof taskId !== 'string' || !TASK_ID_RE.test(taskId)) return null;
381
+ const now = typeof (opts && opts.now) === 'number' ? opts.now : Date.now();
382
+ const { rows } = await readRows(cwd);
383
+ const mine = rows.filter((r) => r.taskId === taskId);
384
+ if (mine.length === 0) return null;
385
+ const [task] = fold(mine, now);
386
+ return { ...task, body: await readBody(cwd, taskId) };
387
+ }
388
+
389
+ /** hasImport(cwd, importId) → true when an 'imported' line with that importId exists. */
390
+ async function hasImport(cwd, importId) {
391
+ if (typeof importId !== 'string' || !importId) return false;
392
+ const { rows } = await readRows(cwd);
393
+ return rows.some((r) => r.kind === 'imported' && r.importId === importId);
394
+ }
395
+
396
+ /**
397
+ * readTaskUsageDays(cwd, { sinceDate, untilDate }) → ascending
398
+ * [{ date, tasks, input_tokens, output_tokens, cache_read_input_tokens,
399
+ * cache_creation_input_tokens, costUsd, byModel }] for local dates
400
+ * (YYYY-MM-DD, inclusive) that have at least one Task. `byModel` maps the
401
+ * Task's `model` (or 'unknown') to { tasks, <USAGE_KEYS> } so a reader can
402
+ * price usage per model (historyDashboard.cjs does).
403
+ */
404
+ async function readTaskUsageDays(cwd, { sinceDate, untilDate } = {}) {
405
+ const { rows } = await readRows(cwd, { sinceDate, untilDate });
406
+ const days = new Map();
407
+ for (const t of fold(rows, Date.now())) {
408
+ const ms = toMs(t.startedAt);
409
+ if (ms == null) continue;
410
+ const date = localDate(ms);
411
+ if ((sinceDate && date < sinceDate) || (untilDate && date > untilDate)) continue;
412
+ let d = days.get(date);
413
+ if (!d) {
414
+ d = { date, tasks: 0, ...Object.fromEntries(USAGE_KEYS.map((k) => [k, 0])), costUsd: 0, byModel: {} };
415
+ days.set(date, d);
416
+ }
417
+ d.tasks += 1;
418
+ const model = typeof t.model === 'string' && t.model ? t.model : 'unknown';
419
+ const m = d.byModel[model] ?? (d.byModel[model] = { tasks: 0, ...Object.fromEntries(USAGE_KEYS.map((k) => [k, 0])) });
420
+ m.tasks += 1;
421
+ const u = t.usage || {};
422
+ for (const k of USAGE_KEYS) {
423
+ const n = Number(u[k]) || 0;
424
+ d[k] += n;
425
+ m[k] += n;
426
+ }
427
+ d.costUsd += Number(t.costUsd) || 0;
428
+ }
429
+ return [...days.values()].sort((a, b) => (a.date < b.date ? -1 : 1));
430
+ }
431
+
432
+ /**
433
+ * listPersistedSessionIds(cwd) → Set of sessionId from every retained 'start'
434
+ * or 'imported' line with persisted === true. A start line is written before
435
+ * the claude process spawns, so its id is here before its transcript exists.
436
+ * Malformed lines are skipped; a missing tasks/ folder yields an empty Set.
437
+ */
438
+ async function listPersistedSessionIds(cwd) {
439
+ const { rows } = await readRows(cwd);
440
+ const ids = new Set();
441
+ for (const r of rows) {
442
+ if ((r.kind === 'start' || r.kind === 'imported') && r.persisted === true
443
+ && typeof r.sessionId === 'string' && r.sessionId) ids.add(r.sessionId);
444
+ }
445
+ return ids;
446
+ }
447
+
448
+ // ─── Retention ────────────────────────────────────────────────────────────
449
+
450
+ /**
451
+ * pruneOld(cwd, { now, maxAgeDays }) → { maxAgeDays, removedDays, removedBodies }.
452
+ * Deletes day files dated before (now - maxAgeDays) and bodies whose mtime is
453
+ * older than that. maxAgeDays defaults to opsRetentionSettings tasksDays.
454
+ */
455
+ async function pruneOld(cwd, { now = Date.now(), maxAgeDays } = {}) {
456
+ const days = Number.isFinite(maxAgeDays) && maxAgeDays > 0
457
+ ? maxAgeDays
458
+ : require('../opsRetentionSettings.cjs').read().tasksDays;
459
+ const cutoffMs = now - days * DAY_MS;
460
+ const cutoffDate = localDate(cutoffMs);
461
+ const removedDays = [];
462
+ for (const { date, file } of await listDayFiles(cwd)) {
463
+ if (date >= cutoffDate) continue;
464
+ assertOpsWrite(file, WRITER);
465
+ await fsp.rm(file, { force: true });
466
+ removedDays.push(date);
467
+ }
468
+ let removedBodies = 0;
469
+ const bodiesDir = opsPath(cwd, NS, 'bodies');
470
+ let names = [];
471
+ try { names = await fsp.readdir(bodiesDir); } catch (e) { if (e.code !== 'ENOENT') throw e; }
472
+ for (const n of names) {
473
+ if (!n.endsWith('.json')) continue;
474
+ const file = opsPath(cwd, NS, 'bodies', n);
475
+ let st;
476
+ try { st = await fsp.stat(file); } catch { continue; }
477
+ if (st.mtimeMs >= cutoffMs) continue;
478
+ assertOpsWrite(file, WRITER);
479
+ await fsp.rm(file, { force: true });
480
+ removedBodies += 1;
481
+ }
482
+ return { maxAgeDays: days, removedDays, removedBodies };
483
+ }
484
+
485
+ function _resetForTests() {
486
+ chains.clear();
487
+ prunedOn.clear();
488
+ }
489
+
490
+ module.exports = {
491
+ appendTaskStart,
492
+ appendTaskEnd,
493
+ appendImported,
494
+ hasImport,
495
+ listTasks,
496
+ getTask,
497
+ readTaskUsageDays,
498
+ listPersistedSessionIds,
499
+ pruneOld,
500
+ BODY_CAP_BYTES,
501
+ _resetForTests,
502
+ };