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
@@ -22,12 +22,13 @@
22
22
  * stamps `now` at append time). Rows that fail to parse or lack a string `at` are skipped.
23
23
  *
24
24
  * epic_state_changed is read from the per-Epic event logs, not from audit rows:
25
- * every `epic.status_changed` event (written by epicTransitions.transitionEpic at
26
- * the transition, lib/epic/epicEventLog.cjs) of every registered project becomes
27
- * one row { at, kind: 'epic_state_changed', cwd, epicId, from, to, externalRef? }
28
- * (epicStateRowOf), merged into the audit rows by `at` (ties: audit rows first,
29
- * then cwd, epicId, seq) so one cursor covers both. Status values map to the
30
- * outside-state words of lib/epic/epicOutsideState.cjs (STATUS_TO_OUTSIDE).
25
+ * every `epic.state_changed` event (written by lib/epic/epicStateEmitter.cjs with
26
+ * the fine-grained outside state, lib/epic/epicEventLog.cjs) of every registered
27
+ * project becomes one row
28
+ * { at, kind: 'epic_state_changed', cwd, epicId, from, to, blockedKind?, externalRef? }
29
+ * (epicStateRowOf; blockedKind only on a `to: 'blocked'` row), merged into the
30
+ * audit rows by `at` (ties: audit rows first, then cwd, epicId, seq) so one cursor
31
+ * covers both. Lifecycle-only `epic.status_changed` events yield no row.
31
32
  * Legacy epic_state_changed audit rows already in the log stay readable.
32
33
  * Projects come from the `projectRoots` option, else — only when `target` is not
33
34
  * given — promptSessionsIpc's registered projects (cached EPIC_ROOTS_TTL_MS).
@@ -136,9 +137,7 @@ const cursorOf = (at, n) => `${at}~${n}`;
136
137
  // ── epic_state_changed from the per-Epic event logs ──
137
138
 
138
139
  const EPIC_STATE_KIND = 'epic_state_changed';
139
- const EPIC_STATUS_EVENT = 'epic.status_changed';
140
- /** Lifecycle status → the outside-state word epicOutsideState.cjs gives an Epic in that status. */
141
- const STATUS_TO_OUTSIDE = Object.freeze({ proposed: 'awaiting_approval', active: 'open', completed: 'closed' });
140
+ const EPIC_STATE_EVENT = 'epic.state_changed';
142
141
  const EPIC_ROOTS_TTL_MS = 10000;
143
142
  const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
144
143
 
@@ -146,26 +145,24 @@ const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
146
145
  const nonEmpty = (v) => (typeof v === 'string' && v !== '' ? v : null);
147
146
  /** @param {unknown} v @returns {v is Record<string, any>} */
148
147
  const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
149
- /** @param {unknown} status */
150
- const outsideOf = (status) => {
151
- const s = nonEmpty(status);
152
- if (s === null) return null;
153
- return Object.prototype.hasOwnProperty.call(STATUS_TO_OUTSIDE, s) ? STATUS_TO_OUTSIDE[/** @type {'proposed'} */ (s)] : s;
154
- };
155
148
 
156
149
  /**
157
- * One epic.status_changed event → its outside epic_state_changed row, or null.
150
+ * One epic.state_changed event → its outside epic_state_changed row, or null
151
+ * (any other kind, epic.status_changed included).
158
152
  * @param {string} cwd project root the event log belongs to
159
153
  * @param {Record<string, any>} ev a parsed event-log record
160
- * @param {string|null} [externalRef]
154
+ * @param {string|null} [externalRef] fallback ref (active index) when the event carries none
161
155
  */
162
156
  function epicStateRowOf(cwd, ev, externalRef = null) {
163
- if (!isObj(ev) || ev.kind !== EPIC_STATUS_EVENT) return null;
157
+ if (!isObj(ev) || ev.kind !== EPIC_STATE_EVENT) return null;
164
158
  const at = nonEmpty(ev.time);
165
159
  const epicId = nonEmpty(ev.epicId);
166
- if (!at || !epicId) return null;
160
+ const to = nonEmpty(ev.to);
161
+ if (!at || !epicId || !to) return null;
167
162
  /** @type {Record<string, any>} */
168
- const row = { at, kind: EPIC_STATE_KIND, cwd, epicId, from: outsideOf(ev.from), to: outsideOf(ev.to) };
163
+ const row = { at, kind: EPIC_STATE_KIND, cwd, epicId, from: ev.from ?? null, to };
164
+ const blockedKind = to === 'blocked' ? nonEmpty(ev.blockedKind) : null;
165
+ if (blockedKind) row.blockedKind = blockedKind;
169
166
  const ref = nonEmpty(ev.externalRef) || nonEmpty(externalRef);
170
167
  if (ref) row.externalRef = ref;
171
168
  return row;
@@ -179,7 +176,7 @@ const indexCache = new Map();
179
176
  const knownRefs = new Map();
180
177
  let rootsCache = { at: 0, roots: /** @type {string[]} */ ([]) };
181
178
 
182
- /** Status-change events of one event-log file, re-reading only bytes appended since the last call. */
179
+ /** epic.state_changed events of one event-log file, re-reading only bytes appended since the last call. */
183
180
  function statusEventsOf(file) {
184
181
  let size;
185
182
  try { size = fs.statSync(file).size; } catch { logCache.delete(file); return []; }
@@ -199,10 +196,10 @@ function statusEventsOf(file) {
199
196
  if (end >= 0) {
200
197
  const events = c.events.slice();
201
198
  for (const line of text.slice(0, end).split('\n')) {
202
- if (!line.includes(EPIC_STATUS_EVENT)) continue;
199
+ if (!line.includes(EPIC_STATE_EVENT)) continue;
203
200
  try {
204
201
  const r = JSON.parse(line);
205
- if (isObj(r) && r.kind === EPIC_STATUS_EVENT) events.push(r);
202
+ if (isObj(r) && r.kind === EPIC_STATE_EVENT) events.push(r);
206
203
  } catch { /* torn line */ }
207
204
  }
208
205
  c = { size, offset: c.offset + Buffer.byteLength(text.slice(0, end + 1), 'utf8'), events };
@@ -373,5 +370,5 @@ function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiv
373
370
 
374
371
  module.exports = {
375
372
  OUTSIDE_EVENT_KINDS, readEventsAfter, CURSOR_FORM, INVALID_AUDIT_CURSOR, MAX_ARCHIVE_GZ_BYTES,
376
- STATUS_TO_OUTSIDE, epicStateRowOf, _resetEpicStateCacheForTests,
373
+ epicStateRowOf, _resetEpicStateCacheForTests,
377
374
  };
@@ -128,16 +128,20 @@ function rotateIfNeeded(target, now, maxBytes) {
128
128
  /**
129
129
  * appendAuditEvent(kind, fields, opts?) — append one JSONL record. `kind` is a short
130
130
  * label ('epic_mint' | 'prd_create' | ...); `fields` is event-specific detail
131
- * (cwd, epicId, status, title, slug, etc). `opts.now` (Date) / `opts.target` are
131
+ * (cwd, epicId, status, title, slug, etc); a `fields.kind` never overrides `kind`
132
+ * and is stored as `fieldKind`. `opts.now` (Date) / `opts.target` are
132
133
  * test seams. Never throws; a rotation failure never drops the append.
133
134
  */
134
135
  function appendAuditEvent(kind, fields = {}, opts = {}) {
135
136
  try {
136
137
  const now = opts.now ?? new Date();
138
+ // The first-argument kind always wins; a caller field named `kind` is kept as `fieldKind`.
139
+ const { kind: fieldKind, ...rest } = fields ?? {};
137
140
  const record = {
138
141
  at: now.toISOString(),
139
142
  kind,
140
- ...fields,
143
+ ...rest,
144
+ ...(fieldKind !== undefined ? { fieldKind } : {}),
141
145
  caller: callerContext(),
142
146
  };
143
147
  const target = opts.target ?? auditLogPath();
@@ -95,9 +95,9 @@ async function readJsonOr(file, fallback) {
95
95
  }
96
96
  }
97
97
 
98
- function readJsonOrSync(file, fallback) {
98
+ function readJsonOrSync(file, fallback, fsImpl = fs) {
99
99
  try {
100
- const raw = fs.readFileSync(file, 'utf8');
100
+ const raw = fsImpl.readFileSync(file, 'utf8');
101
101
  if (raw.trim() === '') return fallback;
102
102
  return JSON.parse(raw);
103
103
  } catch {
@@ -76,7 +76,7 @@ function mintEventId() {
76
76
  * id, title }` of a macro build's saved entry), and `reply` (`{ fromCwd,
77
77
  * fromEpicId, outcome, referencePaths }` — a cross-project reply's origin, plus
78
78
  * a receipt's optional `hash`/`delivery`/`toEpicId`/`fallbackEpicId`/`reason`/
79
- * `reused`). All
79
+ * `reused`/`release`). All
80
80
  * keys are added to the event object only when present in `meta`, never as
81
81
  * `undefined`-valued keys, so events appended without them serialize
82
82
  * identically to before.
@@ -129,10 +129,25 @@ async function appendResponseEventWithReason(cwd, sourcePromptId, text, meta = {
129
129
  if (typeof meta.reply[k] === 'string' && meta.reply[k]) event.reply[k] = meta.reply[k];
130
130
  }
131
131
  if (meta.reply.reused === true) event.reply.reused = true;
132
+ // A verified release claim (crossProjectReply.cjs): { version, commits }.
133
+ const rel = meta.reply.release;
134
+ if (rel && typeof rel === 'object' && typeof rel.version === 'string'
135
+ && Array.isArray(rel.commits) && rel.commits.every((c) => typeof c === 'string')) {
136
+ event.reply.release = { version: rel.version, commits: rel.commits.slice() };
137
+ }
132
138
  }
133
139
  data.events[sourcePromptId] = [...events, event];
134
140
  await config.writeJson(path, data, { writer: 'scheduler' });
135
141
  broadcast(EVENT_APPENDED_CHANNEL, { cwd, promptSessionId: sourcePromptId, event });
142
+ // Outside-state poke (lib/epic/epicStateEmitter.cjs): a verdict or PRD
143
+ // check-in on this chain writes no event-log kind the emitter listens
144
+ // for, so poke it here. Only after a successful write; never changes
145
+ // the result.
146
+ try {
147
+ require('./lib/epic/epicStateEmitter.cjs').pokeEpicState(cwd, sourcePromptId);
148
+ } catch (e) {
149
+ console.error('[promptSessionEvents] pokeEpicState failed', cwd, sourcePromptId, e);
150
+ }
136
151
  return { ok: true };
137
152
  });
138
153
  } catch (e) {
package/src/main/pty.cjs CHANGED
@@ -27,6 +27,7 @@ const { planEpicSpawn } = require('./lib/epic/epicSpawnPlan.cjs');
27
27
  const { resolveEpicSpawnCwd } = require('./lib/epic/epicSpawnCwd.cjs');
28
28
  const telemetryCounters = require('./lib/telemetry/telemetryCounters.cjs');
29
29
  const artifactStore = require('./lib/epic/artifactStore.cjs');
30
+ const artifactNotice = require('./lib/epic/artifactNotice.cjs');
30
31
  const { findEpicByClaudeSessionId } = require('./lib/claude/agentModelResolve.cjs');
31
32
 
32
33
  // Absolute path to the installed package root (src/main/ -> ../../), shown in
@@ -58,8 +59,9 @@ const ARTIFACT_MIN_AGE_MS = 10_000;
58
59
  * Sweep an Epic Terminal's artifact staging folder (runId = tabId) into the
59
60
  * Artifacts store every ARTIFACT_INGEST_MS. Returns stop(), which clears the
60
61
  * interval and runs one final sweep with no age floor (after any in-flight
61
- * sweep). Notices are not posted here — artifact-ready-notice owns them.
62
- * Errors are logged, never thrown.
62
+ * sweep). Each sweep (interval or exit) that published one or more files posts
63
+ * ONE 'artifact-ready' notice to the Epic chat, as the chat turn-end ingest
64
+ * does; an empty sweep posts nothing. Errors are logged, never thrown.
63
65
  */
64
66
  function startArtifactIngest({ cwd, epicId, tabId }) {
65
67
  let running = Promise.resolve();
@@ -75,6 +77,13 @@ function startArtifactIngest({ cwd, epicId, tabId }) {
75
77
  for (const s of res?.skipped || []) {
76
78
  if (s.reason !== 'still being written') console.error('[pty] artifact not ingested', s.path, s.reason);
77
79
  }
80
+ if (res && Array.isArray(res.published) && res.published.length > 0) {
81
+ try {
82
+ await artifactNotice.postArtifactReadyNotice({ cwd, epicId, entries: res.published });
83
+ } catch (err) {
84
+ console.error('[pty] artifact-ready notice failed', tabId, err?.message ?? err);
85
+ }
86
+ }
78
87
  } catch (err) {
79
88
  console.error('[pty] artifact ingest failed', tabId, err?.message ?? err);
80
89
  }
@@ -388,7 +388,7 @@ async function archiveMany(slugs, cwd, { retire = true, jobs } = {}) {
388
388
  for (const slug of slugs) {
389
389
  if (!cancelled.has(slug)) { toArchive.push(slug); continue; }
390
390
  const warning = `"${slug}" is a cancelled job — archiving it would make it satisfy dependsOn. `
391
- + `Dismiss it instead (${DISMISS_ROUTE}); not archived.`;
391
+ + `Dismiss it instead (scheduler_dismiss_cancelled, or ${DISMISS_ROUTE}); not archived.`;
392
392
  warnings.push(warning);
393
393
  refused.push({ ok: false, slug, cancelled: true, warning, error: warning });
394
394
  }
@@ -653,7 +653,7 @@ function artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl = fs }) {
653
653
  */
654
654
  function captureArtifactEvidence({ prdPath, roots, startedAt, fsImpl = fs } = {}) {
655
655
  try {
656
- const text = fs.readFileSync(prdPath, 'utf8');
656
+ const text = fsImpl.readFileSync(prdPath, 'utf8');
657
657
  const fm = parsePrdFile(text).frontmatter;
658
658
  if (!isArtifactOnlyDeclaration(fm)) return null;
659
659
  const check = artifactsCheck({ cwd: roots, paths: fm.artifactPaths, startedAt, finishedAt: null, fsImpl });
@@ -29,6 +29,7 @@
29
29
  * window: string | null,
30
30
  * percent: number | null,
31
31
  * threshold: number | null,
32
+ * baseThreshold?: number | null,
32
33
  * resetsAt: string | null,
33
34
  * detail: string,
34
35
  * }} AutoDispatchHold
@@ -44,6 +45,63 @@ function resetMs(resetsAt) {
44
45
  return Number.isFinite(ms) ? ms : Infinity;
45
46
  }
46
47
 
48
+ const DAY_MS = 24 * 60 * 60 * 1000;
49
+ const HOUR_MS = 60 * 60 * 1000;
50
+
51
+ /** The pro-rated threshold reaches this in a window's final stretch. */
52
+ const PRO_RATE_CEILING = 100;
53
+ /** Share of a window left at which the threshold reaches the ceiling (last 2 days of a week). */
54
+ const PRO_RATE_FULL_FRACTION = 2 / 7;
55
+ /** Length of each usage window kind. */
56
+ const WINDOW_LENGTH_MS = Object.freeze({ weekly: 7 * DAY_MS, fiveHour: 5 * HOUR_MS });
57
+
58
+ /**
59
+ * Window length from its name, or null for an unknown window.
60
+ * @param {string | null | undefined} window
61
+ * @returns {number | null}
62
+ */
63
+ function windowLengthMs(window) {
64
+ if (typeof window !== 'string') return null;
65
+ if (/weekly|seven_day/i.test(window)) return WINDOW_LENGTH_MS.weekly;
66
+ if (/five_hour|session/i.test(window)) return WINDOW_LENGTH_MS.fiveHour;
67
+ return null;
68
+ }
69
+
70
+ /**
71
+ * Effective 'pause above' value for one window: the owner would rather touch
72
+ * the limit than leave credits unspent, so the threshold rises from `base`
73
+ * (whole window left) linearly to PRO_RATE_CEILING once only
74
+ * PRO_RATE_FULL_FRACTION of the window is left. Never below `base`; unknown
75
+ * window, missing/unparseable reset, or non-finite base -> base unchanged.
76
+ * @param {{ base: number, window: string | null | undefined, resetsAt: string | null | undefined, now: number }} args
77
+ * @returns {number}
78
+ */
79
+ function proRatedThreshold({ base, window, resetsAt, now }) {
80
+ if (typeof base !== 'number' || !Number.isFinite(base)) return base;
81
+ if (base >= PRO_RATE_CEILING) return base;
82
+ const length = windowLengthMs(window);
83
+ if (length === null) return base;
84
+ const reset = resetMs(resetsAt);
85
+ if (!Number.isFinite(reset)) return base;
86
+ const f = (reset - now) / length;
87
+ if (!Number.isFinite(f)) return base;
88
+ if (f >= 1) return base;
89
+ if (f <= PRO_RATE_FULL_FRACTION) return PRO_RATE_CEILING;
90
+ const value = base + (PRO_RATE_CEILING - base) * (1 - f) / (1 - PRO_RATE_FULL_FRACTION);
91
+ return Math.max(base, value);
92
+ }
93
+
94
+ /**
95
+ * Human time left: "1.7 days", "4.0 h", "25 min".
96
+ * @param {number} ms
97
+ * @returns {string}
98
+ */
99
+ function formatTimeLeft(ms) {
100
+ if (ms >= DAY_MS) return `${(ms / DAY_MS).toFixed(1)} days`;
101
+ if (ms >= HOUR_MS) return `${(ms / HOUR_MS).toFixed(1)} h`;
102
+ return `${String(Math.max(0, Math.round(ms / 60_000)))} min`;
103
+ }
104
+
47
105
  /**
48
106
  * @param {{
49
107
  * firePolicy: string | null | undefined,
@@ -66,14 +124,13 @@ function evaluateAutoDispatchHold({ firePolicy, threshold, reading, now }) {
66
124
  }
67
125
  if (reading == null || reading.known !== true) return null;
68
126
  if (typeof threshold !== 'number' || !Number.isFinite(threshold)) return null;
69
- const limit = threshold;
70
127
 
71
128
  /** @type {UsageWindow[]} */
72
129
  const candidates = Array.isArray(reading.windows) && reading.windows.length > 0
73
130
  ? reading.windows
74
131
  : [{ window: reading.window, percent: reading.percent, resetsAt: reading.resetsAt }];
75
132
 
76
- /** @type {{ window: string | null, percent: number, resetsAt: string | null, resetAt: number } | null} */
133
+ /** @type {{ window: string | null, percent: number, resetsAt: string | null, resetAt: number, limit: number } | null} */
77
134
  let pick = null;
78
135
  for (const c of candidates) {
79
136
  if (!c) continue;
@@ -81,21 +138,54 @@ function evaluateAutoDispatchHold({ firePolicy, threshold, reading, now }) {
81
138
  if (typeof percent !== 'number' || !Number.isFinite(percent)) continue;
82
139
  const resetAt = resetMs(c.resetsAt);
83
140
  if (resetAt <= now) continue; // already reset: its old reading no longer applies
141
+ const limit = utilizationHold.proRatedThreshold({ base: threshold, window: c.window, resetsAt: c.resetsAt, now });
84
142
  if (percent < limit) continue;
85
143
  if (pick === null || resetAt > pick.resetAt || (resetAt === pick.resetAt && percent > pick.percent)) {
86
- pick = { window: c.window ?? null, percent, resetsAt: c.resetsAt ?? null, resetAt };
144
+ pick = { window: c.window ?? null, percent, resetsAt: c.resetsAt ?? null, resetAt, limit };
87
145
  }
88
146
  }
89
147
  if (pick === null) return null;
90
148
 
149
+ const proRated = pick.limit !== threshold
150
+ ? ` (pause above ${String(threshold)}%, pro-rated: ${formatTimeLeft(pick.resetAt - now)} to reset)`
151
+ : '';
152
+ const shownLimit = Math.round(pick.limit * 10) / 10;
91
153
  return {
92
154
  reason: 'utilization-held',
93
155
  window: pick.window,
94
156
  percent: pick.percent,
95
- threshold: limit,
157
+ threshold: pick.limit,
158
+ baseThreshold: threshold,
96
159
  resetsAt: pick.resetsAt,
97
- detail: `${pick.window ?? 'binding'} window at ${String(pick.percent)}% ≥ ${String(limit)}%, resets ${pick.resetsAt ?? 'unknown'}`,
160
+ detail: `${pick.window ?? 'binding'} window at ${String(pick.percent)}% ≥ ${String(shownLimit)}%${proRated}, resets ${pick.resetsAt ?? 'unknown'}`,
98
161
  };
99
162
  }
100
163
 
101
- module.exports = { evaluateAutoDispatchHold };
164
+ const MINUTE_MS = 60_000;
165
+
166
+ /**
167
+ * Identity of one auto-dispatch hold: reason + window + reset, for the
168
+ * once-per-hold audit keys. The usage API returns a different resets_at string
169
+ * for the same reset on almost every fetch (329 distinct strings for one
170
+ * weekly reset across 640 heartbeat lines, about ±0.5 s either side of the
171
+ * minute), so the reset is rounded to the nearest whole minute. An unparseable
172
+ * resetsAt is used raw ('' when absent) so the key stays stable.
173
+ * @param {{ reason: string, window?: string | null, resetsAt?: string | null }} hold
174
+ * @returns {string}
175
+ */
176
+ function holdIdentityKey(hold) {
177
+ const raw = hold.resetsAt ?? '';
178
+ const ms = typeof hold.resetsAt === 'string' ? Date.parse(hold.resetsAt) : NaN;
179
+ const reset = Number.isFinite(ms) ? new Date(Math.round(ms / MINUTE_MS) * MINUTE_MS).toISOString() : raw;
180
+ return `${hold.reason}|${hold.window ?? ''}|${reset}`;
181
+ }
182
+
183
+ const utilizationHold = {
184
+ evaluateAutoDispatchHold,
185
+ holdIdentityKey,
186
+ proRatedThreshold,
187
+ PRO_RATE_CEILING,
188
+ PRO_RATE_FULL_FRACTION,
189
+ WINDOW_LENGTH_MS,
190
+ };
191
+ module.exports = utilizationHold;