claude-code-session-manager 0.142.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.
Files changed (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -0,0 +1,173 @@
1
+ /**
2
+ * videoScriptSwitchRoute.cjs — the agent path for 'Scripts may run Demo Video'.
3
+ *
4
+ * POST /admin/project-home/videos/script-switch (body ≤ 64 KiB)
5
+ * { enabled, humanRequestQuote, originClaudeSessionId, cwd?, originProjectRoot? }
6
+ * Sets ONE project's switch on or off, and only on a verbatim quote of what
7
+ * the human typed in the calling chat session (humanPromptLedger). Checks,
8
+ * in order, each refusal writing and auditing nothing:
9
+ * 1. 403 human_request_unverified — the quote is not in a prompt the
10
+ * human typed in originClaudeSessionId (the ledger is the only proof);
11
+ * 2. 403 quote_does_not_name_switch — the quote does not say
12
+ * 'Scripts may run Demo Video' (quoteNamesVideoScriptSwitch);
13
+ * 3. 403 quote_does_not_name_project — the target is not the calling
14
+ * session's own project and the quote does not name it
15
+ * (crossProjectFeedback.quoteNamesTarget);
16
+ * 4. 409 request_older_than_switch — the matched prompt is not later
17
+ * than the switch's last change: one human instruction authorizes one
18
+ * write, and never undoes a later click.
19
+ * Success: videoScriptPress.setVideoScriptSwitch(target, enabled, { via:'agent',
20
+ * claudeSessionId, quote, promptAt }), one video_script_switch_changed audit
21
+ * event, 200 { ok, cwd, enabled, changedAt, by, previous }.
22
+ * Setting the value the switch already has re-stamps the attribution.
23
+ *
24
+ * Same shape as lib/tasks/taskSwitchRoute.cjs, minus the held-slot resync
25
+ * (that is Task-only). Scripts, scheduled jobs and Tasks cannot reach this:
26
+ * their prompts are never recorded in humanPromptLedger (only the Chat view
27
+ * records them). Registered by adminRouteRegistry.cjs.
28
+ */
29
+ 'use strict';
30
+
31
+ const path = require('node:path');
32
+ const { z } = require('zod');
33
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
34
+
35
+ const ROUTE_PATH = '/admin/project-home/videos/script-switch';
36
+ const MAX_SWITCH_BODY_BYTES = 64 * 1024;
37
+
38
+ const switchBodySchema = z.object({
39
+ enabled: z.boolean(),
40
+ humanRequestQuote: z.string().min(1).max(2000),
41
+ originClaudeSessionId: z.string().min(1).max(128),
42
+ cwd: z.string().min(1).optional(),
43
+ originProjectRoot: z.string().min(1).optional(),
44
+ }).strict();
45
+
46
+ const SWITCH_RE = /(^|[^a-z0-9])scripts?\s+(may|can)\s+run\s+demo\s+videos?($|[^a-z0-9])/;
47
+
48
+ /** True when the quote names the 'Scripts may run Demo Video' switch (case, quote-mark, hyphen variants; 'can' for 'may'). */
49
+ function quoteNamesVideoScriptSwitch(quote) {
50
+ if (typeof quote !== 'string') return false;
51
+ const q = quote
52
+ .toLowerCase()
53
+ .replace(/[-_'"‘’‚‛“”„‟′″`]/g, ' ')
54
+ .replace(/\s+/g, ' ');
55
+ return SWITCH_RE.test(q);
56
+ }
57
+
58
+ /**
59
+ * @param {{ registerRoute: Function }} adminHttp
60
+ * @param {{ findHumanPromptContaining?: Function, resolveProjectContext?: Function,
61
+ * resolveProjectRoot?: Function, videoScriptPress?: any, appendAuditEvent?: Function,
62
+ * quoteNamesTarget?: Function, now?: () => number }} [deps]
63
+ */
64
+ function registerVideoScriptSwitchRoute(adminHttp, deps = {}) {
65
+ const findPrompt = deps.findHumanPromptContaining
66
+ || ((/** @type {string} */ s, /** @type {string} */ q, /** @type {number} */ n) => require('../feedback-remote/humanPromptLedger.cjs').findHumanPromptContaining(s, q, n));
67
+ const resolveContext = deps.resolveProjectContext
68
+ || ((/** @type {any} */ o) => require('../projectRootResolve.cjs').resolveProjectContext(o));
69
+ const projectRoot = deps.resolveProjectRoot
70
+ || ((/** @type {string} */ c, /** @type {any} */ o) => require('../opsOwnership.cjs').resolveProjectRoot(c, o));
71
+ const store = () => deps.videoScriptPress || require('./videoScriptPress.cjs');
72
+ const audit = deps.appendAuditEvent
73
+ || ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
74
+ const namesTarget = deps.quoteNamesTarget
75
+ || ((/** @type {string} */ q, /** @type {string} */ c) => require('../feedback-remote/crossProjectFeedback.cjs').quoteNamesTarget(q, c));
76
+ const now = deps.now || Date.now;
77
+
78
+ adminHttp.registerRoute('POST', ROUTE_PATH, async (/** @type {any} */ req, /** @type {any} */ res) => {
79
+ const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
80
+ const refuse = (/** @type {number} */ status, /** @type {string} */ error, /** @type {string} */ reason) =>
81
+ sendJson(res, status, { ok: false, error, reason });
82
+
83
+ let raw;
84
+ try {
85
+ raw = await readBody(req, MAX_SWITCH_BODY_BYTES);
86
+ } catch (e) {
87
+ bad(e instanceof Error ? e.message : String(e));
88
+ return;
89
+ }
90
+ let json;
91
+ try { json = JSON.parse(raw || '{}'); } catch {
92
+ bad('body is not valid JSON');
93
+ return;
94
+ }
95
+ const parsed = switchBodySchema.safeParse(json);
96
+ if (!parsed.success) {
97
+ bad(parsed.error.issues);
98
+ return;
99
+ }
100
+ const { enabled, humanRequestQuote: quote, originClaudeSessionId, cwd: rawCwd, originProjectRoot } = parsed.data;
101
+
102
+ // The calling session's own project.
103
+ let origin = null;
104
+ try {
105
+ const ctx = resolveContext({ originClaudeSessionId, originProjectRoot });
106
+ const o = ctx && (ctx.epicCwd || ctx.cwd);
107
+ if (typeof o === 'string' && o) origin = path.resolve(o);
108
+ } catch { origin = null; }
109
+
110
+ let target = origin;
111
+ if (rawCwd !== undefined) {
112
+ try {
113
+ const root = projectRoot(rawCwd, { opsInternal: 'refuse' });
114
+ if (path.resolve(root) !== path.resolve(rawCwd)) throw new Error(`cwd is not a project root (its root is "${root}")`);
115
+ target = path.resolve(root);
116
+ } catch (e) {
117
+ bad(e instanceof Error ? e.message : String(e));
118
+ return;
119
+ }
120
+ }
121
+ if (!target) {
122
+ bad('no target project: pass cwd, or call from a Session Manager chat session whose project can be resolved');
123
+ return;
124
+ }
125
+
126
+ const found = findPrompt(originClaudeSessionId, quote, now());
127
+ if (!found) {
128
+ refuse(403, 'human_request_unverified', 'humanRequestQuote was not found in a prompt the human typed in this chat session');
129
+ return;
130
+ }
131
+ if (!quoteNamesVideoScriptSwitch(quote)) {
132
+ refuse(403, 'quote_does_not_name_switch', "the human's quote does not name the 'Scripts may run Demo Video' switch");
133
+ return;
134
+ }
135
+ if (target !== origin && !namesTarget(quote, target)) {
136
+ refuse(403, 'quote_does_not_name_project', `the target is not this session's project and the human's quote does not name it (${path.basename(target)})`);
137
+ return;
138
+ }
139
+ const current = store().getVideoScriptSwitch(target);
140
+ const promptMs = Number(found.at);
141
+ const changedMs = current && current.changedAt ? Date.parse(current.changedAt) : NaN;
142
+ if (!Number.isFinite(promptMs) || (Number.isFinite(changedMs) && !(promptMs > changedMs))) {
143
+ refuse(409, 'request_older_than_switch', "the human's request is not newer than the switch's last change; ask the human again");
144
+ return;
145
+ }
146
+
147
+ const promptAt = new Date(promptMs).toISOString();
148
+ let saved;
149
+ try {
150
+ saved = store().setVideoScriptSwitch(target, enabled, { via: 'agent', claudeSessionId: originClaudeSessionId, quote, promptAt });
151
+ } catch (e) {
152
+ sendJson(res, 500, { ok: false, error: 'switch_write_failed', details: e instanceof Error ? e.message : String(e) });
153
+ return;
154
+ }
155
+ try {
156
+ audit('video_script_switch_changed', { cwd: saved.cwd, enabled: saved.enabled, via: 'agent', claudeSessionId: originClaudeSessionId, quote });
157
+ } catch { /* audit is best-effort, like the Task switch route */ }
158
+
159
+ sendJson(res, 200, {
160
+ ok: true,
161
+ cwd: saved.cwd,
162
+ enabled: saved.enabled,
163
+ changedAt: saved.changedAt,
164
+ by: saved.by,
165
+ previous: {
166
+ enabled: !!(current && current.enabled),
167
+ by: current ? current.by : null,
168
+ },
169
+ });
170
+ });
171
+ }
172
+
173
+ module.exports = { registerVideoScriptSwitchRoute, quoteNamesVideoScriptSwitch, MAX_SWITCH_BODY_BYTES, ROUTE_PATH };
@@ -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
- * decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, env })
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
 
@@ -12,7 +12,24 @@
12
12
  * a path that escapes `cwd` fails closed.
13
13
  * - http: loopback hosts only (re-checked here, never trusted from the
14
14
  * frontmatter), no redirects followed, HTTP_TIMEOUT_MS timeout; ok when
15
- * the response status equals the expected one (default 200).
15
+ * the response status equals the expected one (default 200) and, when
16
+ * `contains` is set, the first HTTP_BODY_MAX_BYTES of the body include it.
17
+ * With keepBody, each http row also carries { body, bodyBytes, truncated }
18
+ * (body capped at HTTP_BODY_MAX_BYTES); without it rows never hold a body.
19
+ * - httpRetry (opt-in, { attempts?, delayMs?, sleep? }): a dev server that is
20
+ * mid-reload refuses or 404s for a moment, so after the first in-order pass
21
+ * every http row that failed AFTER its request was sent (request/response
22
+ * error, timeout, status mismatch, contains miss) is re-run in order after
23
+ * ONE sleep(delayMs) per round, until none fail or `attempts` is reached
24
+ * (default HTTP_RETRY_ATTEMPTS = 3, clamped 1..3; delayMs default
25
+ * HTTP_RETRY_DELAY_MS). A re-run replaces the row in place (ok, detail and,
26
+ * with keepBody, the body fields). NEVER retried: spec refusals (invalid
27
+ * URL, non-http(s) protocol, non-loopback host, credentials in the URL) and
28
+ * file / command / manual rows. With httpRetry every http row carries
29
+ * `attempts` (1..3; a refusal is 1); without it no row has that key.
30
+ * Worst case per runCriteriaChecks call: each http check at most 3 attempts
31
+ * of at most HTTP_TIMEOUT_MS (15 s) each, plus at most 2 waits of delayMs
32
+ * shared by the whole call (not per check).
16
33
  * - manual: never run — ok: null; detail carries the guidance line.
17
34
  *
18
35
  * Never throws: every failure becomes { ok: false, detail }. Checks run
@@ -27,8 +44,11 @@ const { parseChain, runIsolatedSequence } = require('./definitionOfDone.cjs');
27
44
 
28
45
  const COMMAND_CAP_MS = 300_000;
29
46
  const HTTP_TIMEOUT_MS = 15_000;
47
+ const HTTP_BODY_MAX_BYTES = 1024 * 1024;
30
48
  const FILE_READ_MAX_BYTES = 16 * 1024 * 1024;
31
49
  const DETAIL_MAX_CHARS = 500;
50
+ const HTTP_RETRY_ATTEMPTS = 3;
51
+ const HTTP_RETRY_DELAY_MS = 10_000;
32
52
  const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
33
53
 
34
54
  /** @param {string} s */
@@ -90,27 +110,35 @@ function runFileCheck(spec, cwd) {
90
110
  : { ok: false, detail: `${rel} does not contain ${JSON.stringify(obj.contains)}` };
91
111
  }
92
112
 
113
+ /**
114
+ * refused: internal marker for a spec refusal (never sent, never retried); never copied onto a row.
115
+ * @typedef {{ok: boolean, detail: string, body?: string, bodyBytes?: number, truncated?: boolean, refused?: boolean}} HttpResult
116
+ */
117
+
93
118
  /**
94
119
  * @param {unknown} spec
95
120
  * @param {number} timeoutMs
96
- * @returns {Promise<{ok: boolean, detail: string}>}
121
+ * @param {boolean} [keepBody] attach { body, bodyBytes, truncated } to the result
122
+ * @returns {Promise<HttpResult>}
97
123
  */
98
- function runHttpCheck(spec, timeoutMs) {
99
- /** @type {{url?: unknown, status?: unknown}} */
124
+ function runHttpCheck(spec, timeoutMs, keepBody = false) {
125
+ /** @type {{url?: unknown, status?: unknown, contains?: unknown}} */
100
126
  const obj = typeof spec === 'string' ? { url: spec } : (spec && typeof spec === 'object' ? /** @type {any} */ (spec) : {});
101
127
  let url;
102
- try { url = new URL(String(obj.url)); } catch { return Promise.resolve({ ok: false, detail: 'http check url is not a valid URL' }); }
128
+ try { url = new URL(String(obj.url)); } catch { return Promise.resolve({ ok: false, detail: 'http check url is not a valid URL', refused: true }); }
103
129
  if (url.protocol !== 'http:' && url.protocol !== 'https:') {
104
- return Promise.resolve({ ok: false, detail: `refused: protocol ${url.protocol} (http/https only)` });
130
+ return Promise.resolve({ ok: false, detail: `refused: protocol ${url.protocol} (http/https only)`, refused: true });
105
131
  }
106
132
  if (!LOOPBACK_HOSTS.has(url.hostname) || url.username || url.password) {
107
- return Promise.resolve({ ok: false, detail: `refused: host "${url.hostname}" is not loopback` });
133
+ return Promise.resolve({ ok: false, detail: `refused: host "${url.hostname}" is not loopback`, refused: true });
108
134
  }
109
135
  const want = Number.isInteger(obj.status) ? /** @type {number} */ (obj.status) : 200;
136
+ const contains = typeof obj.contains === 'string' && obj.contains !== '' ? obj.contains : null;
137
+ const readBody = contains !== null || keepBody;
110
138
  const lib = url.protocol === 'https:' ? https : http;
111
139
  return new Promise((resolve) => {
112
140
  let done = false;
113
- /** @param {{ok: boolean, detail: string}} r */
141
+ /** @param {HttpResult} r */
114
142
  const finish = (r) => { if (!done) { done = true; clearTimeout(timer); resolve(r); } };
115
143
  /** @type {import('node:http').ClientRequest} */
116
144
  let req;
@@ -121,11 +149,48 @@ function runHttpCheck(spec, timeoutMs) {
121
149
  try {
122
150
  // Self-signed certs are normal on a loopback dev server.
123
151
  req = lib.request(url, { method: 'GET', ...(lib === https ? { rejectUnauthorized: false } : {}) }, (res) => {
124
- res.resume();
125
152
  const got = res.statusCode;
126
- finish(got === want
127
- ? { ok: true, detail: `HTTP ${got}` }
128
- : { ok: false, detail: `HTTP ${got}, expected ${want}` });
153
+ if (!readBody) {
154
+ res.resume();
155
+ finish(got === want
156
+ ? { ok: true, detail: `HTTP ${got}` }
157
+ : { ok: false, detail: `HTTP ${got}, expected ${want}` });
158
+ return;
159
+ }
160
+ /** @type {Buffer[]} */
161
+ const chunks = [];
162
+ let bytes = 0;
163
+ let truncated = false;
164
+ let settled = false;
165
+ const decide = () => {
166
+ if (settled) return;
167
+ settled = true;
168
+ const buf = Buffer.concat(chunks, bytes);
169
+ const text = buf.toString('utf8');
170
+ /** @type {HttpResult} */
171
+ let r;
172
+ if (got !== want) r = { ok: false, detail: `HTTP ${got}, expected ${want}` };
173
+ else if (contains === null) r = { ok: true, detail: `HTTP ${got}` };
174
+ else if (text.includes(contains)) r = { ok: true, detail: `HTTP ${got}, body contains the text` };
175
+ else r = { ok: false, detail: clip(`HTTP ${got}, body does not contain ${JSON.stringify(contains)}`) };
176
+ if (keepBody) Object.assign(r, { body: text, bodyBytes: bytes, truncated });
177
+ finish(r);
178
+ };
179
+ res.on('data', (/** @type {Buffer} */ chunk) => {
180
+ if (settled) return;
181
+ const room = HTTP_BODY_MAX_BYTES - bytes;
182
+ if (chunk.length > room) {
183
+ if (room > 0) { chunks.push(chunk.subarray(0, room)); bytes += room; }
184
+ truncated = true;
185
+ decide();
186
+ res.destroy();
187
+ return;
188
+ }
189
+ chunks.push(chunk);
190
+ bytes += chunk.length;
191
+ });
192
+ res.on('end', decide);
193
+ res.on('error', (e) => finish({ ok: false, detail: `response failed: ${e && e.message ? e.message : e}` }));
129
194
  });
130
195
  req.on('error', (e) => finish({ ok: false, detail: `request failed: ${e && e.message ? e.message : e}` }));
131
196
  req.end();
@@ -135,35 +200,114 @@ function runHttpCheck(spec, timeoutMs) {
135
200
  });
136
201
  }
137
202
 
203
+ /**
204
+ * @typedef {{id: string, kind: string, ok: boolean|null, detail: string, body?: string, bodyBytes?: number, truncated?: boolean, attempts?: number}} CheckRow
205
+ * @typedef {{ attempts?: number, delayMs?: number, sleep?: (ms: number) => Promise<void> }} HttpRetry
206
+ */
207
+
208
+ /**
209
+ * @param {string} id
210
+ * @param {string} kind
211
+ * @param {{ok: boolean|null, detail: string, body?: string, bodyBytes?: number, truncated?: boolean}} r
212
+ * @param {boolean} keepBody
213
+ * @returns {CheckRow}
214
+ */
215
+ function toRow(id, kind, r, keepBody) {
216
+ /** @type {CheckRow} */
217
+ const row = { id, kind, ok: r.ok, detail: r.detail };
218
+ if (keepBody && kind === 'http' && typeof r.body === 'string') {
219
+ row.body = r.body;
220
+ row.bodyBytes = r.bodyBytes;
221
+ row.truncated = r.truncated;
222
+ }
223
+ return row;
224
+ }
225
+
226
+ /** @param {unknown} e */
227
+ function errDetail(e) {
228
+ return `check error: ${e && /** @type {Error} */ (e).message ? /** @type {Error} */ (e).message : e}`;
229
+ }
230
+
231
+ /**
232
+ * @param {HttpRetry} httpRetry
233
+ * @returns {{attempts: number, delayMs: number, sleep: (ms: number) => Promise<void>}}
234
+ */
235
+ function normalizeRetry(httpRetry) {
236
+ const a = httpRetry.attempts;
237
+ const attempts = typeof a === 'number' && Number.isInteger(a)
238
+ ? Math.min(HTTP_RETRY_ATTEMPTS, Math.max(1, a))
239
+ : HTTP_RETRY_ATTEMPTS;
240
+ const d = httpRetry.delayMs;
241
+ const delayMs = typeof d === 'number' && Number.isFinite(d) && d >= 0 ? d : HTTP_RETRY_DELAY_MS;
242
+ const sleep = typeof httpRetry.sleep === 'function'
243
+ ? httpRetry.sleep
244
+ : (/** @type {number} */ ms) => new Promise((r) => setTimeout(r, ms));
245
+ return { attempts, delayMs, sleep: /** @type {(ms: number) => Promise<void>} */ (sleep) };
246
+ }
247
+
138
248
  /**
139
249
  * Run every criterion's check in `cwd`, in order.
140
250
  *
141
- * @param {{ criteria: unknown, cwd: string, commandCapMs?: number, httpTimeoutMs?: number }} opts
251
+ * @param {{ criteria: unknown, cwd: string, commandCapMs?: number, httpTimeoutMs?: number, keepBody?: boolean, httpRetry?: HttpRetry }} opts
142
252
  * commandCapMs / httpTimeoutMs exist for tests; callers use the defaults.
143
- * @returns {Promise<Array<{id: string, kind: string, ok: boolean|null, detail: string}>>}
253
+ * keepBody (default false): http rows also carry { body, bodyBytes, truncated };
254
+ * off, every row is exactly { id, kind, ok, detail } (gate shadow + job row store no body).
255
+ * httpRetry (default off): re-run failed-after-sent http checks (see header);
256
+ * http rows then also carry `attempts`.
257
+ * @returns {Promise<CheckRow[]>}
144
258
  */
145
- async function runCriteriaChecks({ criteria, cwd, commandCapMs = COMMAND_CAP_MS, httpTimeoutMs = HTTP_TIMEOUT_MS }) {
259
+ async function runCriteriaChecks({ criteria, cwd, commandCapMs = COMMAND_CAP_MS, httpTimeoutMs = HTTP_TIMEOUT_MS, keepBody = false, httpRetry }) {
146
260
  if (!Array.isArray(criteria) || !criteria.length) return [];
261
+ const keep = keepBody === true;
262
+ /** @type {CheckRow[]} */
147
263
  const out = [];
264
+ /** @type {Array<{spec: unknown, retryable: boolean} | null>} per-index http state */
265
+ const httpState = [];
148
266
  for (let i = 0; i < criteria.length; i++) {
149
267
  const c = criteria[i];
150
268
  const id = c && typeof c.id === 'string' ? c.id : `ac-${i + 1}`;
151
269
  const check = c && c.check && typeof c.check === 'object' ? c.check : { kind: 'manual' };
152
270
  const kind = typeof check.kind === 'string' ? check.kind : 'manual';
153
- /** @type {{ok: boolean|null, detail: string}} */
271
+ /** @type {{ok: boolean|null, detail: string, body?: string, bodyBytes?: number, truncated?: boolean, refused?: boolean}} */
154
272
  let r;
155
273
  try {
156
274
  if (kind === 'manual') r = { ok: null, detail: typeof check.spec === 'string' && check.spec ? check.spec : 'manual check' };
157
275
  else if (kind === 'command') r = await runCommandCheck(check.spec, commandCapMs, cwd);
158
276
  else if (kind === 'file') r = runFileCheck(check.spec, cwd);
159
- else if (kind === 'http') r = await runHttpCheck(check.spec, httpTimeoutMs);
277
+ else if (kind === 'http') r = await runHttpCheck(check.spec, httpTimeoutMs, keep);
160
278
  else r = { ok: false, detail: `unknown check kind ${JSON.stringify(kind)}` };
161
279
  } catch (e) {
162
- r = { ok: false, detail: `check error: ${e && /** @type {Error} */ (e).message ? /** @type {Error} */ (e).message : e}` };
280
+ r = { ok: false, detail: errDetail(e) };
163
281
  }
164
- out.push({ id, kind, ok: r.ok, detail: r.detail });
282
+ httpState.push(kind === 'http' ? { spec: check.spec, retryable: r.refused !== true } : null);
283
+ out.push(toRow(id, kind, r, keep));
284
+ }
285
+ if (!httpRetry || typeof httpRetry !== 'object') return out;
286
+
287
+ const { attempts, delayMs, sleep } = normalizeRetry(httpRetry);
288
+ /** @type {number[]} */
289
+ const ran = out.map(() => 1);
290
+ for (let attempt = 2; attempt <= attempts; attempt++) {
291
+ const due = [];
292
+ for (let i = 0; i < out.length; i++) {
293
+ const st = httpState[i];
294
+ if (st && st.retryable && out[i].ok === false) due.push(i);
295
+ }
296
+ if (!due.length) break;
297
+ await sleep(delayMs);
298
+ for (const i of due) {
299
+ const st = /** @type {{spec: unknown, retryable: boolean}} */ (httpState[i]);
300
+ /** @type {HttpResult} */
301
+ let r;
302
+ try { r = await runHttpCheck(st.spec, httpTimeoutMs, keep); } catch (e) { r = { ok: false, detail: errDetail(e) }; }
303
+ ran[i] = attempt;
304
+ out[i] = toRow(out[i].id, out[i].kind, r, keep);
305
+ }
306
+ }
307
+ for (let i = 0; i < out.length; i++) {
308
+ if (httpState[i]) out[i].attempts = ran[i];
165
309
  }
166
310
  return out;
167
311
  }
168
312
 
169
- module.exports = { runCriteriaChecks, COMMAND_CAP_MS, HTTP_TIMEOUT_MS };
313
+ module.exports = { runCriteriaChecks, COMMAND_CAP_MS, HTTP_TIMEOUT_MS, HTTP_BODY_MAX_BYTES, HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS };