claude-code-session-manager 0.141.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/README.md +76 -153
- package/bin/cli.cjs +11 -0
- package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
- package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
- package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
- package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
- package/dist/assets/Scheduler-CNLjn90m.js +16 -0
- package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
- package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
- package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
- package/dist/assets/Toggle-CYajnSdx.js +1 -0
- package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
- package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
- package/dist/assets/index-CdTppjKR.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 +6 -4
- package/plugins/AGENTS.md +4 -3
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- 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 +5 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
- package/scripts/README.md +2 -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 +1032 -112
- package/src/main/adminRouteRegistry.cjs +69 -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 +336 -23
- package/src/main/config.cjs +35 -1
- package/src/main/docEdit.cjs +4 -2
- package/src/main/health.cjs +129 -2
- package/src/main/index.cjs +110 -52
- package/src/main/ipcSchemas.cjs +172 -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 +52 -0
- package/src/main/lib/demo-video-kit/character.cjs +778 -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 +103 -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/projectSounds.cjs +191 -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/sound.cjs +166 -9
- package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
- 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/activeIndexMerge.cjs +5 -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 +356 -0
- package/src/main/lib/epic/artifactStore.cjs +435 -0
- package/src/main/lib/epic/delegationReadiness.cjs +83 -2
- package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
- package/src/main/lib/epic/epicEventLog.cjs +258 -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/epicStateEmitter.cjs +248 -0
- 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 +94 -4
- package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
- package/src/main/lib/externalContract.cjs +48 -4
- package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
- 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 +32 -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 +207 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
- package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
- 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/gitWorktree.cjs +8 -0
- package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
- package/src/main/lib/git/worktreeDeps.cjs +182 -4
- package/src/main/lib/mcpToolCatalog.cjs +399 -29
- package/src/main/lib/opsOwnership.cjs +141 -28
- 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 +309 -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 +387 -228
- package/src/main/lib/prd/prdCriteria.cjs +228 -0
- package/src/main/lib/prd/prdFrontmatter.cjs +43 -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/videoPressLines.cjs +145 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
- package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
- package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
- package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
- package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
- 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 +313 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
- package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
- package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
- package/src/main/lib/scheduler/loadGate.cjs +82 -4
- package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
- package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
- package/src/main/lib/scheduler/queueStore.cjs +16 -0
- package/src/main/lib/scheduler/rcaReport.cjs +79 -15
- package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -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 +9 -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 +251 -0
- package/src/main/lib/scheduler/toolClearance.cjs +258 -0
- package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
- package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
- package/src/main/lib/tasks/mitigationReview.cjs +314 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
- 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 +204 -6
- package/src/main/lib/telemetry/auditLog.cjs +6 -2
- 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/atomicFs.cjs +2 -2
- package/src/main/lib/util/smfileRange.cjs +77 -0
- package/src/main/projectPages.cjs +3 -1
- package/src/main/promptSessionEvents.cjs +21 -1
- package/src/main/pty.cjs +77 -0
- package/src/main/queueOps.cjs +33 -14
- 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 +46 -13
- package/src/main/scheduler/reviewLadder.cjs +9 -25
- package/src/main/scheduler/utilizationHold.cjs +191 -0
- package/src/main/scheduler.cjs +1932 -213
- package/src/main/templates/PRD_AUTHORING.md +11 -3
- package/src/main/webRemote.cjs +463 -6
- package/src/preload/api.d.ts +576 -39
- package/src/preload/apiSurface.json +223 -7
- package/src/preload/index.cjs +48 -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 +98 -87
- 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 +23 -23
- package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
- package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
- package/dist/assets/Scheduler-cyr61UAC.js +0 -16
- package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
- package/dist/assets/index-B2TQz3nd.js +0 -3121
- package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
|
@@ -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 };
|
|
@@ -10,11 +10,17 @@
|
|
|
10
10
|
* The CLI enforces the schema itself; parseValidatorVerdict is the defensive
|
|
11
11
|
* second check plus the rules a schema cannot express: a non-empty REFUTED
|
|
12
12
|
* reason, unique `prd` values, and at least one missKind on every REFUTED
|
|
13
|
-
* entry.
|
|
13
|
+
* entry. With `{ expected }` (prd -> { ids, failedIds }, built by the
|
|
14
|
+
* scheduler from each judged PRD's frontmatter `criteria` and its stored
|
|
15
|
+
* mechanical check results) it also refuses an entry that omits a criterion
|
|
16
|
+
* id or marks met: true a criterion whose mechanical check failed.
|
|
14
17
|
*
|
|
15
|
-
* Pure: no I/O,
|
|
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.
|
|
16
20
|
*/
|
|
17
21
|
|
|
22
|
+
const { HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS } = require('./criteriaChecks.cjs');
|
|
23
|
+
|
|
18
24
|
/** @typedef {'not-landed'|'gate-red'|'behavior-wrong'|'not-checked-live'|'missing-test'|'regression'|'spec-gap'|'security'|'docs-drift'|'other'} MissKind */
|
|
19
25
|
/** @typedef {'Critical'|'Important'|'Minor'} Severity */
|
|
20
26
|
/** @typedef {{ id: string, met: boolean, evidence: string, missKind?: MissKind }} Criterion */
|
|
@@ -22,6 +28,10 @@
|
|
|
22
28
|
/** @typedef {{ prd: string, verdict: 'VERIFIED'|'REFUTED', reason: string, criteria: Criterion[], findings: Finding[] }} VerdictEntry */
|
|
23
29
|
/** @typedef {{ schedulerVerdict: 'PASS'|'FAIL', failReason?: string, verdicts: VerdictEntry[] }} ValidatorVerdict */
|
|
24
30
|
/** @typedef {{ slug: string, verdict: 'verified'|'refuted', reason: string, missKinds: MissKind[] }} VerdictRow */
|
|
31
|
+
/** @typedef {{ ids: string[], failedIds?: string[] }} ExpectedCriteria */
|
|
32
|
+
/** @typedef {Record<string, ExpectedCriteria> | Map<string, ExpectedCriteria>} ExpectedMap */
|
|
33
|
+
/** @typedef {'criterion-missing'|'criterion-met-on-failed-check'} CriteriaErrorCode */
|
|
34
|
+
/** @typedef {{ ok: true, value: ValidatorVerdict } | { ok: false, error: string, code?: CriteriaErrorCode }} ParseResult */
|
|
25
35
|
|
|
26
36
|
/** One-line meaning per miss kind, in MISS_KINDS order. */
|
|
27
37
|
const MISS_KIND_MEANINGS = Object.freeze({
|
|
@@ -78,9 +88,9 @@ const VALIDATOR_VERDICT_SCHEMA = {
|
|
|
78
88
|
properties: {
|
|
79
89
|
id: {
|
|
80
90
|
type: 'string',
|
|
81
|
-
description: "The criterion's 1-based position in the
|
|
91
|
+
description: "The criterion's id: when the judged PRD lists structured criteria with ids (e.g. 'ac-1'), that id exactly; otherwise its 1-based position in the PRD's # Acceptance criteria list, as a string ('1', '2', ...). Return one entry per criterion id.",
|
|
82
92
|
},
|
|
83
|
-
met: { type: 'boolean' },
|
|
93
|
+
met: { type: 'boolean', description: 'Never true when that criterion\'s mechanical check failed.' },
|
|
84
94
|
evidence: { type: 'string', description: 'What was checked and what it showed.' },
|
|
85
95
|
missKind: { type: 'string', enum: [...MISS_KINDS], description: MISS_KIND_DESCRIPTION + ' Set it on every unmet criterion.' },
|
|
86
96
|
},
|
|
@@ -193,13 +203,62 @@ function checkEntry(e, where) {
|
|
|
193
203
|
return null;
|
|
194
204
|
}
|
|
195
205
|
|
|
206
|
+
/** Leading numeric prefix stripped (`3612-a` -> `a`). */
|
|
207
|
+
function bareOf(slug) {
|
|
208
|
+
return String(slug).replace(/^\d+-/, '');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The expected-criteria entry for one judged prd: exact key first, then a
|
|
213
|
+
* bare-slug match (a validator may report `x` for a PRD filed as `3612-x`).
|
|
214
|
+
* @param {ExpectedMap} expected
|
|
215
|
+
* @param {string} prd
|
|
216
|
+
* @returns {ExpectedCriteria|null}
|
|
217
|
+
*/
|
|
218
|
+
function lookupExpected(expected, prd) {
|
|
219
|
+
const entries = expected instanceof Map ? [...expected.entries()] : Object.entries(expected);
|
|
220
|
+
for (const [k, v] of entries) if (k === prd) return v;
|
|
221
|
+
const bare = bareOf(prd);
|
|
222
|
+
for (const [k, v] of entries) if (bareOf(k) === bare) return v;
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Cross-check one entry's criteria against what the scheduler expects.
|
|
228
|
+
* @param {VerdictEntry} entry
|
|
229
|
+
* @param {ExpectedCriteria} exp
|
|
230
|
+
* @param {string} where
|
|
231
|
+
* @returns {{ error: string, code: CriteriaErrorCode }|null}
|
|
232
|
+
*/
|
|
233
|
+
function checkExpectedCriteria(entry, exp, where) {
|
|
234
|
+
const ids = Array.isArray(exp.ids) ? exp.ids.filter((x) => typeof x === 'string') : [];
|
|
235
|
+
const failed = new Set(Array.isArray(exp.failedIds) ? exp.failedIds.filter((x) => typeof x === 'string') : []);
|
|
236
|
+
const reported = new Set(entry.criteria.map((c) => c.id));
|
|
237
|
+
for (const id of ids) {
|
|
238
|
+
if (!reported.has(id)) {
|
|
239
|
+
return { error: `${where} (${entry.prd}): missing criterion id ${id}`, code: 'criterion-missing' };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
for (const c of entry.criteria) {
|
|
243
|
+
if (c.met === true && failed.has(c.id)) {
|
|
244
|
+
return {
|
|
245
|
+
error: `${where} (${entry.prd}): criterion ${c.id} marked met but its mechanical check failed`,
|
|
246
|
+
code: 'criterion-met-on-failed-check',
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
|
|
196
253
|
/**
|
|
197
|
-
* parseValidatorVerdict(value) → { ok: true, value } | { ok: false, error }.
|
|
198
|
-
*
|
|
254
|
+
* parseValidatorVerdict(value, { expected }?) → { ok: true, value } | { ok: false, error, code? }.
|
|
255
|
+
* `expected` maps a judged prd slug to { ids, failedIds }; an entry whose prd
|
|
256
|
+
* has no expected record is checked as before. Never throws.
|
|
199
257
|
* @param {unknown} value
|
|
200
|
-
* @
|
|
258
|
+
* @param {{ expected?: ExpectedMap|null }} [opts]
|
|
259
|
+
* @returns {ParseResult}
|
|
201
260
|
*/
|
|
202
|
-
function parseValidatorVerdict(value) {
|
|
261
|
+
function parseValidatorVerdict(value, opts = {}) {
|
|
203
262
|
try {
|
|
204
263
|
if (!isPlainObject(value)) return { ok: false, error: 'verdict: not an object' };
|
|
205
264
|
const keyErr = checkKeys(value, ['schedulerVerdict', 'verdicts'], ['schedulerVerdict', 'failReason', 'verdicts'], 'verdict');
|
|
@@ -211,15 +270,23 @@ function parseValidatorVerdict(value) {
|
|
|
211
270
|
return { ok: false, error: 'failReason: not a string' };
|
|
212
271
|
}
|
|
213
272
|
if (!Array.isArray(value.verdicts)) return { ok: false, error: 'verdicts: not an array' };
|
|
273
|
+
const expected = opts && (opts.expected instanceof Map || isPlainObject(opts.expected)) ? opts.expected : null;
|
|
214
274
|
/** @type {Set<string>} */
|
|
215
275
|
const seen = new Set();
|
|
216
276
|
for (let i = 0; i < value.verdicts.length; i++) {
|
|
217
277
|
const where = `verdicts[${i}]`;
|
|
218
278
|
const err = checkEntry(value.verdicts[i], where);
|
|
219
279
|
if (err) return { ok: false, error: err };
|
|
220
|
-
const
|
|
221
|
-
if (seen.has(prd)) return { ok: false, error: `${where}.prd: duplicate ${prd}` };
|
|
222
|
-
seen.add(prd);
|
|
280
|
+
const entry = /** @type {VerdictEntry} */ (value.verdicts[i]);
|
|
281
|
+
if (seen.has(entry.prd)) return { ok: false, error: `${where}.prd: duplicate ${entry.prd}` };
|
|
282
|
+
seen.add(entry.prd);
|
|
283
|
+
if (expected) {
|
|
284
|
+
const exp = lookupExpected(/** @type {ExpectedMap} */ (expected), entry.prd);
|
|
285
|
+
if (exp && typeof exp === 'object') {
|
|
286
|
+
const critErr = checkExpectedCriteria(entry, exp, where);
|
|
287
|
+
if (critErr) return { ok: false, ...critErr };
|
|
288
|
+
}
|
|
289
|
+
}
|
|
223
290
|
}
|
|
224
291
|
return { ok: true, value: /** @type {ValidatorVerdict} */ (/** @type {unknown} */ (value)) };
|
|
225
292
|
} catch (err) {
|
|
@@ -227,6 +294,78 @@ function parseValidatorVerdict(value) {
|
|
|
227
294
|
}
|
|
228
295
|
}
|
|
229
296
|
|
|
297
|
+
/**
|
|
298
|
+
* expectedFromCriteria(criteria, checks) → ExpectedCriteria | null.
|
|
299
|
+
* `criteria` is a PRD's frontmatter `criteria` list ({ id, ... }); `checks`
|
|
300
|
+
* its stored mechanical results ({ id, ok }). failedIds = ids whose check
|
|
301
|
+
* came back ok: false (a manual check, ok: null, never counts as failed).
|
|
302
|
+
* Null when the PRD has no structured criteria.
|
|
303
|
+
* @param {unknown} criteria
|
|
304
|
+
* @param {unknown} checks
|
|
305
|
+
* @returns {{ ids: string[], failedIds: string[] }|null}
|
|
306
|
+
*/
|
|
307
|
+
function expectedFromCriteria(criteria, checks) {
|
|
308
|
+
if (!Array.isArray(criteria)) return null;
|
|
309
|
+
const ids = criteria
|
|
310
|
+
.map((c) => (isPlainObject(c) && typeof c.id === 'string' ? c.id : null))
|
|
311
|
+
.filter((x) => typeof x === 'string' && x !== '');
|
|
312
|
+
if (!ids.length) return null;
|
|
313
|
+
const idSet = new Set(ids);
|
|
314
|
+
const failedIds = (Array.isArray(checks) ? checks : [])
|
|
315
|
+
.filter((c) => isPlainObject(c) && c.ok === false && typeof c.id === 'string' && idSet.has(c.id))
|
|
316
|
+
.map((c) => /** @type {string} */ (/** @type {Record<string, unknown>} */ (c).id));
|
|
317
|
+
return { ids, failedIds: [...new Set(failedIds)] };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* formatCriteriaChecksSection(prds) → Markdown for the validator prompt: per
|
|
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.
|
|
325
|
+
* @param {Array<{ slug: string, criteria: unknown, checks: unknown }>} prds
|
|
326
|
+
* @returns {string}
|
|
327
|
+
*/
|
|
328
|
+
function formatCriteriaChecksSection(prds) {
|
|
329
|
+
const oneLine = (v, max = 300) => {
|
|
330
|
+
const t = String(v ?? '').replace(/[\r\n]+/g, ' ').trim();
|
|
331
|
+
return t.length > max ? `${t.slice(0, max)}…` : t;
|
|
332
|
+
};
|
|
333
|
+
const blocks = [];
|
|
334
|
+
for (const p of Array.isArray(prds) ? prds : []) {
|
|
335
|
+
if (!p || !Array.isArray(p.criteria) || !p.criteria.length) continue;
|
|
336
|
+
/** @type {Map<string, Record<string, unknown>>} */
|
|
337
|
+
const byId = new Map();
|
|
338
|
+
for (const c of Array.isArray(p.checks) ? p.checks : []) {
|
|
339
|
+
if (isPlainObject(c) && typeof c.id === 'string') byId.set(c.id, c);
|
|
340
|
+
}
|
|
341
|
+
const lines = [`### ${oneLine(p.slug, 200)}`];
|
|
342
|
+
for (const c of p.criteria) {
|
|
343
|
+
if (!isPlainObject(c) || typeof c.id !== 'string') continue;
|
|
344
|
+
const r = byId.get(c.id);
|
|
345
|
+
const kind = isPlainObject(c.check) && typeof c.check.kind === 'string' ? c.check.kind : 'manual';
|
|
346
|
+
const result = !r ? 'not run' : r.ok === true ? 'PASS' : r.ok === false ? 'FAIL' : 'manual';
|
|
347
|
+
const detail = r && r.detail ? ` — ${oneLine(r.detail)}` : '';
|
|
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
|
+
}
|
|
355
|
+
}
|
|
356
|
+
blocks.push(lines.join('\n'));
|
|
357
|
+
}
|
|
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.`;
|
|
360
|
+
return [
|
|
361
|
+
'## Stored mechanical check results',
|
|
362
|
+
'',
|
|
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.',
|
|
364
|
+
'',
|
|
365
|
+
...blocks,
|
|
366
|
+
].join('\n');
|
|
367
|
+
}
|
|
368
|
+
|
|
230
369
|
/**
|
|
231
370
|
* verdictRowsFromStructured(value) → VerdictRow[] in input order; [] when the
|
|
232
371
|
* value does not pass parseValidatorVerdict.
|
|
@@ -251,4 +390,6 @@ module.exports = {
|
|
|
251
390
|
SEVERITIES,
|
|
252
391
|
parseValidatorVerdict,
|
|
253
392
|
verdictRowsFromStructured,
|
|
393
|
+
expectedFromCriteria,
|
|
394
|
+
formatCriteriaChecksSection,
|
|
254
395
|
};
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* memoryConsolidation.cjs — a weekly, per-project memory review Task.
|
|
5
|
+
*
|
|
6
|
+
* For every project whose human switch 'Scripts may run Tasks' is ON, at most
|
|
7
|
+
* once per 7 days (or earlier, at most once per 24 h, while the project's
|
|
8
|
+
* MEMORY.md index is over the health.cjs memory budget) this starts ONE Task
|
|
9
|
+
* through the existing Task start path — POST /admin/tasks on the app's own
|
|
10
|
+
* loopback admin server (switch check, persona → pinned --model/--effort,
|
|
11
|
+
* slot cap, ledger). The Task:
|
|
12
|
+
* - gets the memoryStale.cjs candidates (memoryTool.stale → scoreMemories)
|
|
13
|
+
* and the index size in its prompt,
|
|
14
|
+
* - runs a maintaining-md-network Drift check, read-only,
|
|
15
|
+
* - answers with ONE keep/move/drop table.
|
|
16
|
+
* This module then posts that table as ONE "Needs you" item
|
|
17
|
+
* (POST /admin/needs-you). Nothing is ever deleted or edited: the Task runs
|
|
18
|
+
* with read-only tools (Read, Grep, Glob) and its prompt forbids writes; the
|
|
19
|
+
* human decides from the Needs you item.
|
|
20
|
+
*
|
|
21
|
+
* Cadence state is the Task ledger itself (caller.pipeline ===
|
|
22
|
+
* PIPELINE) — no new ops namespace, no second writer.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const http = require('node:http');
|
|
26
|
+
const crypto = require('node:crypto');
|
|
27
|
+
const path = require('node:path');
|
|
28
|
+
|
|
29
|
+
const PIPELINE = 'memory-consolidation';
|
|
30
|
+
const MISSION_ID = 'memory-consolidation';
|
|
31
|
+
const AGENT = 'dev-lead';
|
|
32
|
+
const NEEDS_YOU_APP = 'memory-consolidation';
|
|
33
|
+
const DAY_MS = 86_400_000;
|
|
34
|
+
const WEEK_MS = 7 * DAY_MS;
|
|
35
|
+
const OVER_BUDGET_MIN_GAP_MS = DAY_MS;
|
|
36
|
+
const TICK_MS = 60 * 60 * 1000;
|
|
37
|
+
const FIRST_TICK_MS = 5 * 60 * 1000;
|
|
38
|
+
const MAX_CANDIDATES = 60;
|
|
39
|
+
const NEEDS_YOU_WHY_MAX = 1000;
|
|
40
|
+
const PROPOSAL_START = '<<<PROPOSAL';
|
|
41
|
+
const PROPOSAL_END = 'PROPOSAL>>>';
|
|
42
|
+
const READ_ONLY_TOOLS = Object.freeze(['Read', 'Grep', 'Glob']);
|
|
43
|
+
|
|
44
|
+
const NO_DELETE_RULE = 'Do NOT delete, move, rename, edit or create any file. You only propose; the human decides.';
|
|
45
|
+
|
|
46
|
+
/** cwd → true while a consolidation for it is being started or is running. */
|
|
47
|
+
const inFlight = new Set();
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The Task prompt. Pure.
|
|
51
|
+
* @param {{ cwd: string, memoryDir?: string|null, candidates?: Array<any>, budget?: { bytes?: number, lines?: number, maxBytes?: number, maxLines?: number, overBudget?: boolean } | null }} o
|
|
52
|
+
* @returns {string}
|
|
53
|
+
*/
|
|
54
|
+
function buildConsolidationPrompt({ cwd, memoryDir = null, candidates = [], budget = null } = /** @type {any} */ ({})) {
|
|
55
|
+
const list = (Array.isArray(candidates) ? candidates : []).slice(0, MAX_CANDIDATES);
|
|
56
|
+
const lines = list.length
|
|
57
|
+
? list.map((c) => {
|
|
58
|
+
const reasons = Array.isArray(c.reasons) && c.reasons.length ? c.reasons.join('; ') : 'no stale signal';
|
|
59
|
+
const dead = Array.isArray(c.deadRefs) && c.deadRefs.length ? ` dead refs: ${c.deadRefs.slice(0, 5).join(', ')}` : '';
|
|
60
|
+
return `- ${c.name} (age ${c.ageDays ?? '?'} d, inbound links ${c.inboundLinks ?? 0}): ${reasons}.${dead}`;
|
|
61
|
+
}).join('\n')
|
|
62
|
+
: '- (no stale candidates were found)';
|
|
63
|
+
const budgetLine = budget && Number.isFinite(budget.bytes)
|
|
64
|
+
? `MEMORY.md index: ${budget.bytes} bytes / ${budget.lines} lines (budget ${budget.maxBytes} bytes / ${budget.maxLines} lines)${budget.overBudget ? ' — OVER BUDGET: Claude Code loads only the first 200 lines / 25 KB, so entries past that are invisible.' : '.'}`
|
|
65
|
+
: 'MEMORY.md index size: unknown.';
|
|
66
|
+
|
|
67
|
+
return [
|
|
68
|
+
`You are reviewing the auto-memory and markdown network of the project at ${cwd}.`,
|
|
69
|
+
'',
|
|
70
|
+
'HARD RULES',
|
|
71
|
+
`1. ${NO_DELETE_RULE}`,
|
|
72
|
+
'2. Use only read tools (Read, Grep, Glob). Never run a shell command, never write.',
|
|
73
|
+
'3. Your whole answer is ONE keep/move/drop table. It is posted as ONE "Needs you" item for the owner; do not split it.',
|
|
74
|
+
'',
|
|
75
|
+
'INPUTS',
|
|
76
|
+
`Memory folder: ${memoryDir || '(unknown — skip memory files you cannot read)'}`,
|
|
77
|
+
budgetLine,
|
|
78
|
+
'Stale candidates (memoryStale scoreMemories):',
|
|
79
|
+
lines,
|
|
80
|
+
'',
|
|
81
|
+
'STEPS',
|
|
82
|
+
'1. Read each candidate memory file and the MEMORY.md index.',
|
|
83
|
+
'2. Run a maintaining-md-network Drift check (read-only): if',
|
|
84
|
+
' plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md exists in this project, follow its',
|
|
85
|
+
' "Drift check" mode; otherwise check that every fact lives in exactly one place and that links and',
|
|
86
|
+
' paths in CLAUDE.md / AGENTS.md / docs / memories resolve.',
|
|
87
|
+
'3. For each candidate and each drift finding pick one action:',
|
|
88
|
+
' keep (still true and needed), move (belongs in a named doc or memory — give the target), drop (stale or duplicated).',
|
|
89
|
+
'',
|
|
90
|
+
'OUTPUT — exactly this, nothing before or after:',
|
|
91
|
+
PROPOSAL_START,
|
|
92
|
+
'| Item | Action (keep/move/drop) | Target (for move) | Why |',
|
|
93
|
+
'|---|---|---|---|',
|
|
94
|
+
'| ... | ... | ... | ... |',
|
|
95
|
+
PROPOSAL_END,
|
|
96
|
+
].join('\n');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The table between the markers, else the whole result text, trimmed. */
|
|
100
|
+
function extractProposal(text) {
|
|
101
|
+
const s = String(text || '');
|
|
102
|
+
const a = s.indexOf(PROPOSAL_START);
|
|
103
|
+
const b = s.indexOf(PROPOSAL_END, a + 1);
|
|
104
|
+
if (a !== -1 && b !== -1) return s.slice(a + PROPOSAL_START.length, b).trim();
|
|
105
|
+
return s.trim();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function cwdKey(cwd) {
|
|
109
|
+
return crypto.createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Loopback JSON POST to the app's own admin server (index.cjs passes it). */
|
|
113
|
+
function adminPosterFor(adminHttp) {
|
|
114
|
+
return (/** @type {string} */ urlPath, /** @type {any} */ body) => new Promise((resolve, reject) => {
|
|
115
|
+
const server = adminHttp && adminHttp.server;
|
|
116
|
+
const addr = server && typeof server.address === 'function' ? server.address() : null;
|
|
117
|
+
if (!addr || typeof addr !== 'object' || !adminHttp.token) {
|
|
118
|
+
reject(new Error('admin server is not running'));
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const data = Buffer.from(JSON.stringify(body), 'utf8');
|
|
122
|
+
const req = http.request({
|
|
123
|
+
hostname: '127.0.0.1',
|
|
124
|
+
port: addr.port,
|
|
125
|
+
method: 'POST',
|
|
126
|
+
path: urlPath,
|
|
127
|
+
headers: { Authorization: `Bearer ${adminHttp.token}`, 'Content-Type': 'application/json', 'Content-Length': data.length },
|
|
128
|
+
}, (res) => {
|
|
129
|
+
let raw = '';
|
|
130
|
+
res.setEncoding('utf8');
|
|
131
|
+
res.on('data', (c) => { raw += c; });
|
|
132
|
+
res.on('end', () => {
|
|
133
|
+
let json = null;
|
|
134
|
+
try { json = JSON.parse(raw); } catch { /* non-JSON reply */ }
|
|
135
|
+
resolve({ status: res.statusCode, body: json });
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
req.setTimeout(0);
|
|
139
|
+
req.on('error', reject);
|
|
140
|
+
req.end(data);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
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
|
+
|
|
151
|
+
function defaultDeps() {
|
|
152
|
+
return {
|
|
153
|
+
usageHold: () => require('../../scheduler.cjs').currentUsageHold(),
|
|
154
|
+
isTaskSwitchOn: (/** @type {string} */ cwd) => require('./taskSwitch.cjs').isTaskSwitchOn(cwd),
|
|
155
|
+
listTasks: (/** @type {string} */ cwd, /** @type {any} */ o) => require('./taskLedger.cjs').listTasks(cwd, o),
|
|
156
|
+
measureBudget: (/** @type {string} */ cwd) => {
|
|
157
|
+
const health = require('../../health.cjs');
|
|
158
|
+
const m = health.measureProjectMemory(cwd);
|
|
159
|
+
if (!m) return null;
|
|
160
|
+
const budget = health.resolveMemoryBudget();
|
|
161
|
+
const { component } = health.evaluateMemoryBudget([m], budget);
|
|
162
|
+
return { dir: m.dir, bytes: m.bytes, lines: m.lines, maxBytes: budget.maxBytes, maxLines: budget.maxLines, overBudget: component.ok === false };
|
|
163
|
+
},
|
|
164
|
+
staleCandidates: async (/** @type {string} */ cwd) => {
|
|
165
|
+
const r = await require('../../memoryTool.cjs').stale({ cwd });
|
|
166
|
+
return (r && Array.isArray(r.entries) ? r.entries : []).filter((e) => e && e.stale);
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Last consolidation start (ms) within the window, else null. */
|
|
172
|
+
async function lastStartMs(listTasks, cwd, sinceMs) {
|
|
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));
|
|
175
|
+
const ms = t ? Date.parse(t.startedAt) : NaN;
|
|
176
|
+
return Number.isFinite(ms) ? ms : null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Decide and, when due, start one consolidation Task for `cwd`.
|
|
181
|
+
* Resolves { started: false, reason } or { started: true, reason, done } where
|
|
182
|
+
* `done` settles after the Task ran and its Needs you item was posted. Never throws.
|
|
183
|
+
*
|
|
184
|
+
* @param {{ cwd: string, now?: number, deps?: {
|
|
185
|
+
* usageHold?: () => any,
|
|
186
|
+
* isTaskSwitchOn?: (cwd: string) => boolean,
|
|
187
|
+
* listTasks?: (cwd: string, o: any) => Promise<{ tasks: any[] }>,
|
|
188
|
+
* measureBudget?: (cwd: string) => any,
|
|
189
|
+
* staleCandidates?: (cwd: string) => Promise<any[]>,
|
|
190
|
+
* adminPost?: (path: string, body: any) => Promise<{ status: number, body: any }>,
|
|
191
|
+
* } }} o
|
|
192
|
+
*/
|
|
193
|
+
async function maybeStartConsolidation({ cwd, now = Date.now(), deps = {} } = /** @type {any} */ ({})) {
|
|
194
|
+
const d = { ...defaultDeps(), ...deps };
|
|
195
|
+
if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return { started: false, reason: 'invalid_cwd' };
|
|
196
|
+
const key = path.resolve(cwd);
|
|
197
|
+
try {
|
|
198
|
+
if (!d.isTaskSwitchOn(key)) return { started: false, reason: 'switch_off' };
|
|
199
|
+
if (inFlight.has(key)) return { started: false, reason: 'in_flight' };
|
|
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 };
|
|
203
|
+
|
|
204
|
+
let budget = null;
|
|
205
|
+
try { budget = d.measureBudget(key); } catch { budget = null; }
|
|
206
|
+
const overBudget = !!(budget && budget.overBudget);
|
|
207
|
+
|
|
208
|
+
const last = await lastStartMs(d.listTasks, key, now - WEEK_MS);
|
|
209
|
+
if (last != null) {
|
|
210
|
+
if (!overBudget) return { started: false, reason: 'not_due' };
|
|
211
|
+
if (now - last < OVER_BUDGET_MIN_GAP_MS) return { started: false, reason: 'not_due' };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
let candidates = [];
|
|
215
|
+
try { candidates = await d.staleCandidates(key); } catch { candidates = []; }
|
|
216
|
+
|
|
217
|
+
const prompt = buildConsolidationPrompt({ cwd: key, memoryDir: budget ? budget.dir : null, candidates, budget });
|
|
218
|
+
const reason = last == null ? 'weekly' : 'over_budget';
|
|
219
|
+
inFlight.add(key);
|
|
220
|
+
const done = runAndPost({ cwd: key, now, prompt, reason, adminPost: d.adminPost })
|
|
221
|
+
.catch((e) => ({ ok: false, error: e instanceof Error ? e.message : String(e) }))
|
|
222
|
+
.finally(() => { inFlight.delete(key); });
|
|
223
|
+
return { started: true, reason, done };
|
|
224
|
+
} catch (e) {
|
|
225
|
+
return { started: false, reason: 'error', error: e instanceof Error ? e.message : String(e) };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function runAndPost({ cwd, now, prompt, reason, adminPost }) {
|
|
230
|
+
const runId = `${new Date(now).toISOString().slice(0, 10)}-${cwdKey(cwd)}`;
|
|
231
|
+
const task = await adminPost('/admin/tasks', {
|
|
232
|
+
cwd,
|
|
233
|
+
agent: AGENT,
|
|
234
|
+
missionId: MISSION_ID,
|
|
235
|
+
prompt,
|
|
236
|
+
priority: 'batch',
|
|
237
|
+
timeoutSec: 1800,
|
|
238
|
+
slotWaitSec: 1800,
|
|
239
|
+
caller: { pipeline: PIPELINE, runId, step: reason },
|
|
240
|
+
runtime: {
|
|
241
|
+
outputFormat: 'json',
|
|
242
|
+
tools: [...READ_ONLY_TOOLS],
|
|
243
|
+
allowedTools: [...READ_ONLY_TOOLS],
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
const b = task && task.body;
|
|
247
|
+
if (!task || task.status !== 200 || !b || b.ok !== true || b.status !== 'ok') {
|
|
248
|
+
return { ok: false, error: (b && (b.error || b.status)) || `http_${task && task.status}`, taskId: b && b.taskId };
|
|
249
|
+
}
|
|
250
|
+
const resultText = b.envelope && typeof b.envelope.result === 'string' ? b.envelope.result : '';
|
|
251
|
+
const proposal = extractProposal(resultText);
|
|
252
|
+
if (!proposal) return { ok: false, error: 'empty_proposal', taskId: b.taskId };
|
|
253
|
+
|
|
254
|
+
const note = `\n…(full table: Task ${b.taskId}, Scheduler → Tasks)`;
|
|
255
|
+
const why = proposal.length > NEEDS_YOU_WHY_MAX
|
|
256
|
+
? proposal.slice(0, NEEDS_YOU_WHY_MAX - note.length) + note
|
|
257
|
+
: proposal;
|
|
258
|
+
const posted = await adminPost('/admin/needs-you', {
|
|
259
|
+
app: NEEDS_YOU_APP,
|
|
260
|
+
id: `memory-consolidation:${runId}`,
|
|
261
|
+
title: `Memory review for ${path.basename(cwd)}: keep / move / drop`,
|
|
262
|
+
why,
|
|
263
|
+
cwd,
|
|
264
|
+
});
|
|
265
|
+
const ok = !!(posted && posted.status === 200 && posted.body && posted.body.ok);
|
|
266
|
+
return { ok, taskId: b.taskId, needsYou: ok ? posted.body.item : null, error: ok ? undefined : (posted && posted.body && posted.body.error) || 'needs_you_failed' };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Hourly sweep (first after 5 min) over every project with the switch on.
|
|
271
|
+
* index.cjs calls this once the admin server is up. Returns a stop function.
|
|
272
|
+
* @param {{ adminHttp: any, log?: (msg: string, meta?: any) => void, intervalMs?: number }} o
|
|
273
|
+
*/
|
|
274
|
+
function startConsolidationTimer({ adminHttp, log = () => {}, intervalMs = TICK_MS }) {
|
|
275
|
+
const adminPost = adminPosterFor(adminHttp);
|
|
276
|
+
const tick = async () => {
|
|
277
|
+
let projects = [];
|
|
278
|
+
try { projects = require('./taskSwitch.cjs').listTaskProjects().filter((p) => p.enabled); } catch { projects = []; }
|
|
279
|
+
for (const p of projects) {
|
|
280
|
+
const r = await maybeStartConsolidation({ cwd: p.cwd, now: Date.now(), deps: { adminPost } });
|
|
281
|
+
if (r.started) {
|
|
282
|
+
log('memory consolidation started', { cwd: p.cwd, reason: r.reason });
|
|
283
|
+
r.done.then((out) => log('memory consolidation finished', { cwd: p.cwd, ...out }));
|
|
284
|
+
} else if (r.reason === 'error') {
|
|
285
|
+
log('memory consolidation check failed', { cwd: p.cwd, error: r.error });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
const safeTick = () => { tick().catch(() => {}); };
|
|
290
|
+
const first = setTimeout(safeTick, FIRST_TICK_MS);
|
|
291
|
+
const every = setInterval(safeTick, intervalMs);
|
|
292
|
+
if (typeof first.unref === 'function') first.unref();
|
|
293
|
+
if (typeof every.unref === 'function') every.unref();
|
|
294
|
+
return () => { clearTimeout(first); clearInterval(every); };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function _resetForTests() {
|
|
298
|
+
inFlight.clear();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
module.exports = {
|
|
302
|
+
buildConsolidationPrompt,
|
|
303
|
+
maybeStartConsolidation,
|
|
304
|
+
startConsolidationTimer,
|
|
305
|
+
extractProposal,
|
|
306
|
+
adminPosterFor,
|
|
307
|
+
PIPELINE,
|
|
308
|
+
NO_DELETE_RULE,
|
|
309
|
+
READ_ONLY_TOOLS,
|
|
310
|
+
NOT_RUN_STATUSES,
|
|
311
|
+
_resetForTests,
|
|
312
|
+
};
|