peaks-loop 4.1.8 → 4.1.10

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 (29) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +54 -0
  3. package/dist/cli/commands/_register.js +2 -0
  4. package/dist/cli/commands/code-gate-step-08-command.js +21 -11
  5. package/dist/cli/commands/code-gate-step-08-remedy.d.ts +17 -0
  6. package/dist/cli/commands/code-gate-step-08-remedy.js +76 -0
  7. package/dist/cli/commands/code-job-shape-commands.js +21 -5
  8. package/dist/cli/commands/job-init-status-commands.js +45 -5
  9. package/dist/cli/commands/strat-tact-command-helpers.d.ts +16 -0
  10. package/dist/cli/commands/strat-tact-command-helpers.js +162 -0
  11. package/dist/cli/commands/strat-tact-commands.d.ts +3 -0
  12. package/dist/cli/commands/strat-tact-commands.js +176 -0
  13. package/dist/services/code/job-shape-provisional.d.ts +51 -0
  14. package/dist/services/code/job-shape-provisional.js +80 -0
  15. package/dist/services/code/step-08-gate.d.ts +24 -12
  16. package/dist/services/code/step-08-gate.js +54 -97
  17. package/dist/services/code/step-08-session-readers.d.ts +27 -0
  18. package/dist/services/code/step-08-session-readers.js +105 -0
  19. package/dist/services/rd/ast-gate.d.ts +19 -12
  20. package/dist/services/rd/ast-gate.js +10 -0
  21. package/dist/services/rd/canonical-hash.d.ts +1 -0
  22. package/dist/services/rd/canonical-hash.js +38 -0
  23. package/dist/services/rd/impl.js +2 -8
  24. package/dist/services/rd/strategy.js +2 -8
  25. package/dist/services/rd/types.d.ts +10 -10
  26. package/dist/services/rd/types.js +21 -10
  27. package/package.json +5 -5
  28. package/skills/bee/peaks-rd/SKILL.md +25 -3
  29. package/skills/peaks-code/references/step-0-8-gate.md +2 -1
@@ -0,0 +1,176 @@
1
+ /**
2
+ * `peaks strat <sub>` / `peaks tact <sub>` — the STRAT → TACT producer chain.
3
+ *
4
+ * WHY this module exists (backlog §16 / §9.2): the documented chain
5
+ * `strategy.md (STRAT.sig) → impl.json (TACT.sig) → mut-report.json` had no
6
+ * CLI producer, so `mut/mut-report.json` could never receive a real
7
+ * `inputSig`. These commands are thin wrappers over the unchanged rd
8
+ * sub-stages; the service layer stays the single implementation.
9
+ *
10
+ * Hard rules carried over from the services:
11
+ * - H8: a TACT can only anchor to a STRAT whose recomputed sha256 matches
12
+ * the artifact content. `tact write` therefore never accepts a raw
13
+ * `--input-sig`; it re-verifies the strategy JSON first.
14
+ * - H6: AST-gate violations refuse before TACT.sig is written.
15
+ * - One-axis layout: every `--out` lives under
16
+ * `.peaks/_runtime/<sessionId>/`; `--session-id` is required on writes.
17
+ */
18
+ import { mkdir, stat, writeFile } from 'node:fs/promises';
19
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
20
+ import { runAstGate } from '../../services/rd/ast-gate.js';
21
+ import { runStrategicStage } from '../../services/rd/strategic-stage.js';
22
+ import { registerStratSig, runTacticalStage } from '../../services/rd/tactical-stage.js';
23
+ import { CommandRefusal, emitOk, guarded, parseAstContext, readImpl, readStrategy, requireSessionAxis } from './strat-tact-command-helpers.js';
24
+ const CHANGED_FILES_REMEDY = 'Pass --changed-files as existing project-relative paths; the AST gate reads only files inside --project.';
25
+ async function isRegularFile(path) {
26
+ try {
27
+ return (await stat(path)).isFile();
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ /** Containment check: the AST gate must never read outside --project. */
34
+ async function resolveChangedFiles(project, files) {
35
+ for (const file of files) {
36
+ if (isAbsolute(file)) {
37
+ throw new CommandRefusal('INVALID_CHANGED_FILE', CHANGED_FILES_REMEDY, `--changed-files entry is absolute: ${file}`);
38
+ }
39
+ const absolute = resolve(project, file);
40
+ const rel = relative(project, absolute);
41
+ if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
42
+ throw new CommandRefusal('INVALID_CHANGED_FILE', CHANGED_FILES_REMEDY, `--changed-files entry escapes --project: ${file}`);
43
+ }
44
+ if (!(await isRegularFile(absolute))) {
45
+ throw new CommandRefusal('INVALID_CHANGED_FILE', CHANGED_FILES_REMEDY, `--changed-files entry does not exist as a file under --project: ${file}`);
46
+ }
47
+ }
48
+ return [...files];
49
+ }
50
+ /** A TOCTOU failure inside the service still surfaces as a named refusal. */
51
+ async function runTacticalSafely(input) {
52
+ try {
53
+ return await runTacticalStage(input);
54
+ }
55
+ catch (err) {
56
+ if (err instanceof CommandRefusal) {
57
+ throw err;
58
+ }
59
+ throw new CommandRefusal('TACT_WRITE_FAILED', 'Re-run peaks tact write; if the AST gate now reports a violation, fix it first.', `tact write failed: ${err instanceof Error ? err.message : String(err)}`);
60
+ }
61
+ }
62
+ async function runStratWrite(io, a) {
63
+ const project = resolve(a.project);
64
+ const out = requireSessionAxis(project, a.sessionId, a.out);
65
+ await mkdir(dirname(out), { recursive: true });
66
+ const result = await runStrategicStage({
67
+ out,
68
+ goal: a.goal,
69
+ rootCauseAnalysis: a.rootCause,
70
+ impactSurface: a.impact,
71
+ designRationale: a.design
72
+ });
73
+ const jsonPath = `${out}.json`;
74
+ await writeFile(jsonPath, JSON.stringify(result, null, 2), 'utf8');
75
+ emitOk(io, a.json, { path: out, jsonPath, sha256: result.sha256 }, [
76
+ `strategy.md: ${out}`,
77
+ `json: ${jsonPath}`,
78
+ `STRAT.sig: ${result.sha256}`
79
+ ]);
80
+ }
81
+ async function runTactWrite(io, a) {
82
+ const project = resolve(a.project);
83
+ const out = requireSessionAxis(project, a.sessionId, a.out);
84
+ const changedFiles = await resolveChangedFiles(project, a.changedFiles);
85
+ const strategyPath = isAbsolute(a.strategy) ? resolve(a.strategy) : resolve(project, a.strategy);
86
+ const strategy = await readStrategy(strategyPath);
87
+ const context = parseAstContext(a.astContext);
88
+ // Name the violations before the service throws its count-only error.
89
+ const gate = await runAstGate({ project, changedFiles, context });
90
+ if (!gate.passed) {
91
+ throw new CommandRefusal('AST_GATE_FAILED', 'Fix the undocumented API call (or update the locked-version doc summary) and re-run peaks tact write.', `AST gate failed — ${gate.violations
92
+ .map((v) => `${v.api} at ${v.file}:${v.line}`)
93
+ .join('; ')}`);
94
+ }
95
+ await mkdir(dirname(out), { recursive: true });
96
+ // H8: rehydrate the in-process registry from the verified artifact —
97
+ // this CLI process never ran `runStrategicStage`.
98
+ registerStratSig(dirname(out), strategy.sha256);
99
+ const impl = await runTacticalSafely({
100
+ project,
101
+ changedFiles,
102
+ inputSig: strategy.sha256,
103
+ context,
104
+ out
105
+ });
106
+ emitOk(io, a.json, {
107
+ path: out,
108
+ sha256: impl.sha256,
109
+ inputSig: impl.inputSig,
110
+ changedFiles: impl.changedFiles,
111
+ astGateResult: impl.astGateResult
112
+ }, [`impl.json: ${out}`, `TACT.sig: ${impl.sha256}`, `inputSig: ${impl.inputSig}`]);
113
+ }
114
+ async function runTactRead(io, a) {
115
+ const project = resolve(a.project);
116
+ const artifact = isAbsolute(a.artifact) ? resolve(a.artifact) : resolve(project, a.artifact);
117
+ const impl = await readImpl(artifact);
118
+ emitOk(io, a.json, {
119
+ sha256: impl.sha256,
120
+ inputSig: impl.inputSig,
121
+ changedFiles: impl.changedFiles,
122
+ astGateResult: impl.astGateResult
123
+ }, [
124
+ `sha256: ${impl.sha256}`,
125
+ `inputSig: ${impl.inputSig}`,
126
+ `changedFiles: ${impl.changedFiles.join(', ')}`,
127
+ `astGateResult: passed=${impl.astGateResult.passed} violations=${impl.astGateResult.violations.length}`
128
+ ]);
129
+ }
130
+ export function registerStratTactCommands(program, io) {
131
+ const strat = program
132
+ .command('strat')
133
+ .description('STRAT producer: strategy.md + STRAT.sig (spec §4.2 战略审计)');
134
+ registerStratWrite(strat, io);
135
+ const tact = program
136
+ .command('tact')
137
+ .description('TACT producer/reader: impl.json + TACT.sig chained to STRAT.sig');
138
+ registerTactWrite(tact, io);
139
+ registerTactRead(tact, io);
140
+ }
141
+ function registerStratWrite(strat, io) {
142
+ strat
143
+ .command('write')
144
+ .description('Write strategy.md plus its <out>.json sibling. One-axis: --session-id required.')
145
+ .requiredOption('--project <path>', 'project root')
146
+ .requiredOption('--session-id <sid>', 'session id; --out must live under .peaks/_runtime/<sid>/')
147
+ .requiredOption('--out <path>', 'strategy markdown path (inside .peaks/_runtime/<sid>/)')
148
+ .requiredOption('--goal <text>', 'goal of this slice')
149
+ .requiredOption('--root-cause <text>', 'root-cause analysis')
150
+ .requiredOption('--impact <items...>', 'impact surface entries')
151
+ .requiredOption('--design <text>', 'design rationale')
152
+ .option('--json', 'machine-readable output', false)
153
+ .action((a) => guarded(io, a.json, 'strat write', () => runStratWrite(io, a)));
154
+ }
155
+ function registerTactWrite(tact, io) {
156
+ tact
157
+ .command('write')
158
+ .description('Verify the strategy JSON, run the AST gate, then write impl.json + TACT.sig. One-axis: --session-id required.')
159
+ .requiredOption('--project <path>', 'project root')
160
+ .requiredOption('--session-id <sid>', 'session id; --out must live under .peaks/_runtime/<sid>/')
161
+ .requiredOption('--strategy <path>', 'strategy JSON sibling written by `peaks strat write`')
162
+ .requiredOption('--out <path>', 'impl.json path (inside .peaks/_runtime/<sid>/)')
163
+ .requiredOption('--changed-files <paths...>', 'files the tactical stage changed')
164
+ .option('--ast-context <json>', 'AstGateContext JSON ({ deps, docSummaries })')
165
+ .option('--json', 'machine-readable output', false)
166
+ .action((a) => guarded(io, a.json, 'tact write', () => runTactWrite(io, a)));
167
+ }
168
+ function registerTactRead(tact, io) {
169
+ tact
170
+ .command('read')
171
+ .description('Re-read impl.json, recompute TACT.sig, and print the chain anchor.')
172
+ .requiredOption('--artifact <path>', 'impl.json written by `peaks tact write`')
173
+ .option('--project <path>', 'project root (default: cwd)', '.')
174
+ .option('--json', 'machine-readable output', false)
175
+ .action((a) => guarded(io, a.json, 'tact read', () => runTactRead(io, a)));
176
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Backlog §17.1 fix (3) — the provisional Job-shape decision `peaks job init`
3
+ * leaves behind.
4
+ *
5
+ * WHY. `peaks job init` writes `job/<jid>/state.json`, and the Step 0.8 gate
6
+ * reads that ledger with no `job-shape.json` as "`peaks code detect-job` was
7
+ * skipped" — every Bash call in the session is then refused, and the printed
8
+ * remedy is itself a Bash call. The gate cannot tell "the LLM forgot" from
9
+ * "the tooling created a ledger first", so `job init` records the one decision
10
+ * its own ledger implies: isJob=true for this job, at medium confidence,
11
+ * labelled provisional so a reader knows nobody judged the prompt.
12
+ *
13
+ * ORDER: ledger first, decision second (the PRD's chosen order). A decision
14
+ * with no ledger would point at a job that does not exist; a ledger with no
15
+ * decision is exactly the state a later `detect-job` corrects.
16
+ *
17
+ * NEVER OVERWRITES. An existing `job-shape.json` — `isJob: true` or `false`,
18
+ * written by the LLM or by an earlier `job init`, parseable or not — is left
19
+ * byte-identical. Any other failure (an id the decision schema refuses, a
20
+ * read-only runtime dir) is RETURNED rather than thrown: the ledger is already
21
+ * on disk, so the caller must report both facts accurately.
22
+ */
23
+ import { type JobStrategy } from './job-shape-decision.js';
24
+ export interface ProvisionalDecisionInput {
25
+ readonly jobId: string;
26
+ readonly strategy: JobStrategy;
27
+ }
28
+ export type ProvisionalDecisionOutcome = {
29
+ readonly written: true;
30
+ readonly path: string;
31
+ } | {
32
+ readonly written: false;
33
+ readonly path: string;
34
+ readonly reason: 'already-decided';
35
+ } | {
36
+ readonly written: false;
37
+ readonly path: string;
38
+ readonly reason: 'invalid-existing' | 'write-failed';
39
+ readonly error: string;
40
+ };
41
+ /**
42
+ * Ensure `.peaks/_runtime/<sessionId>/job-shape.json` exists, writing a
43
+ * provisional decision only when the path is empty.
44
+ *
45
+ * An existing file is classified by reading it, never by overwriting it: a
46
+ * readable decision is `already-decided`, and an unreadable one is
47
+ * `invalid-existing` so the caller can surface the corruption and the
48
+ * `--force` remedy. The writer's own `JOB_SHAPE_ALREADY_DECIDED` on a race is
49
+ * folded into `already-decided` — the winner's decision stands.
50
+ */
51
+ export declare function ensureProvisionalJobShapeDecision(projectRoot: string, sessionId: string, input: ProvisionalDecisionInput): ProvisionalDecisionOutcome;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Backlog §17.1 fix (3) — the provisional Job-shape decision `peaks job init`
3
+ * leaves behind.
4
+ *
5
+ * WHY. `peaks job init` writes `job/<jid>/state.json`, and the Step 0.8 gate
6
+ * reads that ledger with no `job-shape.json` as "`peaks code detect-job` was
7
+ * skipped" — every Bash call in the session is then refused, and the printed
8
+ * remedy is itself a Bash call. The gate cannot tell "the LLM forgot" from
9
+ * "the tooling created a ledger first", so `job init` records the one decision
10
+ * its own ledger implies: isJob=true for this job, at medium confidence,
11
+ * labelled provisional so a reader knows nobody judged the prompt.
12
+ *
13
+ * ORDER: ledger first, decision second (the PRD's chosen order). A decision
14
+ * with no ledger would point at a job that does not exist; a ledger with no
15
+ * decision is exactly the state a later `detect-job` corrects.
16
+ *
17
+ * NEVER OVERWRITES. An existing `job-shape.json` — `isJob: true` or `false`,
18
+ * written by the LLM or by an earlier `job init`, parseable or not — is left
19
+ * byte-identical. Any other failure (an id the decision schema refuses, a
20
+ * read-only runtime dir) is RETURNED rather than thrown: the ledger is already
21
+ * on disk, so the caller must report both facts accurately.
22
+ */
23
+ import { existsSync } from 'node:fs';
24
+ import { join } from 'node:path';
25
+ import { JobShapeDecisionError, JOB_SHAPE_ALREADY_DECIDED, JOB_SHAPE_FILE_NAME, readJobShapeDecision, writeJobShapeDecision } from './job-shape-decision.js';
26
+ function provisionalRationale(jobId) {
27
+ return (`Provisional decision written by \`peaks job init\` when it created the Job ledger for ` +
28
+ `"${jobId}": a ledger existed before any Job-shape decision was recorded. The job is ` +
29
+ `treated as Job-shaped so the Step 0.8 gate can allow. Re-record it with ` +
30
+ `\`peaks code detect-job --is-job true --suggested-job-id ${jobId} --force\` once the shape is known.`);
31
+ }
32
+ /**
33
+ * Ensure `.peaks/_runtime/<sessionId>/job-shape.json` exists, writing a
34
+ * provisional decision only when the path is empty.
35
+ *
36
+ * An existing file is classified by reading it, never by overwriting it: a
37
+ * readable decision is `already-decided`, and an unreadable one is
38
+ * `invalid-existing` so the caller can surface the corruption and the
39
+ * `--force` remedy. The writer's own `JOB_SHAPE_ALREADY_DECIDED` on a race is
40
+ * folded into `already-decided` — the winner's decision stands.
41
+ */
42
+ export function ensureProvisionalJobShapeDecision(projectRoot, sessionId, input) {
43
+ const path = join(projectRoot, '.peaks', '_runtime', sessionId, JOB_SHAPE_FILE_NAME);
44
+ if (existsSync(path)) {
45
+ try {
46
+ readJobShapeDecision(projectRoot, sessionId);
47
+ return { written: false, path, reason: 'already-decided' };
48
+ }
49
+ catch (err) {
50
+ if (err instanceof JobShapeDecisionError) {
51
+ return { written: false, path, reason: 'invalid-existing', error: err.message };
52
+ }
53
+ throw err;
54
+ }
55
+ }
56
+ try {
57
+ writeJobShapeDecision(projectRoot, sessionId, {
58
+ isJob: true,
59
+ rationale: provisionalRationale(input.jobId),
60
+ suggestedJobId: input.jobId,
61
+ suggestedStrategy: input.strategy,
62
+ confidence: 'medium',
63
+ prompt: `provisional:peaks job init:${input.jobId}`
64
+ });
65
+ return { written: true, path };
66
+ }
67
+ catch (err) {
68
+ // A concurrent writer won the race after the check above; its decision is
69
+ // the one that stands, so this is the same outcome as "already decided".
70
+ if (err instanceof JobShapeDecisionError && err.code === JOB_SHAPE_ALREADY_DECIDED) {
71
+ return { written: false, path, reason: 'already-decided' };
72
+ }
73
+ return {
74
+ written: false,
75
+ path,
76
+ reason: 'write-failed',
77
+ error: err instanceof Error ? err.message : String(err)
78
+ };
79
+ }
80
+ }
@@ -32,14 +32,22 @@
32
32
  * The gate never blocks on the ABSENCE of a decision alone: it runs on
33
33
  * every Bash call in every session, so a normal non-Job session must
34
34
  * keep passing through case (c).
35
+ * Before any of a–c, one exemption: when the hook payload's command is a
36
+ * real `peaks code detect-job` invocation, the gate allows with
37
+ * `allow-remedy-command`. The printed remedy is itself a Bash call, so a
38
+ * gate that blocks it deadlocks the session that needs it. The parse is
39
+ * narrow — a leading env assignment is allowed, the executable tokens
40
+ * must be `peaks`, `code`, `detect-job` in order, and a compound line is
41
+ * not the remedy. A command that only MENTIONS the verb in a quoted
42
+ * string, a comment, or a here-document is not an invocation.
35
43
  *
36
44
  * Karpathy §2 (Simplicity First): no LLM call inside. The regex is the FIRST
37
45
  * time peaks-loop accepts hardcoded keywords — explicitly scoped as a
38
46
  * *fail-closed backup* (case 3), NOT a primary judgement. The LLM still owns
39
47
  * the semantic call via `peaks code detect-job`.
40
48
  */
49
+ import { type Step08Progress } from './step-08-session-readers.js';
41
50
  export declare const STEP_08_GATE_FILE_NAME: "job-shape.json";
42
- export declare const STEP_08_PROGRESS_FILE_NAME: "progress.json";
43
51
  /**
44
52
  * Fail-closed backup regex — see module docstring case 3 for why this
45
53
  * exists. Kept short and explicit; if the prompt mentions any of these
@@ -53,14 +61,6 @@ export declare const STEP_08_PROGRESS_FILE_NAME: "progress.json";
53
61
  * until all done → until all done
54
62
  */
55
63
  export declare const STEP_08_BACKUP_REGEX: RegExp;
56
- export interface Step08Progress {
57
- readonly jobId: string;
58
- readonly done: number;
59
- readonly total: number;
60
- readonly currentSlice: string;
61
- readonly lastCommitSha: string | null;
62
- readonly updatedAt: string;
63
- }
64
64
  export type Step08PromptSource = 'flag' | 'last-prompt-file' | 'stdin-empty';
65
65
  export type Step08Verdict = {
66
66
  readonly kind: 'allow-job';
@@ -68,6 +68,14 @@ export type Step08Verdict = {
68
68
  readonly progress: Step08Progress | null;
69
69
  } | {
70
70
  readonly kind: 'allow-single';
71
+ } | {
72
+ /**
73
+ * The Bash command being gated IS the remedy this gate prints. Named
74
+ * separately so the transcript cannot confuse it with a command in a
75
+ * session that had already recorded a decision.
76
+ */
77
+ readonly kind: 'allow-remedy-command';
78
+ readonly reason: string;
71
79
  } | {
72
80
  readonly kind: 'block-missing-decision';
73
81
  readonly promptSource: Step08PromptSource;
@@ -80,16 +88,20 @@ export type Step08Verdict = {
80
88
  readonly ledgerJobIds: readonly string[];
81
89
  readonly reason: string;
82
90
  };
83
- export declare function runtimeSessionDir(projectRoot: string, sessionId: string): string;
84
91
  export interface EvaluateStep08Input {
85
92
  readonly projectRoot: string;
86
93
  readonly sessionId: string;
87
94
  /**
88
95
  * Explicit prompt text. When omitted, falls back to
89
- * `.peaks/_runtime/<sid>/txt/last-prompt.txt`, then to stdin (the
90
- * caller passes stdin verbatim — usually empty in tests).
96
+ * `.peaks/_runtime/<sid>/txt/last-prompt.txt`. Stdin carries the PreToolUse
97
+ * payload, not the prompt, and is read only when this is omitted.
91
98
  */
92
99
  readonly prompt?: string;
100
+ /**
101
+ * The Bash command the PreToolUse payload carried, when one was supplied.
102
+ * Used only for the remedy exemption — it never feeds the prompt regex.
103
+ */
104
+ readonly command?: string;
93
105
  }
94
106
  export interface EvaluateStep08Result {
95
107
  readonly allow: boolean;
@@ -32,19 +32,24 @@
32
32
  * The gate never blocks on the ABSENCE of a decision alone: it runs on
33
33
  * every Bash call in every session, so a normal non-Job session must
34
34
  * keep passing through case (c).
35
+ * Before any of a–c, one exemption: when the hook payload's command is a
36
+ * real `peaks code detect-job` invocation, the gate allows with
37
+ * `allow-remedy-command`. The printed remedy is itself a Bash call, so a
38
+ * gate that blocks it deadlocks the session that needs it. The parse is
39
+ * narrow — a leading env assignment is allowed, the executable tokens
40
+ * must be `peaks`, `code`, `detect-job` in order, and a compound line is
41
+ * not the remedy. A command that only MENTIONS the verb in a quoted
42
+ * string, a comment, or a here-document is not an invocation.
35
43
  *
36
44
  * Karpathy §2 (Simplicity First): no LLM call inside. The regex is the FIRST
37
45
  * time peaks-loop accepts hardcoded keywords — explicitly scoped as a
38
46
  * *fail-closed backup* (case 3), NOT a primary judgement. The LLM still owns
39
47
  * the semantic call via `peaks code detect-job`.
40
48
  */
41
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
42
- import { join } from 'node:path';
43
49
  import { readJobShapeDecision, JobShapeDecisionError, JOB_SHAPE_NOT_DECIDED } from './job-shape-decision.js';
44
50
  import { describeNextSlice } from '../job/job-progress-store.js';
45
- import { isExpectedFsMiss } from '../../shared/fs-utils.js';
51
+ import { ledgerJobIds, readProgressIfAny, readPromptFromLastPromptFile } from './step-08-session-readers.js';
46
52
  export const STEP_08_GATE_FILE_NAME = 'job-shape.json';
47
- export const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
48
53
  /**
49
54
  * Fail-closed backup regex — see module docstring case 3 for why this
50
55
  * exists. Kept short and explicit; if the prompt mentions any of these
@@ -58,98 +63,6 @@ export const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
58
63
  * until all done → until all done
59
64
  */
60
65
  export const STEP_08_BACKUP_REGEX = /直到|全部|until all done|disavow cost|不用考虑费用|all of them/i;
61
- export function runtimeSessionDir(projectRoot, sessionId) {
62
- return join(projectRoot, '.peaks', '_runtime', sessionId);
63
- }
64
- function progressPath(projectRoot, sessionId, jid) {
65
- // The progress file lives under job/<jid>/progress.json. The jid
66
- // comes from job-shape.json (decision.suggestedJobId) — there is
67
- // exactly one canonical jid per session under Job mode, so we read
68
- // the matching path directly rather than enumerating the job/ dir.
69
- // (Rotating mode spawns new jids but only one is "active" at a time;
70
- // the active jid is the latest write to job-shape.json.)
71
- return join(runtimeSessionDir(projectRoot, sessionId), 'job', jid, STEP_08_PROGRESS_FILE_NAME);
72
- }
73
- function readProgressIfAny(projectRoot, sessionId, jid) {
74
- const path = progressPath(projectRoot, sessionId, jid);
75
- if (!existsSync(path))
76
- return null;
77
- try {
78
- const raw = readFileSync(path, 'utf8');
79
- const parsed = JSON.parse(raw);
80
- if (typeof parsed.jobId === 'string' &&
81
- typeof parsed.done === 'number' &&
82
- typeof parsed.total === 'number' &&
83
- typeof parsed.currentSlice === 'string' &&
84
- typeof parsed.updatedAt === 'string') {
85
- return {
86
- jobId: parsed.jobId,
87
- done: parsed.done,
88
- total: parsed.total,
89
- currentSlice: parsed.currentSlice,
90
- lastCommitSha: typeof parsed.lastCommitSha === 'string' ? parsed.lastCommitSha : null,
91
- updatedAt: parsed.updatedAt
92
- };
93
- }
94
- return null;
95
- }
96
- catch (err) {
97
- // P1 site (S6, 2026-09-15) — same correction as `readPromptFromLastPromptFile`
98
- // below: corrupt progress.json stays loud, and a failure that is not an
99
- // fs miss (module-load ReferenceError, TypeError from a bad field, …)
100
- // propagates instead of reading as "no progress yet".
101
- if (err instanceof SyntaxError)
102
- throw err;
103
- if (!isExpectedFsMiss(err))
104
- throw err;
105
- return null;
106
- }
107
- }
108
- function readPromptFromLastPromptFile(projectRoot, sessionId) {
109
- const path = join(runtimeSessionDir(projectRoot, sessionId), 'txt', 'last-prompt.txt');
110
- if (!existsSync(path))
111
- return '';
112
- try {
113
- return readFileSync(path, 'utf8');
114
- }
115
- catch (err) {
116
- // P1 site (S6, 2026-09-15). This catch was bare — it bound nothing and
117
- // swallowed every error class. The sibling reads in this file had been
118
- // narrowed; this one had not, so the ONE path that feeds the step-08
119
- // backup regex was also the one that could not tell "no prompt file" from
120
- // "the module is broken". On the platform this gate exists for, that is
121
- // the difference between blocking a disavowal prompt and silently
122
- // allowing it. Missing/unreadable text is an empty prompt; anything else
123
- // propagates.
124
- if (!isExpectedFsMiss(err))
125
- throw err;
126
- return '';
127
- }
128
- }
129
- /**
130
- * Job ids this session owns a ledger for, sorted.
131
- *
132
- * A ledger is `job/<jid>/state.json`, which only `peaks job init` writes, and
133
- * `job-shape.json` is written by `peaks code detect-job` and by nothing else —
134
- * so a ledger with no decision is the decision step having been skipped.
135
- */
136
- function ledgerJobIds(projectRoot, sessionId) {
137
- const jobDir = join(runtimeSessionDir(projectRoot, sessionId), 'job');
138
- if (!existsSync(jobDir))
139
- return [];
140
- let names;
141
- try {
142
- names = readdirSync(jobDir);
143
- }
144
- catch (err) {
145
- if (!isExpectedFsMiss(err))
146
- throw err;
147
- return [];
148
- }
149
- return names
150
- .filter((name) => existsSync(join(jobDir, name, 'state.json')))
151
- .sort((left, right) => left.localeCompare(right));
152
- }
153
66
  /**
154
67
  * The reason a Job ledger with no decision is refused — it names both commands,
155
68
  * so the reader sees WHICH step was skipped.
@@ -159,7 +72,44 @@ function noDecisionWithLedgerReason(ledger) {
159
72
  return (`No Job-shape decision was recorded for this session, but it owns a Job ledger (${paths}). ` +
160
73
  'That means `peaks job init` ran and `peaks code detect-job` did not, so every ' +
161
74
  'Job-mode step this gate keys on was skipped. Record the verdict with ' +
162
- '`peaks code detect-job --is-job true|false ...`, then retry.');
75
+ '`peaks code detect-job --is-job false --rationale <text>` (its id defaults to ' +
76
+ '`single-task`), or `peaks code detect-job --is-job true --rationale <text> ' +
77
+ '--suggested-job-id <slug>`, then retry.');
78
+ }
79
+ const DETECT_JOB_TOKENS = ['peaks', 'code', 'detect-job'];
80
+ const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/;
81
+ const REMEDY_COMMAND_REASON = 'The Bash command being run IS the `peaks code detect-job` remedy this gate asks ' +
82
+ 'for when a Job ledger exists without a recorded decision. Allowing it breaks the ' +
83
+ 'deadlock: the remedy is a Bash call and this hook sees every one.';
84
+ /** Quotes group; a separator (`;`, `&`, `|`, `<`, `>`, newline) stands alone. */
85
+ const SHELL_TOKEN_RE = /'[^']*'|"[^"]*"|[^\s;|&<>\n]+|[;|&<>\n]/g;
86
+ /**
87
+ * Whether the command the hook is gating is the remedy this gate prints.
88
+ * Narrow on purpose — no shell parsing: the executable tokens must be
89
+ * `peaks code detect-job`, optionally behind a simple `NAME=value` env
90
+ * assignment. A quoted mention is not an invocation, and neither is a
91
+ * compound line, a comment, a here-document body, or anything carrying a
92
+ * backtick or `$(` — command substitution could run a different command
93
+ * inside what looks like the remedy, so it keeps the gate closed.
94
+ *
95
+ * LIMIT: an env assignment whose value is itself quoted
96
+ * (`A="a b" peaks code detect-job`) is not recognised; the flat tokeniser
97
+ * splits it and the exemption fails closed. A bare `A=b` prefix works.
98
+ */
99
+ function isDetectJobInvocation(command) {
100
+ if (command.includes('`') || command.includes('$('))
101
+ return false;
102
+ const tokens = [];
103
+ for (const match of command.trim().matchAll(SHELL_TOKEN_RE)) {
104
+ const token = match[0];
105
+ if (token === '\n' || (token.length === 1 && ';|&<>'.includes(token)))
106
+ return false;
107
+ tokens.push(token.replace(/^(['"])(.*)\1$/, '$2'));
108
+ }
109
+ let index = 0;
110
+ while (index < tokens.length && ENV_ASSIGNMENT_RE.test(tokens[index] ?? ''))
111
+ index += 1;
112
+ return DETECT_JOB_TOKENS.every((token, offset) => tokens[index + offset] === token);
163
113
  }
164
114
  /** Pure evaluator — does NOT write, does NOT exit. The CLI wrapper reads `allow`. */
165
115
  export function evaluateStep08(input) {
@@ -185,6 +135,13 @@ export function evaluateStep08(input) {
185
135
  }
186
136
  /** `job-shape.json` is missing — see the module header for the three answers. */
187
137
  function decideWithoutJobShapeDecision(input) {
138
+ if (input.command !== undefined && isDetectJobInvocation(input.command)) {
139
+ return {
140
+ allow: true,
141
+ verdict: { kind: 'allow-remedy-command', reason: REMEDY_COMMAND_REASON },
142
+ nextSliceLine: null
143
+ };
144
+ }
188
145
  const promptText = input.prompt ?? readPromptFromLastPromptFile(input.projectRoot, input.sessionId);
189
146
  const promptSource = input.prompt !== undefined
190
147
  ? 'flag'
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Step 0.8 gate — the session's on-disk inputs.
3
+ *
4
+ * Extracted from `step-08-gate.ts` when the remedy exemption pushed that file
5
+ * past the 300-line cap. Each reader answers ONE question about the session
6
+ * directory; the gate keeps the decision.
7
+ */
8
+ export interface Step08Progress {
9
+ readonly jobId: string;
10
+ readonly done: number;
11
+ readonly total: number;
12
+ readonly currentSlice: string;
13
+ readonly lastCommitSha: string | null;
14
+ readonly updatedAt: string;
15
+ }
16
+ export declare function readProgressIfAny(projectRoot: string, sessionId: string, jid: string): Step08Progress | null;
17
+ export declare function readPromptFromLastPromptFile(projectRoot: string, sessionId: string): string;
18
+ /**
19
+ * Job ids this session owns a ledger for, sorted.
20
+ *
21
+ * A ledger is `job/<jid>/state.json`, which only `peaks job init` writes.
22
+ * `peaks code detect-job` writes the deliberate `job-shape.json`; since backlog
23
+ * §17.1 fix (3) `peaks job init` also writes a PROVISIONAL one right after the
24
+ * ledger. A ledger with no decision is therefore a ledger from before that fix
25
+ * or a provisional write that failed — not proof the decision step was skipped.
26
+ */
27
+ export declare function ledgerJobIds(projectRoot: string, sessionId: string): string[];