claude-code-session-manager 0.138.0 → 0.139.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 (91) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-CgDhqrsU.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-CkhTvG7C.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/{index-CgCxpunJ.js → index-C-d0DCre.js} +523 -515
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +469 -450
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +2 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +22 -2
  33. package/src/main/ipcSchemas.cjs +122 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  37. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  38. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  39. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  40. package/src/main/lib/epic/epicSettle.cjs +1 -1
  41. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  42. package/src/main/lib/epic/externalRef.cjs +37 -0
  43. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  44. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  45. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  46. package/src/main/lib/externalContract.cjs +111 -0
  47. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  48. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  49. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  50. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  51. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  52. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  53. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  54. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +120 -2
  56. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  57. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  58. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  59. package/src/main/lib/historyRollup.cjs +32 -5
  60. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  61. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  62. package/src/main/lib/promptSessionSchema.cjs +4 -0
  63. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  64. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  65. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  66. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  67. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  68. package/src/main/scheduler.cjs +29 -0
  69. package/src/main/templates/PRD_AUTHORING.md +1 -0
  70. package/src/main/transcripts.cjs +62 -7
  71. package/src/main/webRemote.cjs +122 -18
  72. package/src/preload/api.d.ts +71 -8
  73. package/src/preload/apiSurface.cjs +7 -0
  74. package/src/preload/apiSurface.json +408 -83
  75. package/src/preload/index.cjs +15 -3
  76. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  77. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  78. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  79. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  80. package/dist/assets/History-BwO3coo4.js +0 -2
  81. package/dist/assets/Library-BDV69fSe.js +0 -32
  82. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  83. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  84. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  85. package/dist/assets/Settings-COT34hBF.js +0 -2
  86. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  87. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  88. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  89. package/dist/assets/Toggle-CENi19iK.js +0 -1
  90. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  91. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
@@ -0,0 +1,233 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicOutsideState.cjs — pure "what state is this Epic in?" for outside apps.
5
+ *
6
+ * An Epic's own `status` stays `active` until a human closes it, so it cannot
7
+ * say when the work is verified. This turns the session row, the Epic's event
8
+ * chain and the scheduler queue rows into one state with a reason. Finished
9
+ * PRDs whose queue rows are gone are still known from their check-ins.
10
+ *
11
+ * Unlike epicSettle (windowed) this reads the whole event chain and keys
12
+ * verdicts by bare slug with the newest winning, so a refuted PRD stops
13
+ * blocking once a validator later verifies the same PRD. Unlike the renderer's
14
+ * epicDisplayStatus it is not a display rule. No fs, no clock, no mutation.
15
+ */
16
+
17
+ const { bareSlug } = require('../prd/depSlugResolve.cjs');
18
+ const { isCancelledRow } = require('./epicSettle.cjs');
19
+
20
+ // Mirrors epicSettle's (unexported) isValidatorCheckin.
21
+ const isValidatorCheckin = (e, bare) =>
22
+ e.agentType === 'validator' || (e.agentType == null && bare.startsWith('validate-'));
23
+
24
+ const EPIC_OUTSIDE_STATES = Object.freeze([
25
+ 'closed',
26
+ 'awaiting_approval',
27
+ 'needs_input',
28
+ 'blocked',
29
+ 'working',
30
+ 'in_review',
31
+ 'verified',
32
+ 'open',
33
+ ]);
34
+
35
+ const REASON_MAX = 300;
36
+
37
+ const ts = (at) => {
38
+ const t = typeof at === 'string' ? Date.parse(at) : NaN;
39
+ return Number.isFinite(t) ? t : NaN;
40
+ };
41
+
42
+ const cut = (s) => (typeof s === 'string' ? s.slice(0, REASON_MAX) : '');
43
+
44
+ const isObj = (v) => v != null && typeof v === 'object';
45
+
46
+ const isValidatorSlug = (bare) => bare.startsWith('validate-');
47
+
48
+ const bySlug = (a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
49
+
50
+ // Is `t` (with its array index) newer than `prev`? A dated entry beats an
51
+ // undated one; among equals the later array entry wins.
52
+ const isNewer = (t, prev) => !prev || (Number.isNaN(t) ? Number.isNaN(prev.t) : Number.isNaN(prev.t) || t >= prev.t);
53
+
54
+ const isCheckin = (e) => e.kind === 'response' && typeof e.prdSlug === 'string' && e.prdSlug && e.validation === 'unvalidated';
55
+
56
+ /**
57
+ * The PRDs an Epic is known to have: the union, by bare slug, of its live
58
+ * queue rows and the job check-ins on its chain. The scheduler drops a row
59
+ * soon after its job finishes; the check-in stays on the chain forever.
60
+ *
61
+ * @param {any} session
62
+ * @param {any[]} events already filtered to objects
63
+ * @param {any[]} allRows already filtered to objects
64
+ * @returns {Map<string, { bare: string, slug: string, row: any, checkin: null | { event: any, t: number }, completedCheckin: null | { event: any, t: number }, status: string, validator: boolean }>}
65
+ */
66
+ function buildKnownPrds(session, events, allRows) {
67
+ const sessionId = isObj(session) && typeof session.id === 'string' && session.id ? session.id : null;
68
+ const rows = sessionId
69
+ ? allRows.filter((r) => r.epicId === sessionId || r.sourcePromptId === sessionId)
70
+ : [];
71
+ /** @type {Map<string, any>} */
72
+ const known = new Map();
73
+ const entry = (bare) => {
74
+ let k = known.get(bare);
75
+ if (!k) {
76
+ k = { bare, slug: '', row: null, checkin: null, completedCheckin: null, status: '', validator: false };
77
+ known.set(bare, k);
78
+ }
79
+ return k;
80
+ };
81
+ for (const r of rows) {
82
+ if (typeof r.slug !== 'string' || !r.slug) continue;
83
+ const k = entry(bareSlug(r.slug));
84
+ k.row = r; // a later row for the same PRD wins
85
+ }
86
+ for (const e of events) {
87
+ if (!isCheckin(e)) continue;
88
+ const k = entry(bareSlug(e.prdSlug));
89
+ const t = ts(e.at);
90
+ if (isNewer(t, k.checkin)) k.checkin = { event: e, t };
91
+ if (e.outcome === 'completed' && isNewer(t, k.completedCheckin)) k.completedCheckin = { event: e, t };
92
+ }
93
+ for (const k of known.values()) {
94
+ k.slug = k.row ? k.row.slug : k.checkin.event.prdSlug;
95
+ k.status = k.row
96
+ ? (typeof k.row.status === 'string' ? k.row.status : '')
97
+ : (typeof k.checkin.event.outcome === 'string' ? k.checkin.event.outcome : '');
98
+ const src = k.row || k.checkin.event;
99
+ k.validator = k.row
100
+ ? (k.row.agentType === 'validator' || isValidatorSlug(k.bare))
101
+ : isValidatorCheckin(src, k.bare);
102
+ }
103
+ return known;
104
+ }
105
+
106
+ /**
107
+ * Full slugs (as written in the row or the check-in) of the Epic's known
108
+ * PRDs, sorted, no repeats.
109
+ * @param {{ session?: any, events?: any[], jobs?: any[] }} [args]
110
+ * @returns {string[]}
111
+ */
112
+ function knownPrdSlugs(args) {
113
+ const a = isObj(args) ? args : {};
114
+ const events = Array.isArray(a.events) ? a.events.filter(isObj) : [];
115
+ const allRows = Array.isArray(a.jobs) ? a.jobs.filter(isObj) : [];
116
+ const known = buildKnownPrds(isObj(a.session) ? a.session : {}, events, allRows);
117
+ return [...new Set([...known.values()].map((k) => k.slug))].sort();
118
+ }
119
+
120
+ function refutedReason(text) {
121
+ const s = typeof text === 'string' ? text : '';
122
+ const i = s.indexOf(' — ');
123
+ return i >= 0 ? s.slice(i + 3).trim() : '';
124
+ }
125
+
126
+ function reviewReason(row) {
127
+ const n = isObj(row.reviewNotice) ? row.reviewNotice : null;
128
+ if (!n) return '';
129
+ if (typeof n.reason === 'string' && n.reason) return n.reason;
130
+ return typeof n.summary === 'string' ? n.summary : '';
131
+ }
132
+
133
+ /**
134
+ * @param {{ session?: any, events?: any[], jobs?: any[], needsInput?: boolean, chatBusy?: boolean }} [args]
135
+ * @returns {{
136
+ * state: string,
137
+ * blocked: null | { kind: 'refuted'|'failed'|'needs_review'|'quarantined', prds: { slug: string, reason: string }[] },
138
+ * prds: { total: number, pending: number, running: number, completed: number, failed: number, needsReview: number, quarantined: number, skipped: number },
139
+ * verified: string[],
140
+ * refuted: { slug: string, reason: string }[],
141
+ * unvalidated: string[],
142
+ * }}
143
+ */
144
+ function computeEpicOutsideState(args) {
145
+ const a = isObj(args) ? args : {};
146
+ const session = isObj(a.session) ? a.session : {};
147
+ const events = Array.isArray(a.events) ? a.events.filter(isObj) : [];
148
+ const allRows = Array.isArray(a.jobs) ? a.jobs.filter(isObj) : [];
149
+ const needsInput = a.needsInput === true;
150
+ const chatBusy = a.chatBusy === true;
151
+
152
+ const known = [...buildKnownPrds(session, events, allRows).values()];
153
+
154
+ const prds = { total: 0, pending: 0, running: 0, completed: 0, failed: 0, needsReview: 0, quarantined: 0, skipped: 0 };
155
+ for (const k of known) {
156
+ prds.total++;
157
+ switch (k.status) {
158
+ case 'pending': prds.pending++; break;
159
+ case 'running':
160
+ case 'investigating': prds.running++; break;
161
+ case 'completed': prds.completed++; break;
162
+ case 'failed': prds.failed++; break;
163
+ case 'needs_review': prds.needsReview++; break;
164
+ case 'quarantined': prds.quarantined++; break;
165
+ case 'skipped': prds.skipped++; break;
166
+ default: break;
167
+ }
168
+ }
169
+
170
+ // Newest verdict per bare slug over the whole chain (later array entry wins a tie).
171
+ const verdicts = new Map(); // bare -> { event, t }
172
+ for (const e of events) {
173
+ if (e.kind !== 'response' || typeof e.prdSlug !== 'string') continue;
174
+ if (e.validation !== 'verified' && e.validation !== 'refuted') continue;
175
+ const bare = bareSlug(e.prdSlug);
176
+ const t = ts(e.at);
177
+ if (isNewer(t, verdicts.get(bare))) verdicts.set(bare, { event: e, t });
178
+ }
179
+
180
+ const verified = [];
181
+ const refuted = [];
182
+ for (const [bare, { event }] of verdicts) {
183
+ if (event.validation === 'verified') verified.push(bare);
184
+ else refuted.push({ slug: bare, reason: cut(refutedReason(event.text)) });
185
+ }
186
+ verified.sort();
187
+ refuted.sort(bySlug);
188
+
189
+ // A completed work PRD is unvalidated unless a verdict lands at or after its
190
+ // newest completed check-in (or after the row's finishedAt when it has none).
191
+ const unvalidatedSet = new Set();
192
+ let completedWork = 0;
193
+ for (const k of known) {
194
+ if (k.status !== 'completed' || k.validator) continue;
195
+ completedWork++;
196
+ const v = verdicts.get(k.bare);
197
+ if (!v) { unvalidatedSet.add(k.bare); continue; }
198
+ const finished = k.completedCheckin ? k.completedCheckin.t : ts(k.row ? k.row.finishedAt : undefined);
199
+ if (Number.isFinite(finished) && (!Number.isFinite(v.t) || v.t < finished)) unvalidatedSet.add(k.bare);
200
+ }
201
+ const unvalidated = [...unvalidatedSet].sort();
202
+
203
+ const checkinText = (k) => (k.checkin && typeof k.checkin.event.text === 'string' ? k.checkin.event.text : '');
204
+ const errorOf = (k) => (k.row ? (typeof k.row.error === 'string' ? k.row.error : '') : checkinText(k));
205
+ const reviewOf = (k) => (k.row ? reviewReason(k.row) : checkinText(k));
206
+ const knownPrds = (status, reasonOf, skipCancelled = true) => known
207
+ .filter((k) => k.status === status && !(skipCancelled && k.row && isCancelledRow(k.row)))
208
+ .map((k) => ({ slug: k.bare, reason: cut(reasonOf(k)) }))
209
+ .sort(bySlug);
210
+
211
+ const result = (state, blocked = null) => ({ state, blocked, prds, verified, refuted, unvalidated });
212
+
213
+ if (session.status === 'completed') return result('closed');
214
+ if (session.status === 'proposed') return result('awaiting_approval');
215
+ if (needsInput && !chatBusy) return result('needs_input');
216
+
217
+ if (refuted.length > 0) return result('blocked', { kind: 'refuted', prds: refuted.map((p) => ({ ...p })) });
218
+ const failed = knownPrds('failed', errorOf);
219
+ if (failed.length > 0) return result('blocked', { kind: 'failed', prds: failed });
220
+ const parked = knownPrds('needs_review', reviewOf);
221
+ if (parked.length > 0) return result('blocked', { kind: 'needs_review', prds: parked });
222
+ const quarantined = knownPrds('quarantined', (k) => reviewOf(k) || errorOf(k), false);
223
+ if (quarantined.length > 0) return result('blocked', { kind: 'quarantined', prds: quarantined });
224
+
225
+ if (chatBusy || known.some((k) => k.status === 'pending' || k.status === 'running' || k.status === 'investigating')) {
226
+ return result('working');
227
+ }
228
+ if (completedWork > 0 && unvalidated.length === 0) return result('verified');
229
+ if (unvalidated.length > 0) return result('in_review');
230
+ return result('open');
231
+ }
232
+
233
+ module.exports = { computeEpicOutsideState, knownPrdSlugs, EPIC_OUTSIDE_STATES };
@@ -118,4 +118,4 @@ function evaluateEpicSettle({ epicId, cwd, events, jobs, now, horizonMs } = {})
118
118
  return { settled, uncovered, verified, refuted, failed, parked, cancelled, digestKey, hasContent };
119
119
  }
120
120
 
121
- module.exports = { evaluateEpicSettle, DEFAULT_SETTLE_HORIZON_MS };
121
+ module.exports = { evaluateEpicSettle, DEFAULT_SETTLE_HORIZON_MS, isCancelledRow };
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicStateWatcher.cjs — turns "outside apps poll for Epic state" into events.
5
+ *
6
+ * runEpicStateWatch({ cwds, jobs }) reads every open Epic of each cwd through
7
+ * epicOutsideRead.listOpenEpicRecords, compares each record's outside-facing
8
+ * state with the snapshot at schedulerPaths.epicStateSnapshotPath(), appends
9
+ * one `epic_state_changed` audit row per change, then rewrites the snapshot.
10
+ *
11
+ * Snapshot: { version: 1, epics: { "<cwd>\0<epicId>": { state, blockedKind, externalRef, at } } }.
12
+ * No snapshot file → the run seeds it and emits nothing. Entries of cwds not in
13
+ * the call, and of a cwd whose read threw, are kept as they are. Never rejects;
14
+ * concurrent calls share one in-flight promise. Not scheduled here — the
15
+ * scheduler tick calls it.
16
+ */
17
+
18
+ const outsideRead = require('./epicOutsideRead.cjs');
19
+ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
20
+ const { epicStateSnapshotPath } = require('../scheduler/schedulerPaths.cjs');
21
+ const { writeJsonAtomic, readJsonOr } = require('../util/atomicFs.cjs');
22
+
23
+ const SNAPSHOT_VERSION = 1;
24
+ const PAGE_LIMIT = 200;
25
+ const SEP = '\0';
26
+
27
+ let isTabBusy = () => false;
28
+ /** Test seam: registered-project list passed to the reader; undefined = the reader's default. */
29
+ let projectRoots;
30
+ let inflight = null;
31
+
32
+ const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
33
+ const str = (v) => (typeof v === 'string' && v !== '' ? v : null);
34
+
35
+ /** @param {{ isTabBusy?: (epicId: string) => boolean | Promise<boolean>, projectRoots?: () => string[] }} [opts] */
36
+ function configureEpicStateWatcher(opts = {}) {
37
+ const o = isObj(opts) ? opts : {};
38
+ isTabBusy = typeof o.isTabBusy === 'function' ? o.isTabBusy : () => false;
39
+ projectRoots = typeof o.projectRoots === 'function' ? o.projectRoots : undefined;
40
+ }
41
+
42
+ function readerOpts(jobs, extra) {
43
+ const o = { isTabBusy, listJobs: () => jobs, ...extra };
44
+ if (projectRoots) o.projectRoots = projectRoots;
45
+ return o;
46
+ }
47
+
48
+ /** Every open record of one cwd, paging until hasMore is false. Throws on a reader failure. */
49
+ async function readAllOpen(cwd, jobs) {
50
+ const out = [];
51
+ let offset = 0;
52
+ for (;;) {
53
+ const page = await outsideRead.listOpenEpicRecords(cwd, readerOpts(jobs, { limit: PAGE_LIMIT, offset }));
54
+ const epics = isObj(page) && Array.isArray(page.epics) ? page.epics : [];
55
+ out.push(...epics);
56
+ if (!page || !page.hasMore || epics.length === 0) return out;
57
+ offset += epics.length;
58
+ }
59
+ }
60
+
61
+ function entryOf(rec, at) {
62
+ return {
63
+ state: str(rec.state),
64
+ blockedKind: isObj(rec.blocked) ? str(rec.blocked.kind) : null,
65
+ externalRef: str(rec.externalRef),
66
+ at,
67
+ };
68
+ }
69
+
70
+ function change(cwd, epicId, from, to, blockedKind, externalRef) {
71
+ const row = { cwd, epicId, from, to };
72
+ if (blockedKind) row.blockedKind = blockedKind;
73
+ if (externalRef) row.externalRef = externalRef;
74
+ return row;
75
+ }
76
+
77
+ async function closedOrGone(cwd, epicId, jobs) {
78
+ try {
79
+ const rec = await outsideRead.getEpicRecord(cwd, readerOpts(jobs, { id: epicId }));
80
+ return rec && rec.status === 'completed' ? 'closed' : 'gone';
81
+ } catch {
82
+ return 'gone';
83
+ }
84
+ }
85
+
86
+ async function watchOnce({ cwds, jobs } = {}) {
87
+ const changes = [];
88
+ try {
89
+ const cwdList = Array.isArray(cwds) ? [...new Set(cwds.filter((c) => typeof c === 'string' && c))] : [];
90
+ const jobList = Array.isArray(jobs) ? jobs : [];
91
+ const file = epicStateSnapshotPath();
92
+ const prev = await readJsonOr(file, null);
93
+ const seeding = !isObj(prev) || !isObj(prev.epics);
94
+ const prevEpics = seeding ? {} : prev.epics;
95
+ const next = { ...prevEpics };
96
+ const now = new Date().toISOString();
97
+
98
+ for (const cwd of cwdList) {
99
+ let records;
100
+ try {
101
+ records = await readAllOpen(cwd, jobList);
102
+ } catch (e) {
103
+ console.error('[epicStateWatcher] read failed, skipping', cwd, e?.message ?? String(e));
104
+ continue;
105
+ }
106
+ const prefix = `${cwd}${SEP}`;
107
+ const seen = new Set();
108
+ for (const rec of records) {
109
+ const epicId = isObj(rec) ? str(rec.epicId) : null;
110
+ if (!epicId) continue;
111
+ const key = `${prefix}${epicId}`;
112
+ seen.add(key);
113
+ const old = isObj(prevEpics[key]) ? prevEpics[key] : null;
114
+ const cur = entryOf(rec, now);
115
+ if (!old) {
116
+ if (!seeding) changes.push(change(cwd, epicId, null, cur.state, cur.blockedKind, cur.externalRef));
117
+ next[key] = cur;
118
+ } else if (old.state !== cur.state || (old.blockedKind ?? null) !== cur.blockedKind) {
119
+ changes.push(change(cwd, epicId, str(old.state), cur.state, cur.blockedKind, cur.externalRef));
120
+ next[key] = cur;
121
+ } else {
122
+ next[key] = { ...cur, at: str(old.at) || now };
123
+ }
124
+ }
125
+ for (const key of Object.keys(prevEpics)) {
126
+ if (!key.startsWith(prefix) || seen.has(key)) continue;
127
+ const epicId = key.slice(prefix.length);
128
+ const old = isObj(prevEpics[key]) ? prevEpics[key] : {};
129
+ const to = await closedOrGone(cwd, epicId, jobList);
130
+ changes.push(change(cwd, epicId, str(old.state), to, null, str(old.externalRef)));
131
+ delete next[key];
132
+ }
133
+ }
134
+
135
+ for (const row of changes) appendAuditEvent('epic_state_changed', row);
136
+ try {
137
+ await writeJsonAtomic(file, { version: SNAPSHOT_VERSION, epics: next });
138
+ } catch (e) {
139
+ console.error('[epicStateWatcher] snapshot write failed', e?.message ?? String(e));
140
+ }
141
+ } catch (e) {
142
+ console.error('[epicStateWatcher] watch failed', e?.message ?? String(e));
143
+ }
144
+ return changes;
145
+ }
146
+
147
+ /**
148
+ * @param {{ cwds: string[], jobs: any[] }} args
149
+ * @returns {Promise<Array<{ cwd: string, epicId: string, from: string|null, to: string|null, blockedKind?: string, externalRef?: string }>>}
150
+ */
151
+ function runEpicStateWatch(args) {
152
+ if (inflight) return inflight;
153
+ inflight = watchOnce(args).finally(() => { inflight = null; });
154
+ return inflight;
155
+ }
156
+
157
+ module.exports = { configureEpicStateWatcher, runEpicStateWatch };
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * externalRef.cjs — the one shared validator for an Epic's `source.externalRef`:
5
+ * an outside app's own id for the Epic it asked Session Manager to create.
6
+ *
7
+ * Every entry point that accepts an externalRef runs it through
8
+ * normalizeExternalRef. The STORED shape (EpicSourceSchema in
9
+ * promptSessionSchema.cjs) is deliberately lenient — any string — so a stricter
10
+ * rule here never makes dropInvalidSessions drop a whole row on read.
11
+ */
12
+
13
+ const EXTERNAL_REF_MAX = 200;
14
+ // Letters, digits and . _ : / @ - only, 1..EXTERNAL_REF_MAX characters.
15
+ const EXTERNAL_REF_PATTERN = new RegExp(`^[A-Za-z0-9._:/@-]{1,${EXTERNAL_REF_MAX}}$`);
16
+
17
+ /**
18
+ * @param {unknown} value
19
+ * @returns {{ ok: true, value: string | undefined } | { ok: false, error: string }}
20
+ * Never throws.
21
+ */
22
+ function normalizeExternalRef(value) {
23
+ if (value === undefined || value === null) return { ok: true, value: undefined };
24
+ if (typeof value !== 'string') {
25
+ return { ok: false, error: 'externalRef must be a string.' };
26
+ }
27
+ const trimmed = value.trim();
28
+ if (!EXTERNAL_REF_PATTERN.test(trimmed)) {
29
+ return {
30
+ ok: false,
31
+ error: `externalRef must be 1 to ${EXTERNAL_REF_MAX} characters of letters, digits or . _ : / @ - after trimming.`,
32
+ };
33
+ }
34
+ return { ok: true, value: trimmed };
35
+ }
36
+
37
+ module.exports = { EXTERNAL_REF_MAX, EXTERNAL_REF_PATTERN, normalizeExternalRef };
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * externalRefIndex.cjs — machine-level index from (project cwd, externalRef)
5
+ * to the Epic an earlier handoff created, so a repeat handoff still finds that
6
+ * Epic after it completes and leaves the project's active index.
7
+ *
8
+ * File: externalRefIndexPath() (schedulerHome()/external-refs.json)
9
+ * { version: 1, refs: { "<cwd>\0<ref>": { epicId, at, producer?, fromCwd?, macroId? } } }
10
+ * The key is built the same way macroAdminRoutes.cjs builds its run keys.
11
+ * cwd is used exactly as given — callers pass the resolved absolute project cwd.
12
+ *
13
+ * A missing, empty or corrupt file reads as empty and is replaced by the next
14
+ * record. Writes are serialized through one in-module promise chain; the lock
15
+ * is an in-memory Map — every caller lives in the one Electron main process.
16
+ */
17
+
18
+ const { writeJsonAtomic, readJsonOr } = require('../util/atomicFs.cjs');
19
+ const { externalRefIndexPath } = require('../scheduler/schedulerPaths.cjs');
20
+ const { readActiveIndex } = require('./epicMint.cjs');
21
+
22
+ const VERSION = 1;
23
+
24
+ function refKey(cwd, externalRef) {
25
+ return `${cwd}\u0000${externalRef}`;
26
+ }
27
+
28
+ function validKey(cwd, externalRef) {
29
+ return typeof cwd === 'string' && cwd !== '' && typeof externalRef === 'string' && externalRef !== '';
30
+ }
31
+
32
+ function isPlainObject(v) {
33
+ return !!v && typeof v === 'object' && !Array.isArray(v);
34
+ }
35
+
36
+ async function readIndexFile() {
37
+ const parsed = await readJsonOr(externalRefIndexPath(), null);
38
+ if (!isPlainObject(parsed) || !isPlainObject(parsed.refs)) return { version: VERSION, refs: {} };
39
+ return { version: VERSION, refs: { ...parsed.refs } };
40
+ }
41
+
42
+ function cleanEntry({ epicId, at, producer, fromCwd, macroId }) {
43
+ /** @type {Record<string, string>} */
44
+ const entry = { epicId, at };
45
+ if (typeof producer === 'string' && producer) entry.producer = producer;
46
+ if (typeof fromCwd === 'string' && fromCwd) entry.fromCwd = fromCwd;
47
+ if (typeof macroId === 'string' && macroId) entry.macroId = macroId;
48
+ return entry;
49
+ }
50
+
51
+ /** Tail of the serialized write chain; never rejects. */
52
+ let writeChain = Promise.resolve();
53
+
54
+ /**
55
+ * Record (or overwrite) the Epic for (cwd, externalRef). Resolves to the stored entry.
56
+ */
57
+ function recordExternalRef({ cwd, externalRef, epicId, producer, fromCwd, macroId }) {
58
+ if (!validKey(cwd, externalRef)) return Promise.reject(new TypeError('recordExternalRef: cwd and externalRef must be non-empty strings'));
59
+ if (typeof epicId !== 'string' || !epicId) return Promise.reject(new TypeError('recordExternalRef: epicId must be a non-empty string'));
60
+ const run = writeChain.then(async () => {
61
+ const index = await readIndexFile();
62
+ const entry = cleanEntry({ epicId, at: new Date().toISOString(), producer, fromCwd, macroId });
63
+ index.refs[refKey(cwd, externalRef)] = entry;
64
+ await writeJsonAtomic(externalRefIndexPath(), index);
65
+ return { ...entry };
66
+ });
67
+ writeChain = run.then(() => undefined, () => undefined);
68
+ return run;
69
+ }
70
+
71
+ /** The stored entry for (cwd, externalRef), or null. Waits for pending records. */
72
+ async function lookupExternalRef({ cwd, externalRef }) {
73
+ if (!validKey(cwd, externalRef)) return null;
74
+ await writeChain;
75
+ const index = await readIndexFile();
76
+ const entry = index.refs[refKey(cwd, externalRef)];
77
+ if (!isPlainObject(entry) || typeof entry.epicId !== 'string' || !entry.epicId) return null;
78
+ return { ...entry };
79
+ }
80
+
81
+ /**
82
+ * The Epic for (cwd, externalRef) plus `open` (still in the active index), or
83
+ * null. On an index miss, scans the project's open sessions for
84
+ * source.externalRef === externalRef and records the hit.
85
+ */
86
+ async function findEpicByExternalRef({ cwd, externalRef }) {
87
+ if (!validKey(cwd, externalRef)) return null;
88
+ const sessions = readActiveIndex(cwd).sessions;
89
+ const entry = await lookupExternalRef({ cwd, externalRef });
90
+ if (entry) return { ...entry, open: Object.prototype.hasOwnProperty.call(sessions, entry.epicId) };
91
+ for (const [epicId, session] of Object.entries(sessions)) {
92
+ const source = isPlainObject(session) && isPlainObject(session.source) ? session.source : null;
93
+ if (!source || source.externalRef !== externalRef) continue;
94
+ const recorded = await recordExternalRef({
95
+ cwd,
96
+ externalRef,
97
+ epicId,
98
+ producer: source.producer,
99
+ fromCwd: source.fromCwd,
100
+ macroId: source.macroId,
101
+ });
102
+ return { ...recorded, open: true };
103
+ }
104
+ return null;
105
+ }
106
+
107
+ /** key -> tail promise of the callers queued on that key (never rejects). */
108
+ const locks = new Map();
109
+
110
+ /**
111
+ * Run async `fn` so calls with the same (cwd, externalRef) never overlap.
112
+ * Different keys run concurrently. fn's result or rejection passes through.
113
+ */
114
+ async function withExternalRefLock({ cwd, externalRef }, fn) {
115
+ const key = refKey(cwd, externalRef);
116
+ const prev = locks.get(key) || Promise.resolve();
117
+ /** @type {() => void} */
118
+ let release = () => {};
119
+ const mine = new Promise((resolve) => { release = () => resolve(undefined); });
120
+ const tail = prev.then(() => mine);
121
+ locks.set(key, tail);
122
+ await prev;
123
+ try {
124
+ return await fn();
125
+ } finally {
126
+ release();
127
+ if (locks.get(key) === tail) locks.delete(key);
128
+ }
129
+ }
130
+
131
+ module.exports = {
132
+ recordExternalRef,
133
+ lookupExternalRef,
134
+ findEpicByExternalRef,
135
+ withExternalRefLock,
136
+ };