peaks-loop 4.1.7 → 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.
Files changed (85) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +72 -0
  3. package/config/eslint/tsconfig.lint.json +1 -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/dispatch-from-dag.js +17 -0
  9. package/dist/cli/commands/job-commands.js +15 -5
  10. package/dist/cli/commands/job-init-status-commands.js +45 -5
  11. package/dist/cli/commands/lint-baseline-command.d.ts +15 -0
  12. package/dist/cli/commands/lint-baseline-command.js +64 -0
  13. package/dist/cli/commands/lint-commands.js +27 -51
  14. package/dist/cli/commands/request-command-options.d.ts +6 -0
  15. package/dist/cli/commands/request-commands.js +2 -0
  16. package/dist/cli/commands/request-mark-qa-initiated-command.d.ts +3 -0
  17. package/dist/cli/commands/request-mark-qa-initiated-command.js +80 -0
  18. package/dist/cli/commands/request-transition-failures.js +1 -0
  19. package/dist/cli/commands/reviewer-commands.d.ts +6 -6
  20. package/dist/cli/commands/reviewer-commands.js +154 -56
  21. package/dist/cli/commands/reviewer-config-commands.d.ts +9 -0
  22. package/dist/cli/commands/reviewer-config-commands.js +133 -0
  23. package/dist/services/artifacts/artifact-lint-service.js +102 -27
  24. package/dist/services/artifacts/artifact-prerequisites.d.ts +1 -0
  25. package/dist/services/artifacts/artifact-prerequisites.js +13 -13
  26. package/dist/services/artifacts/artifact-template-bodies.d.ts +7 -1
  27. package/dist/services/artifacts/artifact-template-bodies.js +14 -3
  28. package/dist/services/artifacts/artifact-templates.d.ts +6 -1
  29. package/dist/services/artifacts/artifact-templates.js +8 -5
  30. package/dist/services/artifacts/backcompat-acceptance.js +7 -5
  31. package/dist/services/artifacts/prerequisite-checks.d.ts +34 -9
  32. package/dist/services/artifacts/prerequisite-checks.js +28 -9
  33. package/dist/services/artifacts/qa-initiated-marker.d.ts +24 -0
  34. package/dist/services/artifacts/qa-initiated-marker.js +36 -0
  35. package/dist/services/artifacts/request-artifact-metadata.d.ts +9 -0
  36. package/dist/services/artifacts/request-artifact-metadata.js +9 -0
  37. package/dist/services/artifacts/request-artifact-service.js +6 -10
  38. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +2 -1
  39. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -3
  40. package/dist/services/code/job-shape-provisional.d.ts +51 -0
  41. package/dist/services/code/job-shape-provisional.js +80 -0
  42. package/dist/services/code/step-08-gate.d.ts +24 -12
  43. package/dist/services/code/step-08-gate.js +54 -97
  44. package/dist/services/code/step-08-session-readers.d.ts +27 -0
  45. package/dist/services/code/step-08-session-readers.js +105 -0
  46. package/dist/services/dispatch/isolation-lease.d.ts +3 -2
  47. package/dist/services/dispatch/isolation-lease.js +15 -6
  48. package/dist/services/job/subagent-job-wrapper.d.ts +20 -7
  49. package/dist/services/job/subagent-job-wrapper.js +53 -5
  50. package/dist/services/lint/eslint-report.d.ts +19 -0
  51. package/dist/services/lint/eslint-report.js +60 -0
  52. package/dist/services/lint/eslint-runner-support.d.ts +18 -1
  53. package/dist/services/lint/eslint-runner-support.js +35 -2
  54. package/dist/services/lint/eslint-runner-types.d.ts +21 -1
  55. package/dist/services/lint/eslint-runner.js +43 -33
  56. package/dist/services/prd/gate-evidence-derivation.d.ts +2 -4
  57. package/dist/services/prd/gate-evidence-derivation.js +3 -1
  58. package/dist/services/qa/bdd-test-style-contract.d.ts +17 -0
  59. package/dist/services/qa/bdd-test-style-contract.js +41 -0
  60. package/dist/services/qa/bdd-test-style-verifier.d.ts +9 -6
  61. package/dist/services/qa/bdd-test-style-verifier.js +24 -37
  62. package/dist/services/rd/reviewer-dispatch-policy.d.ts +18 -14
  63. package/dist/services/rd/reviewer-dispatch-policy.js +14 -11
  64. package/dist/services/release/release-state.js +20 -5
  65. package/dist/services/reviewer/model-family.js +1 -1
  66. package/dist/services/reviewer/reviewer-artifacts.d.ts +12 -0
  67. package/dist/services/reviewer/reviewer-artifacts.js +67 -0
  68. package/dist/services/reviewer/reviewer-config-write.d.ts +18 -0
  69. package/dist/services/reviewer/reviewer-config-write.js +71 -0
  70. package/dist/services/reviewer/reviewer-config.d.ts +33 -5
  71. package/dist/services/reviewer/reviewer-config.js +102 -46
  72. package/dist/services/reviewer/reviewer-envelopes.d.ts +8 -0
  73. package/dist/services/reviewer/reviewer-envelopes.js +53 -0
  74. package/dist/services/reviewer/reviewer-service.d.ts +7 -4
  75. package/dist/services/reviewer/reviewer-service.js +46 -52
  76. package/dist/services/reviewer/reviewer-types.d.ts +9 -1
  77. package/dist/services/session/getSessionDir.js +16 -7
  78. package/dist/services/web/daemon-registry.d.ts +6 -4
  79. package/dist/services/web/daemon-registry.js +92 -17
  80. package/package.json +5 -5
  81. package/schemas/reviewer-envelope.schema.json +1 -1
  82. package/skills/bee/peaks-reviewer/SKILL.md +20 -4
  83. package/skills/bee/peaks-reviewer/references/reviewer-schema.md +12 -7
  84. package/skills/bee/peaks-security-audit/SKILL.md +20 -0
  85. package/skills/peaks-code/references/step-0-8-gate.md +2 -1
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "metadata": {
3
3
  "pluginRoot": ".",
4
- "version": "4.1.7"
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.7",
10
+ "version": "4.1.9",
11
11
  "author": {
12
12
  "name": "SquabbyZ"
13
13
  },
package/CHANGELOG.md CHANGED
@@ -1,5 +1,77 @@
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
+
28
+ ## 4.1.8 — 2026-10-19(24h backlog 清扫:25 个切片,棱镜与证据链收紧,测试判定重新成为代码属性)
29
+
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 调用前拒绝),升级路径均已覆盖。
31
+
32
+ ### 1. 证据链与前置条件(`4f15ccaf`、`3ad4aef4`、`bd559bc4`、`2468133e`、`fbb98dc9`)
33
+
34
+ - **缺失与存在但不合法被区分**:前置条件检查现在返回 `absent` / `body` 两种 kind,`LINT_GATE_FAILED` 点名具体 artifact 与行号,不再让"文件不存在"和"文件在但内容不合规"共用一句报错。
35
+ - **`- type:` / `- state:` 在作者时校验**:角色感知的取值校验,缺失 `- state:` 行也会被 lint 抓住;`request init` 写出裸 token,`feature (…)` 这类括注不再能通过。
36
+ - **`getSessionDir` 真正执行单段契约**:`a/b` 不再被当作合法 session id,34 个调用点不受影响。
37
+ - **`rd/security-review.md` / `rd/third-party-review.md` 按 rid 分文件**:两个切片在同一次会话中不再互相覆盖;裸路径保留为 back-compat legacy 层。
38
+
39
+ ### 2. Third-party reviewer(`64238afa`、`bedfb7af`、`e5f839cb`)
40
+
41
+ - `skip` 不再伪装成 `passed: true`;`peaks reviewer config` 有完整的 flag 驱动面,`status` 区分未配置 / provider 不足 / 已配置。
42
+ - `THIRD_PARTY_REVIEW` 解析 `rd/third-party-review-<rid>.md`;producer 在第一次 `mkdir` 前用 `REQUEST_ID_PATTERN` 校验 rid;commit-leg 接受清单按 declared 路径键控,并接受该行自己的 legacy 层作为同 `until` 的别名——v4.1.7 播种的旧清单不会被升级打断。
43
+ - `distinctFromKarpathy` 两侧都把 `skipped`/空视为"无可比 family";`schemaPath` 变为真正读取项:绝对路径 → 项目副本 → 包内副本,全部缺失时在调用 provider 前以 `SCHEMA_MISSING` 拒绝并列出所有候选,`status` 报告获胜路径与来源。
44
+
45
+ ### 3. Lint 与策略(`f4809134`、`6b733390`、`cd3f5637`)
46
+
47
+ - eslint 的 dot-directory 不再静默跳过;`peaks lint --config` 与 `lint baseline --baseline-file` 的读/写路径一致;空作用域有显式 `EMPTY_SCOPE` 而非静默零。baseline 只减不增的棘轮保持,三个切片期间曾两次拒绝上涨。
48
+
49
+ ### 4. Dispatch / job(`8fec96be`、`ad3a72a2`、`aee3532d`)
50
+
51
+ - `--isolation container` 恢复真实退出码与 JSON envelope(`child.unref()` 推迟到 `close`)。
52
+ - `job subagent-cleanup` 只在真正收尾了 ledger 行时报告 `cleaned:true`。
53
+ - `--from-dag` 校验每个节点的 role。
54
+
55
+ ### 5. Release 与模板(`59867889`、`41073d7a`)
56
+
57
+ - `readReleaseState` 对未知 stage 失败关闭。
58
+ - QA 模板在 `openspec/changes/` 缺失时渲染 `- N/A — …`,不再把无法填写的 `<id>` 段交给 QA 再因未填而拒绝;目录存在时保持原文。
59
+
60
+ ### 6. 测试判定成为代码属性(`b6174b8c`)
61
+
62
+ - **daemon spawn lock 的真实 bug**:`writeFileSync({flag:'wx'})` 是先建后写,并发读者把零字节 body 当 stale,删除活锁后各自起一个 daemon。现在"年轻且不可读"视为持有,回收是原子 quarantine rename + moved-body + own-create 校验,还原用 `COPYFILE_EXCL`,release 不删不属于自己的年轻锁。
63
+ - 六个负载敏感测试:四个按文件超时、walker 只排除自己的临时 fixture 树、`staged-size-leg` 的判定改为 `judgeChangeSet`(非空但全在策略外的变更集与干净树同义),并带 synthetic 输入与 throwing control——回退修复在干净 checkout 上也会变红。
64
+
65
+ ### 7. CI(`ec477874`)
66
+
67
+ - `ci.yml` 的七个 job 全部设置 `timeout-minutes`(20–60),不再继承 GitHub 的 360 分钟默认。
68
+
69
+ ### 8. 文档与记忆(`df379817`、`83373f67`、`15ba24bd`、`92b17867`、`664de2b5`)
70
+
71
+ - `docs/superpowers/**` 的历史计划文档显式豁免引用完整性;`.peaks/memory/` 的 36 个指针类 / 47 处机械修复(skill 迁移、mut 包抽取、`integration/` 缩写)。
72
+ - security-audit SKILL 写明 `--judged` 循环的终止条件(先冻结 `src/`、审计最后、修复后只重跑一次、其余记为 accepted residual)。
73
+ - backlog 增加 `## Decision record — 2026-10-19`:meta 层保持冻结、体积债只维持 ratchet、integration 不进入默认配置、覆盖率地板等首个全绿 CI、中文 README 为权威;其余残余逐条写明接受理由。
74
+
3
75
  ## 4.1.7 — 2026-10-18(提交腿硬门、契约表派生、过期债棘轮,以及 canonical store 与 IDE skill 树的漂移检查)
4
76
 
5
77
  **版本级别**: 未发布区间 `v4.1.6..HEAD` 共 **5 个 commit**(**1 feat / 2 refactor / 1 chore / 1 docs**)。取 **patch**,依维护者 2026-07-22 的常设规则"默认版本新增采用最小的版本位"。
@@ -40,6 +40,7 @@
40
40
  "../../src/**/*",
41
41
  "../../tests/**/*",
42
42
  "../../scripts/**/*",
43
+ "../../.husky/**/*",
43
44
  "../../packages/*/src/**/*",
44
45
  "../../packages/*/tests/**/*",
45
46
  "../../packages/*/vitest.config.ts"
@@ -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
@@ -30,7 +30,24 @@ import { buildDagSuccessEnvelope } from './dispatch-dag-envelope.js';
30
30
  import { emitDagFailure } from './dispatch-dag-failure.js';
31
31
  import { assertGraphNodesMapped, loadDagRuntime, readDagOrFail, resolveDagIds, topologicalLevelsOrFail } from './dispatch-dag-preflight.js';
32
32
  import { makeCliRunner, makeNoopWriter, planFirstLevelWaves, resolveDagDispatcher } from './dispatch-dag-runners.js';
33
+ import { RECOMMENDED_ROLES, validateRole } from './sub-agent-shared.js';
33
34
  export async function runDispatchFromDag(role, options, asJson, io) {
35
+ // Backlog §2.1: the warm path refuses an invalid role in `preflightDispatch`,
36
+ // but this branch returns before it ever runs. Validate here, before the DAG
37
+ // file is opened, so both paths share one rule and no DAG work can start.
38
+ const validation = validateRole(role);
39
+ if (validation !== null) {
40
+ emitDagFailure(io, asJson, {
41
+ role,
42
+ code: 'INVALID_ROLE',
43
+ message: validation,
44
+ nextActions: [
45
+ 'Use a non-empty role string with no control characters.',
46
+ `Recommended: ${RECOMMENDED_ROLES}.`
47
+ ]
48
+ });
49
+ return;
50
+ }
34
51
  if (!options.fromDag)
35
52
  return;
36
53
  const scope = { role, asJson, io };
@@ -11,12 +11,12 @@
11
11
  // `tests/unit/standards/gratuitous-async-guard.test.ts`, which keys its 14-site
12
12
  // set on `file | declaration text`.
13
13
  import { Command } from 'commander';
14
- import { ok } from 'peaks-loop-shared/result';
14
+ import { fail, ok } from 'peaks-loop-shared/result';
15
15
  import { addJsonOption, printResult } from '../cli-helpers.js';
16
16
  import { JobStateStore } from '../../services/job/job-state-store.js';
17
17
  import { JobRotation } from '../../services/job/job-rotation.js';
18
18
  import { SubAgentJobWrapper } from '../../services/job/subagent-job-wrapper.js';
19
- import { asJson } from './job-command-shared.js';
19
+ import { asJson, failResult } from './job-command-shared.js';
20
20
  import { SESSION_ID_HELP, resolveJobStateRoot } from './job-state-root.js';
21
21
  import { registerJobInitStatusCommands } from './job-init-status-commands.js';
22
22
  import { registerJobCheckpointCommands } from './job-checkpoint-commands.js';
@@ -48,15 +48,25 @@ function registerJobSubagentCleanupCommand(job, io) {
48
48
  .command('subagent-cleanup')
49
49
  .requiredOption('--job-id <jid>')
50
50
  .requiredOption('--batch-id <bid>')
51
- .option('--force')
51
+ .option('--force', 'clean ledger rows whose status is not queued')
52
52
  .option('--session-id <sid>', SESSION_ID_HELP)
53
53
  .option('--project <repo>')).action(async (opts) => {
54
- const wrapper = new SubAgentJobWrapper(new JobStateStore(resolveJobStateRoot(opts, opts.jobId).rootDir), async () => ({ batchId: opts.batchId }));
54
+ const { rootDir, sessionId, projectRoot } = resolveJobStateRoot(opts, opts.jobId);
55
+ const wrapper = new SubAgentJobWrapper(new JobStateStore(rootDir), () => Promise.resolve({ batchId: opts.batchId }));
55
56
  const r = await wrapper.cleanup({
56
57
  jobId: opts.jobId,
57
58
  batchId: opts.batchId,
58
- force: !!opts.force
59
+ force: !!opts.force,
60
+ projectRoot,
61
+ sessionId
59
62
  });
63
+ if (!r.cleaned) {
64
+ failResult(io, fail('subagent-cleanup', 'BATCH_NOT_CLEANED', `No queued ledger entry for batch ${opts.batchId} in session ${sessionId}; nothing was cleaned.`, r, [
65
+ `The ledger is .peaks/_sub_agents/${sessionId}/active-dispatches.json — check --batch-id.`,
66
+ ...(r.skipped.length > 0 ? ['Rows in a non-queued status need --force.'] : [])
67
+ ]), opts);
68
+ return;
69
+ }
60
70
  printResult(io, ok('subagent-cleanup', r), asJson(opts));
61
71
  });
62
72
  }
@@ -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,15 @@
1
+ import { type EslintRunResult } from '../../services/lint/eslint-runner.js';
2
+ import { type ProgramIO } from '../cli-helpers.js';
3
+ export type LintBaselineOptions = {
4
+ scope?: string;
5
+ config?: string;
6
+ timeoutMs?: string;
7
+ json?: boolean;
8
+ baselineFile?: string;
9
+ allowEmpty?: boolean;
10
+ };
11
+ export declare function writeBaselineJson(projectRoot: string, baselineFile: string, result: EslintRunResult): {
12
+ path: string;
13
+ violations: number;
14
+ };
15
+ export declare function emitBaseline(io: ProgramIO, options: LintBaselineOptions, timeoutMs: number | undefined): void;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * `peaks lint baseline` writer — split out of `lint-commands.ts` for the
3
+ * 300-raw-line cap. Writes the project baseline and refuses to write one from a
4
+ * run that examined nothing (backlog §2.41).
5
+ */
6
+ import { mkdirSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { fail, ok } from 'peaks-loop-shared/result';
9
+ import { CLI_VERSION } from 'peaks-loop-shared/version';
10
+ import { repoRelativeKey } from '../../shared/path-utils.js';
11
+ import { resolveProjectRoot, runEslint } from '../../services/lint/eslint-runner.js';
12
+ import { printResult } from '../cli-helpers.js';
13
+ export function writeBaselineJson(projectRoot, baselineFile, result) {
14
+ const fullPath = join(projectRoot, baselineFile);
15
+ mkdirSync(dirname(fullPath), { recursive: true });
16
+ // Write the SAME key the reader matches on. Writing ESLint's absolute
17
+ // `filePath` here is what re-rooted the file on whichever machine ran the
18
+ // command, so the next checkout inherited keys it could not match.
19
+ const violations = result.findings.map((f) => ({
20
+ ruleId: f.ruleId,
21
+ file: repoRelativeKey(f.filePath, projectRoot),
22
+ line: f.line,
23
+ severity: f.severity,
24
+ message: f.message
25
+ }));
26
+ const payload = {
27
+ version: 1,
28
+ generatedAt: new Date().toISOString(),
29
+ toolVersion: `peaks-loop-${CLI_VERSION}`,
30
+ violations
31
+ };
32
+ writeFileSync(fullPath, JSON.stringify(payload, null, 2), 'utf8');
33
+ return { path: fullPath, violations: violations.length };
34
+ }
35
+ export function emitBaseline(io, options, timeoutMs) {
36
+ const cwd = process.cwd();
37
+ // The flag governs BOTH sides: the runner subtracts the named file below,
38
+ // and `writeBaselineJson` writes back to it.
39
+ const baselineFile = options.baselineFile ?? '.peaks/lint/baseline.json';
40
+ const result = runEslint({
41
+ cwd,
42
+ diffOnly: false,
43
+ baselineFile,
44
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
45
+ ...(options.config !== undefined ? { configPath: options.config } : {}),
46
+ ...(options.allowEmpty === true ? { allowEmpty: true } : {}),
47
+ ...(timeoutMs !== undefined ? { timeoutMs } : {})
48
+ });
49
+ // §2.41: an empty population must never erase every recorded violation.
50
+ if (result.state !== 'ok' && result.state !== 'baseline-missing') {
51
+ printResult(io, fail('code.lint.baseline', result.state.toUpperCase().replace(/-/g, '_'), `peaks code lint baseline state: ${result.state}${result.reason === undefined ? '' : ` — ${result.reason}`}`, { ...result }, ['Nothing was written; the existing baseline is unchanged.']), options.json);
52
+ return;
53
+ }
54
+ const written = writeBaselineJson(resolveProjectRoot(cwd), baselineFile, result);
55
+ printResult(io, ok('code.lint.baseline', {
56
+ state: result.state,
57
+ findings: result.findings.length,
58
+ checkedFiles: result.checkedFiles,
59
+ ignoredFiles: result.ignoredFiles,
60
+ ...written
61
+ }, [], [
62
+ 'Commit baseline.json (or .gitignore it). Peaks-Loop ships its own baseline as a reference fixture.'
63
+ ]), options.json);
64
+ }