peaks-loop 4.1.8 → 4.1.9

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.
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "metadata": {
3
3
  "pluginRoot": ".",
4
- "version": "4.1.8"
4
+ "version": "4.1.9"
5
5
  },
6
6
  "plugins": [
7
7
  {
8
8
  "name": "peaks-loop",
9
9
  "description": "Loop Engineering CLI — workflow primitive / loop guards / evaluators / slice orchestration",
10
- "version": "4.1.8",
10
+ "version": "4.1.9",
11
11
  "author": {
12
12
  "name": "SquabbyZ"
13
13
  },
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.1.9 — 2026-10-19(Step 0.8 gate:remedy 豁免、provisional 决策与 exit code 可见性)
4
+
5
+ **版本级别**: 未发布区间 `v4.1.8..HEAD` 共 **6 个 commit**(**2 fix / 1 style / 3 docs**)。取 **patch**,依维护者 2026-07-22 的常设规则"默认版本新增采用最小的版本位"。无破坏性 CLI 变更。
6
+
7
+ ### 1. Step 0.8 gate 不再阻塞自己的 remedy(`ec106774`,backlog §17.1 (1)+(2))
8
+
9
+ - `peaks code gate-step-08` 在 `--prompt` 缺省时读取 PreToolUse hook 的 stdin JSON,识别真实的 `peaks code detect-job` 调用并以 `allow-remedy-command` 放行。解析刻意收窄:分隔符、引号/注释/heredoc 提及、反引号与 `$(` 仍然关闭;豁免不写 `job-shape.json`。
10
+ - `peaks code detect-job --is-job false` 的 `--suggested-job-id` 变为可选,默认 `single-task`;`--is-job true` 仍必填,显式 id 仍优先。
11
+
12
+ ### 2. Ledger 必有决策,gate 必报 exit code(`d08cf12f`,backlog §17.1 (3)+(4))
13
+
14
+ - `peaks job init` 创建 ledger 后,若 session 没有 `job-shape.json`,写入一条 provisional 决策(`isJob: true`、job id、请求的 strategy、`confidence: medium`,rationale 标注 provisional)。已有决策只读不覆盖;不可读文件以 `invalid-existing` 上报并给出带 `--force` 的 remedy;写失败同样显式上报。
15
+ - 打印的 provisional remedy 被集成测试逐字执行,保证它不是一条会失败的命令。
16
+ - `gate-step-08` 的两条 block 路径现在在 JSON envelope 中携带 `exitCode: 2`,并在 stderr 中明确写出 `exit 2`。
17
+
18
+ ### 3. 证据与测试
19
+
20
+ - 两个切片合计:单测 38 项、集成 38 项;`tsc --noEmit`、`pnpm build`、repo/staged gate 全绿。
21
+ - code review 对第二个切片曾给出 BLOCK(`runJobInit` 超 50 行),修复后 PASS-WITH-FINDINGS;Karpathy review 两个切片均为 pass(各经过一轮修复:`$(`/反引号与 `--force` remedy);security audit `warn`(仅 LOW,均是已知的 §16 单段路径缺口与非逃逸面);perf audit pass。
22
+ - CI run `39253585358`(`c7947285`)全绿后才发版。
23
+
24
+ ### 4. 残留(非阻塞,已记录)
25
+
26
+ - 窄解析的 fail-closed 情形、2s stdin timeout 无自动化测试、schema 不接受的 job id、跨 job 的 `suggestedJobId` 保留、`isJob:false` + 新 ledger 不拒绝、并发 `JOB_SHAPE_ALREADY_DECIDED` 分支未测、PowerShell native exit 2→1 映射。
27
+
3
28
  ## 4.1.8 — 2026-10-19(24h backlog 清扫:25 个切片,棱镜与证据链收紧,测试判定重新成为代码属性)
4
29
 
5
30
  **版本级别**: 未发布区间 `v4.1.7..HEAD` 共 **57 个 commit**(**5 feat / 14 fix / 2 refactor / 3 test / 1 ci / 31 docs / 1 memory**)。取 **patch**,依维护者 2026-07-22 的常设规则"默认版本新增采用最小的版本位"。本版**无破坏性 CLI 变更**;有两处刻意的行为收紧(`config` 请求的 security review 现在按 rid 分文件;reviewer 的 `schemaPath` 缺失会在 provider 调用前拒绝),升级路径均已覆盖。
@@ -3,6 +3,7 @@ import { fail, ok } from 'peaks-loop-shared/result';
3
3
  import { evaluateStep08, STEP_08_BACKUP_REGEX } from '../../services/code/step-08-gate.js';
4
4
  import { buildContextAuditHint } from '../../services/context/context-audit-hint.js';
5
5
  import { resolveOuterSessionId } from '../../services/session/binding-status-service.js';
6
+ import { printGateStep08RemedyCommand, readHookCommand } from './code-gate-step-08-remedy.js';
6
7
  import { readActiveSid } from './code-runtime-session.js';
7
8
  export function registerCodeGateStep08Command(code, io) {
8
9
  // v3.1.2 Step 0.8 — Mechanical PreToolUse gate.
@@ -20,9 +21,9 @@ export function registerCodeGateStep08Command(code, io) {
20
21
  'line naming the largest context consumer (audit cached ≥ 5 min; fail-soft).')
21
22
  .requiredOption('--project <path>', 'target project root (the hook passes "." so resolveCanonicalProjectRoot promotes it to the git root)')
22
23
  .option('--session-id <sid>', 'override session id (default: read from active presence)')
23
- .option('--prompt <text>', 'explicit prompt text (default: read last-prompt.txt; stdin ignored)')).action((opts) => runGateStep08(opts, io));
24
+ .option('--prompt <text>', 'explicit prompt text (default: read last-prompt.txt; also skips the stdin hook-payload read)')).action((opts) => runGateStep08(opts, io));
24
25
  }
25
- function runGateStep08(opts, io) {
26
+ async function runGateStep08(opts, io) {
26
27
  try {
27
28
  const sessionId = opts.sessionId ?? readActiveSid(opts.project);
28
29
  if (sessionId === null) {
@@ -31,7 +32,8 @@ function runGateStep08(opts, io) {
31
32
  printGateStep08NoSession(io, opts.json);
32
33
  return;
33
34
  }
34
- const context = resolveGateStep08Context(opts, sessionId);
35
+ const command = opts.prompt === undefined ? await readHookCommand() : undefined;
36
+ const context = resolveGateStep08Context(opts, sessionId, command);
35
37
  const verdict = context.result.verdict;
36
38
  if (verdict.kind === 'allow-job') {
37
39
  printGateStep08AllowJob(verdict, context, io, opts.json);
@@ -41,6 +43,10 @@ function runGateStep08(opts, io) {
41
43
  printGateStep08AllowSingle(context, io, opts.json);
42
44
  return;
43
45
  }
46
+ if (verdict.kind === 'allow-remedy-command') {
47
+ printGateStep08RemedyCommand(verdict, context.hintActions, io, opts.json);
48
+ return;
49
+ }
44
50
  if (verdict.kind === 'block-missing-decision') {
45
51
  // Block: the prompt matched the backup regex, so the LLM is treated as
46
52
  // having skipped `peaks code detect-job` on a Job-shaped request.
@@ -60,7 +66,7 @@ function runGateStep08(opts, io) {
60
66
  reportGateStep08Failure(io, err, opts.json);
61
67
  }
62
68
  }
63
- function resolveGateStep08Context(opts, sessionId) {
69
+ function resolveGateStep08Context(opts, sessionId, command) {
64
70
  // hint. Runs ONLY when the window is ≥ 0.70 full, caches the audit
65
71
  // result for ≥ 5 min so the transcript is scanned at most once per
66
72
  // TTL window, and is fail-soft (null → no extra line). It never
@@ -77,6 +83,8 @@ function resolveGateStep08Context(opts, sessionId) {
77
83
  };
78
84
  if (opts.prompt !== undefined)
79
85
  evalInput.prompt = opts.prompt;
86
+ if (command !== undefined)
87
+ evalInput.command = command;
80
88
  const result = evaluateStep08(evalInput);
81
89
  return { result, hintActions };
82
90
  }
@@ -110,16 +118,17 @@ function printGateStep08AllowSingle(context, io, json) {
110
118
  printResult(io, envelope, json);
111
119
  }
112
120
  function printGateStep08Blocked(verdict, context, io, json) {
113
- const blockMessage = 'BLOCKED: prompt looks Job-shaped but peaks code detect-job has not been called. Run `peaks code detect-job --is-job true ...` to record your Job-shape verdict, then retry.';
121
+ const blockMessage = 'BLOCKED: prompt looks Job-shaped but peaks code detect-job has not been called. Run `peaks code detect-job --is-job true --rationale <text> --suggested-job-id <slug>` (or `--is-job false --rationale <text>`, whose id defaults to `single-task`) to record your Job-shape verdict, then retry.';
114
122
  const envelope = fail('code.gate-step-08', 'STEP_08_BLOCKED', blockMessage, {
115
123
  promptSource: verdict.promptSource,
116
- backupRegex: STEP_08_BACKUP_REGEX.toString()
124
+ backupRegex: STEP_08_BACKUP_REGEX.toString(),
125
+ exitCode: 2
117
126
  }, [
118
- 'Run `peaks code detect-job --is-job true --rationale <text> --suggested-job-id <slug>` to record the Job-shape verdict.',
127
+ 'Run `peaks code detect-job --is-job true --rationale <text> --suggested-job-id <slug>` (or `--is-job false --rationale <text>`, whose id defaults to `single-task`) to record the Job-shape verdict.',
119
128
  'Then re-run the Bash tool call.',
120
129
  ...context.hintActions
121
130
  ]);
122
- io.stderr(`${blockMessage}\n`);
131
+ io.stderr(`${blockMessage}\nThis gate blocks with exit 2; a harness that reports it as non-blocking has overridden the hook's exit code.\n`);
123
132
  printResult(io, envelope, json);
124
133
  process.exitCode = 2;
125
134
  }
@@ -127,13 +136,14 @@ function printGateStep08BlockedWithLedger(verdict, context, io, json) {
127
136
  const blockMessage = `BLOCKED: ${verdict.reason}`;
128
137
  const envelope = fail('code.gate-step-08', 'STEP_08_BLOCKED_WITH_LEDGER', blockMessage, {
129
138
  ledgerJobIds: verdict.ledgerJobIds,
130
- backupRegex: STEP_08_BACKUP_REGEX.toString()
139
+ backupRegex: STEP_08_BACKUP_REGEX.toString(),
140
+ exitCode: 2
131
141
  }, [
132
- 'Run `peaks code detect-job --is-job true --rationale <text> --suggested-job-id <slug>` (or `--is-job false`) to record the Job-shape verdict the Job ledger presumes.',
142
+ 'Run `peaks code detect-job --is-job true --rationale <text> --suggested-job-id <slug>` (or `--is-job false --rationale <text>`, whose id defaults to `single-task`) to record the Job-shape verdict the Job ledger presumes.',
133
143
  'Then re-run the Bash tool call.',
134
144
  ...context.hintActions
135
145
  ]);
136
- io.stderr(`${blockMessage}\n`);
146
+ io.stderr(`${blockMessage}\nThis gate blocks with exit 2; a harness that reports it as non-blocking has overridden the hook's exit code.\n`);
137
147
  printResult(io, envelope, json);
138
148
  process.exitCode = 2;
139
149
  }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `peaks code gate-step-08` — the remedy arm.
3
+ *
4
+ * The Step 0.8 gate fires before every Bash call, so the remedy it prints
5
+ * (`peaks code detect-job ...`) is itself a Bash call the gate would refuse.
6
+ * This module reads the PreToolUse payload that names the command and prints
7
+ * the named allow when that command is the remedy.
8
+ */
9
+ import { type ProgramIO } from '../cli-helpers.js';
10
+ import type { Step08Verdict } from '../../services/code/step-08-gate.js';
11
+ type AllowRemedyCommandVerdict = Extract<Step08Verdict, {
12
+ kind: 'allow-remedy-command';
13
+ }>;
14
+ /** The command the hook is gating, when the payload carries one. */
15
+ export declare function readHookCommand(): Promise<string | undefined>;
16
+ export declare function printGateStep08RemedyCommand(verdict: AllowRemedyCommandVerdict, hintActions: readonly string[], io: ProgramIO, json?: boolean): void;
17
+ export {};
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `peaks code gate-step-08` — the remedy arm.
3
+ *
4
+ * The Step 0.8 gate fires before every Bash call, so the remedy it prints
5
+ * (`peaks code detect-job ...`) is itself a Bash call the gate would refuse.
6
+ * This module reads the PreToolUse payload that names the command and prints
7
+ * the named allow when that command is the remedy.
8
+ */
9
+ import { ok } from 'peaks-loop-shared/result';
10
+ import { printResult } from '../cli-helpers.js';
11
+ import { pluckObject, pluckString } from '../../services/ide/hook-translator.js';
12
+ const HOOK_STDIN_TIMEOUT_MS = 2_000;
13
+ /**
14
+ * Read the PreToolUse payload the Bash matcher pipes in. A TTY means a manual
15
+ * invocation with nothing to read. The timer guards against a pipe the parent
16
+ * never closes — this gate runs before EVERY Bash call, so it must not be the
17
+ * thing that hangs one.
18
+ */
19
+ function readStdin() {
20
+ if (process.stdin.isTTY)
21
+ return Promise.resolve('');
22
+ return new Promise((resolveStdin) => {
23
+ let data = '';
24
+ let settled = false;
25
+ const finish = (value) => {
26
+ if (settled)
27
+ return;
28
+ settled = true;
29
+ clearTimeout(timer);
30
+ process.stdin.pause();
31
+ resolveStdin(value);
32
+ };
33
+ const timer = setTimeout(() => finish(''), HOOK_STDIN_TIMEOUT_MS);
34
+ timer.unref();
35
+ process.stdin.setEncoding('utf8');
36
+ process.stdin.on('data', (chunk) => {
37
+ data += String(chunk);
38
+ });
39
+ process.stdin.on('end', () => finish(data));
40
+ process.stdin.on('error', () => finish(''));
41
+ });
42
+ }
43
+ /** JSON.parse whose failure is a value, not a silent null return. */
44
+ function parseJson(raw) {
45
+ try {
46
+ return { ok: true, value: JSON.parse(raw) };
47
+ }
48
+ catch {
49
+ return { ok: false };
50
+ }
51
+ }
52
+ /** The `tool_input.command` of the hook payload, or undefined when there is none. */
53
+ function commandFromHookPayload(raw) {
54
+ if (raw.trim().length === 0)
55
+ return undefined;
56
+ const parsed = parseJson(raw);
57
+ if (!parsed.ok)
58
+ return undefined;
59
+ const toolInput = pluckObject(parsed.value, ['tool_input']) ?? pluckObject(parsed.value, ['input']);
60
+ if (toolInput === undefined)
61
+ return undefined;
62
+ return pluckString(toolInput, ['command']);
63
+ }
64
+ /** The command the hook is gating, when the payload carries one. */
65
+ export async function readHookCommand() {
66
+ return commandFromHookPayload(await readStdin());
67
+ }
68
+ export function printGateStep08RemedyCommand(verdict, hintActions, io, json) {
69
+ const envelope = ok('code.gate-step-08', {
70
+ allow: true,
71
+ mode: 'remedy-command',
72
+ decision: null,
73
+ nextSlice: null
74
+ }, [], [verdict.reason, ...hintActions]);
75
+ printResult(io, envelope, json);
76
+ }
@@ -11,6 +11,8 @@ import { writeJobShapeDecision, JobShapeDecisionError, JOB_SHAPE_NOT_DECIDED, JO
11
11
  import { findProjectRoot } from '../../services/config/config-safety.js';
12
12
  import { getSkillPresence } from '../../services/skills/skill-presence-service.js';
13
13
  import { registerCodeJobShapeReadCommand } from './code-job-shape-commands-read-job-shape.js';
14
+ /** A non-Job decision names no Job; it records this valid, deterministic slug. */
15
+ const DEFAULT_SINGLE_TASK_JOB_ID = 'single-task';
14
16
  export function registerCodeJobShapeCommands(code, io) {
15
17
  // v3.1.1 Step 0.8 — Job-shape decision recorder.
16
18
  // The CLI is a *recorder*, not a judge. The LLM supplies the verdict
@@ -20,11 +22,13 @@ export function registerCodeJobShapeCommands(code, io) {
20
22
  addJsonOption(code
21
23
  .command('detect-job')
22
24
  .description("v3.1.1 Step 0.8: record the LLM's Job-shape judgement. CLI is a recorder, NOT a detector. " +
23
- 'Pass --is-job true|false, --rationale <text>, --suggested-job-id <slug>. ' +
25
+ 'Pass --is-job true|false and --rationale <text>; --suggested-job-id <slug> is required ' +
26
+ 'when --is-job true and defaults to `single-task` when false. ' +
24
27
  'Downstream steps call `peaks code read-job-shape` and refuse to proceed if missing.')
25
28
  .requiredOption('--is-job <bool>', "true | false (the LLM's semantic verdict)")
26
29
  .requiredOption('--rationale <text>', '1-3 sentences the LLM writes explaining the call')
27
- .requiredOption('--suggested-job-id <jid>', 'LLM-chosen stable id, slug-safe (/^[a-z0-9][a-z0-9-]{2,40}$/)')
30
+ .option('--suggested-job-id <jid>', 'LLM-chosen stable id, slug-safe (/^[a-z0-9][a-z0-9-]{2,40}$/). ' +
31
+ 'Required when --is-job true; defaults to `single-task` when --is-job false.')
28
32
  .option('--suggested-strategy <single|rotating>', 'single | rotating', 'single')
29
33
  .option('--confidence <high|medium|low>', 'high | medium | low', 'medium')
30
34
  .option('--force', 'overwrite an existing decision file')
@@ -49,9 +53,21 @@ export function registerCodeJobShapeCommands(code, io) {
49
53
  process.exitCode = 1;
50
54
  return;
51
55
  }
56
+ // The id names the Job a decision creates, so only a Job decision
57
+ // requires one. A non-Job decision records the deterministic default;
58
+ // an explicit id still wins for both values of --is-job.
59
+ const suggestedJobId = opts.suggestedJobId ?? (opts.isJob === 'false' ? DEFAULT_SINGLE_TASK_JOB_ID : undefined);
60
+ if (suggestedJobId === undefined) {
61
+ printResult(io, fail('code.detect-job', 'INVALID_FLAG', '--suggested-job-id is required when --is-job true (it names the Job the decision creates)', { provided: null }, [
62
+ 'Pass --suggested-job-id <slug> (lowercase, digits, dashes; 3-41 chars)',
63
+ 'Or answer --is-job false and let the id default to `single-task`'
64
+ ]), opts.json);
65
+ process.exitCode = 1;
66
+ return;
67
+ }
52
68
  const jidRe = /^[a-z0-9][a-z0-9-]{2,40}$/;
53
- if (!jidRe.test(opts.suggestedJobId)) {
54
- printResult(io, fail('code.detect-job', 'INVALID_FLAG', `--suggested-job-id must match /^[a-z0-9][a-z0-9-]{2,40}$/ (got "${opts.suggestedJobId}")`, { provided: opts.suggestedJobId }, ['Pass a slug-safe id (lowercase, digits, dashes; 3-41 chars)']), opts.json);
69
+ if (!jidRe.test(suggestedJobId)) {
70
+ printResult(io, fail('code.detect-job', 'INVALID_FLAG', `--suggested-job-id must match /^[a-z0-9][a-z0-9-]{2,40}$/ (got "${suggestedJobId}")`, { provided: suggestedJobId }, ['Pass a slug-safe id (lowercase, digits, dashes; 3-41 chars)']), opts.json);
55
71
  process.exitCode = 1;
56
72
  return;
57
73
  }
@@ -86,7 +102,7 @@ export function registerCodeJobShapeCommands(code, io) {
86
102
  const record = writeJobShapeDecision(projectRoot, sessionId, {
87
103
  isJob: opts.isJob === 'true',
88
104
  rationale: opts.rationale,
89
- suggestedJobId: opts.suggestedJobId,
105
+ suggestedJobId,
90
106
  suggestedStrategy: opts.suggestedStrategy,
91
107
  confidence: opts.confidence,
92
108
  prompt: promptText
@@ -4,6 +4,7 @@ import { JobStateStore } from '../../services/job/job-state-store.js';
4
4
  import { JobOrchestrator } from '../../services/job/job-orchestrator.js';
5
5
  import { emitJobEvent } from '../../services/job/job-event-emitter.js';
6
6
  import { JobInitInputSchema } from '../../services/job/job-types.js';
7
+ import { ensureProvisionalJobShapeDecision } from '../../services/code/job-shape-provisional.js';
7
8
  import { getCurrentSessionId } from '../../services/skills/skill-presence-service.js';
8
9
  import { asJson, failResult, projectRoot } from './job-command-shared.js';
9
10
  import { SESSION_ID_HELP, resolveJobStateRoot } from './job-state-root.js';
@@ -54,6 +55,37 @@ function parseJobInitInput(opts, sessionId, project) {
54
55
  json: opts.json
55
56
  });
56
57
  }
58
+ /**
59
+ * The advice a provisional outcome owes the caller. `written` and
60
+ * `already-decided` are the expected outcomes and stay silent; the two failure
61
+ * arms carry the exact command that repairs them (the unreadable-file arm needs
62
+ * `--force`, because a decision file exists but cannot be replaced without it).
63
+ */
64
+ function provisionalAdvice(jobId, outcome) {
65
+ if (outcome.written || outcome.reason === 'already-decided') {
66
+ return { warnings: [], nextActions: [] };
67
+ }
68
+ const force = outcome.reason === 'invalid-existing' ? ' --force' : '';
69
+ const remedy = `peaks code detect-job --is-job true --suggested-job-id ${jobId}${force}`;
70
+ const problem = outcome.reason === 'invalid-existing'
71
+ ? `The existing Job-shape decision at ${outcome.path} is unreadable (${outcome.error})`
72
+ : `Could not write the provisional Job-shape decision at ${outcome.path}: ${outcome.error}`;
73
+ return {
74
+ warnings: [`${problem}. Run \`${remedy}\` to replace it.`],
75
+ nextActions: [
76
+ `Run \`${remedy}\`; until a readable decision exists \`peaks code gate-step-08\` blocks Bash calls in this session.`
77
+ ]
78
+ };
79
+ }
80
+ /** The success envelope, unchanged except for advice when the decision is unreadable. */
81
+ function printJobInitResult(io, opts, report) {
82
+ const { warnings, nextActions } = provisionalAdvice(report.state.jobId, report.provisional);
83
+ printResult(io, ok('init', {
84
+ jobId: report.state.jobId,
85
+ sliceCount: report.state.slices.length,
86
+ statePath: report.statePath
87
+ }, warnings, nextActions), asJson(opts));
88
+ }
57
89
  function runJobInit(opts, io) {
58
90
  const project = projectRoot(opts);
59
91
  // Resolve sessionId: explicit flag > PEAKS_SESSION_ID > caller-first session binding
@@ -80,12 +112,20 @@ function runJobInit(opts, io) {
80
112
  mainLoopStrategy: parsed.data.mainLoopStrategy,
81
113
  rotateEvery: parsed.data.rotateEvery
82
114
  });
83
- emitJobStarted(state);
84
- printResult(io, ok('init', {
115
+ // Step 0.8 — a ledger must never exist without a decision. The ledger is
116
+ // already on disk (the `orch.init` line above), so this either leaves the
117
+ // session with a decision or reports why it could not; it never refuses the
118
+ // ledger that was just written. An existing decision is never overwritten.
119
+ const provisional = ensureProvisionalJobShapeDecision(project, sessionId, {
85
120
  jobId: state.jobId,
86
- sliceCount: state.slices.length,
87
- statePath: `${jobRoot.rootDir}/${state.jobId}/state.json`
88
- }), asJson(opts));
121
+ strategy: parsed.data.mainLoopStrategy
122
+ });
123
+ emitJobStarted(state);
124
+ printJobInitResult(io, opts, {
125
+ state,
126
+ statePath: `${jobRoot.rootDir}/${state.jobId}/state.json`,
127
+ provisional
128
+ });
89
129
  }
90
130
  function runJobStatus(opts, io) {
91
131
  const store = new JobStateStore(resolveJobStateRoot(opts, opts.jobId).rootDir);
@@ -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[];
@@ -0,0 +1,105 @@
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
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { isExpectedFsMiss } from '../../shared/fs-utils.js';
11
+ const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
12
+ function runtimeSessionDir(projectRoot, sessionId) {
13
+ return join(projectRoot, '.peaks', '_runtime', sessionId);
14
+ }
15
+ function progressPath(projectRoot, sessionId, jid) {
16
+ // The progress file lives under job/<jid>/progress.json. The jid
17
+ // comes from job-shape.json (decision.suggestedJobId) — there is
18
+ // exactly one canonical jid per session under Job mode, so we read
19
+ // the matching path directly rather than enumerating the job/ dir.
20
+ // (Rotating mode spawns new jids but only one is "active" at a time;
21
+ // the active jid is the latest write to job-shape.json.)
22
+ return join(runtimeSessionDir(projectRoot, sessionId), 'job', jid, STEP_08_PROGRESS_FILE_NAME);
23
+ }
24
+ export function readProgressIfAny(projectRoot, sessionId, jid) {
25
+ const path = progressPath(projectRoot, sessionId, jid);
26
+ if (!existsSync(path))
27
+ return null;
28
+ try {
29
+ const raw = readFileSync(path, 'utf8');
30
+ const parsed = JSON.parse(raw);
31
+ if (typeof parsed.jobId === 'string' &&
32
+ typeof parsed.done === 'number' &&
33
+ typeof parsed.total === 'number' &&
34
+ typeof parsed.currentSlice === 'string' &&
35
+ typeof parsed.updatedAt === 'string') {
36
+ return {
37
+ jobId: parsed.jobId,
38
+ done: parsed.done,
39
+ total: parsed.total,
40
+ currentSlice: parsed.currentSlice,
41
+ lastCommitSha: typeof parsed.lastCommitSha === 'string' ? parsed.lastCommitSha : null,
42
+ updatedAt: parsed.updatedAt
43
+ };
44
+ }
45
+ return null;
46
+ }
47
+ catch (err) {
48
+ // P1 site (S6, 2026-09-15) — same correction as `readPromptFromLastPromptFile`
49
+ // below: corrupt progress.json stays loud, and a failure that is not an
50
+ // fs miss (module-load ReferenceError, TypeError from a bad field, …)
51
+ // propagates instead of reading as "no progress yet".
52
+ if (err instanceof SyntaxError)
53
+ throw err;
54
+ if (!isExpectedFsMiss(err))
55
+ throw err;
56
+ return null;
57
+ }
58
+ }
59
+ export function readPromptFromLastPromptFile(projectRoot, sessionId) {
60
+ const path = join(runtimeSessionDir(projectRoot, sessionId), 'txt', 'last-prompt.txt');
61
+ if (!existsSync(path))
62
+ return '';
63
+ try {
64
+ return readFileSync(path, 'utf8');
65
+ }
66
+ catch (err) {
67
+ // P1 site (S6, 2026-09-15). This catch was bare — it bound nothing and
68
+ // swallowed every error class. The sibling reads in this file had been
69
+ // narrowed; this one had not, so the ONE path that feeds the step-08
70
+ // backup regex was also the one that could not tell "no prompt file" from
71
+ // "the module is broken". On the platform this gate exists for, that is
72
+ // the difference between blocking a disavowal prompt and silently
73
+ // allowing it. Missing/unreadable text is an empty prompt; anything else
74
+ // propagates.
75
+ if (!isExpectedFsMiss(err))
76
+ throw err;
77
+ return '';
78
+ }
79
+ }
80
+ /**
81
+ * Job ids this session owns a ledger for, sorted.
82
+ *
83
+ * A ledger is `job/<jid>/state.json`, which only `peaks job init` writes.
84
+ * `peaks code detect-job` writes the deliberate `job-shape.json`; since backlog
85
+ * §17.1 fix (3) `peaks job init` also writes a PROVISIONAL one right after the
86
+ * ledger. A ledger with no decision is therefore a ledger from before that fix
87
+ * or a provisional write that failed — not proof the decision step was skipped.
88
+ */
89
+ export function ledgerJobIds(projectRoot, sessionId) {
90
+ const jobDir = join(runtimeSessionDir(projectRoot, sessionId), 'job');
91
+ if (!existsSync(jobDir))
92
+ return [];
93
+ let names;
94
+ try {
95
+ names = readdirSync(jobDir);
96
+ }
97
+ catch (err) {
98
+ if (!isExpectedFsMiss(err))
99
+ throw err;
100
+ return [];
101
+ }
102
+ return names
103
+ .filter((name) => existsSync(join(jobDir, name, 'state.json')))
104
+ .sort((left, right) => left.localeCompare(right));
105
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peaks-loop",
3
- "version": "4.1.8",
3
+ "version": "4.1.9",
4
4
  "description": "Loop Engineering CLI — workflow primitive / loop guards / evaluators / slice orchestration",
5
5
  "author": "SquabbyZ",
6
6
  "keywords": [
@@ -129,10 +129,10 @@
129
129
  "picomatch": "4.0.4",
130
130
  "yaml": "^2.9.0",
131
131
  "zod": "^4.4.3",
132
- "peaks-loop-internal-runtime": "0.0.48",
133
- "peaks-loop-mut": "0.1.62",
134
- "peaks-loop-shared-channel": "0.0.65",
135
- "peaks-loop-shared": "0.0.97"
132
+ "peaks-loop-internal-runtime": "0.0.49",
133
+ "peaks-loop-mut": "0.1.63",
134
+ "peaks-loop-shared": "0.0.98",
135
+ "peaks-loop-shared-channel": "0.0.66"
136
136
  },
137
137
  "devDependencies": {
138
138
  "@changesets/cli": "2.31.1",
@@ -16,7 +16,8 @@ The CLI does NOT judge whether the request is Job-shaped — that is the LLM's j
16
16
  ### Action sequence
17
17
 
18
18
  1. LLM reads the user prompt and applies judgement → `isJob: boolean + rationale + suggestedJobId + suggestedStrategy + confidence`.
19
- 2. LLM calls `peaks code detect-job --is-job <bool> --rationale <text> --suggested-job-id <jid> --suggested-strategy <single|rotating> --confidence <high|medium|low> [--force]`.
19
+ 2. LLM calls `peaks code detect-job --is-job <bool> --rationale <text> [--suggested-job-id <jid>] --suggested-strategy <single|rotating> --confidence <high|medium|low> [--force]`.
20
+ `--suggested-job-id` is required when `--is-job true` and optional when `--is-job false`, where it defaults to `single-task`.
20
21
  3. CLI records to `.peaks/_runtime/<sessionId>/job-shape.json`.
21
22
  4. If `isJob: true` → `peaks job init --job-id <jid> --slice-list <...> --main-loop-strategy <strategy> --rotate-every 3` (BEFORE Step 1).
22
23
  5. Downstream steps (Step 1, Step 0.81, etc.) call `read-job-shape` to refuse if missing.