claude-code-session-manager 0.143.0 → 0.144.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/README.md +3 -1
- package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
- package/dist/assets/{History-DTttbvPb.js → History-C3E6y_7t.js} +2 -2
- package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
- package/dist/assets/{Panel-B_D4Bg7L.js → Panel-CnfWs46Z.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
- package/dist/assets/Scheduler-D8un7N3B.js +16 -0
- package/dist/assets/{SkillReferenceGraph-D1b2aiol.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
- package/dist/assets/{Skills-cfV7sgk6.js → Skills-Bg5O2Hyn.js} +23 -23
- package/dist/assets/{TiptapBody-DVXtEIVy.js → TiptapBody-BdzoBmqu.js} +27 -27
- package/dist/assets/{Toggle-CYajnSdx.js → Toggle-Dt5K1OXt.js} +1 -1
- package/dist/assets/{VoiceButton-DJ4gGRuE.js → VoiceButton-CTLyRgdF.js} +1 -1
- package/dist/assets/{historyTotals-D3MoHY2U.js → historyTotals-B2_KWBga.js} +1 -1
- package/dist/assets/{index-CdTppjKR.js → index-446b69rr.js} +698 -697
- package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +439 -436
- package/package.json +4 -2
- package/plugins/session-manager-dev/skills/develop/SKILL.md +14 -13
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
- package/scripts/README.md +1 -1
- package/scripts/scheduler-mcp-server.cjs +77 -0
- package/src/main/adminRouteRegistry.cjs +6 -0
- package/src/main/agentLibrary.cjs +60 -11
- package/src/main/agentsIpc.cjs +19 -0
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +109 -0
- package/src/main/health.cjs +59 -17
- package/src/main/index.cjs +4 -0
- package/src/main/ipcSchemas.cjs +50 -1
- package/src/main/lib/claude/agentArmory.cjs +128 -0
- package/src/main/lib/claude/agentModelResolve.cjs +3 -2
- package/src/main/lib/claude/agentSnapshot.cjs +24 -3
- package/src/main/lib/claude/builtinTools.cjs +110 -0
- package/src/main/lib/claude/environmentProfiles.cjs +1 -1
- package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
- package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
- package/src/main/lib/claude/personaToolScope.cjs +77 -6
- package/src/main/lib/epic/epicDepsSync.cjs +66 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
- package/src/main/lib/epic/epicSettle.cjs +48 -4
- package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
- package/src/main/lib/epic/epicValidationHook.cjs +9 -1
- package/src/main/lib/epic/planReviewInput.cjs +123 -0
- package/src/main/lib/epic/restorableSessions.cjs +1 -0
- package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
- package/src/main/lib/externalContract.cjs +12 -0
- package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +24 -3
- package/src/main/lib/feedback-remote/pendingReplies.cjs +8 -4
- package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
- package/src/main/lib/feedback-remote/replyClaims.cjs +15 -6
- package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
- package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
- package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
- package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
- package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
- package/src/main/lib/git/gitWorktree.cjs +1 -1
- package/src/main/lib/git/worktreeDeps.cjs +9 -3
- package/src/main/lib/mcpToolCatalog.cjs +43 -5
- package/src/main/lib/mcpToolsProbe.cjs +19 -2
- package/src/main/lib/packs/packCatalog.cjs +98 -5
- package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
- package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
- package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
- package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
- package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
- package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +94 -0
- package/src/main/lib/prd/prdCreate.cjs +48 -5
- package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
- package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
- package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
- package/src/main/lib/process/peerChatSession.cjs +165 -0
- package/src/main/lib/project-pages/videoScriptPress.cjs +6 -0
- package/src/main/lib/project-pages/videoScriptRunRoute.cjs +24 -4
- package/src/main/lib/promptSessionSchema.cjs +2 -0
- package/src/main/lib/scheduler/baselineGate.cjs +31 -2
- package/src/main/lib/scheduler/planRecordHarvest.cjs +104 -12
- package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
- package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
- package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
- package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
- package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +12 -2
- package/src/main/lib/tasks/memoryConsolidation.cjs +109 -37
- package/src/main/lib/tasks/taskAdminRoutes.cjs +26 -14
- package/src/main/lib/tasks/taskRun.cjs +3 -1
- package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
- package/src/main/projectPages.cjs +22 -14
- package/src/main/pty.cjs +3 -0
- package/src/main/runVerify.cjs +3 -2
- package/src/main/scheduler/planReviewHold.cjs +140 -0
- package/src/main/scheduler/prdParser.cjs +1 -0
- package/src/main/scheduler/reviewLadder.cjs +2 -0
- package/src/main/scheduler/utilizationHold.cjs +7 -2
- package/src/main/scheduler.cjs +532 -78
- package/src/main/seedAgentPersonas.cjs +11 -6
- package/src/main/seedStatus.cjs +1 -1
- package/src/main/templates/PRD_AUTHORING.md +16 -1
- package/src/main/webRemote.cjs +47 -7
- package/src/preload/api.d.ts +71 -1
- package/src/preload/apiSurface.json +28 -0
- package/src/preload/index.cjs +9 -0
- package/src/seed/agents/architect.md +28 -43
- package/src/seed/agents/dev-lead.md +3 -1
- package/src/seed/agents/md-network-curator.md +27 -0
- package/src/seed/agents/plan-reviewer.md +47 -0
- package/src/seed/agents/validator.md +2 -1
- package/dist/assets/AppSettings-BO4jDVGO.js +0 -2
- package/dist/assets/HomeClaudeConfig-DADP5bfn.js +0 -3
- package/dist/assets/ProjectClaudeConfig-DPnDJKcr.js +0 -26
- package/dist/assets/Scheduler-CNLjn90m.js +0 -16
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* peerChatSession.cjs — given the accepted socket of a loopback HTTP request,
|
|
5
|
+
* find the client process and read SM_CHAT_SESSION_ID / SM_PROJECT_ROOT from
|
|
6
|
+
* its environment (or its nearest ancestor's; up to 6 hops). Lets a press made
|
|
7
|
+
* from an SM chat (agent curl from its Bash tool) record the asking Epic.
|
|
8
|
+
*
|
|
9
|
+
* Read-only, same-uid processes only. Never logs or returns the environment —
|
|
10
|
+
* only the two variables. Never throws or rejects; null on any miss.
|
|
11
|
+
* SECURITY: the resolved chat/Epic is self-asserted by any same-uid process
|
|
12
|
+
* (it can set these variables to anything). It is provenance only and must
|
|
13
|
+
* never be used to authorize anything.
|
|
14
|
+
* Linux: /proc. darwin: lsof + ps (execFile, no shell). Others: null.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const nodeFs = require('fs');
|
|
18
|
+
const childProcess = require('child_process');
|
|
19
|
+
|
|
20
|
+
const ID_RE = /^[A-Za-z0-9-]{8,64}$/;
|
|
21
|
+
const MAX_HOPS = 6;
|
|
22
|
+
const DEADLINE_MS = 1500;
|
|
23
|
+
|
|
24
|
+
function pickVars(envMap) {
|
|
25
|
+
const id = envMap.SM_CHAT_SESSION_ID;
|
|
26
|
+
if (typeof id !== 'string' || !ID_RE.test(id)) return null;
|
|
27
|
+
const root = envMap.SM_PROJECT_ROOT;
|
|
28
|
+
return { chatSessionId: id, projectRoot: typeof root === 'string' && root ? root : null };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function parseEnviron(buf) {
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const part of String(buf).split('\0')) {
|
|
34
|
+
const i = part.indexOf('=');
|
|
35
|
+
if (i <= 0) continue;
|
|
36
|
+
const k = part.slice(0, i);
|
|
37
|
+
if (k === 'SM_CHAT_SESSION_ID' || k === 'SM_PROJECT_ROOT') out[k] = part.slice(i + 1);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ── Linux ──────────────────────────────────────────────────────────────────
|
|
43
|
+
|
|
44
|
+
function findInode(fs, clientLocalPort, serverPort) {
|
|
45
|
+
const lp = clientLocalPort.toString(16).toUpperCase().padStart(4, '0');
|
|
46
|
+
const rp = serverPort.toString(16).toUpperCase().padStart(4, '0');
|
|
47
|
+
for (const f of ['/proc/net/tcp', '/proc/net/tcp6']) {
|
|
48
|
+
let text;
|
|
49
|
+
try { text = fs.readFileSync(f, 'utf8'); } catch { continue; }
|
|
50
|
+
for (const line of String(text).split('\n').slice(1)) {
|
|
51
|
+
const c = line.trim().split(/\s+/);
|
|
52
|
+
if (c.length < 10) continue;
|
|
53
|
+
const l = (c[1] || '').split(':')[1];
|
|
54
|
+
const r = (c[2] || '').split(':')[1];
|
|
55
|
+
if (l && r && l.toUpperCase() === lp && r.toUpperCase() === rp && c[9] && c[9] !== '0') return c[9];
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function findPidByInode(fs, inode, uid, deadline, now) {
|
|
62
|
+
const want = `socket:[${inode}]`;
|
|
63
|
+
let pids;
|
|
64
|
+
try { pids = fs.readdirSync('/proc').filter((n) => /^\d+$/.test(n)); } catch { return null; }
|
|
65
|
+
for (const pid of pids) {
|
|
66
|
+
if (now() > deadline) return null;
|
|
67
|
+
try {
|
|
68
|
+
if (uid != null && fs.statSync(`/proc/${pid}`).uid !== uid) continue;
|
|
69
|
+
for (const fd of fs.readdirSync(`/proc/${pid}/fd`)) {
|
|
70
|
+
try {
|
|
71
|
+
if (fs.readlinkSync(`/proc/${pid}/fd/${fd}`) === want) return Number(pid);
|
|
72
|
+
} catch { /* fd vanished / EACCES */ }
|
|
73
|
+
}
|
|
74
|
+
} catch { /* EACCES / gone */ }
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function linuxResolve(socket, deps, deadline, now) {
|
|
80
|
+
const fs = deps.fs || nodeFs;
|
|
81
|
+
const uid = deps.getuid ? deps.getuid() : (typeof process.getuid === 'function' ? process.getuid() : null);
|
|
82
|
+
const inode = findInode(fs, socket.remotePort, socket.localPort);
|
|
83
|
+
if (!inode) return null;
|
|
84
|
+
let pid = findPidByInode(fs, inode, uid, deadline, now);
|
|
85
|
+
for (let hop = 0; pid && hop <= MAX_HOPS && now() <= deadline; hop++) {
|
|
86
|
+
try {
|
|
87
|
+
const found = pickVars(parseEnviron(fs.readFileSync(`/proc/${pid}/environ`, 'latin1')));
|
|
88
|
+
if (found) return found;
|
|
89
|
+
} catch { /* unreadable */ }
|
|
90
|
+
let ppid = 0;
|
|
91
|
+
try {
|
|
92
|
+
const stat = String(fs.readFileSync(`/proc/${pid}/stat`, 'latin1'));
|
|
93
|
+
ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
|
|
94
|
+
} catch { return null; }
|
|
95
|
+
if (!Number.isInteger(ppid) || ppid <= 1) return null;
|
|
96
|
+
pid = ppid;
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ── darwin ─────────────────────────────────────────────────────────────────
|
|
102
|
+
|
|
103
|
+
function run(execFile, file, args, timeout) {
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
try {
|
|
106
|
+
execFile(file, args, { timeout, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => resolve(err ? null : String(stdout)));
|
|
107
|
+
} catch { resolve(null); }
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function darwinResolve(socket, deps, deadline, now) {
|
|
112
|
+
const execFile = deps.execFile || childProcess.execFile;
|
|
113
|
+
const left = () => Math.max(100, Math.min(1000, deadline - now()));
|
|
114
|
+
const out = await run(execFile, 'lsof', ['-nP', `-iTCP:${socket.remotePort}`, '-sTCP:ESTABLISHED', '-Fp'], left());
|
|
115
|
+
if (!out) return null;
|
|
116
|
+
const self = process.pid;
|
|
117
|
+
const pids = out.split('\n').filter((l) => /^p\d+$/.test(l)).map((l) => Number(l.slice(1))).filter((p) => p !== self);
|
|
118
|
+
for (let pid of pids.slice(0, 4)) {
|
|
119
|
+
for (let hop = 0; hop <= MAX_HOPS && now() < deadline; hop++) {
|
|
120
|
+
const cmd = await run(execFile, 'ps', ['-E', '-ww', '-o', 'command=', '-p', String(pid)], left());
|
|
121
|
+
if (cmd) {
|
|
122
|
+
const env = {};
|
|
123
|
+
// ps -E prints argv then the environment: the LAST match is the env's.
|
|
124
|
+
const id = [...cmd.matchAll(/ SM_CHAT_SESSION_ID=(\S+)/g)].pop();
|
|
125
|
+
const root = [...cmd.matchAll(/ SM_PROJECT_ROOT=(\S+)/g)].pop();
|
|
126
|
+
if (id) env.SM_CHAT_SESSION_ID = id[1];
|
|
127
|
+
if (root) env.SM_PROJECT_ROOT = root[1];
|
|
128
|
+
const found = pickVars(env);
|
|
129
|
+
if (found) return found;
|
|
130
|
+
}
|
|
131
|
+
const pp = await run(execFile, 'ps', ['-o', 'ppid=', '-p', String(pid)], left());
|
|
132
|
+
const ppid = Number(String(pp || '').trim());
|
|
133
|
+
if (!Number.isInteger(ppid) || ppid <= 1) break;
|
|
134
|
+
pid = ppid;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @param {{ remotePort?: number, localPort?: number }} socket
|
|
142
|
+
* @param {{ fs?: any, execFile?: any, getuid?: () => number, platform?: string, now?: () => number }} [deps]
|
|
143
|
+
* @returns {Promise<{ chatSessionId: string, projectRoot: string|null } | null>}
|
|
144
|
+
*/
|
|
145
|
+
async function resolvePeerChatSession(socket, deps = {}) {
|
|
146
|
+
try {
|
|
147
|
+
if (!socket || !Number.isInteger(socket.remotePort) || !Number.isInteger(socket.localPort)) return null;
|
|
148
|
+
const now = deps.now || Date.now;
|
|
149
|
+
const deadline = now() + DEADLINE_MS;
|
|
150
|
+
const platform = deps.platform || process.platform;
|
|
151
|
+
if (platform === 'linux') return linuxResolve(socket, deps, deadline, now) || null;
|
|
152
|
+
if (platform === 'darwin') {
|
|
153
|
+
let timer;
|
|
154
|
+
const cap = new Promise((r) => { timer = setTimeout(() => r(null), DEADLINE_MS); });
|
|
155
|
+
try {
|
|
156
|
+
return (await Promise.race([darwinResolve(socket, deps, deadline, now), cap])) || null;
|
|
157
|
+
} finally { clearTimeout(timer); }
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
module.exports = { resolvePeerChatSession };
|
|
@@ -179,6 +179,12 @@ function validRun(run) {
|
|
|
179
179
|
if (externalRef !== undefined && externalRef !== null && !boundedString(externalRef, 500)) return null;
|
|
180
180
|
const out = { entryId, epicId, slug, kind, at };
|
|
181
181
|
if (typeof externalRef === 'string') out.externalRef = externalRef;
|
|
182
|
+
if (run.caller !== undefined) {
|
|
183
|
+
const { CallerSchema } = require('../epic/scriptStartedBy.cjs');
|
|
184
|
+
const c = CallerSchema.safeParse(run.caller);
|
|
185
|
+
if (c.success) out.caller = c.data;
|
|
186
|
+
}
|
|
187
|
+
if (boundedString(run.fromEpicId, 200)) out.fromEpicId = run.fromEpicId;
|
|
182
188
|
return out;
|
|
183
189
|
}
|
|
184
190
|
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* videoScriptRunRoute.cjs — a project's own script presses Demo Video.
|
|
3
3
|
*
|
|
4
4
|
* POST /admin/project-home/videos/run (body ≤ 64 KiB)
|
|
5
|
-
* { cwd, kind, target?, length?, style?, character?, voiceId?, focus?, reviewFirst?, externalRef
|
|
5
|
+
* { cwd, kind, target?, length?, style?, character?, voiceId?, focus?, reviewFirst?, externalRef?,
|
|
6
|
+
* caller?: { pipeline?, runId?, step?, attempt? } }
|
|
6
7
|
* curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/project-home/videos/run" -H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H 'Content-Type: application/json' -d '{"cwd":"/abs/project","kind":"blog-post","target":"posts/hello.md","externalRef":"post:hello"}'
|
|
7
8
|
*
|
|
8
9
|
* Starts ONE builtin-demo-video job for the cwd through the same renderer
|
|
@@ -10,7 +11,10 @@
|
|
|
10
11
|
* launchSession run 'job'), so persona, checks, review stage and the single
|
|
11
12
|
* mint authority are the human press's own. Checks, in order, each refusal
|
|
12
13
|
* launching nothing:
|
|
13
|
-
* 1. 400 — body/cwd (resolveCwd from projectHomeAdminRoutes.cjs)
|
|
14
|
+
* 1. 400 — body/cwd (resolveCwd from projectHomeAdminRoutes.cjs), or a caller
|
|
15
|
+
* failing CallerSchema (epic/scriptStartedBy.cjs). caller names the script;
|
|
16
|
+
* every press sends startedBy (+ the resolved calling chat) so the minted
|
|
17
|
+
* Epic's source says a script started it; ledger + audit record the caller;
|
|
14
18
|
* 2. 403 scripts_not_allowed — the project's 'Scripts may run Demo Video'
|
|
15
19
|
* switch is off (videoScriptPress.isVideoScriptSwitchOn);
|
|
16
20
|
* 3. 400 — the press choices (videoPressLines.parseScriptPress), a voiceId
|
|
@@ -43,6 +47,7 @@
|
|
|
43
47
|
const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
|
|
44
48
|
const { normalizeExternalRef } = require('../epic/externalRef.cjs');
|
|
45
49
|
const { parseScriptPress, pressLines } = require('./videoPressLines.cjs');
|
|
50
|
+
const { CallerSchema } = require('../epic/scriptStartedBy.cjs');
|
|
46
51
|
|
|
47
52
|
const fs = require('node:fs');
|
|
48
53
|
const path = require('node:path');
|
|
@@ -53,7 +58,7 @@ const MAX_RUN_BODY_BYTES = 64 * 1024;
|
|
|
53
58
|
const MACRO_ID = 'builtin-demo-video';
|
|
54
59
|
const ACTIVE = new Set(['pending', 'held', 'running']);
|
|
55
60
|
const PRESS_KEYS = ['kind', 'target', 'length', 'style', 'character', 'voiceId', 'focus', 'reviewFirst'];
|
|
56
|
-
const ALLOWED_KEYS = new Set(['cwd', 'externalRef', ...PRESS_KEYS]);
|
|
61
|
+
const ALLOWED_KEYS = new Set(['cwd', 'externalRef', 'caller', ...PRESS_KEYS]);
|
|
57
62
|
const SWITCH_REASON = "the 'Scripts may run Demo Video' switch is off for this project; a human turns it on in Project Home > Video";
|
|
58
63
|
|
|
59
64
|
/** cwd -> launch promise; one scripted launch per project at a time. */
|
|
@@ -76,7 +81,7 @@ function launchError(result) {
|
|
|
76
81
|
* listJobRows?: () => Promise<any[]>, resolveCwd?: (c: unknown) => any, videoScriptPress?: any,
|
|
77
82
|
* listVoices?: (cwd: string) => { voices: Array<{ id: string }> }, builtinMacros?: any[],
|
|
78
83
|
* appendAuditEvent?: Function, withExternalRefLock?: Function, now?: () => number,
|
|
79
|
-
* readHistoryTail?: (cwd: string) => Promise<string
|
|
84
|
+
* readHistoryTail?: (cwd: string) => Promise<string>, startedByFromRequest?: Function }} [deps]
|
|
80
85
|
*/
|
|
81
86
|
function registerAdminRoute(adminHttp, deps = {}) {
|
|
82
87
|
const resolveCwd = deps.resolveCwd
|
|
@@ -112,6 +117,13 @@ function registerAdminRoute(adminHttp, deps = {}) {
|
|
|
112
117
|
const unknown = Object.keys(body).find((k) => !ALLOWED_KEYS.has(k));
|
|
113
118
|
if (unknown) return bad(`unknown field: ${unknown}`);
|
|
114
119
|
|
|
120
|
+
let caller;
|
|
121
|
+
if (body.caller !== undefined) {
|
|
122
|
+
const c = CallerSchema.safeParse(body.caller);
|
|
123
|
+
if (!c.success) return bad(`invalid caller: ${c.error.issues.map((i) => `${i.path.join('.') || 'caller'} ${i.message}`).join('; ')}`);
|
|
124
|
+
caller = c.data;
|
|
125
|
+
}
|
|
126
|
+
|
|
115
127
|
const resolved = resolveCwd(body.cwd);
|
|
116
128
|
if (!resolved || !resolved.ok) {
|
|
117
129
|
sendJson(res, resolved?.status || 400, { ok: false, error: oneLine(resolved?.error || 'cwd rejected') });
|
|
@@ -180,6 +192,9 @@ function registerAdminRoute(adminHttp, deps = {}) {
|
|
|
180
192
|
return;
|
|
181
193
|
}
|
|
182
194
|
|
|
195
|
+
const startedByFn = deps.startedByFromRequest
|
|
196
|
+
|| ((/** @type {any} */ a, /** @type {any} */ d) => require('../epic/scriptStartedBy.cjs').startedByFromRequest(a, d));
|
|
197
|
+
const startedBy = await startedByFn({ route: ROUTE_PATH, caller, socket: req.socket }, deps);
|
|
183
198
|
const payload = {
|
|
184
199
|
cwd,
|
|
185
200
|
agentName: macro.agentName,
|
|
@@ -188,6 +203,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
|
|
|
188
203
|
prompt: `${macro.prompt}\n\nAdditional instructions: ${pressLines(cfg).join('\n')}`,
|
|
189
204
|
macroId: MACRO_ID,
|
|
190
205
|
via: 'script',
|
|
206
|
+
startedBy,
|
|
191
207
|
...(cfg.review ? { reviewStage: true } : {}),
|
|
192
208
|
...(externalRef !== undefined ? { externalRef } : {}),
|
|
193
209
|
};
|
|
@@ -220,6 +236,8 @@ function registerAdminRoute(adminHttp, deps = {}) {
|
|
|
220
236
|
kind: cfg.kind,
|
|
221
237
|
at: new Date(now()).toISOString(),
|
|
222
238
|
...(externalRef !== undefined ? { externalRef } : {}),
|
|
239
|
+
...(caller ? { caller } : {}),
|
|
240
|
+
...(startedBy.fromEpicId ? { fromEpicId: startedBy.fromEpicId } : {}),
|
|
223
241
|
});
|
|
224
242
|
} catch (e) {
|
|
225
243
|
recorded = false;
|
|
@@ -230,6 +248,8 @@ function registerAdminRoute(adminHttp, deps = {}) {
|
|
|
230
248
|
route: ROUTE_PATH, cwd, macroId: MACRO_ID, kind: cfg.kind,
|
|
231
249
|
entryId: result.entryId, epicId: result.epicId, slug, stage,
|
|
232
250
|
...(externalRef !== undefined ? { externalRef } : {}),
|
|
251
|
+
...(caller ? { caller } : {}),
|
|
252
|
+
...(startedBy.fromEpicId ? { fromEpicId: startedBy.fromEpicId } : {}),
|
|
233
253
|
});
|
|
234
254
|
} catch { /* audit is best-effort */ }
|
|
235
255
|
sendJson(res, 200, {
|
|
@@ -52,6 +52,8 @@ const EpicSourceSchema = z.object({
|
|
|
52
52
|
// Zod strips undeclared keys on the merge path; a stricter shape could make dropInvalidSessions (ipcSchemas.cjs) drop a whole row holding an older or malformed value.
|
|
53
53
|
proposal: z.unknown().optional(),
|
|
54
54
|
autoApprove: z.unknown().optional(),
|
|
55
|
+
// Script-started Epics: { kind: 'script', route, ... }; absent = a person pressed it. Lenient on load; epic/scriptStartedBy.cjs is the entry-point validator.
|
|
56
|
+
startedBy: z.unknown().optional(),
|
|
55
57
|
// Cross-project thread: replyTo = the asking Epic a reply goes back to
|
|
56
58
|
// ({ cwd, epicId, claudeSessionId }); replyOf = the Epic a reply answers.
|
|
57
59
|
replyTo: z.unknown().optional(),
|
|
@@ -84,7 +84,32 @@ function failingStep(outcome) {
|
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
/**
|
|
87
|
-
*
|
|
87
|
+
* The file part of a failing-test id: before ' > ' (vitest), '::' (pytest) or
|
|
88
|
+
* ':TS' (tsc); the whole id otherwise.
|
|
89
|
+
* @param {string} id
|
|
90
|
+
* @returns {string}
|
|
91
|
+
*/
|
|
92
|
+
function idFilePart(id) {
|
|
93
|
+
for (const sep of [' > ', '::', ':TS']) {
|
|
94
|
+
const i = id.indexOf(sep);
|
|
95
|
+
if (i > 0) return id.slice(0, i).trim();
|
|
96
|
+
}
|
|
97
|
+
return id;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* True when `text` names at least one failing id, or that id's file part.
|
|
102
|
+
* @param {unknown} text
|
|
103
|
+
* @param {string[]} ids
|
|
104
|
+
* @returns {boolean}
|
|
105
|
+
*/
|
|
106
|
+
function reasonNamesFailure(text, ids) {
|
|
107
|
+
if (typeof text !== 'string' || text.length === 0) return false;
|
|
108
|
+
return ids.some((id) => text.includes(id) || text.includes(idFilePart(id)));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, failReason, env })
|
|
88
113
|
* → { complete, reason, preexisting }
|
|
89
114
|
*
|
|
90
115
|
* Checks run in a fixed order; the first failed check is the reason.
|
|
@@ -97,10 +122,13 @@ function failingStep(outcome) {
|
|
|
97
122
|
* @param {boolean} params.ancestorOk - landedCommit is an ancestor of (or equal to) the pre-gate HEAD.
|
|
98
123
|
* @param {boolean} params.cleanOk - tree clean before and after the gate.
|
|
99
124
|
* @param {boolean} params.headStable - HEAD unmoved across the gate.
|
|
125
|
+
* @param {string} [params.failReason] - the run's recorded FAIL reason (verdicts sidecar `reason`).
|
|
126
|
+
* Checked LAST: it must name a HEAD failing id or its file part, else 'fail-not-about-gate' —
|
|
127
|
+
* a FAIL on an outside blocker over an already-red suite is not a success.
|
|
100
128
|
* @param {object} [params.env] - defaults to process.env.
|
|
101
129
|
* @returns {{complete: boolean, reason: string, preexisting: string[]}}
|
|
102
130
|
*/
|
|
103
|
-
function decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, env = process.env } = {}) {
|
|
131
|
+
function decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, failReason, env = process.env } = {}) {
|
|
104
132
|
const no = (reason) => ({ complete: false, reason, preexisting: [] });
|
|
105
133
|
if (env?.SM_BASELINE_GATE_AUTHORITY_DISABLE === '1') return no('kill-switch');
|
|
106
134
|
if (!job || job.status !== 'needs_review' || job.verifierVerdict !== 'sentinel_fail') {
|
|
@@ -122,6 +150,7 @@ function decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, an
|
|
|
122
150
|
if (!headIds || !baseIds) return no('unparseable-output');
|
|
123
151
|
const baseSet = new Set(baseIds);
|
|
124
152
|
if (headIds.some((id) => !baseSet.has(id))) return no('new-failures');
|
|
153
|
+
if (!reasonNamesFailure(failReason, headIds)) return no('fail-not-about-gate');
|
|
125
154
|
return { complete: true, reason: 'baseline-identical', preexisting: headIds };
|
|
126
155
|
}
|
|
127
156
|
|
|
@@ -25,6 +25,76 @@ function errMsg(e) {
|
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
const DECLARED_PREFIX = `${OPS_ROOT_DIR}/${NAMESPACE}/`;
|
|
28
|
+
const CROSS_EPIC_EXISTS = 'exists in another Epic folder; not overwritten';
|
|
29
|
+
const SYMLINKED_PARENT = 'symlinked parent refused';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* refusedParent(chain) → { path, reason } | null
|
|
33
|
+
* lstat-checks each source parent in order (outermost first) without ever
|
|
34
|
+
* following a link. A symlink anywhere in the chain is refused; a missing
|
|
35
|
+
* entry ends the check (nothing below it exists to copy); any other lstat
|
|
36
|
+
* error is refused too, so an unreadable parent never lets a pass through.
|
|
37
|
+
* @param {string[]} chain @param {typeof fs} [fsImpl]
|
|
38
|
+
* @returns {{ path: string, reason: string } | null}
|
|
39
|
+
*/
|
|
40
|
+
function refusedParent(chain, fsImpl = fs) {
|
|
41
|
+
for (const p of chain) {
|
|
42
|
+
let st;
|
|
43
|
+
try {
|
|
44
|
+
st = fsImpl.lstatSync(p);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
if (e && /** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT') return null;
|
|
47
|
+
return { path: p, reason: `cannot check parent: ${errMsg(e)}` };
|
|
48
|
+
}
|
|
49
|
+
if (st.isSymbolicLink()) return { path: p, reason: SYMLINKED_PARENT };
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* destExists(dest) → true when anything (file, folder, symlink — never
|
|
56
|
+
* followed) sits at `dest`. Any lstat error other than ENOENT counts as
|
|
57
|
+
* existing, so an unreadable destination is never overwritten.
|
|
58
|
+
* @param {string} dest @param {typeof fs} [fsImpl]
|
|
59
|
+
*/
|
|
60
|
+
function destExists(dest, fsImpl = fs) {
|
|
61
|
+
try {
|
|
62
|
+
fsImpl.lstatSync(dest);
|
|
63
|
+
return true;
|
|
64
|
+
} catch (e) {
|
|
65
|
+
return !(e && /** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* createExclusive(dest, text, fsImpl) → true when created, false when `dest`
|
|
71
|
+
* already existed (EEXIST). Writes a temp file beside `dest`, then hard-links
|
|
72
|
+
* it into place: link fails with EEXIST rather than overwriting, so create-only
|
|
73
|
+
* is one atomic step with no check-then-write gap. The temp file is always
|
|
74
|
+
* removed. Other errors throw.
|
|
75
|
+
* @param {string} dest @param {string} text @param {any} [fsImpl]
|
|
76
|
+
*/
|
|
77
|
+
function createExclusive(dest, text, fsImpl = fs) {
|
|
78
|
+
const link = fsImpl.linkSync || fs.linkSync;
|
|
79
|
+
const unlink = fsImpl.unlinkSync || fs.unlinkSync;
|
|
80
|
+
const mkdir = fsImpl.mkdirSync || fs.mkdirSync;
|
|
81
|
+
const write = fsImpl.writeFileSync || fs.writeFileSync;
|
|
82
|
+
const dir = path.dirname(dest);
|
|
83
|
+
mkdir(dir, { recursive: true });
|
|
84
|
+
const tmp = path.join(dir, `.${path.basename(dest)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
85
|
+
try {
|
|
86
|
+
write(tmp, text, { encoding: 'utf8', flag: 'wx' });
|
|
87
|
+
try {
|
|
88
|
+
link(tmp, dest);
|
|
89
|
+
} catch (e) {
|
|
90
|
+
if (e && /** @type {NodeJS.ErrnoException} */ (e).code === 'EEXIST') return false;
|
|
91
|
+
throw e;
|
|
92
|
+
}
|
|
93
|
+
return true;
|
|
94
|
+
} finally {
|
|
95
|
+
try { unlink(tmp); } catch { /* already gone */ }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
28
98
|
|
|
29
99
|
/**
|
|
30
100
|
* parseDeclaredPath(p) → { folder, name } | { reason }
|
|
@@ -53,8 +123,9 @@ function parseDeclaredPath(p) {
|
|
|
53
123
|
* → { copied: string[], skipped: { path, reason }[] }
|
|
54
124
|
* Copies every record in the job's own `plan-records/<epicId>/` folder, plus
|
|
55
125
|
* each well-formed `declaredPaths` entry (the PRD's frontmatter
|
|
56
|
-
* artifactPaths), whose folder may be a different Epic's
|
|
57
|
-
* destination
|
|
126
|
+
* artifactPaths), whose folder may be a different Epic's — create-only there:
|
|
127
|
+
* an existing destination in another Epic's folder is never overwritten.
|
|
128
|
+
* `copied` holds destination absolute paths.
|
|
58
129
|
*/
|
|
59
130
|
function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths = [], fsImpl = fs } = {}) {
|
|
60
131
|
/** @type {string[]} */
|
|
@@ -70,8 +141,10 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths =
|
|
|
70
141
|
* set and the source does not exist (reported with that reason).
|
|
71
142
|
* @param {string} src @param {string} folder @param {string} name
|
|
72
143
|
* @param {string} [missingReason]
|
|
144
|
+
* @param {boolean} [createOnly] another Epic's folder: never overwrite an
|
|
145
|
+
* existing destination (checked with lstat, so a symlink counts as existing)
|
|
73
146
|
*/
|
|
74
|
-
function copyOne(src, folder, name, missingReason) {
|
|
147
|
+
function copyOne(src, folder, name, missingReason, createOnly = false) {
|
|
75
148
|
seen.add(src);
|
|
76
149
|
try {
|
|
77
150
|
if (!NAME_RE.test(name)) { skipped.push({ path: src, reason: 'name not allowed' }); return; }
|
|
@@ -97,6 +170,11 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths =
|
|
|
97
170
|
|
|
98
171
|
const text = fsImpl.readFileSync(src, 'utf8');
|
|
99
172
|
if (Buffer.byteLength(text, 'utf8') > MAX_BYTES) { skipped.push({ path: src, reason: 'oversize after read' }); return; }
|
|
173
|
+
if (createOnly) {
|
|
174
|
+
if (!createExclusive(dest, text, fsImpl)) { skipped.push({ path: src, reason: CROSS_EPIC_EXISTS }); return; }
|
|
175
|
+
copied.push(dest);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
100
178
|
writeTextAtomicSync(dest, text);
|
|
101
179
|
copied.push(dest);
|
|
102
180
|
} catch (e) {
|
|
@@ -105,10 +183,10 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths =
|
|
|
105
183
|
}
|
|
106
184
|
|
|
107
185
|
try {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
}
|
|
186
|
+
// An unsafe epicId only disqualifies pass 1 (the job's own folder); each
|
|
187
|
+
// declared path is validated on its own in pass 2.
|
|
188
|
+
const ownFolderSafe = typeof epicId === 'string' && EPIC_ID_RE.test(epicId);
|
|
189
|
+
if (!ownFolderSafe) skipped.push({ path: String(epicId), reason: 'unsafe epicId' });
|
|
112
190
|
if (typeof worktreeDir !== 'string' || !path.isAbsolute(worktreeDir)
|
|
113
191
|
|| typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) {
|
|
114
192
|
skipped.push({ path: String(worktreeDir), reason: 'worktreeDir and projectRoot must be absolute paths' });
|
|
@@ -116,10 +194,13 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths =
|
|
|
116
194
|
}
|
|
117
195
|
if (path.resolve(worktreeDir) === path.resolve(projectRoot)) return { copied, skipped };
|
|
118
196
|
const wtRoot = path.resolve(worktreeDir);
|
|
197
|
+
const opsSrc = path.join(wtRoot, OPS_ROOT_DIR);
|
|
198
|
+
const recordsSrc = path.join(opsSrc, NAMESPACE);
|
|
119
199
|
|
|
120
200
|
// Pass 1: everything in the job's own plan-records/<epicId>/ folder.
|
|
121
201
|
folderPass: {
|
|
122
|
-
|
|
202
|
+
if (!ownFolderSafe) break folderPass;
|
|
203
|
+
const srcDir = path.join(recordsSrc, epicId);
|
|
123
204
|
let destDir;
|
|
124
205
|
try {
|
|
125
206
|
destDir = path.resolve(opsPath(projectRoot, NAMESPACE, epicId));
|
|
@@ -128,6 +209,10 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths =
|
|
|
128
209
|
break folderPass;
|
|
129
210
|
}
|
|
130
211
|
if (destDir === srcDir) break folderPass;
|
|
212
|
+
// Never read through a symlinked session-manager-operations/,
|
|
213
|
+
// plan-records/ or epic folder: it could point outside the worktree.
|
|
214
|
+
const refused = refusedParent([opsSrc, recordsSrc, srcDir], fsImpl);
|
|
215
|
+
if (refused) { skipped.push(refused); break folderPass; }
|
|
131
216
|
let srcStat;
|
|
132
217
|
try {
|
|
133
218
|
srcStat = fsImpl.lstatSync(srcDir);
|
|
@@ -150,22 +235,29 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths =
|
|
|
150
235
|
|
|
151
236
|
// Pass 2: records the PRD declared in frontmatter artifactPaths.
|
|
152
237
|
const declared = Array.isArray(declaredPaths) ? declaredPaths : [];
|
|
153
|
-
|
|
238
|
+
// The shared parents are checked once; a symlink there refuses the pass.
|
|
239
|
+
const sharedRefused = declared.length ? refusedParent([opsSrc, recordsSrc], fsImpl) : null;
|
|
240
|
+
if (sharedRefused) skipped.push(sharedRefused);
|
|
241
|
+
for (const p of sharedRefused ? [] : declared) {
|
|
154
242
|
const parsed = parseDeclaredPath(p);
|
|
155
243
|
if (!('folder' in parsed)) { skipped.push({ path: String(p), reason: parsed.reason }); continue; }
|
|
156
|
-
const src = path.join(
|
|
244
|
+
const src = path.join(recordsSrc, parsed.folder, parsed.name);
|
|
157
245
|
if (seen.has(src)) continue;
|
|
158
246
|
// Pass 1 refuses a symlinked/non-directory own folder; hold every
|
|
159
247
|
// declared folder to the same rule so a declaration cannot bypass it.
|
|
160
248
|
const folderDir = path.dirname(src);
|
|
249
|
+
const folderRefused = refusedParent([folderDir], fsImpl);
|
|
250
|
+
if (folderRefused) { seen.add(src); skipped.push(folderRefused); continue; }
|
|
161
251
|
let folderStat = null;
|
|
162
252
|
try { folderStat = fsImpl.lstatSync(folderDir); } catch { /* missing: copyOne reports */ }
|
|
163
|
-
if (folderStat && (
|
|
253
|
+
if (folderStat && (!folderStat.isDirectory())) {
|
|
164
254
|
seen.add(src);
|
|
165
255
|
skipped.push({ path: src, reason: 'declared epic folder is not a directory' });
|
|
166
256
|
continue;
|
|
167
257
|
}
|
|
168
|
-
|
|
258
|
+
// Another Epic's folder is create-only: a job may add a record there
|
|
259
|
+
// (a validator writing into the Epic it validates) but never overwrite one.
|
|
260
|
+
copyOne(src, parsed.folder, parsed.name, 'declared plan record not found in worktree', parsed.folder !== epicId);
|
|
169
261
|
}
|
|
170
262
|
} catch (e) {
|
|
171
263
|
skipped.push({ path: String(worktreeDir), reason: `harvest failed: ${errMsg(e)}` });
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* planReleaseRoute.cjs — POST /admin/scheduler/release-plan: the planner's one
|
|
3
|
+
* call that releases a plan held for independent review.
|
|
4
|
+
*
|
|
5
|
+
* body { cwd, epicId, validateSlug, rejected: [{ finding, reason }],
|
|
6
|
+
* accepted: number, rereview?: boolean }
|
|
7
|
+
*
|
|
8
|
+
* - release: records plan-records/<epic>/<slug>.plan-review.json release
|
|
9
|
+
* { by: 'planner', rejected, accepted }. A second call → 200 alreadyReleased.
|
|
10
|
+
* Every rejected entry needs a non-empty one-line reason (400 otherwise).
|
|
11
|
+
* - rereview: true instead asks for ONE more review after a block. Accepted
|
|
12
|
+
* only when the latest review has a `block` decision and round is 1 and the
|
|
13
|
+
* plan is not released; writes rereviewRequested: true, else 400 + reason.
|
|
14
|
+
* - cwd must be an existing absolute project root outside session-manager-operations/ → else 400 bad_cwd.
|
|
15
|
+
* - unsafe epicId / validateSlug → 400.
|
|
16
|
+
*/
|
|
17
|
+
'use strict';
|
|
18
|
+
|
|
19
|
+
const { z } = require('zod');
|
|
20
|
+
const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
|
|
21
|
+
const { planReviewPath, readPlanReview, recordPlanRelease } = require('./planReviewStore.cjs');
|
|
22
|
+
const fs = require('node:fs');
|
|
23
|
+
const { assertOpsWrite, resolveProjectRoot } = require('../opsOwnership.cjs');
|
|
24
|
+
const { writeJsonAtomic } = require('../util/atomicFs.cjs');
|
|
25
|
+
const { EPIC_ID_RE } = require('./planRecordHarvest.cjs');
|
|
26
|
+
|
|
27
|
+
const MAX_BODY_BYTES = 256 * 1024;
|
|
28
|
+
const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
29
|
+
|
|
30
|
+
const bodySchema = z.object({
|
|
31
|
+
cwd: z.string().min(1),
|
|
32
|
+
epicId: z.string(),
|
|
33
|
+
validateSlug: z.string(),
|
|
34
|
+
rejected: z.array(z.object({ finding: z.string(), reason: z.string() })).optional().default([]),
|
|
35
|
+
accepted: z.number().finite().min(0).optional().default(0),
|
|
36
|
+
rereview: z.boolean().optional(),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/** @param {any} record */
|
|
40
|
+
function latestHasBlock(record) {
|
|
41
|
+
const reviews = record && Array.isArray(record.reviews) ? record.reviews : [];
|
|
42
|
+
const last = reviews[reviews.length - 1];
|
|
43
|
+
const prds = last && last.review && Array.isArray(last.review.prds) ? last.review.prds : [];
|
|
44
|
+
return prds.some((/** @type {any} */ p) => p && p.decision === 'block');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param {{ registerRoute: Function }} adminHttp */
|
|
48
|
+
function registerPlanReleaseRoute(adminHttp) {
|
|
49
|
+
adminHttp.registerRoute('POST', '/admin/scheduler/release-plan', async (/** @type {any} */ req, /** @type {any} */ res) => {
|
|
50
|
+
const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
|
|
51
|
+
let raw;
|
|
52
|
+
try { raw = await readBody(req, MAX_BODY_BYTES); } catch (e) {
|
|
53
|
+
bad(e instanceof Error ? e.message : String(e));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let json;
|
|
57
|
+
try { json = JSON.parse(raw || '{}'); } catch { bad('body is not valid JSON'); return; }
|
|
58
|
+
const parsed = bodySchema.safeParse(json);
|
|
59
|
+
if (!parsed.success) { bad(parsed.error.issues); return; }
|
|
60
|
+
const { epicId, validateSlug, rejected, accepted, rereview } = parsed.data;
|
|
61
|
+
/** @type {string} */
|
|
62
|
+
let cwd;
|
|
63
|
+
try {
|
|
64
|
+
cwd = resolveProjectRoot(parsed.data.cwd, { opsInternal: 'refuse' });
|
|
65
|
+
if (!fs.statSync(cwd).isDirectory()) throw new Error('not a directory');
|
|
66
|
+
} catch {
|
|
67
|
+
sendJson(res, 400, { ok: false, error: 'bad_cwd' });
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (!EPIC_ID_RE.test(epicId) || !SLUG_RE.test(validateSlug) || validateSlug.includes('..')) {
|
|
71
|
+
bad('unsafe epicId or validateSlug');
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const prior = readPlanReview(cwd, epicId, validateSlug);
|
|
76
|
+
|
|
77
|
+
if (rereview) {
|
|
78
|
+
let reason = null;
|
|
79
|
+
if (!prior || !Array.isArray(prior.reviews) || prior.reviews.length === 0) reason = 'no review on record for this plan';
|
|
80
|
+
else if (prior.release) reason = 'the plan is already released';
|
|
81
|
+
else if (!latestHasBlock(prior)) reason = 'the latest review has no block decision';
|
|
82
|
+
else if (prior.round !== 1) reason = `a re-review is allowed once per plan; the plan is at round ${prior.round}`;
|
|
83
|
+
else if (prior.rereviewRequested) reason = 're-review was already requested';
|
|
84
|
+
if (reason) { sendJson(res, 400, { ok: false, error: 'rereview_refused', reason }); return; }
|
|
85
|
+
const file = planReviewPath(cwd, epicId, validateSlug);
|
|
86
|
+
assertOpsWrite(file, 'scheduler');
|
|
87
|
+
await writeJsonAtomic(file, { ...prior, rereviewRequested: true });
|
|
88
|
+
sendJson(res, 200, { ok: true, rereviewRequested: true });
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const missing = rejected.findIndex((r) => !r.reason.trim());
|
|
93
|
+
if (missing !== -1) {
|
|
94
|
+
sendJson(res, 400, { ok: false, error: 'reason_required', reason: `rejected[${missing}] needs a non-empty one-line reason` });
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const out = await recordPlanRelease({
|
|
98
|
+
cwd, epicId, validateSlug, by: 'planner',
|
|
99
|
+
rejected: rejected.map((r) => ({ finding: r.finding, reason: r.reason.trim() })),
|
|
100
|
+
accepted,
|
|
101
|
+
});
|
|
102
|
+
if (out && out.alreadyReleased) { sendJson(res, 200, { ok: true, alreadyReleased: true }); return; }
|
|
103
|
+
sendJson(res, 200, { ok: true, released: true, accepted, rejected: rejected.length });
|
|
104
|
+
} catch (e) {
|
|
105
|
+
sendJson(res, 500, { ok: false, error: 'release_failed', details: e instanceof Error ? e.message : String(e) });
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
module.exports = { registerPlanReleaseRoute };
|