claude-code-session-manager 0.138.0 → 0.140.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/README.md +352 -79
- package/dist/assets/AppSettings-CMFEM68R.js +2 -0
- package/dist/assets/History--JwsFnbn.js +2 -0
- package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
- package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
- package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
- package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
- package/dist/assets/Skills-DtRzghn5.js +67 -0
- package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
- package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
- package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
- package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
- package/dist/assets/index-CtxruO1L.js +3121 -0
- package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +467 -451
- package/package.json +17 -6
- package/plugins/AGENTS.md +60 -0
- package/plugins/CLAUDE.md +1 -60
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
- package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
- package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
- package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
- package/scripts/README.md +2 -0
- package/scripts/hooks/guard-tool-risk.cjs +91 -0
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
- package/scripts/ops-sweep.cjs +53 -23
- package/scripts/scheduler-mcp-server.cjs +360 -35
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +2 -2
- package/src/main/config.cjs +112 -8
- package/src/main/docEdit.cjs +6 -1
- package/src/main/exchanges.cjs +70 -5
- package/src/main/files.cjs +7 -27
- package/src/main/health.cjs +48 -15
- package/src/main/historyAggregator.cjs +172 -63
- package/src/main/historyDashboard.cjs +87 -17
- package/src/main/index.cjs +78 -4
- package/src/main/ipcSchemas.cjs +233 -20
- package/src/main/lib/AGENTS.md +54 -0
- package/src/main/lib/CLAUDE.md +1 -54
- package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
- package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
- package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
- package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
- package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
- package/src/main/lib/claude/modelPricing.cjs +148 -0
- package/src/main/lib/claude/personaToolScope.cjs +12 -6
- package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
- package/src/main/lib/claude/runClaudeP.cjs +6 -1
- package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
- package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
- package/src/main/lib/ephemeralCwd.cjs +37 -2
- package/src/main/lib/epic/delegationReadiness.cjs +42 -9
- package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
- package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
- package/src/main/lib/epic/epicOutsideState.cjs +233 -0
- package/src/main/lib/epic/epicSettle.cjs +1 -1
- package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
- package/src/main/lib/epic/epicValidationHook.cjs +24 -4
- package/src/main/lib/epic/externalRef.cjs +37 -0
- package/src/main/lib/epic/externalRefIndex.cjs +136 -0
- package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
- package/src/main/lib/epic/restorableSessions.cjs +151 -17
- package/src/main/lib/epic/transcriptUsage.cjs +197 -0
- package/src/main/lib/externalContract.cjs +137 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
- package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
- package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
- package/src/main/lib/git/branchSweep.cjs +209 -4
- package/src/main/lib/git/gitWorktree.cjs +41 -5
- package/src/main/lib/guardShims.cjs +1 -1
- package/src/main/lib/historyRollup.cjs +58 -5
- package/src/main/lib/insideHome.cjs +27 -1
- package/src/main/lib/mcpToolCatalog.cjs +232 -25
- package/src/main/lib/mdDocCensus.cjs +59 -78
- package/src/main/lib/mdDocRefs.cjs +71 -93
- package/src/main/lib/mdNetworkScan.cjs +245 -250
- package/src/main/lib/mdReviewRecord.cjs +22 -9
- package/src/main/lib/memoryMdNetwork.cjs +5 -12
- package/src/main/lib/opsOwnership.cjs +18 -2
- package/src/main/lib/opsRetentionSettings.cjs +28 -4
- package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
- package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
- package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
- package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
- package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/depSlugResolve.cjs +104 -4
- package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
- package/src/main/lib/prd/prdCreate.cjs +351 -23
- package/src/main/lib/prd/prdDisposition.cjs +11 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
- package/src/main/lib/process/loginItem.cjs +171 -0
- package/src/main/lib/process/loginItemPlan.cjs +193 -0
- package/src/main/lib/project-pages/playerBridge.cjs +4 -0
- package/src/main/lib/project-pages/videoReview.cjs +268 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
- package/src/main/lib/promptSessionSchema.cjs +4 -0
- package/src/main/lib/remoteTranscriptTail.cjs +32 -1
- package/src/main/lib/scheduler/cpuSample.cjs +131 -4
- package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
- package/src/main/lib/scheduler/loadGate.cjs +24 -6
- package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
- package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
- package/src/main/lib/scheduler/queueStore.cjs +7 -0
- package/src/main/lib/scheduler/rcaReport.cjs +21 -1
- package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
- package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
- package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
- package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
- package/src/main/lib/scheduler/validationQuality.cjs +282 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
- package/src/main/lib/tasks/taskIpc.cjs +80 -0
- package/src/main/lib/tasks/taskLedger.cjs +502 -0
- package/src/main/lib/tasks/taskRun.cjs +313 -0
- package/src/main/lib/tasks/taskSwitch.cjs +120 -0
- package/src/main/lib/telemetry/auditEvents.cjs +176 -0
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
- package/src/main/loginItemIpc.cjs +35 -0
- package/src/main/loopEfficiencyHandlers.cjs +11 -2
- package/src/main/projectPages.cjs +6 -15
- package/src/main/promptSessionEvents.cjs +9 -1
- package/src/main/queueOps.cjs +260 -3
- package/src/main/runVerify.cjs +53 -25
- package/src/main/scheduler/AGENTS.md +26 -0
- package/src/main/scheduler/CLAUDE.md +1 -26
- package/src/main/scheduler/budget.cjs +239 -9
- package/src/main/scheduler/cancelDependents.cjs +154 -0
- package/src/main/scheduler/prdParser.cjs +4 -1
- package/src/main/scheduler/starvation.cjs +20 -18
- package/src/main/scheduler.cjs +774 -64
- package/src/main/supervisor.cjs +5 -1
- package/src/main/templates/PRD_AUTHORING.md +7 -1
- package/src/main/transcripts.cjs +62 -7
- package/src/main/validationQualityHandlers.cjs +199 -0
- package/src/main/webRemote.cjs +132 -20
- package/src/preload/api.d.ts +434 -28
- package/src/preload/apiSurface.cjs +7 -0
- package/src/preload/apiSurface.json +485 -81
- package/src/preload/index.cjs +38 -5
- package/src/seed/agents/validator.md +19 -8
- package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
- package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
- package/dist/assets/Button-Bk23rEnZ.js +0 -1
- package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
- package/dist/assets/Extensions-CXem-uwI.js +0 -2
- package/dist/assets/History-BwO3coo4.js +0 -2
- package/dist/assets/Library-BDV69fSe.js +0 -32
- package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
- package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
- package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
- package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
- package/dist/assets/Settings-COT34hBF.js +0 -2
- package/dist/assets/Skills-BgexoUkQ.js +0 -29
- package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
- package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
- package/dist/assets/Toggle-CENi19iK.js +0 -1
- package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
- package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
- package/dist/assets/index-CgCxpunJ.js +0 -3116
|
@@ -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(typeof event.reason === 'string' ? event.reason : 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, refutedReason, 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 };
|
|
@@ -79,12 +79,15 @@ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now, jobBud
|
|
|
79
79
|
|
|
80
80
|
const stamp = new Date(now).toISOString().replace(/\D/g, '').slice(0, 14);
|
|
81
81
|
const slug = `${SWEEP_SLUG_PREFIX}-${stamp}`;
|
|
82
|
-
|
|
82
|
+
// Plan records are a gitignored runtime namespace: the job writes the record
|
|
83
|
+
// in its worktree and the scheduler copies it to the main checkout, so the
|
|
84
|
+
// PRD is artifact-only and never commits it.
|
|
85
|
+
const recordPath = `session-manager-operations/plan-records/${epicId}/${slug}.md`;
|
|
83
86
|
|
|
84
87
|
const acceptanceCriteria = names.map(
|
|
85
88
|
(name) => `${name} verified against its PRD file (find it by slug under $SM_PROJECT_ROOT/session-manager-operations/scheduler/epics/${epicId}/prds/ or prds-archived/, possibly in a timestamped subfolder)`,
|
|
86
89
|
);
|
|
87
|
-
acceptanceCriteria.push(`Record written
|
|
90
|
+
acceptanceCriteria.push(`Record written at ${recordPath}, relative to the job worktree's repository root (git rev-parse --show-toplevel), never relative to a subdirectory you cd'd into. Do not git add or commit it — the scheduler copies it to the main checkout`);
|
|
88
91
|
|
|
89
92
|
const base = baseSha
|
|
90
93
|
? `Base: ${baseSha}`
|
|
@@ -103,6 +106,8 @@ function buildSweepValidatorInput({ epicId, cwd, uncovered, baseSha, now, jobBud
|
|
|
103
106
|
outOfScope: ['Editing product code', 'Queuing fix PRDs'],
|
|
104
107
|
gate: ['none'],
|
|
105
108
|
files: [recordPath],
|
|
109
|
+
deliverable: 'artifact',
|
|
110
|
+
artifactPaths: [recordPath],
|
|
106
111
|
estimateMinutes: validatorEstimateMinutes(covered.map((e) => e.gateMs), { factor }),
|
|
107
112
|
agentType: 'validator',
|
|
108
113
|
tag: 'build',
|
|
@@ -43,12 +43,32 @@ function defaultReadActiveIndex(cwd) {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/** The digest's record-folder lines: absolute main-checkout paths when cwd resolves. */
|
|
47
|
+
function recordFolderLines(cwd, epicId) {
|
|
48
|
+
try {
|
|
49
|
+
if (typeof cwd === 'string' && cwd) {
|
|
50
|
+
const { opsPath } = require('../opsOwnership.cjs');
|
|
51
|
+
return [
|
|
52
|
+
`Plan record folder (on disk in the main checkout, not committed): ${opsPath(cwd, 'plan-records', epicId)}${path.sep}`,
|
|
53
|
+
`Legacy validation record folder: ${opsPath(cwd, 'reviews', 'validation', epicId)}${path.sep}`,
|
|
54
|
+
];
|
|
55
|
+
}
|
|
56
|
+
} catch { /* fall through to the relative form */ }
|
|
57
|
+
return [
|
|
58
|
+
`Plan record folder (relative to the project root): session-manager-operations/plan-records/${epicId}/`,
|
|
59
|
+
`Legacy validation record folder: session-manager-operations/reviews/validation/${epicId}/`,
|
|
60
|
+
];
|
|
61
|
+
}
|
|
62
|
+
|
|
46
63
|
/**
|
|
47
64
|
* buildSettledDigest — pure builder for the ONE plan-digest prompt.
|
|
48
65
|
* Empty sections are omitted. `notValidatedReason` explains why the
|
|
49
|
-
* settle.uncovered slugs were not sent to a sweep validator.
|
|
66
|
+
* settle.uncovered slugs were not sent to a sweep validator. `cwd` is the
|
|
67
|
+
* project root: plan records live on disk in its main checkout
|
|
68
|
+
* (plan-records/<epicId>/, never committed), so the digest names that
|
|
69
|
+
* absolute folder plus the legacy reviews/validation/<epicId>/ one.
|
|
50
70
|
*/
|
|
51
|
-
function buildSettledDigest(settle, { epicId, notValidatedReason } = {}) {
|
|
71
|
+
function buildSettledDigest(settle, { epicId, notValidatedReason, cwd } = {}) {
|
|
52
72
|
const s = settle || {};
|
|
53
73
|
const verified = s.verified || [];
|
|
54
74
|
const refuted = s.refuted || [];
|
|
@@ -58,7 +78,7 @@ function buildSettledDigest(settle, { epicId, notValidatedReason } = {}) {
|
|
|
58
78
|
const notValidated = (s.uncovered || []).map((u) => (typeof u === 'string' ? u : u.slug));
|
|
59
79
|
const lines = [
|
|
60
80
|
`PLAN SETTLED — no PRD of this session is pending or running. This is ONE digest, not a per-PRD request.`,
|
|
61
|
-
|
|
81
|
+
...recordFolderLines(cwd, epicId),
|
|
62
82
|
'Do NOT re-verify VERIFIED PRDs — a validator already checked them.',
|
|
63
83
|
];
|
|
64
84
|
if (verified.length) {
|
|
@@ -200,7 +220,7 @@ async function runEpicSettle({ cwd, epicId } = {}, deps = {}) {
|
|
|
200
220
|
}
|
|
201
221
|
}
|
|
202
222
|
|
|
203
|
-
const prompt = buildSettledDigest(digestSettle, { epicId, notValidatedReason });
|
|
223
|
+
const prompt = buildSettledDigest(digestSettle, { epicId, notValidatedReason, cwd });
|
|
204
224
|
sendPrompt(epicId, prompt, { origin: 'scheduler' });
|
|
205
225
|
await appendResponseEvent(
|
|
206
226
|
cwd, epicId,
|
|
@@ -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
|
+
};
|