peaks-loop 4.0.11 → 4.0.12

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 (25) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/cli/commands/code-commands.js +2 -0
  3. package/dist/cli/commands/code-orchestrator-can-do.d.ts +17 -0
  4. package/dist/cli/commands/code-orchestrator-can-do.js +75 -0
  5. package/dist/cli/commands/workspace/reconcile-command.js +5 -2
  6. package/dist/services/code/orchestrator-can-do.d.ts +114 -0
  7. package/dist/services/code/orchestrator-can-do.js +205 -0
  8. package/dist/services/doctor/doctor-service/checks/skill-presence.js +1 -1
  9. package/dist/services/doctor/doctor-service/checks/workspace-layout.d.ts +5 -2
  10. package/dist/services/doctor/doctor-service/checks/workspace-layout.js +70 -9
  11. package/dist/services/doctor/doctor-service/types.d.ts +9 -0
  12. package/dist/services/hooks/presence-marker-detector.d.ts +7 -5
  13. package/dist/services/hooks/presence-marker-detector.js +45 -85
  14. package/dist/services/migration/v2-10-to-v2-11-service.js +1 -3
  15. package/dist/services/sc/sc-service.d.ts +11 -7
  16. package/dist/services/sc/sc-service.js +29 -26
  17. package/dist/services/session/binding-store.d.ts +6 -6
  18. package/dist/services/skills/hooks-settings-service.d.ts +1 -1
  19. package/dist/services/skills/hooks-settings-service.js +1 -1
  20. package/dist/services/skills/skill-presence-service.d.ts +0 -1
  21. package/dist/services/skills/skill-presence-service.js +112 -102
  22. package/dist/services/skills/skill-statusline-service.js +71 -39
  23. package/package.json +4 -4
  24. package/skills/peaks-code/SKILL.md +6 -0
  25. package/skills/peaks-code/references/session-overload-signal-index.md +60 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.0.12 — 2026-08-05 (5-slice optimization bundle)
4
+
5
+ **publish.yml strict tag gate** (slice 1, commit `f60f7597`):
6
+ - New `gate-strict-tag-format` step inserted after `Checkout` (publish.yml lines 104-130). Runs `git describe --tags --exact-match HEAD` and validates against `^v[0-9]+\.[0-9]+\.[0-9]+$`; rejects `v1` / `v4.0` / `v4.0.11-rc1` / `v4.0.11+sha` shapes with `::error title=strict-tag-format::`.
7
+ - Drift guard: `tests/unit/publish-tag-strict.test.ts` (4 cases).
8
+
9
+ **PreToolUse:Bash hook JSON output validation** (slice 2, commit `eb13e44c`):
10
+ - Regression fix for the 2026-07-27 root cause. `.claude/settings.json` line 14 + `src/services/skills/hooks-settings-service.ts:86` both now append ` --json` to the `peaks gate enforce` hook command.
11
+ - Drift guard: `tests/unit/hooks/gate-enforce-template-json-flag.test.ts` (3 cases).
12
+ - PRD mis-reference correction noted: the actual hook template owner is `hooks-settings-service.ts`, not `claude-settings-template.ts` (the latter carries `peaks code gate-step-08`, a different hook path).
13
+
14
+ **Session-overload signal index** (slice 3, commit `6ef12bde`):
15
+ - New `skills/peaks-code/references/session-overload-signal-index.md` (60 lines): 7-signal lookup table (prompt size / auto-compact zone / sub-agent dispatch guard / statusline compact bar / in-flight batch deferral / compact stalled / sub-agent heartbeat) with thresholds + files + LLM actions + decision flowchart.
16
+ - SKILL.md Step N+2 section gets a 1-line "See also" pointer (+141 bytes; under 30000 cap).
17
+ - Codifies red line: LLM MUST NOT re-ask user about cost/length/context (cite `references/job-loop.md:59` red line #2).
18
+
19
+ **active-skill.json → sid-scoped lease projection** (slice 4, 3 sub-slices):
20
+ - Slice 4-A (`dc350c2c`): `skill-presence-service.ts` write path removed; `presence-marker-detector.ts` deprecated-constant comments added.
21
+ - Slice 4-B (`7699f70f`): `skill-statusline-service.ts` `readPresenceReadOnly` rewritten to canonical-only (drops `legacyPresence: true`, enumerates `listPresenceLeases`, deletes `PRESENCE_FILE` / `PRESENCE_FILE_LEGACY`). Fixes the "new session statusline empty" issue (root cause: outerSessionId drift between session.json and the global single-slot file).
22
+ - Slice 4-C (`1b08a62c`): doctor / sc / migration / hooks / skills / reconcile-command all migrated to canonical lease reads. New `STALE_SINGLE_SLOT_FILES` workspace-layout check surfaces orphan `.peaks/_runtime/active-skill.json` as a "stale single-slot presence" diagnostic (not an error). Drift guard: `tests/unit/workspace/active-skill-json-cleanup.test.ts` (3 cases).
23
+ - Multi-session on one project is now safe (each session writes its own `presence-<callerId>.json` under `.peaks/_runtime/<sid>/presence-index/`; the deprecated single-slot global file no longer races).
24
+
25
+ **Orchestrator-can-do probe CLI** (slice 5, commit `52736c82`):
26
+ - New `peaks code orchestrator-can-do --slice-spec <text> --json` command (the 2026-08-05 lesson converted into a downstream-inheritable CLI). Evaluates 4 boundary questions (source code? sub-agent available? requires user decision? context sustainable?) and returns `{ canDoInSession, blockers, warnings, suggestions, contextRatio, subAgentAvailable }`.
27
+ - SKILL.md gains a Step 0.51 paragraph pointing at it (LLM must run this probe before deciding to push a slice to the next session).
28
+ - 17 unit tests cover all 4 boundary branches.
29
+ - Anti-fake-green pattern: any future orchestrator capability judgment MUST call this CLI rather than re-derive the 4-question matrix from intuition.
30
+
31
+ **Lockstep bump.** peaks-loop-shared `0.0.41 → 0.0.42` (CLI_VERSION re-stamped to 4.0.12); peaks-loop-mut `0.1.14 → 0.1.15`; peaks-loop-shared-channel `0.0.18 → 0.0.19`.
32
+
3
33
  ## 4.0.11 — 2026-08-05 (BDD test-style + statusline bugs)
4
34
 
5
35
  **BDD given-when-then test style** (rid-2026-08-05-bdd-test-style, 5 slice / 19 commit):
@@ -26,6 +26,7 @@ import { registerCodeRunCommand } from './code-run-command.js';
26
26
  import { registerCodeModeGateCommands } from './code-mode-gate-commands.js';
27
27
  import { registerCodeJobShapeCommands } from './code-job-shape-commands.js';
28
28
  import { registerCodeRuntimeCommands } from './code-runtime-commands.js';
29
+ import { registerCodeOrchestratorCanDoCommand } from './code-orchestrator-can-do.js';
29
30
  const STEP_ORDER = [
30
31
  'load-memory',
31
32
  'standards-preflight',
@@ -114,5 +115,6 @@ export function registerCodeCommands(program, io) {
114
115
  registerCodeModeGateCommands(code, io);
115
116
  registerCodeJobShapeCommands(code, io);
116
117
  registerCodeRuntimeCommands(code, io);
118
+ registerCodeOrchestratorCanDoCommand(code, io);
117
119
  registerCodeRunCommand(code, io);
118
120
  }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Slice 2026-08-05-orchestrator-can-do-probe — CLI shim for
3
+ * `peaks code orchestrator-can-do`.
4
+ *
5
+ * Thin entry point that wires the `orchestrator-can-do` subcommand
6
+ * to the parent `code` command. The actual probe logic lives in
7
+ * `../../services/code/orchestrator-can-do.ts`.
8
+ *
9
+ * Encodes the 2026-08-05 lesson (`.peaks/memory/2026-08-05-peaks-code-
10
+ * orchestrator-capability-misjudgment.md`) — the peaks-code orchestrator
11
+ * MUST delegate source-code changes via sub-agent dispatch, not via
12
+ * direct Edit/Write. The probe returns a structured verdict so the LLM
13
+ * does not need to vibes-call "can this slice run in the current session".
14
+ */
15
+ import type { Command } from 'commander';
16
+ import { type ProgramIO } from '../cli-helpers.js';
17
+ export declare function registerCodeOrchestratorCanDoCommand(code: Command, io: ProgramIO): void;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Slice 2026-08-05-orchestrator-can-do-probe — CLI shim for
3
+ * `peaks code orchestrator-can-do`.
4
+ *
5
+ * Thin entry point that wires the `orchestrator-can-do` subcommand
6
+ * to the parent `code` command. The actual probe logic lives in
7
+ * `../../services/code/orchestrator-can-do.ts`.
8
+ *
9
+ * Encodes the 2026-08-05 lesson (`.peaks/memory/2026-08-05-peaks-code-
10
+ * orchestrator-capability-misjudgment.md`) — the peaks-code orchestrator
11
+ * MUST delegate source-code changes via sub-agent dispatch, not via
12
+ * direct Edit/Write. The probe returns a structured verdict so the LLM
13
+ * does not need to vibes-call "can this slice run in the current session".
14
+ */
15
+ import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
16
+ import { fail, ok } from 'peaks-loop-shared/result';
17
+ import { evaluateOrchestratorCanDo, OrchestratorCanDoError, ORCHESTRATOR_PRECOMPACT_RATIO, ORCHESTRATOR_REDLINE_RATIO, } from '../../services/code/orchestrator-can-do.js';
18
+ import { findProjectRoot } from '../../services/config/config-safety.js';
19
+ export function registerCodeOrchestratorCanDoCommand(code, io) {
20
+ addJsonOption(code
21
+ .command('orchestrator-can-do')
22
+ .description('2026-08-05 lesson: probe whether the LLM orchestrator can execute a slice in the ' +
23
+ 'current session. Evaluates 4 boundary questions (source-code touched? sub-agent ' +
24
+ 'available? requires user decision? context sustainable?) and returns a structured ' +
25
+ 'verdict with canDoInSession, blockers, warnings, and concrete next-action ' +
26
+ 'suggestions. Default to canDoInSession=true unless hard blockers are present; ' +
27
+ 'sub-agent dispatch (`peaks sub-agent dispatch rd`) is the canonical delegation path ' +
28
+ 'for source-code changes.')
29
+ .requiredOption('--slice-spec <text>', 'short description of the slice (e.g. "modify src/services/foo.ts")')
30
+ .option('--project <path>', 'target project root (default: findProjectRoot(cwd))')
31
+ .option('--peaks-bin <path>', 'peaks binary path (test seam; default: peaks on PATH)')).action(async (opts) => {
32
+ try {
33
+ const projectRoot = opts.project ?? findProjectRoot(process.cwd()) ?? process.cwd();
34
+ const peaksBin = opts.peaksBin ?? 'peaks';
35
+ const result = await evaluateOrchestratorCanDo({
36
+ sliceSpec: opts.sliceSpec,
37
+ projectRoot,
38
+ probeSubAgentAvailable: () => probeSubAgentAvailableWithBin(projectRoot, peaksBin),
39
+ probeContextRatio: () => probeContextRatioWithBin(projectRoot, peaksBin),
40
+ });
41
+ printResult(io, ok('code.orchestrator-can-do', result, [...result.warnings], [...result.suggestions, ...summaryLines(result)]), opts.json);
42
+ if (!result.canDoInSession)
43
+ process.exitCode = 1;
44
+ }
45
+ catch (err) {
46
+ if (err instanceof OrchestratorCanDoError) {
47
+ printResult(io, fail('code.orchestrator-can-do', err.code, err.message, null, [
48
+ 'Pass --slice-spec <text> describing what the slice should change',
49
+ ]), opts.json);
50
+ process.exitCode = 1;
51
+ return;
52
+ }
53
+ printResult(io, fail('code.orchestrator-can-do', 'PROBE_FAILED', getErrorMessage(err), null, [
54
+ 'Verify --slice-spec is non-empty and --project is a valid path',
55
+ ]), opts.json);
56
+ process.exitCode = 1;
57
+ }
58
+ });
59
+ }
60
+ function summaryLines(result) {
61
+ const lines = [];
62
+ lines.push(`verdict: ${result.canDoInSession ? 'canDoInSession=true' : 'canDoInSession=false (blockers present)'}; ` +
63
+ `q1=src[${result.q1SourceCodeTouched ? 'Y' : 'N'}] q2=subagent[${result.q2SubAgentAvailable ? 'Y' : 'N'}] ` +
64
+ `q3=user-decision[${result.q3RequiresUserDecision ? 'Y' : 'N'}] q4=ratio=${result.contextRatio.toFixed(2)} ` +
65
+ `(red-line ${ORCHESTRATOR_REDLINE_RATIO} / pre-compact ${ORCHESTRATOR_PRECOMPACT_RATIO})`);
66
+ return lines;
67
+ }
68
+ async function probeSubAgentAvailableWithBin(projectRoot, peaksBin) {
69
+ const { probeSubAgentAvailable } = await import('../../services/code/orchestrator-can-do.js');
70
+ return probeSubAgentAvailable(projectRoot, peaksBin);
71
+ }
72
+ async function probeContextRatioWithBin(projectRoot, peaksBin) {
73
+ const { probeContextRatio } = await import('../../services/code/orchestrator-can-do.js');
74
+ return probeContextRatio(projectRoot, peaksBin);
75
+ }
@@ -26,9 +26,12 @@ export function registerWorkspaceReconcileCommand(workspace, io) {
26
26
  'By default (no --apply) the command performs four actions:\n' +
27
27
  ' 1. Migrates legacy runtime files into .peaks/_runtime/: ' +
28
28
  '.peaks/.session.json -> .peaks/_runtime/session.json, ' +
29
- '.peaks/.active-skill.json -> .peaks/_runtime/active-skill.json, ' +
30
29
  '.peaks/sop-state/ -> .peaks/_runtime/sop-state/ ' +
31
- '(idempotent; no-op if already on the new layout).\n' +
30
+ '(idempotent; no-op if already on the new layout). ' +
31
+ 'Single-slot presence files (.peaks/.active-skill.json and ' +
32
+ '.peaks/_runtime/active-skill.json) are no longer migrated; ' +
33
+ 'they were removed in slice 4.0.11 and should be deleted ' +
34
+ 'manually if present.\n' +
32
35
  ' 2. Re-points .peaks/_runtime/session.json to the canonical session ' +
33
36
  'using a 4-tier heuristic: active-skill binding -> latest session.json mtime -> ' +
34
37
  'latest any-file mtime -> dir-name sort.\n' +
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Slice 2026-08-05-orchestrator-can-do-probe — service layer for
3
+ * `peaks code orchestrator-can-do`.
4
+ *
5
+ * Encodes the 2026-08-05 lesson (`.peaks/memory/2026-08-05-peaks-code-
6
+ * orchestrator-capability-misjudgment.md`): the peaks-code orchestrator
7
+ * MUST NOT Edit/Write `src/` files directly, but MUST delegate via
8
+ * `peaks sub-agent dispatch`. The decision "can this slice run in the
9
+ * current session" must be a structured probe — not a vibes call.
10
+ *
11
+ * The probe answers 4 boundary questions:
12
+ * Q1 — Is the change to source code? (keywords: src/, *.ts, *.tsx,
13
+ * *.js, package.json, tsconfig, workflows/). If yes → NOT a
14
+ * blocker; orchestrator delegates to sub-agent.
15
+ * Q2 — Can a sub-agent be dispatched? (probe `peaks sub-agent
16
+ * dispatch --role rd --help`). If no → blocker.
17
+ * Q3 — Does the slice require user decisions? (keywords: design,
18
+ * decide, ?, 选择, 决定). If yes → soft warning, NOT a blocker
19
+ * (the LLM should AskUserQuestion, which is cheap).
20
+ * Q4 — Is context usage sustainable? (probe `peaks code context-now
21
+ * --json`). ratio ≥ 0.95 → blocker (red-line); ≥ 0.85 →
22
+ * blocker (auto-compact-now).
23
+ *
24
+ * Decision rule:
25
+ * canDoInSession === (blockers.length === 0)
26
+ *
27
+ * Concrete suggestion when canDoInSession=true and slice touches
28
+ * source code:
29
+ * `peaks sub-agent dispatch rd --prompt "<slice-spec>" --request-id
30
+ * <rid> --project . --batch-id <uuid>`
31
+ *
32
+ * Pure-function module. The CLI shim (code-orchestrator-can-do.ts)
33
+ * adapts the envelope into the program's `ResultEnvelope<T>` shape.
34
+ */
35
+ /** Slice 2026-08-05-orchestrator-can-do-probe: red-line threshold. */
36
+ export declare const ORCHESTRATOR_REDLINE_RATIO = 0.95;
37
+ /** Slice 2026-08-05-orchestrator-can-do-probe: pre-compact threshold. */
38
+ export declare const ORCHESTRATOR_PRECOMPACT_RATIO = 0.85;
39
+ /** Source-code keywords that signal "do NOT Edit/Write directly". */
40
+ export declare const SOURCE_CODE_KEYWORDS: readonly string[];
41
+ /** Decision-marker keywords that signal "needs user AskUserQuestion". */
42
+ export declare const DECISION_KEYWORDS: readonly string[];
43
+ export interface ContextProbe {
44
+ /** 0.0–1.0; ≥0.85 = pre-compact; ≥0.95 = red-line. */
45
+ readonly ratio: number;
46
+ /** Source tag from `peaks code context-now`. */
47
+ readonly source: string;
48
+ }
49
+ export interface OrchestratorCanDoInput {
50
+ readonly sliceSpec: string;
51
+ readonly projectRoot: string;
52
+ /**
53
+ * Test seam — caller injects probe results. Production CLI builds
54
+ * these via `probeSubAgentAvailable` + `probeContextRatio`. When the
55
+ * test seam is set, the CLI's actual probes are skipped.
56
+ */
57
+ readonly probeSubAgentAvailable?: () => Promise<boolean>;
58
+ readonly probeContextRatio?: () => Promise<ContextProbe>;
59
+ }
60
+ export interface OrchestratorCanDoResult {
61
+ /** canDoInSession === (blockers.length === 0). */
62
+ readonly canDoInSession: boolean;
63
+ readonly blockers: readonly string[];
64
+ readonly warnings: readonly string[];
65
+ readonly suggestions: readonly string[];
66
+ readonly contextRatio: number;
67
+ readonly subAgentAvailable: boolean;
68
+ /** Diagnostic — which of the 4 boundary questions fired. */
69
+ readonly q1SourceCodeTouched: boolean;
70
+ readonly q2SubAgentAvailable: boolean;
71
+ readonly q3RequiresUserDecision: boolean;
72
+ readonly q4ContextRatio: number;
73
+ }
74
+ export declare class OrchestratorCanDoError extends Error {
75
+ readonly code: 'MISSING_SLICE_SPEC' | 'PROBE_FAILED';
76
+ constructor(message: string, code: 'MISSING_SLICE_SPEC' | 'PROBE_FAILED');
77
+ }
78
+ /**
79
+ * Q1: does the slice touch source code? Pure keyword scan over
80
+ * the slice-spec string. Case-insensitive substring match.
81
+ */
82
+ export declare function detectSourceCodeTouched(sliceSpec: string): boolean;
83
+ /**
84
+ * Q3: does the slice require user decisions? Pure keyword scan
85
+ * over the slice-spec string.
86
+ */
87
+ export declare function detectRequiresUserDecision(sliceSpec: string): boolean;
88
+ /**
89
+ * Q2: probe `peaks sub-agent dispatch --role rd --help`. Returns
90
+ * true when the subprocess exits 0. Resolves to false on spawn
91
+ * failure or non-zero exit.
92
+ */
93
+ export declare function probeSubAgentAvailable(projectRoot: string, peaksBin?: string): Promise<boolean>;
94
+ /**
95
+ * Q4: probe `peaks code context-now --json`. Parses the data.ratio
96
+ * field. Falls back to {ratio: 0, source: 'unavailable'} when the
97
+ * subprocess fails or returns malformed JSON.
98
+ */
99
+ export declare function probeContextRatio(projectRoot: string, peaksBin?: string): Promise<ContextProbe>;
100
+ /**
101
+ * Build the structured OrchestratorCanDoResult. Pure over the 4 Q
102
+ * signals + sliceSpec. Decision rule is: canDoInSession === !blockers.
103
+ */
104
+ export declare function buildOrchestratorCanDoResult(input: OrchestratorCanDoInput, signals: {
105
+ q1SourceCodeTouched: boolean;
106
+ q2SubAgentAvailable: boolean;
107
+ q3RequiresUserDecision: boolean;
108
+ q4ContextRatio: number;
109
+ }): OrchestratorCanDoResult;
110
+ /**
111
+ * Evaluate a slice-spec end-to-end. Probes Q2/Q4 via subprocess
112
+ * (overridable via test seams in `input`). Q1/Q3 are pure.
113
+ */
114
+ export declare function evaluateOrchestratorCanDo(input: OrchestratorCanDoInput): Promise<OrchestratorCanDoResult>;
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Slice 2026-08-05-orchestrator-can-do-probe — service layer for
3
+ * `peaks code orchestrator-can-do`.
4
+ *
5
+ * Encodes the 2026-08-05 lesson (`.peaks/memory/2026-08-05-peaks-code-
6
+ * orchestrator-capability-misjudgment.md`): the peaks-code orchestrator
7
+ * MUST NOT Edit/Write `src/` files directly, but MUST delegate via
8
+ * `peaks sub-agent dispatch`. The decision "can this slice run in the
9
+ * current session" must be a structured probe — not a vibes call.
10
+ *
11
+ * The probe answers 4 boundary questions:
12
+ * Q1 — Is the change to source code? (keywords: src/, *.ts, *.tsx,
13
+ * *.js, package.json, tsconfig, workflows/). If yes → NOT a
14
+ * blocker; orchestrator delegates to sub-agent.
15
+ * Q2 — Can a sub-agent be dispatched? (probe `peaks sub-agent
16
+ * dispatch --role rd --help`). If no → blocker.
17
+ * Q3 — Does the slice require user decisions? (keywords: design,
18
+ * decide, ?, 选择, 决定). If yes → soft warning, NOT a blocker
19
+ * (the LLM should AskUserQuestion, which is cheap).
20
+ * Q4 — Is context usage sustainable? (probe `peaks code context-now
21
+ * --json`). ratio ≥ 0.95 → blocker (red-line); ≥ 0.85 →
22
+ * blocker (auto-compact-now).
23
+ *
24
+ * Decision rule:
25
+ * canDoInSession === (blockers.length === 0)
26
+ *
27
+ * Concrete suggestion when canDoInSession=true and slice touches
28
+ * source code:
29
+ * `peaks sub-agent dispatch rd --prompt "<slice-spec>" --request-id
30
+ * <rid> --project . --batch-id <uuid>`
31
+ *
32
+ * Pure-function module. The CLI shim (code-orchestrator-can-do.ts)
33
+ * adapts the envelope into the program's `ResultEnvelope<T>` shape.
34
+ */
35
+ import { execFile } from 'node:child_process';
36
+ import { promisify } from 'node:util';
37
+ import { randomUUID } from 'node:crypto';
38
+ const execFileAsync = promisify(execFile);
39
+ /** Slice 2026-08-05-orchestrator-can-do-probe: red-line threshold. */
40
+ export const ORCHESTRATOR_REDLINE_RATIO = 0.95;
41
+ /** Slice 2026-08-05-orchestrator-can-do-probe: pre-compact threshold. */
42
+ export const ORCHESTRATOR_PRECOMPACT_RATIO = 0.85;
43
+ /** Source-code keywords that signal "do NOT Edit/Write directly". */
44
+ export const SOURCE_CODE_KEYWORDS = [
45
+ 'src/',
46
+ 'source/',
47
+ '.ts',
48
+ '.tsx',
49
+ '.js',
50
+ '.jsx',
51
+ 'package.json',
52
+ 'tsconfig',
53
+ 'workflows/',
54
+ '.py',
55
+ '.go',
56
+ '.rs',
57
+ ];
58
+ /** Decision-marker keywords that signal "needs user AskUserQuestion". */
59
+ export const DECISION_KEYWORDS = [
60
+ 'design',
61
+ 'decide',
62
+ 'choose',
63
+ '?',
64
+ '选择',
65
+ '决定',
66
+ 'design decision',
67
+ 'user choice',
68
+ ];
69
+ export class OrchestratorCanDoError extends Error {
70
+ code;
71
+ constructor(message, code) {
72
+ super(message);
73
+ this.code = code;
74
+ this.name = 'OrchestratorCanDoError';
75
+ }
76
+ }
77
+ /**
78
+ * Q1: does the slice touch source code? Pure keyword scan over
79
+ * the slice-spec string. Case-insensitive substring match.
80
+ */
81
+ export function detectSourceCodeTouched(sliceSpec) {
82
+ const lower = sliceSpec.toLowerCase();
83
+ return SOURCE_CODE_KEYWORDS.some((kw) => lower.includes(kw.toLowerCase()));
84
+ }
85
+ /**
86
+ * Q3: does the slice require user decisions? Pure keyword scan
87
+ * over the slice-spec string.
88
+ */
89
+ export function detectRequiresUserDecision(sliceSpec) {
90
+ const lower = sliceSpec.toLowerCase();
91
+ return DECISION_KEYWORDS.some((kw) => lower.includes(kw.toLowerCase()));
92
+ }
93
+ /**
94
+ * Q2: probe `peaks sub-agent dispatch --role rd --help`. Returns
95
+ * true when the subprocess exits 0. Resolves to false on spawn
96
+ * failure or non-zero exit.
97
+ */
98
+ export async function probeSubAgentAvailable(projectRoot, peaksBin = 'peaks') {
99
+ try {
100
+ await execFileAsync(peaksBin, ['sub-agent', 'dispatch', '--role', 'rd', '--help'], {
101
+ cwd: projectRoot,
102
+ timeout: 5000,
103
+ });
104
+ return true;
105
+ }
106
+ catch {
107
+ return false;
108
+ }
109
+ }
110
+ /**
111
+ * Q4: probe `peaks code context-now --json`. Parses the data.ratio
112
+ * field. Falls back to {ratio: 0, source: 'unavailable'} when the
113
+ * subprocess fails or returns malformed JSON.
114
+ */
115
+ export async function probeContextRatio(projectRoot, peaksBin = 'peaks') {
116
+ try {
117
+ const { stdout } = await execFileAsync(peaksBin, ['code', 'context-now', '--project', projectRoot, '--json'], {
118
+ cwd: projectRoot,
119
+ timeout: 10000,
120
+ });
121
+ const parsed = JSON.parse(stdout);
122
+ const ratio = typeof parsed.data?.ratio === 'number' ? parsed.data.ratio : 0;
123
+ const source = typeof parsed.data?.source === 'string' ? parsed.data.source : 'unavailable';
124
+ return { ratio, source };
125
+ }
126
+ catch {
127
+ return { ratio: 0, source: 'unavailable' };
128
+ }
129
+ }
130
+ /**
131
+ * Build the structured OrchestratorCanDoResult. Pure over the 4 Q
132
+ * signals + sliceSpec. Decision rule is: canDoInSession === !blockers.
133
+ */
134
+ export function buildOrchestratorCanDoResult(input, signals) {
135
+ const blockers = [];
136
+ const warnings = [];
137
+ const suggestions = [];
138
+ // Q2 — sub-agent availability is a hard precondition.
139
+ if (!signals.q2SubAgentAvailable) {
140
+ blockers.push('sub-agent dispatch unavailable (peaks sub-agent dispatch --help failed)');
141
+ suggestions.push('verify peaks CLI is on PATH; check `peaks --version`');
142
+ }
143
+ // Q4 — context ratio gate. ≥0.95 → red-line; ≥0.85 → pre-compact.
144
+ if (signals.q4ContextRatio >= ORCHESTRATOR_REDLINE_RATIO) {
145
+ blockers.push(`context red-line (ratio=${signals.q4ContextRatio.toFixed(2)} ≥ ${ORCHESTRATOR_REDLINE_RATIO}); auto-compact now or push to next session`);
146
+ suggestions.push('peaks compact auto --execute');
147
+ }
148
+ else if (signals.q4ContextRatio >= ORCHESTRATOR_PRECOMPACT_RATIO) {
149
+ blockers.push(`context near limit (ratio=${signals.q4ContextRatio.toFixed(2)} ≥ ${ORCHESTRATOR_PRECOMPACT_RATIO}); auto-compact or push to next session`);
150
+ suggestions.push('peaks compact auto --execute');
151
+ }
152
+ // Q3 — user-decision keywords → soft warning, NOT a blocker. The
153
+ // LLM should AskUserQuestion, which is cheap.
154
+ if (signals.q3RequiresUserDecision) {
155
+ warnings.push('slice-spec contains decision keywords; AskUserQuestion before proceeding');
156
+ }
157
+ // Q1 — source-code touched is NOT a blocker. The orchestrator
158
+ // delegates via sub-agent dispatch.
159
+ if (signals.q1SourceCodeTouched && signals.q2SubAgentAvailable) {
160
+ const batchId = randomUUID();
161
+ const rid = 'rid-' + Date.now().toString(36);
162
+ suggestions.push(`peaks sub-agent dispatch rd --prompt "<slice-spec>" --request-id ${rid} --project ${input.projectRoot} --batch-id ${batchId}`);
163
+ }
164
+ // When canDoInSession=true and there's no source code touched,
165
+ // surface a generic "do it" suggestion.
166
+ const canDoInSession = blockers.length === 0;
167
+ if (canDoInSession && !signals.q1SourceCodeTouched) {
168
+ suggestions.push(`non-source-code slice; orchestrator may handle in-session (e.g. via Write/Edit tools or directly)`);
169
+ }
170
+ return {
171
+ canDoInSession,
172
+ blockers,
173
+ warnings,
174
+ suggestions,
175
+ contextRatio: signals.q4ContextRatio,
176
+ subAgentAvailable: signals.q2SubAgentAvailable,
177
+ q1SourceCodeTouched: signals.q1SourceCodeTouched,
178
+ q2SubAgentAvailable: signals.q2SubAgentAvailable,
179
+ q3RequiresUserDecision: signals.q3RequiresUserDecision,
180
+ q4ContextRatio: signals.q4ContextRatio,
181
+ };
182
+ }
183
+ /**
184
+ * Evaluate a slice-spec end-to-end. Probes Q2/Q4 via subprocess
185
+ * (overridable via test seams in `input`). Q1/Q3 are pure.
186
+ */
187
+ export async function evaluateOrchestratorCanDo(input) {
188
+ if (!input.sliceSpec || input.sliceSpec.trim().length === 0) {
189
+ throw new OrchestratorCanDoError('--slice-spec is required', 'MISSING_SLICE_SPEC');
190
+ }
191
+ const q1SourceCodeTouched = detectSourceCodeTouched(input.sliceSpec);
192
+ const q3RequiresUserDecision = detectRequiresUserDecision(input.sliceSpec);
193
+ const probeSubAgent = input.probeSubAgentAvailable ?? (() => probeSubAgentAvailable(input.projectRoot));
194
+ const probeContext = input.probeContextRatio ?? (() => probeContextRatio(input.projectRoot));
195
+ const [subAgentAvailable, ctxProbe] = await Promise.all([
196
+ probeSubAgent(),
197
+ probeContext(),
198
+ ]);
199
+ return buildOrchestratorCanDoResult(input, {
200
+ q1SourceCodeTouched,
201
+ q2SubAgentAvailable: subAgentAvailable,
202
+ q3RequiresUserDecision,
203
+ q4ContextRatio: ctxProbe.ratio,
204
+ });
205
+ }
@@ -33,7 +33,7 @@ function run({ options, presence }) {
33
33
  {
34
34
  id: 'skill-presence:current',
35
35
  ok: true,
36
- message: 'No active Peaks skill presence (.peaks/.active-skill.json absent or invalid)'
36
+ message: 'No active Peaks skill presence (no canonical lease under .peaks/_runtime/<sid>/leases/)'
37
37
  },
38
38
  {
39
39
  id: 'skill-presence:freshness',
@@ -4,8 +4,10 @@
4
4
  *
5
5
  * Build-hygiene check that surfaces any leftover top-level session
6
6
  * dirs (`.peaks/<YYYY-MM-DD-session-<hex>>/`), the legacy runtime
7
- * dotfiles (`.peaks/.session.json`, `.peaks/.active-skill.json`),
8
- * OR per-change-id top-level dirs (`.peaks/NNN-YYYY-MM-DD-<slug>/`).
7
+ * dotfiles (`.peaks/.session.json`), the stale single-slot
8
+ * presence file (`.peaks/_runtime/active-skill.json`, the deprecated
9
+ * project-level marker removed in slice 4.0.11), OR per-change-id
10
+ * top-level dirs (`.peaks/NNN-YYYY-MM-DD-<slug>/`).
9
11
  *
10
12
  * The post-F3 canonical layout puts session dirs under
11
13
  * `.peaks/_runtime/<sid>/` and the runtime binding at
@@ -29,5 +31,6 @@ export declare function inspectWorkspaceLayout(opts: {
29
31
  topLevelScanner?: (root: string) => string[];
30
32
  dotfileScanner?: (root: string) => string[];
31
33
  perChangeIdScanner?: (root: string) => string[];
34
+ staleSingleSlotScanner?: (root: string) => string[];
32
35
  }): WorkspaceLayoutInspection;
33
36
  export declare const check: DoctorCheckPlugin;
@@ -4,8 +4,10 @@
4
4
  *
5
5
  * Build-hygiene check that surfaces any leftover top-level session
6
6
  * dirs (`.peaks/<YYYY-MM-DD-session-<hex>>/`), the legacy runtime
7
- * dotfiles (`.peaks/.session.json`, `.peaks/.active-skill.json`),
8
- * OR per-change-id top-level dirs (`.peaks/NNN-YYYY-MM-DD-<slug>/`).
7
+ * dotfiles (`.peaks/.session.json`), the stale single-slot
8
+ * presence file (`.peaks/_runtime/active-skill.json`, the deprecated
9
+ * project-level marker removed in slice 4.0.11), OR per-change-id
10
+ * top-level dirs (`.peaks/NNN-YYYY-MM-DD-<slug>/`).
9
11
  *
10
12
  * The post-F3 canonical layout puts session dirs under
11
13
  * `.peaks/_runtime/<sid>/` and the runtime binding at
@@ -31,7 +33,24 @@ const SESSION_DIR_PATTERN = /^\d{4}-\d{2}-\d{2}-session-[a-f0-9]+$/;
31
33
  * `0NN-session-...`, `YYYY-MM-DD-session-...`).
32
34
  */
33
35
  const PER_CHANGE_ID_PATTERN = /^\d{3}-\d{4}-\d{2}-\d{2}-[a-z][a-z0-9-]*[a-z0-9]$/;
34
- const LEGACY_DOTFILES = ['.session.json', '.active-skill.json'];
36
+ // Slice 4.0.11 statusline-sid-scoped-lease C: `.peaks/.active-skill.json`
37
+ // is REMOVED from LEGACY_DOTFILES (the file should not exist on
38
+ // healthy post-4.0.11 projects; treating it as a generic legacy
39
+ // dotfile is misleading). The new single-slot presence file
40
+ // `.peaks/_runtime/active-skill.json` is reported separately under
41
+ // `STALE_SINGLE_SLOT_FILES` so the operator gets a clear "stale
42
+ // single-slot presence" message instead of a generic legacy warning.
43
+ const LEGACY_DOTFILES = ['.session.json'];
44
+ // Top-level single-slot presence files that are stale after the
45
+ // sid-scoped lease projection (slice 4.0.8) shipped. Reported
46
+ // separately from LEGACY_DOTFILES so the doctor message names the
47
+ // specific issue ("stale single-slot presence") and the operator
48
+ // can delete the file. The canonical sid-scoped lease at
49
+ // `.peaks/_runtime/<sid>/leases/presence-*.json` is the source of truth.
50
+ const STALE_SINGLE_SLOT_FILES = [
51
+ 'active-skill.json',
52
+ '.active-skill.json'
53
+ ];
35
54
  /**
36
55
  * Pure helper that inspects the on-disk workspace layout for
37
56
  * post-F3-canonical violations. Exported so tests can drive the
@@ -42,10 +61,12 @@ export function inspectWorkspaceLayout(opts) {
42
61
  const topLevel = opts.topLevelScanner ?? defaultTopLevelSessionDirScanner;
43
62
  const dotfiles = opts.dotfileScanner ?? defaultLegacyDotfileScanner;
44
63
  const perChangeId = opts.perChangeIdScanner ?? defaultPerChangeIdDirScanner;
64
+ const staleSingleSlot = opts.staleSingleSlotScanner ?? defaultStaleSingleSlotScanner;
45
65
  return {
46
66
  topLevelSessionDirs: safeList(() => topLevel(opts.projectRoot)),
47
67
  legacyDotfiles: safeList(() => dotfiles(opts.projectRoot)),
48
- perChangeIdDirs: safeList(() => perChangeId(opts.projectRoot))
68
+ perChangeIdDirs: safeList(() => perChangeId(opts.projectRoot)),
69
+ staleSingleSlotFiles: safeList(() => staleSingleSlot(opts.projectRoot))
49
70
  };
50
71
  }
51
72
  function safeList(reader) {
@@ -103,6 +124,39 @@ function defaultLegacyDotfileScanner(projectRoot) {
103
124
  }
104
125
  return offenders;
105
126
  }
127
+ /**
128
+ * Slice 4.0.11 statusline-sid-scoped-lease C: surface the deprecated
129
+ * single-slot presence files (`.peaks/_runtime/active-skill.json` and
130
+ * the legacy `.peaks/.active-skill.json`) as a separate offender
131
+ * category. The canonical sid-scoped lease projection
132
+ * (`.peaks/_runtime/<sid>/leases/presence-*.json`) is the source of
133
+ * truth; these single-slot files should be deleted so the doctor
134
+ * report is clean.
135
+ *
136
+ * The reported path is the project-relative form so the doctor's
137
+ * human-readable output stays consistent with `legacyDotfiles`.
138
+ */
139
+ function defaultStaleSingleSlotScanner(projectRoot) {
140
+ const offenders = [];
141
+ const candidates = [
142
+ join(projectRoot, '.peaks', '_runtime', 'active-skill.json'),
143
+ join(projectRoot, '.peaks', '.active-skill.json')
144
+ ];
145
+ const reported = [
146
+ join('.peaks', '_runtime', 'active-skill.json'),
147
+ join('.peaks', '.active-skill.json')
148
+ ];
149
+ for (let i = 0; i < candidates.length; i++) {
150
+ const candidate = candidates[i];
151
+ const reportedPath = reported[i];
152
+ if (candidate === undefined || reportedPath === undefined)
153
+ continue;
154
+ if (existsSync(candidate)) {
155
+ offenders.push(reportedPath);
156
+ }
157
+ }
158
+ return offenders;
159
+ }
106
160
  function defaultPerChangeIdDirScanner(projectRoot) {
107
161
  const peaksRoot = join(projectRoot, '.peaks');
108
162
  if (!existsSync(peaksRoot))
@@ -136,7 +190,7 @@ function defaultPerChangeIdDirScanner(projectRoot) {
136
190
  function defaultWorkspaceLayoutProbe(projectRootResolver) {
137
191
  const projectRoot = projectRootResolver();
138
192
  if (projectRoot === null) {
139
- return { topLevelSessionDirs: [], legacyDotfiles: [], perChangeIdDirs: [] };
193
+ return { topLevelSessionDirs: [], legacyDotfiles: [], perChangeIdDirs: [], staleSingleSlotFiles: [] };
140
194
  }
141
195
  return inspectWorkspaceLayout({ projectRoot });
142
196
  }
@@ -148,22 +202,29 @@ function run({ options, projectRootResolver }) {
148
202
  // return a 2-field shape (no perChangeIdDirs). Treat missing
149
203
  // field as empty.
150
204
  const perChangeIdDirs = layout.perChangeIdDirs ?? [];
151
- if (layout.topLevelSessionDirs.length === 0 && layout.legacyDotfiles.length === 0 && perChangeIdDirs.length === 0) {
205
+ // Slice 4.0.11: probes injected by pre-4.0.11 tests also omit
206
+ // staleSingleSlotFiles. Treat missing field as empty.
207
+ const staleSingleSlotFiles = layout.staleSingleSlotFiles ?? [];
208
+ if (layout.topLevelSessionDirs.length === 0 &&
209
+ layout.legacyDotfiles.length === 0 &&
210
+ perChangeIdDirs.length === 0 &&
211
+ staleSingleSlotFiles.length === 0) {
152
212
  return [{
153
213
  id: 'build:workspace-layout-canonical',
154
214
  ok: true,
155
- message: 'Workspace layout is canonical: no top-level session dirs, no legacy runtime dotfiles, no per-change-id top-level dirs'
215
+ message: 'Workspace layout is canonical: no top-level session dirs, no legacy runtime dotfiles, no per-change-id top-level dirs, no stale single-slot presence files'
156
216
  }];
157
217
  }
158
218
  const offenders = [
159
219
  ...layout.topLevelSessionDirs.map((p) => `top-level session dir: ${p}`),
160
220
  ...layout.legacyDotfiles.map((p) => `legacy dotfile: ${p}`),
161
- ...perChangeIdDirs.map((p) => `per-change-id top-level dir: ${p}`)
221
+ ...perChangeIdDirs.map((p) => `per-change-id top-level dir: ${p}`),
222
+ ...staleSingleSlotFiles.map((p) => `stale single-slot presence: ${p}`)
162
223
  ];
163
224
  return [{
164
225
  id: 'build:workspace-layout-canonical',
165
226
  ok: false,
166
- message: `Workspace layout is not canonical. Offenders: ${offenders.join('; ')}. Run \`peaks workspace migrate --to-runtime --project <repo> --apply\` to consolidate.`
227
+ message: `Workspace layout is not canonical. Offenders: ${offenders.join('; ')}. Run \`peaks workspace migrate --to-runtime --project <repo> --apply\` to consolidate; delete stale single-slot presence files manually after migration.`
167
228
  }];
168
229
  }
169
230
  catch (error) {