claude-code-session-manager 0.142.0 → 0.143.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 (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +20 -107
  3. package/dist/assets/{AppSettings-BcZgIvvY.js → AppSettings-BO4jDVGO.js} +1 -1
  4. package/dist/assets/{History-DpZuJXi1.js → History-DTttbvPb.js} +1 -1
  5. package/dist/assets/{HomeClaudeConfig-D32ZJtU-.js → HomeClaudeConfig-DADP5bfn.js} +2 -2
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-B_D4Bg7L.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BTClYV6i.js → ProjectClaudeConfig-DPnDJKcr.js} +1 -1
  8. package/dist/assets/{Scheduler-DPobKx1Z.js → Scheduler-CNLjn90m.js} +8 -8
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-cfV7sgk6.js} +1 -1
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-DVXtEIVy.js} +1 -1
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-CYajnSdx.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-DJ4gGRuE.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-D3MoHY2U.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-CdTppjKR.js} +436 -436
  16. package/dist/index.html +1 -1
  17. package/dist-web/app.js +356 -356
  18. package/package.json +3 -3
  19. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  20. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  21. package/plugins/session-manager-dev/skills/develop/SKILL.md +9 -3
  22. package/scripts/README.md +1 -0
  23. package/scripts/scheduler-mcp-server.cjs +304 -6
  24. package/src/main/adminRouteRegistry.cjs +10 -0
  25. package/src/main/build-info.json +4 -4
  26. package/src/main/chatRunner.cjs +105 -7
  27. package/src/main/config.cjs +5 -1
  28. package/src/main/health.cjs +38 -2
  29. package/src/main/index.cjs +12 -4
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/cast.md +10 -1
  32. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  33. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  34. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  35. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  36. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  37. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  38. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  39. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  40. package/src/main/lib/epic/artifactStore.cjs +78 -35
  41. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  42. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  43. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  44. package/src/main/lib/epic/epicValidationHook.cjs +13 -2
  45. package/src/main/lib/externalContract.cjs +12 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  47. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  48. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +30 -0
  49. package/src/main/lib/feedback-remote/pendingReplies.cjs +18 -0
  50. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  51. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  52. package/src/main/lib/git/gitWorktree.cjs +8 -0
  53. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  54. package/src/main/lib/git/worktreeDeps.cjs +113 -10
  55. package/src/main/lib/mcpToolCatalog.cjs +102 -8
  56. package/src/main/lib/opsOwnership.cjs +113 -28
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  58. package/src/main/lib/prd/prdCreate.cjs +350 -227
  59. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  60. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  61. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  62. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  63. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  64. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  65. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  66. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  67. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  68. package/src/main/lib/scheduler/planRecordHarvest.cjs +120 -52
  69. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  70. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  71. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  72. package/src/main/lib/scheduler/scheduleJobSchema.cjs +13 -0
  73. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  74. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  75. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  76. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +16 -5
  77. package/src/main/lib/tasks/memoryConsolidation.cjs +14 -2
  78. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  79. package/src/main/lib/tasks/taskAdminRoutes.cjs +78 -3
  80. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  81. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  82. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  83. package/src/main/lib/util/atomicFs.cjs +2 -2
  84. package/src/main/promptSessionEvents.cjs +16 -1
  85. package/src/main/pty.cjs +11 -2
  86. package/src/main/queueOps.cjs +1 -1
  87. package/src/main/runVerify.cjs +1 -1
  88. package/src/main/scheduler/utilizationHold.cjs +96 -6
  89. package/src/main/scheduler.cjs +533 -39
  90. package/src/main/templates/PRD_AUTHORING.md +7 -2
  91. package/src/preload/api.d.ts +47 -1
  92. package/src/preload/apiSurface.json +14 -0
  93. package/src/preload/index.cjs +2 -0
  94. package/src/seed/agents/demo-video-builder.md +15 -8
  95. package/src/seed/agents/validator.md +20 -19
@@ -18,12 +18,13 @@
18
18
  * taskSwitchRoute.cjs (humanPromptLedger.findHumanPromptContaining);
19
19
  * headless jobs and Tasks never record prompts there, so they fail here
20
20
  * too;
21
- * 4. 403 quote_does_not_name_slots — the quote is not a change request:
22
- * a change verb (set / raise / bump / lower / make …), a limit word
23
- * (limit / cap / slots / sessions / parallel / concurrent) AND the new
24
- * number given as the target ("to 14", "= 14", "at 14", "14 parallel
25
- * sessions"). Naming a limit and a number in passing is not enough;
26
- * a question or a percentage target is refused too.
21
+ * 4. 403 quote_does_not_name_slots — no sentence of the quote is the
22
+ * one accepted form (see SLOT_COMMAND), or no whole sentence of the
23
+ * matched human prompt that contains the quote (or that the quote
24
+ * wholly covers) is that form — so "don't raise the limit to 14" or
25
+ * "raise the limit to 14?" never authorize via the quote
26
+ * 'raise the limit to 14'. The reason gives the form, e.g. say
27
+ * 'raise the limit to 14'.
27
28
  * Success: sessionSlots.setCap(cap) (persists + wakes waiters), one
28
29
  * slot_cap_changed audit event { from, to, epicId, quote, promptAt },
29
30
  * 200 { ok, from, to }.
@@ -45,99 +46,112 @@ const slotsBodySchema = z.object({
45
46
  callerJobSlug: z.string().max(256).optional(),
46
47
  }).strict();
47
48
 
48
- const LIMIT_WORDS = '(?:limit|limits|cap|caps|slot|slots|session|sessions|parallel|parallelism|concurrent|concurrency)';
49
- const CHANGE_VERBS = '(?:set|raise|increase|bump|lift|lower|reduce|drop|change|move|make)';
50
- const NEGATION = '(?:not|never|no|dont|don t|won t|wont|can t|cant|shouldn t|shouldnt)';
51
- const TARGET = '(?:to|=|at)';
52
- const QUESTION_WORDS = '(?:will|would|do|does|did|may|might|are|is|can|could|should|shall|whether|want to)';
53
- // A question word (or a '?') before the change verb, in the same clause, makes
54
- // the quote a question ("will you raise the limit to 14"), never a request.
55
- // A clause ends at , ; . ! or a line break (all normalized to ' . ').
56
- const QUESTION_BEFORE_VERB = new RegExp(`(?:^| )(?:${QUESTION_WORDS}|\\?)(?: [^.]*)? ${CHANGE_VERBS}(?= |$)`);
57
- // Any '?' after a change verb, anywhere later in the quote, makes it a question.
58
- const QUESTION_AFTER_VERB = new RegExp(`(?:^| )${CHANGE_VERBS} (?:.* )?\\?`);
59
- const PERCENT_WORDS = '(?:percent|per cent|pct|percentage)';
60
- // Closing quotes and brackets a human (or a copy-paste) leaves after a '?'.
61
- const TRAILING_CLOSERS = /[\s"'`\u201d\u2019\u00bb)\]}>]+$/;
62
-
63
- const NUMBER_WORDS = [
64
- 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
65
- 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen',
66
- 'nineteen', 'twenty',
67
- ];
68
- const TENS = { 20: 'twenty', 30: 'thirty' };
69
- const ANY_NUMBER = `(?:\\d+|${[...NUMBER_WORDS, 'thirty', 'forty', 'fifty'].join('|')})`;
70
- // One filler word: letters only, never a number word, so a gap can never
71
- // swallow half of "thirty two" or step over a different number.
72
- const WORD = `(?!${ANY_NUMBER}(?: |$))[a-z]+`;
73
- const gap = (/** @type {number} */ n) => `(?: ${WORD}){0,${n}}`;
74
-
75
- /** @param {number} n */
76
- function wordsFor(n) {
77
- if (n < 0) return [];
78
- if (n <= 20) return [NUMBER_WORDS[n]];
79
- const tens = Math.floor(n / 10) * 10;
80
- const unit = n % 10;
81
- const t = TENS[/** @type {20|30} */ (tens)];
82
- if (!t) return [];
83
- return unit === 0 ? [t] : [`${t} ${NUMBER_WORDS[unit]}`];
49
+ // The one accepted sentence form, matched against a whole sentence after
50
+ // lowercasing and collapsing spaces:
51
+ // [please|ok|okay|so|now|then[,]] set|raise|increase|bump|lower|reduce|change
52
+ // [the|our] [session|slot|parallel] limit|cap|slots to <digits> [sessions|slots]
53
+ // Nothing else may be in that sentence. Anything else —
54
+ // questions, negations, percentages, number words, extra words — is refused.
55
+ const SLOT_COMMAND = new RegExp(
56
+ '^(?:(?:please|ok|okay|so|now|then),? )?'
57
+ + '(?:set|raise|increase|bump|lower|reduce|change) '
58
+ + '(?:(?:the|our) )?'
59
+ + '(?:(?:session|slot|parallel) )?'
60
+ + '(?:limit|cap|slots) to (\\d+)'
61
+ + '(?: (?:sessions|slots))?$',
62
+ );
63
+
64
+ /** The accepted form, as the refusal states it. @param {number} cap */
65
+ function acceptedFormHint(cap) {
66
+ return `say 'raise the limit to ${cap}' (one sentence: [please|ok|okay|so|now|then] `
67
+ + 'set|raise|increase|bump|lower|reduce|change [the|our] [session|slot|parallel] limit|cap|slots '
68
+ + 'to <number in digits> [sessions|slots], with nothing else in the sentence, a comma only right after '
69
+ + 'the lead-in word, and no question mark)';
84
70
  }
85
71
 
86
- /** @param {unknown} quote */
87
- function normalizeQuote(quote) {
88
- return String(quote)
89
- .toLowerCase()
90
- .replace(/\d+[.,]\d+/g, ' # ') // a decimal is never a cap; never let "14.5" read as 14
91
- .replace(/%/g, ' percent ') // "14%" reads as "14 percent": a percentage, never a cap
92
- .replace(/=/g, ' = ')
93
- .replace(/[.!;,\r\n]/g, ' . ') // a clause boundary: no gap word or question scan crosses it
94
- .replace(/\?/g, ' ? ') // a question mark: no gap word crosses it
95
- .replace(/[:()[\]{}]/g, ' | ') // a phrase break: no gap word crosses it, the question scan does
96
- .replace(/[^a-z0-9=.#?| ]/g, ' ')
97
- .replace(/\s+/g, ' ')
98
- .trim();
72
+ /**
73
+ * Sentence spans of `text`: split on . ! ? ; and line breaks, the terminator
74
+ * kept with its sentence; a decimal ("14.5") is not split. Returns the
75
+ * lowercased, whitespace-collapsed body, its trimmed [start, end) in `text`,
76
+ * and the terminator ('' at the end of the text).
77
+ * @param {string} text
78
+ * @returns {Array<{ body: string, start: number, end: number, term: string }>}
79
+ */
80
+ function splitSentences(text) {
81
+ // Same-length mask keeps indices aligned with `text`.
82
+ const masked = text.toLowerCase().replace(/(\d)[.,](?=\d)/g, '$1#');
83
+ const out = [];
84
+ const sentence = /([^.!?;\r\n]*)([.!?;\r\n]|$)/g;
85
+ let m;
86
+ while ((m = sentence.exec(masked)) !== null) {
87
+ const raw = m[1];
88
+ const lead = raw.length - raw.replace(/^\s+/, '').length;
89
+ const trail = raw.length - raw.replace(/\s+$/, '').length;
90
+ const start = m.index + lead;
91
+ const end = m.index + raw.length - trail;
92
+ if (end > start) out.push({ body: raw.replace(/\s+/g, ' ').trim(), start, end, term: m[2] });
93
+ if (m[2] === '') break; // end of the text
94
+ }
95
+ return out;
96
+ }
97
+
98
+ /** @param {string} body @param {string} term @param {number} cap */
99
+ function sentenceNamesCap(body, term, cap) {
100
+ if (term === '?' || !body) return false;
101
+ const hit = SLOT_COMMAND.exec(body);
102
+ return !!hit && hit[1] === String(cap);
99
103
  }
100
104
 
101
105
  /**
102
- * The anchored change-request patterns for `cap`:
103
- * A. verb … limit word … to|=|at <cap> ("raise the limit to 14")
104
- * B. verb … [to|=|at] <cap> … limit word ("make it 16 parallel sessions")
105
- * The verb must be the base form and not negated; the number must stand alone.
106
+ * True only when the human prompt `promptText` (the text the ledger matched)
107
+ * has a whole sentence in the strict SLOT_COMMAND form naming `cap` that
108
+ * either contains an occurrence of `quote` or lies wholly inside one. The
109
+ * quote is located the way humanPromptLedger matches it (lowercased,
110
+ * whitespace collapsed). A sentence the quote only partly overlaps never
111
+ * authorizes. Refuses on doubt.
112
+ * @param {unknown} promptText
113
+ * @param {unknown} quote
106
114
  * @param {number} cap
107
115
  */
108
- function changeRequestPatterns(cap) {
109
- const num = `(?:${[String(cap), ...wordsFor(cap)].join('|')})`;
110
- // The number must stand alone and not be a percentage ("14 percent", "14%").
111
- const numEnd = `(?= |$)(?! ${ANY_NUMBER}(?: |$))(?! ${PERCENT_WORDS}(?: |$))`;
112
- const verb = `(?<!${NEGATION}${gap(2)} )(?<=^| )${CHANGE_VERBS}`;
113
- const verbAtStart = `(?:^| )${verb}`;
114
- return [
115
- new RegExp(`${verbAtStart}${gap(4)} ${LIMIT_WORDS}${gap(3)} ${TARGET} ${num}${numEnd}`),
116
- new RegExp(`${verbAtStart}${gap(4)}(?: ${TARGET})? ${num}${numEnd}${gap(2)} ${LIMIT_WORDS}(?= |$)`),
117
- ];
116
+ function promptSentenceNamesSlots(promptText, quote, cap) {
117
+ if (typeof promptText !== 'string' || typeof quote !== 'string') return false;
118
+ if (!Number.isInteger(cap) || cap < 0) return false;
119
+ const q = quote.replace(/\s+/g, ' ').trim().toLowerCase();
120
+ if (!q) return false;
121
+ // Normalized prompt + map from each normalized char to its index in promptText.
122
+ const lower = promptText.toLowerCase();
123
+ let norm = '';
124
+ /** @type {number[]} */
125
+ const map = [];
126
+ for (let i = 0; i < lower.length; i++) {
127
+ if (/\s/.test(lower[i])) {
128
+ if (norm.length && norm[norm.length - 1] !== ' ') { norm += ' '; map.push(i); }
129
+ } else { norm += lower[i]; map.push(i); }
130
+ }
131
+ const sentences = splitSentences(promptText);
132
+ for (let at = norm.indexOf(q); at !== -1; at = norm.indexOf(q, at + 1)) {
133
+ const qs = map[at];
134
+ const qe = map[at + q.length - 1] + 1;
135
+ for (const s of sentences) {
136
+ const contains = s.start <= qs && qe <= s.end;
137
+ const covered = qs <= s.start && s.end <= qe;
138
+ if ((contains || covered) && sentenceNamesCap(s.body, s.term, cap)) return true;
139
+ }
140
+ }
141
+ return false;
118
142
  }
119
143
 
120
144
  /**
121
- * True only when the quote is a request to CHANGE the session limit to `cap`:
122
- * a change verb, a limit word, and `cap` (digits, or English words up to
123
- * thirty-nine) given as the new target. Mentioning a limit and a number is not
124
- * enough — "lets see first 10 sessions chugging and then we will move the
125
- * limit via the mcp" authorizes nothing. A question (ends with '?', or a
126
- * '?' anywhere after the change verb, or a question word — will, would, do,
127
- * does, did, may, might, are, is, can, could, should, shall, whether, want to —
128
- * before the verb in its clause) and a percentage target ("14%", "14 percent",
129
- * "14 per cent", "14 pct", "14 percentage") authorize nothing either.
130
- * Refuses on doubt.
145
+ * True only when one sentence of the quote is exactly the SLOT_COMMAND form
146
+ * naming `cap` in digits. Sentences split on . ! ? ; and line breaks; a
147
+ * sentence ended by '?' never authorizes; a decimal ("14.5") is not split, so
148
+ * it never reads as 14. Refuses on doubt.
131
149
  * @param {unknown} quote
132
150
  * @param {number} cap
133
151
  */
134
152
  function quoteNamesSlots(quote, cap) {
135
153
  if (typeof quote !== 'string' || !Number.isInteger(cap) || cap < 0) return false;
136
- if (/\?$/.test(quote.replace(TRAILING_CLOSERS, ''))) return false; // a question is not a request
137
- const q = normalizeQuote(quote);
138
- if (QUESTION_AFTER_VERB.test(q)) return false;
139
- if (QUESTION_BEFORE_VERB.test(q)) return false;
140
- return changeRequestPatterns(cap).some((re) => re.test(q));
154
+ return splitSentences(quote).some((x) => sentenceNamesCap(x.body, x.term, cap));
141
155
  }
142
156
 
143
157
  /**
@@ -205,8 +219,8 @@ function registerSlotsRoute(adminHttp, deps = {}) {
205
219
  refuse(403, 'human_request_unverified', 'quote was not found in a prompt the human typed in this chat session');
206
220
  return;
207
221
  }
208
- if (!quoteNamesSlots(quote, cap)) {
209
- refuse(403, 'quote_does_not_name_slots', `the human's quote does not ask to change the session limit to ${cap}`);
222
+ if (!quoteNamesSlots(quote, cap) || !promptSentenceNamesSlots(found.text, quote, cap)) {
223
+ refuse(403, 'quote_does_not_name_slots', `the human's quote does not ask to change the session limit to ${cap} in the accepted form; ${acceptedFormHint(cap)}`);
210
224
  return;
211
225
  }
212
226
 
@@ -234,4 +248,4 @@ function registerSlotsRoute(adminHttp, deps = {}) {
234
248
  });
235
249
  }
236
250
 
237
- module.exports = { registerSlotsRoute, quoteNamesSlots, MAX_SLOTS_BODY_BYTES };
251
+ module.exports = { registerSlotsRoute, quoteNamesSlots, promptSentenceNamesSlots, MAX_SLOTS_BODY_BYTES };
@@ -0,0 +1,97 @@
1
+ // @ts-check
2
+ 'use strict';
3
+ // GET /admin/usage-hold — the usage hold Session Manager is applying to
4
+ // automatic claude -p runs right now ('pause above'), the same hold
5
+ // POST /admin/tasks refuses on. Answers
6
+ // 200 { ok: true, hold, threshold }
7
+ // where hold is null when nothing is held, else
8
+ // { reason, window, percent, threshold, resetsAt, detail } (+ baseThreshold
9
+ // when set) — publicHold below, the same shape every 429 usage_held answers,
10
+ // and threshold is the saved 'pause above' percent. A failed read answers
11
+ // 503 { ok: false, error: 'usage_hold_error', details }.
12
+ // Read by scripts that start claude -p directly (e.g. Self's Kiln daily job
13
+ // while its Task switch is off): they check `hold === null` before an
14
+ // automatic run. Read-only: ignores any query string, reads no body, writes nothing.
15
+
16
+ const { sendJson } = require('../feedback-remote/localAdminHttp.cjs');
17
+
18
+ /**
19
+ * @typedef {import('../../scheduler/utilizationHold.cjs').AutoDispatchHold} AutoDispatchHold
20
+ * @typedef {{
21
+ * reason: AutoDispatchHold['reason'] | null,
22
+ * window: string | null,
23
+ * percent: number | null,
24
+ * threshold: number | null,
25
+ * resetsAt: string | null,
26
+ * detail: string | null,
27
+ * baseThreshold?: number,
28
+ * }} PublicHold
29
+ */
30
+
31
+ /**
32
+ * Builds the hold's one outside shape from a real hold. baseThreshold (the
33
+ * saved 'pause above' before pro-rating) is forwarded only when it is a
34
+ * finite number.
35
+ * @param {AutoDispatchHold} hold
36
+ * @returns {PublicHold}
37
+ */
38
+ function toPublicHold(hold) {
39
+ /** @type {PublicHold} */
40
+ const out = {
41
+ reason: hold.reason ?? null,
42
+ window: hold.window ?? null,
43
+ percent: hold.percent ?? null,
44
+ threshold: hold.threshold ?? null,
45
+ resetsAt: hold.resetsAt ?? null,
46
+ detail: hold.detail ?? null,
47
+ };
48
+ if (typeof hold.baseThreshold === 'number' && Number.isFinite(hold.baseThreshold)) {
49
+ out.baseThreshold = hold.baseThreshold;
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /**
55
+ * The hold's one outside shape, shared by GET /admin/usage-hold and every
56
+ * 429 usage_held answer; null when nothing is held.
57
+ * @param {AutoDispatchHold | null | undefined} hold
58
+ * @returns {PublicHold | null}
59
+ */
60
+ function publicHold(hold) {
61
+ return hold == null ? null : toPublicHold(hold);
62
+ }
63
+
64
+ /**
65
+ * The 429 usage_held body: the public hold minus detail, with detail and the
66
+ * caller's hint at the top level. A 429 usage_held always carries a real hold.
67
+ * @param {AutoDispatchHold} hold
68
+ * @param {string} hint
69
+ */
70
+ function usageHeldBody(hold, hint) {
71
+ const { detail, ...rest } = toPublicHold(hold);
72
+ return { ok: false, error: 'usage_held', hold: rest, detail, hint };
73
+ }
74
+
75
+ /**
76
+ * @param {{ registerRoute: Function }} adminHttp
77
+ * @param {{ usageHold?: () => AutoDispatchHold | null, threshold?: () => number }} [deps]
78
+ */
79
+ function registerUsageHoldRoute(adminHttp, deps = {}) {
80
+ const usageHold = deps.usageHold || (() => require('../../scheduler.cjs').currentUsageHold());
81
+ const threshold = deps.threshold || (() => require('../../scheduler.cjs').usageHoldThreshold());
82
+
83
+ adminHttp.registerRoute('GET', '/admin/usage-hold', (/** @type {unknown} */ _req, /** @type {import('node:http').ServerResponse} */ res) => {
84
+ let hold;
85
+ let t;
86
+ try {
87
+ hold = usageHold() ?? null;
88
+ t = threshold();
89
+ } catch (e) {
90
+ sendJson(res, 503, { ok: false, error: 'usage_hold_error', details: e instanceof Error ? e.message : String(e) });
91
+ return;
92
+ }
93
+ sendJson(res, 200, { ok: true, hold: publicHold(hold), threshold: t });
94
+ });
95
+ }
96
+
97
+ module.exports = { registerUsageHoldRoute, publicHold, usageHeldBody };
@@ -15,9 +15,12 @@
15
15
  * mechanical check results) it also refuses an entry that omits a criterion
16
16
  * id or marks met: true a criterion whose mechanical check failed.
17
17
  *
18
- * Pure: no I/O, no dependencies, never throws, never mutates its input.
18
+ * Pure: no I/O, never throws, never mutates its input. Its one dependency is
19
+ * criteriaChecks.cjs, for the http retry constants the prompt section names.
19
20
  */
20
21
 
22
+ const { HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS } = require('./criteriaChecks.cjs');
23
+
21
24
  /** @typedef {'not-landed'|'gate-red'|'behavior-wrong'|'not-checked-live'|'missing-test'|'regression'|'spec-gap'|'security'|'docs-drift'|'other'} MissKind */
22
25
  /** @typedef {'Critical'|'Important'|'Minor'} Severity */
23
26
  /** @typedef {{ id: string, met: boolean, evidence: string, missKind?: MissKind }} Criterion */
@@ -316,8 +319,9 @@ function expectedFromCriteria(criteria, checks) {
316
319
 
317
320
  /**
318
321
  * formatCriteriaChecksSection(prds) → Markdown for the validator prompt: per
319
- * judged PRD, each criterion id, its statement, and its stored mechanical
320
- * check result. '' when no PRD has structured criteria.
322
+ * judged PRD, each criterion id, its statement, and its mechanical check
323
+ * result (http/file run at validator dispatch; command as stored), plus the
324
+ * body sidecar path of each http row. '' when no PRD has structured criteria.
321
325
  * @param {Array<{ slug: string, criteria: unknown, checks: unknown }>} prds
322
326
  * @returns {string}
323
327
  */
@@ -341,15 +345,22 @@ function formatCriteriaChecksSection(prds) {
341
345
  const kind = isPlainObject(c.check) && typeof c.check.kind === 'string' ? c.check.kind : 'manual';
342
346
  const result = !r ? 'not run' : r.ok === true ? 'PASS' : r.ok === false ? 'FAIL' : 'manual';
343
347
  const detail = r && r.detail ? ` — ${oneLine(r.detail)}` : '';
344
- lines.push(`- \`${oneLine(c.id, 60)}\` (${kind}) ${result}${detail}: ${oneLine(c.statement)}`);
348
+ const ranAt = r && typeof r.ranAt === 'string' && r.ranAt ? ` (ran ${oneLine(r.ranAt, 40)})` : '';
349
+ const attempts = r && Number.isInteger(r.attempts) && /** @type {number} */ (r.attempts) > 1 ? ` (${r.attempts} attempts)` : '';
350
+ lines.push(`- \`${oneLine(c.id, 60)}\` (${kind}) ${result}${ranAt}${attempts}${detail}: ${oneLine(c.statement)}`);
351
+ if (r && typeof r.bodyPath === 'string' && r.bodyPath) {
352
+ const bytes = Number.isFinite(r.bodyBytes) ? r.bodyBytes : 0;
353
+ lines.push(` - body: ${oneLine(r.bodyPath, 500)} (${bytes} bytes${r.truncated === true ? ', truncated at 1 MiB' : ''})`);
354
+ }
345
355
  }
346
356
  blocks.push(lines.join('\n'));
347
357
  }
348
358
  if (!blocks.length) return '';
359
+ const retrySentence = `A failed \`http\` check was retried (up to ${HTTP_RETRY_ATTEMPTS} attempts, ${Math.round(HTTP_RETRY_DELAY_MS / 1000)} s apart) before it was recorded, so a FAIL row is a repeated failure.`;
349
360
  return [
350
361
  '## Stored mechanical check results',
351
362
  '',
352
- 'The scheduler ran each structured criterion\'s mechanical check when the PRD finished. In your verdict JSON, return one `criteria` entry per criterion id below, using that id exactly. A criterion whose check is FAIL must be `met: false` — a verdict marking it met is refused.',
363
+ 'The `http` and `file` checks below were run by the scheduler outside your sandbox just before you started. `command` rows show a stored result or `not run` — re-run those yourself. Your Bash cannot reach host loopback, so never probe a running service: judge `http` criteria from these results. ' + retrySentence + ' Each `http` row names a `body:` file holding the response body; judge structural expectations (for example every item has a non-empty field) by reading that file inside your sandbox. In your verdict JSON, return one `criteria` entry per criterion id below, using that id exactly. A criterion whose check is FAIL must be `met: false` — a verdict marking it met is refused.',
353
364
  '',
354
365
  ...blocks,
355
366
  ].join('\n');
@@ -141,8 +141,16 @@ function adminPosterFor(adminHttp) {
141
141
  });
142
142
  }
143
143
 
144
+ /**
145
+ * Task statuses (or POST /admin/tasks error codes) for a Task that never ran:
146
+ * refused by the usage hold, or never given a slot. Such a Task does not use
147
+ * up a cadence window.
148
+ */
149
+ const NOT_RUN_STATUSES = Object.freeze(['usage_held', 'usage_hold_error', 'slot_timeout', 'too_many_waiting']);
150
+
144
151
  function defaultDeps() {
145
152
  return {
153
+ usageHold: () => require('../../scheduler.cjs').currentUsageHold(),
146
154
  isTaskSwitchOn: (/** @type {string} */ cwd) => require('./taskSwitch.cjs').isTaskSwitchOn(cwd),
147
155
  listTasks: (/** @type {string} */ cwd, /** @type {any} */ o) => require('./taskLedger.cjs').listTasks(cwd, o),
148
156
  measureBudget: (/** @type {string} */ cwd) => {
@@ -162,8 +170,8 @@ function defaultDeps() {
162
170
 
163
171
  /** Last consolidation start (ms) within the window, else null. */
164
172
  async function lastStartMs(listTasks, cwd, sinceMs) {
165
- const { tasks } = await listTasks(cwd, { pipeline: PIPELINE, since: new Date(sinceMs).toISOString(), limit: 1 });
166
- const t = tasks && tasks[0];
173
+ const { tasks } = await listTasks(cwd, { pipeline: PIPELINE, since: new Date(sinceMs).toISOString(), limit: 50 });
174
+ const t = (Array.isArray(tasks) ? tasks : []).find((x) => x && !NOT_RUN_STATUSES.includes(x.status));
167
175
  const ms = t ? Date.parse(t.startedAt) : NaN;
168
176
  return Number.isFinite(ms) ? ms : null;
169
177
  }
@@ -174,6 +182,7 @@ async function lastStartMs(listTasks, cwd, sinceMs) {
174
182
  * `done` settles after the Task ran and its Needs you item was posted. Never throws.
175
183
  *
176
184
  * @param {{ cwd: string, now?: number, deps?: {
185
+ * usageHold?: () => any,
177
186
  * isTaskSwitchOn?: (cwd: string) => boolean,
178
187
  * listTasks?: (cwd: string, o: any) => Promise<{ tasks: any[] }>,
179
188
  * measureBudget?: (cwd: string) => any,
@@ -189,6 +198,8 @@ async function maybeStartConsolidation({ cwd, now = Date.now(), deps = {} } = /*
189
198
  if (!d.isTaskSwitchOn(key)) return { started: false, reason: 'switch_off' };
190
199
  if (inFlight.has(key)) return { started: false, reason: 'in_flight' };
191
200
  if (typeof d.adminPost !== 'function') return { started: false, reason: 'no_admin_server' };
201
+ const hold = d.usageHold();
202
+ if (hold) return { started: false, reason: 'usage_held', hold };
192
203
 
193
204
  let budget = null;
194
205
  try { budget = d.measureBudget(key); } catch { budget = null; }
@@ -296,5 +307,6 @@ module.exports = {
296
307
  PIPELINE,
297
308
  NO_DELETE_RULE,
298
309
  READ_ONLY_TOOLS,
310
+ NOT_RUN_STATUSES,
299
311
  _resetForTests,
300
312
  };
@@ -32,7 +32,7 @@
32
32
  const fs = require('node:fs');
33
33
  const path = require('node:path');
34
34
  const crypto = require('node:crypto');
35
- const { adminPosterFor, extractProposal } = require('./memoryConsolidation.cjs');
35
+ const { adminPosterFor, extractProposal, NOT_RUN_STATUSES } = require('./memoryConsolidation.cjs');
36
36
  const { OPS_ROOT_DIR } = require('../opsOwnership.cjs');
37
37
 
38
38
  const PIPELINE = 'mitigation-review';
@@ -146,6 +146,7 @@ function stateFile() {
146
146
 
147
147
  function defaultDeps() {
148
148
  return {
149
+ usageHold: () => require('../../scheduler.cjs').currentUsageHold(),
149
150
  isTaskSwitchOn: (/** @type {string} */ cwd) => require('./taskSwitch.cjs').isTaskSwitchOn(cwd),
150
151
  readRegistry: (/** @type {string} */ cwd) => {
151
152
  try { return fs.readFileSync(path.join(cwd, REGISTRY_REL), 'utf8'); } catch { return null; }
@@ -184,6 +185,9 @@ async function maybeStartMitigationReview({ cwd, now = Date.now(), deps = {} } =
184
185
  if (inFlight.has(key)) return { started: false, reason: 'in_flight' };
185
186
  const registry = d.readRegistry(key);
186
187
  if (typeof registry !== 'string') return { started: false, reason: 'no_registry' };
188
+ // Before resolving the model: resolveModelCatalog can run claude -p probes.
189
+ const hold = d.usageHold();
190
+ if (hold) return { started: false, reason: 'usage_held', hold };
187
191
  const to = await d.resolveDefaultExecutorModel(key);
188
192
  if (typeof to !== 'string' || !to) return { started: false, reason: 'model_unresolved' };
189
193
 
@@ -192,6 +196,7 @@ async function maybeStartMitigationReview({ cwd, now = Date.now(), deps = {} } =
192
196
  if (prev === to) return { started: false, reason: 'unchanged' };
193
197
  if (prev != null && typeof d.adminPost !== 'function') return { started: false, reason: 'no_admin_server' };
194
198
 
199
+ const prevEntry = state[key];
195
200
  d.writeState({ ...state, [key]: { model: to, seenAt: new Date(now).toISOString() } });
196
201
  if (prev == null) return { started: false, reason: 'first_seen', to };
197
202
 
@@ -202,6 +207,21 @@ async function maybeStartMitigationReview({ cwd, now = Date.now(), deps = {} } =
202
207
  inFlight.add(key);
203
208
  const done = runAndPost({ cwd: key, now, prompt, from: prev, to, adminPost: d.adminPost })
204
209
  .catch((e) => ({ ok: false, error: e instanceof Error ? e.message : String(e) }))
210
+ .then((out) => {
211
+ // A review that never ran (held, or no slot) must not use up this change.
212
+ if (out && NOT_RUN_STATUSES.includes(out.error)) {
213
+ try {
214
+ const cur = d.readState() || {};
215
+ if (cur[key] && cur[key].model === to) {
216
+ const next = { ...cur };
217
+ if (prevEntry === undefined) delete next[key];
218
+ else next[key] = prevEntry;
219
+ d.writeState(next);
220
+ }
221
+ } catch { /* best effort: the next change still reviews */ }
222
+ }
223
+ return out;
224
+ })
205
225
  .finally(() => { inFlight.delete(key); });
206
226
  return { started: true, reason: 'model_changed', from: prev, to, done };
207
227
  } catch (e) {
@@ -15,11 +15,24 @@
15
15
  * 422 model_unresolved, 422 effort_unresolved. The persona BODY is
16
16
  * never read into the prompt or argv;
17
17
  * 4. 409 session_busy when another running Task holds the session;
18
- * 5. ledger start line, THEN sessionSlots.waitForSlot by priority lane
18
+ * then buildTaskArgs (400);
19
+ * 5. the usage hold (scheduler.currentUsageHold — the same 'pause
20
+ * above' rule the PRD queue holds at): a hold → 429 usage_held
21
+ * { hold: { reason, window, percent, threshold, resetsAt }, detail,
22
+ * hint }, a throw → 503 usage_hold_error, both before any ledger
23
+ * line. No body key, priority or caller bypasses it — this loopback
24
+ * route cannot prove a human. One 'task_usage_held' audit event per
25
+ * project root per hold (holdIdentityKey), not per request;
26
+ * 6. ledger start line, THEN sessionSlots.waitForSlot by priority lane
19
27
  * (null → 'slot_timeout', too_many_waiting → 429);
20
- * 6. taskRun.runTask, token released in finally, ledger end line with
28
+ * 7. once the slot is granted the usage hold is read AGAIN: a hold or
29
+ * a throw releases the token and writes the end line status
30
+ * 'usage_held' + slotWaitMs; a hold replies 429 usage_held, a throw
31
+ * 503 usage_hold_error (both + taskId, slotWaitMs) — a Task that
32
+ * waited through the hold never spawns;
33
+ * 8. taskRun.runTask, token released in finally, ledger end line with
21
34
  * costUsd from modelPricing.costOfUsage;
22
- * 7. 200 { ok: true, taskId, status, stdout, envelope, usage, costUsd,
35
+ * 9. 200 { ok: true, taskId, status, stdout, envelope, usage, costUsd,
23
36
  * cliCostUsd, durationMs, slotWaitMs, exitCode, model, effort,
24
37
  * sessionId, quota }.
25
38
  * A req/res 'close' before the reply aborts the wait or the run
@@ -83,6 +96,7 @@ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
83
96
  const { resolveProjectRoot } = require('../opsOwnership.cjs');
84
97
  const { phaseOfTask } = require('../phaseProjection.cjs');
85
98
  const { registerTaskSwitchRoute } = require('./taskSwitchRoute.cjs');
99
+ const { usageHeldBody } = require('../scheduler/usageHoldRoute.cjs');
86
100
 
87
101
  const MAX_BODY_BYTES = 4 * 1024 * 1024;
88
102
  const MAX_IMPORT_BODY_BYTES = 8 * 1024 * 1024;
@@ -426,12 +440,17 @@ function liveTaskIdsFor(root) {
426
440
  return ids;
427
441
  }
428
442
 
443
+ const USAGE_HOLD_HINT =
444
+ "Usage is above 'pause above': automatic Tasks wait until the window resets or usage drops below it. "
445
+ + 'Retry after hold.resetsAt; never run claude -p directly instead. GET /admin/usage-hold reads the hold.';
446
+
429
447
  /**
430
448
  * @param {{ registerRoute: Function }} adminHttp
431
449
  * @param {{ taskSwitch?: any, resolveInfo?: Function, sessionSlots?: any, runTask?: Function,
432
450
  * buildTaskArgs?: Function, buildTaskEnv?: Function, ledger?: any, costOfUsage?: Function,
433
451
  * now?: () => number, randomUUID?: () => string, resolveProjectRoot?: Function,
434
452
  * syncInteractiveReserve?: () => any, knownMcpServers?: () => Record<string, object>,
453
+ * usageHold?: () => any, appendAuditEvent?: (kind: string, fields: Record<string, any>) => void,
435
454
  * switchRouteDeps?: Record<string, any> }} [deps]
436
455
  */
437
456
  function registerAdminRoute(adminHttp, deps = {}) {
@@ -461,6 +480,31 @@ function registerAdminRoute(adminHttp, deps = {}) {
461
480
  const safeSync = () => {
462
481
  try { syncReserve(); } catch { /* a failed sync never changes the response */ }
463
482
  };
483
+ // The usage hold ('pause above'): read lazily so scheduler.cjs never loads at module load.
484
+ const usageHold = deps.usageHold || (() => require('../../scheduler.cjs').currentUsageHold());
485
+ const audit = (/** @type {string} */ kind, /** @type {Record<string, any>} */ fields) =>
486
+ (deps.appendAuditEvent || require('../telemetry/auditLog.cjs').appendAuditEvent)(kind, fields);
487
+ /** project root → holdIdentityKey of the hold last audited for it; cleared when a read returns null. */
488
+ const heldAudited = new Map();
489
+ /** @param {string} root @param {any} hold */
490
+ const auditHold = (root, hold) => {
491
+ try {
492
+ const key = require('../../scheduler/utilizationHold.cjs').holdIdentityKey(hold);
493
+ if (heldAudited.get(root) === key) return;
494
+ heldAudited.set(root, key);
495
+ audit('task_usage_held', {
496
+ cwd: root, reason: hold.reason, window: hold.window, percent: hold.percent,
497
+ threshold: hold.threshold, resetsAt: hold.resetsAt,
498
+ });
499
+ } catch { /* an audit failure never changes the response */ }
500
+ };
501
+ /** @param {string} root @returns {any} the hold, or null; throws when the read throws. */
502
+ const readHold = (root) => {
503
+ const hold = usageHold();
504
+ if (!hold) { heldAudited.delete(root); return null; }
505
+ auditHold(root, hold);
506
+ return hold;
507
+ };
464
508
 
465
509
  /** sessionId → taskId for every Task currently between its start line and its end line. */
466
510
  const busySessions = new Map();
@@ -594,6 +638,19 @@ function registerAdminRoute(adminHttp, deps = {}) {
594
638
  }
595
639
  const env = buildEnv(runtime, process.env);
596
640
 
641
+ // Last check before the ledger start line: the usage hold.
642
+ let heldNow;
643
+ try {
644
+ heldNow = readHold(cwd);
645
+ } catch (e) {
646
+ reply(503, { ok: false, error: 'usage_hold_error', details: e instanceof Error ? e.message : String(e) });
647
+ return;
648
+ }
649
+ if (heldNow) {
650
+ reply(429, usageHeldBody(heldNow, USAGE_HOLD_HINT));
651
+ return;
652
+ }
653
+
597
654
  const ac = new AbortController();
598
655
  const onClose = () => { if (!replied) ac.abort(); };
599
656
  req.on('close', onClose);
@@ -658,6 +715,24 @@ function registerAdminRoute(adminHttp, deps = {}) {
658
715
  return;
659
716
  }
660
717
 
718
+ // The hold may have engaged while this Task waited for its slot.
719
+ // A failed read is fail-closed but is not a hold: 503 usage_hold_error, never 429.
720
+ let heldLate;
721
+ try {
722
+ heldLate = readHold(cwd);
723
+ } catch (e) {
724
+ try { slots().release(token); } catch { /* */ }
725
+ await end({ status: 'usage_held', slotWaitMs });
726
+ reply(503, { ok: false, error: 'usage_hold_error', taskId, slotWaitMs, details: e instanceof Error ? e.message : String(e) });
727
+ return;
728
+ }
729
+ if (heldLate) {
730
+ try { slots().release(token); } catch { /* */ }
731
+ await end({ status: 'usage_held', slotWaitMs });
732
+ reply(429, { ...usageHeldBody(heldLate, USAGE_HOLD_HINT), taskId, slotWaitMs });
733
+ return;
734
+ }
735
+
661
736
  live.slotAcquired = true;
662
737
 
663
738
  let droppedLines = 0;
@@ -62,10 +62,10 @@ const KINDS = new Set([KIND_STARTED, KIND_STATUS_CHANGED]);
62
62
  /** Pre-event-log kinds still on disk (≤ tasksDays old) → their current kind. */
63
63
  const LEGACY_KINDS = { start: KIND_STARTED, end: KIND_STATUS_CHANGED, imported: KIND_STATUS_CHANGED };
64
64
 
65
- /** Terminal Task statuses (taskRun.cjs + taskAdminRoutes.cjs + read-side 'interrupted'). */
65
+ /** Terminal Task statuses (taskRun.cjs + taskAdminRoutes.cjs incl. the slot-grant 'usage_held' + read-side 'interrupted'). */
66
66
  const TERMINAL_STATUSES = Object.freeze([
67
67
  'ok', 'error', 'rate_limited', 'timeout', 'spawn_failed', 'caller_gone', 'slot_timeout',
68
- 'too_many_waiting', 'interrupted',
68
+ 'too_many_waiting', 'interrupted', 'usage_held',
69
69
  ]);
70
70
 
71
71
  /**