claude-code-session-manager 0.140.0 → 0.142.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -70
- package/bin/cli.cjs +11 -0
- package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
- package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
- package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
- package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
- package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
- package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
- package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
- package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
- package/dist/assets/Toggle-CiYCWLjh.js +1 -0
- package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
- package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
- package/dist/assets/index-Cn5E9958.js +3133 -0
- package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +496 -484
- package/package.json +4 -2
- package/plugins/AGENTS.md +4 -3
- package/plugins/session-manager-dev/hooks/hooks.json +15 -0
- package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
- package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
- package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
- package/scripts/README.md +1 -0
- package/scripts/hooks/guard-tool-risk.cjs +5 -1
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
- package/scripts/scheduler-mcp-server.cjs +737 -110
- package/src/main/adminRouteRegistry.cjs +59 -0
- package/src/main/agentLibrary.cjs +72 -4
- package/src/main/agentsIpc.cjs +3 -2
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +231 -16
- package/src/main/config.cjs +30 -0
- package/src/main/docEdit.cjs +4 -2
- package/src/main/health.cjs +91 -0
- package/src/main/index.cjs +98 -48
- package/src/main/ipcSchemas.cjs +171 -8
- package/src/main/lib/AGENTS.md +1 -1
- package/src/main/lib/chatBootRecovery.cjs +2 -0
- package/src/main/lib/claude/agentModelResolve.cjs +51 -25
- package/src/main/lib/claude/agentSnapshot.cjs +186 -0
- package/src/main/lib/claude/environmentProfiles.cjs +242 -0
- package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
- package/src/main/lib/claude/personaToolScope.cjs +82 -31
- package/src/main/lib/claude/runClaudeP.cjs +4 -2
- package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
- package/src/main/lib/claude/usageCircuit.cjs +49 -21
- package/src/main/lib/claude/vaultRefs.cjs +277 -0
- package/src/main/lib/demo-video-kit/capture.cjs +282 -12
- package/src/main/lib/demo-video-kit/cast.md +43 -0
- package/src/main/lib/demo-video-kit/character.cjs +722 -30
- package/src/main/lib/demo-video-kit/checks.cjs +120 -1
- package/src/main/lib/demo-video-kit/export.cjs +218 -0
- package/src/main/lib/demo-video-kit/frames.cjs +104 -9
- package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
- package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
- package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
- package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
- package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
- package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
- package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
- package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
- package/src/main/lib/epic/artifactIpc.cjs +153 -0
- package/src/main/lib/epic/artifactNotice.cjs +72 -0
- package/src/main/lib/epic/artifactRetention.cjs +310 -0
- package/src/main/lib/epic/artifactStore.cjs +392 -0
- package/src/main/lib/epic/delegationReadiness.cjs +76 -2
- package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
- package/src/main/lib/epic/epicEventLog.cjs +214 -0
- package/src/main/lib/epic/epicMint.cjs +43 -1
- package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
- package/src/main/lib/epic/epicOutsideState.cjs +18 -4
- package/src/main/lib/epic/epicPurge.cjs +347 -0
- package/src/main/lib/epic/epicReopen.cjs +5 -2
- package/src/main/lib/epic/epicSettle.cjs +4 -13
- package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
- package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
- package/src/main/lib/epic/epicTransitions.cjs +139 -0
- package/src/main/lib/epic/epicValidationHook.cjs +81 -2
- package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
- package/src/main/lib/externalContract.cjs +37 -4
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
- package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
- package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
- package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
- package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
- package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
- package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
- package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
- package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
- package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
- package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
- package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
- package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
- package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
- package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
- package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
- package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
- package/src/main/lib/git/worktreeDeps.cjs +77 -2
- package/src/main/lib/mcpToolCatalog.cjs +315 -30
- package/src/main/lib/opsOwnership.cjs +29 -1
- package/src/main/lib/opsRetentionSettings.cjs +27 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
- package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
- package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
- package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
- package/src/main/lib/phaseProjection.cjs +103 -0
- package/src/main/lib/prd/depSlugResolve.cjs +4 -13
- package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
- package/src/main/lib/prd/prdCreate.cjs +67 -5
- package/src/main/lib/prd/prdCriteria.cjs +225 -0
- package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
- package/src/main/lib/prd/prdGateFiles.cjs +125 -49
- package/src/main/lib/prd/prdSizing.cjs +3 -1
- package/src/main/lib/process/cleanEnv.cjs +52 -1
- package/src/main/lib/process/leftoverRenice.cjs +178 -0
- package/src/main/lib/process/memoryScope.cjs +31 -3
- package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
- package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
- package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
- package/src/main/lib/project-pages/voicePreview.cjs +196 -0
- package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
- package/src/main/lib/promptSessionSchema.cjs +6 -0
- package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
- package/src/main/lib/scheduler/cpuSample.cjs +133 -42
- package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
- package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
- package/src/main/lib/scheduler/loadGate.cjs +82 -4
- package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
- package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
- package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
- package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
- package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
- package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
- package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
- package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
- package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
- package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
- package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
- package/src/main/lib/scheduler/toolClearance.cjs +258 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
- package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
- package/src/main/lib/tasks/mitigationReview.cjs +294 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
- package/src/main/lib/tasks/taskIpc.cjs +22 -18
- package/src/main/lib/tasks/taskLedger.cjs +147 -25
- package/src/main/lib/tasks/taskRun.cjs +186 -17
- package/src/main/lib/tasks/taskSwitch.cjs +85 -12
- package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
- package/src/main/lib/telemetry/auditEvents.cjs +207 -6
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
- package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
- package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
- package/src/main/lib/toolUseClassify.cjs +181 -0
- package/src/main/lib/util/smfileRange.cjs +77 -0
- package/src/main/projectPages.cjs +3 -1
- package/src/main/promptSessionEvents.cjs +5 -0
- package/src/main/pty.cjs +68 -0
- package/src/main/queueOps.cjs +32 -13
- package/src/main/runVerify.cjs +74 -9
- package/src/main/scheduler/AGENTS.md +1 -0
- package/src/main/scheduler/budget.cjs +6 -5
- package/src/main/scheduler/prdParser.cjs +62 -14
- package/src/main/scheduler/reviewLadder.cjs +45 -28
- package/src/main/scheduler/starvation.cjs +69 -0
- package/src/main/scheduler/utilizationHold.cjs +101 -0
- package/src/main/scheduler.cjs +1745 -210
- package/src/main/templates/PRD_AUTHORING.md +13 -2
- package/src/main/webRemote.cjs +463 -6
- package/src/preload/api.d.ts +529 -38
- package/src/preload/apiSurface.json +209 -7
- package/src/preload/index.cjs +46 -1
- package/src/seed/agents/architect.md +6 -1
- package/src/seed/agents/blender-artist.md +2 -1
- package/src/seed/agents/competitive-analyst.md +3 -1
- package/src/seed/agents/competitive-researcher.md +2 -1
- package/src/seed/agents/demo-video-builder.md +87 -83
- package/src/seed/agents/dev-lead.md +3 -3
- package/src/seed/agents/project-home-builder.md +9 -31
- package/src/seed/agents/validator.md +9 -10
- package/dist/assets/AppSettings-CMFEM68R.js +0 -2
- package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
- package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
- package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
- package/dist/assets/index-CtxruO1L.js +0 -3121
- package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* jobMemoryStats.cjs — recorded per-job memory peaks → per-agentType reservation
|
|
5
|
+
* and one shared spike buffer, so the memory gate can reserve what jobs really use
|
|
6
|
+
* instead of a flat 2,500 MB (≈p93 of 2,457 measured scopes: p50 670, p75 1,269,
|
|
7
|
+
* p90 1,994, p95 2,663, max 9,142 MB).
|
|
8
|
+
*
|
|
9
|
+
* Store: `<schedulerHome>/job-memory-peaks.jsonl`, one `{agentType, peakMb, at}`
|
|
10
|
+
* per line, trimmed to the newest MAX_SAMPLES, rewritten via util/atomicFs.cjs.
|
|
11
|
+
* Reads are cached CACHE_MS. Quantiles are nearest-rank. Pure Node, no Electron.
|
|
12
|
+
*
|
|
13
|
+
* The default instance's functions are the module exports; createJobMemoryStats()
|
|
14
|
+
* builds one with injected { fs, now, storePath, writeTextAtomicSync, writeTextAtomic } for tests
|
|
15
|
+
* (writeTextAtomicSync: recordPeak's write; writeTextAtomic: the backfill's async write).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const nodeFs = require('node:fs');
|
|
19
|
+
const path = require('node:path');
|
|
20
|
+
const atomicFs = require('../util/atomicFs.cjs');
|
|
21
|
+
|
|
22
|
+
const STORE_FILE = 'job-memory-peaks.jsonl';
|
|
23
|
+
const MAX_SAMPLES = 2000;
|
|
24
|
+
const RECENT_PER_TYPE = 200;
|
|
25
|
+
const MIN_SAMPLES = 30;
|
|
26
|
+
const CACHE_MS = 60_000;
|
|
27
|
+
const DEFAULT_RESERVATION_MB = 2500;
|
|
28
|
+
const DEFAULT_TYPICAL_MB = 1000;
|
|
29
|
+
const DEFAULT_SPIKE_BUFFER_MB = 1500;
|
|
30
|
+
const RESERVATION_CLAMP = [800, 4000];
|
|
31
|
+
const TYPICAL_CLAMP = [300, 2500];
|
|
32
|
+
const SPIKE_CLAMP = [500, 3000];
|
|
33
|
+
const DEFAULT_MAX_FILES = 2000;
|
|
34
|
+
const BACKFILL_BATCH = 50; // run-log files read concurrently per batch
|
|
35
|
+
const PEAK_LINE_RE = /\[scheduler\] memory scope (\S+): peak=(\d+)MB/g;
|
|
36
|
+
|
|
37
|
+
function clamp(v, [lo, hi]) { return Math.min(hi, Math.max(lo, v)); }
|
|
38
|
+
|
|
39
|
+
/** Nearest-rank quantile: the ceil(q*n)-th smallest value (1-based). `values` need not be sorted. */
|
|
40
|
+
function quantile(values, q) {
|
|
41
|
+
if (!values.length) return NaN;
|
|
42
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
43
|
+
const rank = Math.max(1, Math.ceil(q * sorted.length));
|
|
44
|
+
return sorted[Math.min(sorted.length, rank) - 1];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function normalizeSample(s) {
|
|
48
|
+
if (!s || typeof s !== 'object') return null;
|
|
49
|
+
const peakMb = Number(s.peakMb);
|
|
50
|
+
if (!Number.isFinite(peakMb) || peakMb < 0) return null;
|
|
51
|
+
const agentType = typeof s.agentType === 'string' && s.agentType ? s.agentType : 'unknown';
|
|
52
|
+
const at = Number.isFinite(Number(s.at)) ? Number(s.at) : 0;
|
|
53
|
+
const out = { agentType, peakMb: Math.round(peakMb), at };
|
|
54
|
+
// Optional provenance: the run folder + scope unit, so the boot backfill never re-adds a peak.
|
|
55
|
+
if (typeof s.runId === 'string' && s.runId) out.runId = s.runId;
|
|
56
|
+
if (typeof s.unit === 'string' && s.unit) out.unit = s.unit;
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function defaultStorePath() {
|
|
61
|
+
return path.join(require('./schedulerPaths.cjs').schedulerHome(), STORE_FILE);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function createJobMemoryStats(deps = {}) {
|
|
65
|
+
const fs = deps.fs || nodeFs;
|
|
66
|
+
const now = deps.now || Date.now;
|
|
67
|
+
const writeText = deps.writeTextAtomicSync || atomicFs.writeTextAtomicSync;
|
|
68
|
+
const writeTextAsync = deps.writeTextAtomic || atomicFs.writeTextAtomic;
|
|
69
|
+
const resolveStorePath = () => (typeof deps.storePath === 'function' ? deps.storePath() : deps.storePath) || defaultStorePath();
|
|
70
|
+
let cache = null; // { at, file, samples }
|
|
71
|
+
let liveDuringWrite = null; // live recordPeak samples landing while the backfill's async write is in flight
|
|
72
|
+
|
|
73
|
+
function parseSamples(text) {
|
|
74
|
+
const out = [];
|
|
75
|
+
for (const line of String(text).split('\n')) {
|
|
76
|
+
if (!line.trim()) continue;
|
|
77
|
+
try {
|
|
78
|
+
const s = normalizeSample(JSON.parse(line));
|
|
79
|
+
if (s) out.push(s);
|
|
80
|
+
} catch { /* skip a torn line */ }
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function readSamplesUncached(file) {
|
|
86
|
+
let text;
|
|
87
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
|
|
88
|
+
return parseSamples(text);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function readSamplesAsync(file) {
|
|
92
|
+
let text;
|
|
93
|
+
try { text = await fs.promises.readFile(file, 'utf8'); } catch { return []; }
|
|
94
|
+
return parseSamples(text);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const serialize = (kept) => kept.map((x) => JSON.stringify(x)).join('\n') + (kept.length ? '\n' : '');
|
|
98
|
+
|
|
99
|
+
/** All stored samples, oldest first (file order). Cached CACHE_MS per store path. */
|
|
100
|
+
function loadSamples() {
|
|
101
|
+
const file = resolveStorePath();
|
|
102
|
+
const t = now();
|
|
103
|
+
if (cache && cache.file === file && t - cache.at < CACHE_MS) return cache.samples;
|
|
104
|
+
const samples = readSamplesUncached(file);
|
|
105
|
+
cache = { at: t, file, samples };
|
|
106
|
+
return samples;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function writeSamples(file, samples) {
|
|
110
|
+
const kept = samples.slice(-MAX_SAMPLES);
|
|
111
|
+
writeText(file, serialize(kept));
|
|
112
|
+
cache = { at: now(), file, samples: kept };
|
|
113
|
+
return kept;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function writeSamplesAsync(file, samples) {
|
|
117
|
+
const kept = samples.slice(-MAX_SAMPLES);
|
|
118
|
+
await writeTextAsync(file, serialize(kept));
|
|
119
|
+
cache = { at: now(), file, samples: kept };
|
|
120
|
+
return kept;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function appendSamples(newSamples) {
|
|
124
|
+
const file = resolveStorePath();
|
|
125
|
+
const existing = readSamplesUncached(file);
|
|
126
|
+
return writeSamples(file, [...existing, ...newSamples]);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Records one job's peak. Returns the stored sample, or null when the input is unusable. */
|
|
130
|
+
function recordPeak({ agentType, peakMb, at, runId, unit } = {}) {
|
|
131
|
+
const s = normalizeSample({ agentType, peakMb, at: at === undefined ? now() : at, runId, unit });
|
|
132
|
+
if (!s) return null;
|
|
133
|
+
appendSamples([s]);
|
|
134
|
+
if (liveDuringWrite) liveDuringWrite.push(s);
|
|
135
|
+
return s;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Peaks to take quantiles of: agentType's newest 200 when it has ≥30, else all when ≥30, else null. */
|
|
139
|
+
function basisFor(agentType) {
|
|
140
|
+
const all = loadSamples();
|
|
141
|
+
const own = all.filter((s) => s.agentType === agentType);
|
|
142
|
+
if (own.length >= MIN_SAMPLES) return own.slice(-RECENT_PER_TYPE).map((s) => s.peakMb);
|
|
143
|
+
if (all.length >= MIN_SAMPLES) return all.map((s) => s.peakMb);
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** p75 peak for agentType (MB), clamped 800-4000; 2500 with too few samples. */
|
|
148
|
+
function reservationMb(agentType) {
|
|
149
|
+
const basis = basisFor(agentType);
|
|
150
|
+
if (!basis) return DEFAULT_RESERVATION_MB;
|
|
151
|
+
return clamp(quantile(basis, 0.75), RESERVATION_CLAMP);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** p50 peak for agentType (MB), clamped 300-2500; 1000 with too few samples. */
|
|
155
|
+
function typicalPeakMb(agentType) {
|
|
156
|
+
const basis = basisFor(agentType);
|
|
157
|
+
if (!basis) return DEFAULT_TYPICAL_MB;
|
|
158
|
+
return clamp(quantile(basis, 0.5), TYPICAL_CLAMP);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** p95 − p75 of all samples (one job at its p95 while the rest sit near p75), clamped 500-3000; 1500 with too few. */
|
|
162
|
+
function spikeBufferMb() {
|
|
163
|
+
const all = loadSamples().map((s) => s.peakMb);
|
|
164
|
+
if (all.length < MIN_SAMPLES) return DEFAULT_SPIKE_BUFFER_MB;
|
|
165
|
+
return clamp(quantile(all, 0.95) - quantile(all, 0.75), SPIKE_CLAMP);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** True once the store holds ≥ MIN_SAMPLES peaks, i.e. the quantiles above are measured, not fallbacks. */
|
|
169
|
+
function isMeasured() {
|
|
170
|
+
return loadSamples().length >= MIN_SAMPLES;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Directory entries under dir (async), or [] when unreadable. */
|
|
174
|
+
async function listDir(dir) {
|
|
175
|
+
try { return await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return []; }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Yields the event loop once (between read batches). */
|
|
179
|
+
const yieldTurn = () => new Promise((resolve) => setImmediate(resolve));
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Seeds the store from run logs' 'memory scope <unit>: peak=<N>MB' lines
|
|
183
|
+
* (agentType 'unknown', at = log mtime) while it holds fewer than MIN_SAMPLES.
|
|
184
|
+
* `runsDir` is the scheduler runs folder (<runId>/<slug>.log). Only the newest
|
|
185
|
+
* maxFiles × 2 run folders (by name — names are timestamps) are listed, whether
|
|
186
|
+
* or not they hold logs, so a sparse runs folder never costs a listing per run;
|
|
187
|
+
* among them the walk stops once maxFiles logs are picked, and only picked logs
|
|
188
|
+
* are read and stat'd. A peak is deduped by run folder + scope unit (a stored
|
|
189
|
+
* sample without a runId — a peak recorded before live peaks carried one — can
|
|
190
|
+
* only match by unit).
|
|
191
|
+
*
|
|
192
|
+
* I/O: the store reads, run-log listings/reads/stats and the final store write
|
|
193
|
+
* (util/atomicFs writeTextAtomic) are all fs.promises, run-log reads in batches
|
|
194
|
+
* of at most BACKFILL_BATCH with an event-loop yield between batches. Nothing
|
|
195
|
+
* runs synchronously except one case: when a live recordPeak lands while that
|
|
196
|
+
* async write is in flight (our rename may have replaced its line), the store
|
|
197
|
+
* is re-read and the missing live peak re-appended with the same synchronous
|
|
198
|
+
* writer recordPeak itself uses. Never rejects. Resolves to the number added.
|
|
199
|
+
*/
|
|
200
|
+
async function backfillFromRunLogs(runsDir, { maxFiles = DEFAULT_MAX_FILES } = {}) {
|
|
201
|
+
try {
|
|
202
|
+
if (typeof runsDir !== 'string' || !runsDir) return 0;
|
|
203
|
+
const file = resolveStorePath();
|
|
204
|
+
const existing = await readSamplesAsync(file);
|
|
205
|
+
if (existing.length >= MIN_SAMPLES) return 0;
|
|
206
|
+
const budget = Math.max(0, Math.floor(Number(maxFiles) || 0));
|
|
207
|
+
if (!budget) return 0;
|
|
208
|
+
const keyOf = (runId, unit) => `${runId}\0${unit}`;
|
|
209
|
+
const seen = new Set();
|
|
210
|
+
const legacyUnits = new Set(); // stored peaks with no run folder
|
|
211
|
+
const noteStored = (samples) => {
|
|
212
|
+
for (const x of samples) {
|
|
213
|
+
if (!x.unit) continue;
|
|
214
|
+
if (x.runId) seen.add(keyOf(x.runId, x.unit));
|
|
215
|
+
else legacyUnits.add(x.unit);
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
noteStored(existing);
|
|
219
|
+
const isStored = (runId, unit) => seen.has(keyOf(runId, unit)) || legacyUnits.has(unit);
|
|
220
|
+
const runIds = (await listDir(runsDir)).filter((e) => e.isDirectory()).map((e) => e.name)
|
|
221
|
+
.sort().reverse().slice(0, budget * 2);
|
|
222
|
+
// Pick the newest `budget` logs: [{ runId, p }], newest run first.
|
|
223
|
+
const picked = [];
|
|
224
|
+
for (const runId of runIds) {
|
|
225
|
+
if (picked.length >= budget) break;
|
|
226
|
+
const dir = path.join(runsDir, runId);
|
|
227
|
+
const logs = (await listDir(dir)).filter((e) => e.isFile() && e.name.endsWith('.log')).map((e) => e.name).sort();
|
|
228
|
+
for (const name of logs) {
|
|
229
|
+
if (picked.length >= budget) break;
|
|
230
|
+
picked.push({ runId, p: path.join(dir, name) });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const readOne = async ({ runId, p }) => {
|
|
234
|
+
let text;
|
|
235
|
+
try { text = await fs.promises.readFile(p, 'utf8'); } catch { return null; }
|
|
236
|
+
let mtimeMs = 0;
|
|
237
|
+
try { mtimeMs = (await fs.promises.stat(p)).mtimeMs; } catch { /* keep 0 */ }
|
|
238
|
+
return { runId, text: String(text), mtimeMs };
|
|
239
|
+
};
|
|
240
|
+
const perRun = new Map(); // runId → samples, insertion order = newest run first
|
|
241
|
+
for (let i = 0; i < picked.length; i += BACKFILL_BATCH) {
|
|
242
|
+
if (i > 0) await yieldTurn();
|
|
243
|
+
const results = await Promise.all(picked.slice(i, i + BACKFILL_BATCH).map(readOne));
|
|
244
|
+
for (const r of results) {
|
|
245
|
+
if (!r) continue;
|
|
246
|
+
if (!perRun.has(r.runId)) perRun.set(r.runId, []);
|
|
247
|
+
const found = perRun.get(r.runId);
|
|
248
|
+
for (const m of r.text.matchAll(PEAK_LINE_RE)) {
|
|
249
|
+
const unit = m[1];
|
|
250
|
+
if (isStored(r.runId, unit)) continue;
|
|
251
|
+
seen.add(keyOf(r.runId, unit));
|
|
252
|
+
found.push({ agentType: 'unknown', peakMb: Number(m[2]), at: Math.round(r.mtimeMs), runId: r.runId, unit });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// Re-read the store: a live recordPeak may have landed while the logs were read.
|
|
257
|
+
liveDuringWrite = [];
|
|
258
|
+
let samples;
|
|
259
|
+
try {
|
|
260
|
+
const current = await readSamplesAsync(file);
|
|
261
|
+
seen.clear();
|
|
262
|
+
noteStored(current);
|
|
263
|
+
samples = [...perRun.values()].reverse().flat() // oldest first, like the live store
|
|
264
|
+
.filter((x) => !isStored(x.runId, x.unit));
|
|
265
|
+
if (!samples.length) return 0;
|
|
266
|
+
await writeSamplesAsync(file, [...current, ...samples]);
|
|
267
|
+
} finally {
|
|
268
|
+
const landed = liveDuringWrite;
|
|
269
|
+
liveDuringWrite = null;
|
|
270
|
+
if (landed.length && samples && samples.length) {
|
|
271
|
+
const stored = readSamplesUncached(file);
|
|
272
|
+
const have = new Set(stored.map((x) => JSON.stringify(x)));
|
|
273
|
+
const missing = landed.filter((x) => !have.has(JSON.stringify(x)));
|
|
274
|
+
if (missing.length) writeSamples(file, [...stored, ...missing]);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return Math.min(samples.length, MAX_SAMPLES);
|
|
278
|
+
} catch {
|
|
279
|
+
return 0;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
recordPeak,
|
|
285
|
+
reservationMb,
|
|
286
|
+
typicalPeakMb,
|
|
287
|
+
spikeBufferMb,
|
|
288
|
+
isMeasured,
|
|
289
|
+
backfillFromRunLogs,
|
|
290
|
+
loadSamples,
|
|
291
|
+
_resetCache() { cache = null; },
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const defaultInstance = createJobMemoryStats();
|
|
296
|
+
|
|
297
|
+
module.exports = {
|
|
298
|
+
recordPeak: defaultInstance.recordPeak,
|
|
299
|
+
reservationMb: defaultInstance.reservationMb,
|
|
300
|
+
typicalPeakMb: defaultInstance.typicalPeakMb,
|
|
301
|
+
spikeBufferMb: defaultInstance.spikeBufferMb,
|
|
302
|
+
isMeasured: defaultInstance.isMeasured,
|
|
303
|
+
backfillFromRunLogs: defaultInstance.backfillFromRunLogs,
|
|
304
|
+
createJobMemoryStats,
|
|
305
|
+
quantile,
|
|
306
|
+
STORE_FILE,
|
|
307
|
+
MAX_SAMPLES,
|
|
308
|
+
RECENT_PER_TYPE,
|
|
309
|
+
MIN_SAMPLES,
|
|
310
|
+
CACHE_MS,
|
|
311
|
+
DEFAULT_RESERVATION_MB,
|
|
312
|
+
BACKFILL_BATCH,
|
|
313
|
+
};
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* loadGate.cjs — CPU-load launch gate for the scheduler (PRD 1085).
|
|
5
5
|
*
|
|
6
|
-
* The scheduler already gates launches on free memory (
|
|
7
|
-
*
|
|
6
|
+
* The scheduler already gates launches on free memory (measuredMemoryGate
|
|
7
|
+
* below, PRD 4019) and on a static per-project cap
|
|
8
8
|
* (schedulerConfig.projectJobCap). Neither sees CPU. Observed 2026-09-01 on
|
|
9
9
|
* starry-night-ships: 4 concurrent executors each running a Godot test
|
|
10
10
|
* battery under its own Xvfb, loadavg 12.95 on 14 cores. Under that
|
|
@@ -49,7 +49,9 @@ const SATURATED_BUSY = 0.85;
|
|
|
49
49
|
|
|
50
50
|
// The busy fraction every band above judges is NET of this app's own process
|
|
51
51
|
// tree (PRD 3495; cpuSample.cjs readOwnProcessTicks) — the app must not gate on
|
|
52
|
-
// its own renderer/main load
|
|
52
|
+
// its own renderer/main load — and of every process at nice 19 (PRD 4021): those
|
|
53
|
+
// yield to jobs, so they are not load to defend. Raw, own and idle-priority
|
|
54
|
+
// shares are still reported. A sampler
|
|
53
55
|
// without a net figure (non-Linux, legacy injection) falls back to raw.
|
|
54
56
|
function busyOf(sample) {
|
|
55
57
|
if (!sample) return null;
|
|
@@ -186,6 +188,7 @@ function createLoadGate({
|
|
|
186
188
|
cpuBusyRaw: null,
|
|
187
189
|
cpuBusyNet: null,
|
|
188
190
|
cpuOwnBusy: null,
|
|
191
|
+
cpuIdleNice: null,
|
|
189
192
|
cpuIowait: null,
|
|
190
193
|
cpuWindowMs: null,
|
|
191
194
|
standDown: false,
|
|
@@ -244,6 +247,7 @@ function createLoadGate({
|
|
|
244
247
|
cpuBusyRaw: sample ? round3(sample.busyFraction) : null,
|
|
245
248
|
cpuBusyNet: round3(busy),
|
|
246
249
|
cpuOwnBusy: sample && Number.isFinite(sample.ownFraction) ? round3(sample.ownFraction) : null,
|
|
250
|
+
cpuIdleNice: sample && Number.isFinite(sample.idleNiceShare) ? round3(sample.idleNiceShare) : null,
|
|
247
251
|
cpuIowait: sample ? Number(sample.iowaitFraction.toFixed(3)) : null,
|
|
248
252
|
cpuWindowMs: sample ? sample.windowMs : null,
|
|
249
253
|
standDown,
|
|
@@ -282,4 +286,78 @@ function createLoadGate({
|
|
|
282
286
|
return { evaluate, observe, snapshot, endHold, isSaturated };
|
|
283
287
|
}
|
|
284
288
|
|
|
285
|
-
|
|
289
|
+
/**
|
|
290
|
+
* Human-readable explanation for a `reason: 'load-deferred'` tick, surfaced
|
|
291
|
+
* to the renderer via lastTick.detail (scheduler.cjs). Names the gate, the
|
|
292
|
+
* measured ratio, the threshold, the net CPU sample, the idle-priority (nice 19)
|
|
293
|
+
* share left out of it when above 0, and how long this gate itself has held a
|
|
294
|
+
* batch that slots and memory admitted (heldMs). Pure.
|
|
295
|
+
*/
|
|
296
|
+
function formatLoadGateDetail(load) {
|
|
297
|
+
const heldMinutes = Math.round(load.heldMs / 60_000);
|
|
298
|
+
let cpu = load.cpuBusy == null
|
|
299
|
+
? 'no CPU sample yet'
|
|
300
|
+
: `CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`;
|
|
301
|
+
if (load.cpuBusy != null && load.cpuIdleNice > 0) {
|
|
302
|
+
cpu += ` (excl. ${Math.round(load.cpuIdleNice * 100)}% at nice 19)`;
|
|
303
|
+
}
|
|
304
|
+
return `CPU load gate: loadavg1 ${load.loadavg1} / ${load.cores} cores = ${load.ratio} > threshold ${load.threshold}, ${cpu}, held ${heldMinutes}m with slots and memory free`;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* measuredMemoryGate({ jobBudgetMb, running, batch, stats }) → decision
|
|
309
|
+
*
|
|
310
|
+
* The memory gate's math (PRD 4019). `jobBudgetMb` is MemAvailable minus the host
|
|
311
|
+
* reserve (scheduler.cjs availableForJobs). Admitting the first k jobs of `batch`
|
|
312
|
+
* needs
|
|
313
|
+
* spikeBufferMb() (one, shared)
|
|
314
|
+
* + Σ running max(0, typicalPeakMb(agentType) − rssMb) (growth still to come)
|
|
315
|
+
* + Σ first k batch jobs reservationMb(agentType) (p75; RSS 0 at launch)
|
|
316
|
+
* Running jobs' resident memory is already out of MemAvailable, so each keeps only
|
|
317
|
+
* its typical growth; its RSS credit is capped at that typical peak.
|
|
318
|
+
*
|
|
319
|
+
* With too few samples (`stats.isMeasured()` false) the typical peak IS the
|
|
320
|
+
* reservation (2,500 MB fallback) and there is no spike buffer — exactly the old
|
|
321
|
+
* flat MIN_FREE_MB_PER_JOB rule. Infinity budget (non-Linux) admits everything.
|
|
322
|
+
*
|
|
323
|
+
* running: [{ agentType, rssMb }]; batch: [{ agentType }]; stats: jobMemoryStats.
|
|
324
|
+
* Returns { allowed, measured, needMb, reservationMb, spikeBufferMb, growthMb,
|
|
325
|
+
* consumedMb } where needMb/reservationMb are for the first job NOT admitted
|
|
326
|
+
* (or the last admitted when the whole batch fits). Pure.
|
|
327
|
+
*/
|
|
328
|
+
function measuredMemoryGate({ jobBudgetMb, running = [], batch = [], stats }) {
|
|
329
|
+
const typeOf = (j) => (j && typeof j.agentType === 'string' && j.agentType) || 'dev-lead';
|
|
330
|
+
const measured = Boolean(stats.isMeasured && stats.isMeasured());
|
|
331
|
+
const spikeBufferMb = measured ? stats.spikeBufferMb() : 0;
|
|
332
|
+
let growthMb = 0;
|
|
333
|
+
let consumedMb = 0;
|
|
334
|
+
for (const r of running) {
|
|
335
|
+
const t = typeOf(r);
|
|
336
|
+
const typical = measured ? stats.typicalPeakMb(t) : stats.reservationMb(t);
|
|
337
|
+
const rss = Math.max(0, Number(r && r.rssMb) || 0);
|
|
338
|
+
const credit = Math.min(rss, typical);
|
|
339
|
+
consumedMb += credit;
|
|
340
|
+
growthMb += typical - credit;
|
|
341
|
+
}
|
|
342
|
+
let needMb = spikeBufferMb + growthMb;
|
|
343
|
+
let reservationMb = 0;
|
|
344
|
+
let allowed = 0;
|
|
345
|
+
for (const j of batch) {
|
|
346
|
+
reservationMb = stats.reservationMb(typeOf(j));
|
|
347
|
+
const next = needMb + reservationMb;
|
|
348
|
+
if (jobBudgetMb !== Infinity && !(jobBudgetMb >= next)) { needMb = next; break; }
|
|
349
|
+
needMb = next;
|
|
350
|
+
allowed++;
|
|
351
|
+
}
|
|
352
|
+
return { allowed, measured, needMb, reservationMb, spikeBufferMb, growthMb, consumedMb };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Human-readable breakdown of a memory-gate decision for the tick detail + heartbeat. Pure. */
|
|
356
|
+
function formatMemoryGateDetail({ availableMb, threshold, reservedHostMb, gate }) {
|
|
357
|
+
const basis = gate.measured ? 'measured' : 'fallback, too few samples';
|
|
358
|
+
return `memory gate: ${availableMb} MB free, need ${threshold} MB = host ${reservedHostMb}` +
|
|
359
|
+
` + new job ${gate.reservationMb} + spike buffer ${gate.spikeBufferMb}` +
|
|
360
|
+
` + running growth ${gate.growthMb} (consumed=${gate.consumedMb} MB credited; ${basis})`;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
module.exports = { measuredMemoryGate, formatMemoryGateDetail, formatLoadGateDetail, isLoadGated, createLoadGate, topCpuConsumers, AUDIT_INTERVAL_MS, MOSTLY_IDLE_BUSY, SATURATED_BUSY };
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
const fs = require('node:fs');
|
|
13
13
|
const path = require('node:path');
|
|
14
14
|
const { OPS_ROOT_DIR, opsPath, checkOpsWrite, assertOpsWrite } = require('../opsOwnership.cjs');
|
|
15
|
-
const { writeTextAtomicSync } = require('../util/atomicFs.cjs');
|
|
15
|
+
const { writeTextAtomicSync, writeJsonAtomic } = require('../util/atomicFs.cjs');
|
|
16
16
|
|
|
17
17
|
const NAMESPACE = 'plan-records';
|
|
18
18
|
const WRITER = 'scheduler';
|
|
@@ -105,4 +105,34 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl = fs } =
|
|
|
105
105
|
return { copied, skipped };
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
/**
|
|
109
|
+
* saveValidatorVerdicts({ cwd, epicId, validateSlug, record, write, appendEvent })
|
|
110
|
+
* → Promise<string> (the written path)
|
|
111
|
+
* Writes `plan-records/<epicId>/<validateSlug>.verdicts.json` as the namespace
|
|
112
|
+
* owner, then appends one `validator.verdict` { validateSlug, verdicts:
|
|
113
|
+
* [{ prd, verdict }] } event to the Epic's event log. A write failure rejects
|
|
114
|
+
* (the caller logs it); an event-log append failure is logged, never thrown.
|
|
115
|
+
*/
|
|
116
|
+
async function saveValidatorVerdicts({
|
|
117
|
+
cwd, epicId, validateSlug, record, write = writeJsonAtomic, appendEvent = null,
|
|
118
|
+
} = {}) {
|
|
119
|
+
const file = opsPath(cwd, NAMESPACE, epicId, `${validateSlug}.verdicts.json`);
|
|
120
|
+
assertOpsWrite(file, WRITER);
|
|
121
|
+
await write(file, record);
|
|
122
|
+
try {
|
|
123
|
+
const append = appendEvent || require('../epic/epicEventLog.cjs').appendEpicEvent;
|
|
124
|
+
const rows = Array.isArray(record && record.verdicts) ? record.verdicts : [];
|
|
125
|
+
await append(cwd, epicId, {
|
|
126
|
+
kind: 'validator.verdict',
|
|
127
|
+
validateSlug,
|
|
128
|
+
verdicts: rows
|
|
129
|
+
.filter((v) => v && typeof v === 'object')
|
|
130
|
+
.map((v) => ({ prd: String(v.prd ?? ''), verdict: String(v.verdict ?? '') })),
|
|
131
|
+
});
|
|
132
|
+
} catch (e) {
|
|
133
|
+
console.error('[planRecordHarvest] validator.verdict event append failed', epicId, validateSlug, errMsg(e));
|
|
134
|
+
}
|
|
135
|
+
return file;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = { harvestPlanRecords, saveValidatorVerdicts, MAX_BYTES, NAME_RE, EPIC_ID_RE };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* prdOutcomeRecord.cjs — one structured outcome record per finished PRD run
|
|
5
|
+
* (Managed Agents' "outcome", kept local).
|
|
6
|
+
*
|
|
7
|
+
* Layout: session-manager-operations/scheduler/epics/<epicId>/outcomes/<slug>.json
|
|
8
|
+
* { schemaVersion, slug, epicId, recordedAt, verdict, commits, files, gates, checks, ...extra }
|
|
9
|
+
* Written atomically (util/atomicFs) as the 'scheduler' namespace owner; the
|
|
10
|
+
* latest terminal run of a slug overwrites the previous record. After the
|
|
11
|
+
* write, one `outcome.recorded` { slug, verdict } event is appended to the
|
|
12
|
+
* Epic's event log (lib/epic/epicEventLog.cjs). An event-append failure is
|
|
13
|
+
* logged, never thrown — the record on disk is the source of truth.
|
|
14
|
+
*
|
|
15
|
+
* `verdict` is the job's terminal status (completed / failed / needs_review);
|
|
16
|
+
* the verifier's own verdict string travels inside `gates`.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const path = require('node:path');
|
|
20
|
+
const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
|
|
21
|
+
const { writeJsonAtomic } = require('../util/atomicFs.cjs');
|
|
22
|
+
|
|
23
|
+
const WRITER = 'scheduler';
|
|
24
|
+
const SCHEMA_VERSION = 1;
|
|
25
|
+
const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
26
|
+
const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
|
|
27
|
+
const MAX_FILES = 500;
|
|
28
|
+
const MAX_COMMITS = 100;
|
|
29
|
+
|
|
30
|
+
function assertIds(epicId, slug) {
|
|
31
|
+
if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) throw new Error(`prdOutcomeRecord: invalid epicId "${epicId}"`);
|
|
32
|
+
if (typeof slug !== 'string' || !SLUG_RE.test(slug) || slug.includes('..')) throw new Error(`prdOutcomeRecord: invalid slug "${slug}"`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Absolute path of a slug's outcome record. Throws on an unsafe epicId/slug. */
|
|
36
|
+
function outcomeRecordPath(cwd, epicId, slug) {
|
|
37
|
+
assertIds(epicId, slug);
|
|
38
|
+
return opsPath(cwd, 'scheduler', 'epics', epicId, 'outcomes', `${slug}.json`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function strList(v, cap) {
|
|
42
|
+
return (Array.isArray(v) ? v : []).filter((x) => typeof x === 'string' && x).slice(0, cap);
|
|
43
|
+
}
|
|
44
|
+
function objList(v) {
|
|
45
|
+
return (Array.isArray(v) ? v : []).filter((x) => x && typeof x === 'object');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* writeOutcomeRecord({ cwd, epicId, slug, commits, files, gates, checks, verdict, extra?, write?, appendEvent? })
|
|
50
|
+
* → Promise<string> (the written path). Rejects on a bad id or write failure.
|
|
51
|
+
*/
|
|
52
|
+
async function writeOutcomeRecord({
|
|
53
|
+
cwd, epicId, slug, commits, files, gates, checks, verdict, extra = null,
|
|
54
|
+
write = writeJsonAtomic, appendEvent = null,
|
|
55
|
+
} = {}) {
|
|
56
|
+
const file = outcomeRecordPath(cwd, epicId, slug);
|
|
57
|
+
assertOpsWrite(file, WRITER);
|
|
58
|
+
const record = {
|
|
59
|
+
...(extra && typeof extra === 'object' ? extra : {}),
|
|
60
|
+
schemaVersion: SCHEMA_VERSION,
|
|
61
|
+
slug,
|
|
62
|
+
epicId,
|
|
63
|
+
recordedAt: new Date().toISOString(),
|
|
64
|
+
verdict: verdict == null ? null : String(verdict),
|
|
65
|
+
commits: strList(commits, MAX_COMMITS),
|
|
66
|
+
files: strList(files, MAX_FILES),
|
|
67
|
+
gates: objList(gates),
|
|
68
|
+
checks: objList(checks),
|
|
69
|
+
};
|
|
70
|
+
await write(file, record);
|
|
71
|
+
try {
|
|
72
|
+
const append = appendEvent || require('../epic/epicEventLog.cjs').appendEpicEvent;
|
|
73
|
+
await append(cwd, epicId, { kind: 'outcome.recorded', slug, verdict: record.verdict });
|
|
74
|
+
} catch (e) {
|
|
75
|
+
console.error('[prdOutcomeRecord] outcome.recorded event append failed', epicId, slug, e && e.message ? e.message : e);
|
|
76
|
+
}
|
|
77
|
+
return file;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Pure: derive { verdict, commits, files, gates, checks } from a finalized
|
|
82
|
+
* job row plus the run's verifyResult. `gates` holds the verifier verdict
|
|
83
|
+
* (always) and the row's gate re-run (gateShadow) when one is recorded;
|
|
84
|
+
* `checks` holds the structured-criteria results when present.
|
|
85
|
+
*/
|
|
86
|
+
function buildOutcomeFromJob({ job, verifyResult = null, commits = [], files = [] }) {
|
|
87
|
+
const j = job || {};
|
|
88
|
+
/** @type {Array<Record<string, unknown>>} */
|
|
89
|
+
const gates = [{
|
|
90
|
+
source: 'verifier',
|
|
91
|
+
verdict: (verifyResult && verifyResult.verdict) || j.verifierVerdict || (j.exitCode === 0 ? 'clean' : null),
|
|
92
|
+
reason: (verifyResult && verifyResult.reason) || j.error || null,
|
|
93
|
+
exitCode: j.exitCode ?? null,
|
|
94
|
+
terminalReason: j.terminalReason ?? null,
|
|
95
|
+
}];
|
|
96
|
+
const shadow = j.gateShadow && typeof j.gateShadow === 'object' ? j.gateShadow : null;
|
|
97
|
+
if (shadow) {
|
|
98
|
+
gates.push({
|
|
99
|
+
source: `gate:${shadow.source ?? 'prd'}`,
|
|
100
|
+
status: shadow.status ?? null,
|
|
101
|
+
head: shadow.head ?? null,
|
|
102
|
+
ranAt: shadow.ranAt ?? null,
|
|
103
|
+
results: Array.isArray(shadow.results) ? shadow.results : [],
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
let checks = [];
|
|
107
|
+
if (shadow && Array.isArray(shadow.criteriaChecks)) checks = shadow.criteriaChecks;
|
|
108
|
+
else if (j.criteriaChecks && Array.isArray(j.criteriaChecks.results)) checks = j.criteriaChecks.results;
|
|
109
|
+
return { verdict: j.status ?? null, commits, files, gates, checks };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Files touched by `shas` in `cwd` (union, sorted). Never throws — a git
|
|
114
|
+
* error yields whatever was collected so far.
|
|
115
|
+
*/
|
|
116
|
+
async function listCommitFiles(cwd, shas) {
|
|
117
|
+
const { execGit } = require('../git/gitExec.cjs');
|
|
118
|
+
const out = new Set();
|
|
119
|
+
for (const sha of strList(shas, MAX_COMMITS)) {
|
|
120
|
+
try {
|
|
121
|
+
const text = await execGit(cwd, ['show', '--name-only', '--format=', '--no-renames', sha], { timeout: 10_000 });
|
|
122
|
+
for (const line of String(text).split('\n')) {
|
|
123
|
+
const p = line.trim();
|
|
124
|
+
if (p) out.add(p.split(path.sep).join('/'));
|
|
125
|
+
}
|
|
126
|
+
} catch { /* unknown sha / non-git cwd */ }
|
|
127
|
+
}
|
|
128
|
+
return [...out].sort().slice(0, MAX_FILES);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = {
|
|
132
|
+
writeOutcomeRecord, outcomeRecordPath, buildOutcomeFromJob, listCommitFiles, SCHEMA_VERSION,
|
|
133
|
+
};
|