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.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +54 -0
- package/dist/cli/commands/_register.js +2 -0
- package/dist/cli/commands/code-gate-step-08-command.js +21 -11
- package/dist/cli/commands/code-gate-step-08-remedy.d.ts +17 -0
- package/dist/cli/commands/code-gate-step-08-remedy.js +76 -0
- package/dist/cli/commands/code-job-shape-commands.js +21 -5
- package/dist/cli/commands/job-init-status-commands.js +45 -5
- package/dist/cli/commands/strat-tact-command-helpers.d.ts +16 -0
- package/dist/cli/commands/strat-tact-command-helpers.js +162 -0
- package/dist/cli/commands/strat-tact-commands.d.ts +3 -0
- package/dist/cli/commands/strat-tact-commands.js +176 -0
- package/dist/services/code/job-shape-provisional.d.ts +51 -0
- package/dist/services/code/job-shape-provisional.js +80 -0
- package/dist/services/code/step-08-gate.d.ts +24 -12
- package/dist/services/code/step-08-gate.js +54 -97
- package/dist/services/code/step-08-session-readers.d.ts +27 -0
- package/dist/services/code/step-08-session-readers.js +105 -0
- package/dist/services/rd/ast-gate.d.ts +19 -12
- package/dist/services/rd/ast-gate.js +10 -0
- package/dist/services/rd/canonical-hash.d.ts +1 -0
- package/dist/services/rd/canonical-hash.js +38 -0
- package/dist/services/rd/impl.js +2 -8
- package/dist/services/rd/strategy.js +2 -8
- package/dist/services/rd/types.d.ts +10 -10
- package/dist/services/rd/types.js +21 -10
- package/package.json +5 -5
- package/skills/bee/peaks-rd/SKILL.md +25 -3
- 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.
|
|
4
|
+
"version": "4.1.10"
|
|
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.
|
|
10
|
+
"version": "4.1.10",
|
|
11
11
|
"author": {
|
|
12
12
|
"name": "SquabbyZ"
|
|
13
13
|
},
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,59 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.1.10 — 2026-10-20(STRAT→TACT→MUT 生产者链,canonical digest 递归修复)
|
|
4
|
+
|
|
5
|
+
**版本级别**: 未发布区间 `v4.1.9..HEAD` 共 **3 个 commit**(**1 feat / 1 fix / 1 docs**)。取 **patch**,依维护者 2026-07-22 的常设规则"默认版本新增采用最小的版本位"。CLI 新增 `peaks strat` / `peaks tact` 两个动词组,均为既有 service 的薄包装;无破坏性变更(canonical digest 的值变了,但只影响修复前产生的临时 artifact)。
|
|
6
|
+
|
|
7
|
+
### 1. STRAT → TACT → MUT 生产者链(`45b378e9`,backlog §16 / §9.2)
|
|
8
|
+
|
|
9
|
+
- `peaks strat write`:写 strategy.md + `<out>.json`,生成 STRAT.sig。
|
|
10
|
+
- `peaks tact write`:校验 strategy JSON 的递归 sha256 与 markdown 的 `STRAT.sig:` 行,注册 STRAT.sig,跑 AST gate,写 impl.json(`inputSig` = STRAT.sig)。
|
|
11
|
+
- `peaks tact read`:重新校验 impl.json 并输出 `{ sha256, inputSig, changedFiles, astGateResult }`——文档里长期缺失的命令现在真实存在。
|
|
12
|
+
- 单轴写入守卫(`--session-id` 必填、`--out` 必须在 `.peaks/_runtime/<sid>/` 下)、`--changed-files` 项目内包含校验、AST 违规/篡改 artifact 的命名 refusal。
|
|
13
|
+
- 端到端测试:`strat write → tact write → tact read → mut`,`mut-report.json#inputSig` 等于 TACT.sig,并覆盖 passing-threshold 分支。
|
|
14
|
+
|
|
15
|
+
### 2. Canonical digest 递归修复(`45b378e9`)
|
|
16
|
+
|
|
17
|
+
- 旧实现 `JSON.stringify(rest, Object.keys(rest).sort())` 是数组 replacer,会在每一层过滤 key,导致嵌套对象(`astGateResult` 等)被哈希成 `{}`;伪造嵌套 verdict 仍能通过验证。
|
|
18
|
+
- 现在逐层排序 key,verifier 对**解析前原始 JSON**求哈希,`StrategyOutput` / `ImplOutput` 及嵌套 schema 均为 `.strict()`。嵌套字段、数组项、未知字段的篡改全部拒绝。
|
|
19
|
+
- 注:digest 是 checksum 不是 MAC;同时改内容并重算签名的 artifact 仍会通过(H8 固有)。
|
|
20
|
+
|
|
21
|
+
### 3. Backlog 与测试稳定性(`442c0e96`、`77a38b82`)
|
|
22
|
+
|
|
23
|
+
- §2.38 关闭:`peaks job add-slice` 已存在并追加 ledger。
|
|
24
|
+
- §9.50 关闭:AC-6 的 macOS gate 已在 CI 中通过。
|
|
25
|
+
- 全量 pre-push 暴露并修复:`tact read` 注册后的 invocation-check 夹具,以及 rule-D 对 `requireSessionAxis` 守卫的识别(补 `isUnsafePathInput`)。
|
|
26
|
+
|
|
27
|
+
### 4. 证据
|
|
28
|
+
|
|
29
|
+
- 531 files / 5798 tests 在 pre-push 全量套件中通过;`tsc --noEmit`、`pnpm build`、repo/staged gate 全绿。
|
|
30
|
+
- code review(两轮,HIGH 已修)PASS-WITH-FINDINGS;Karpathy pass;security `warn`(1 LOW,词法单轴 symlink);perf `warn`(1 LOW,AST gate 双跑);QA PASS(AC1–AC9);`verify-pipeline complete: true`。
|
|
31
|
+
|
|
32
|
+
## 4.1.9 — 2026-10-19(Step 0.8 gate:remedy 豁免、provisional 决策与 exit code 可见性)
|
|
33
|
+
|
|
34
|
+
**版本级别**: 未发布区间 `v4.1.8..HEAD` 共 **6 个 commit**(**2 fix / 1 style / 3 docs**)。取 **patch**,依维护者 2026-07-22 的常设规则"默认版本新增采用最小的版本位"。无破坏性 CLI 变更。
|
|
35
|
+
|
|
36
|
+
### 1. Step 0.8 gate 不再阻塞自己的 remedy(`ec106774`,backlog §17.1 (1)+(2))
|
|
37
|
+
|
|
38
|
+
- `peaks code gate-step-08` 在 `--prompt` 缺省时读取 PreToolUse hook 的 stdin JSON,识别真实的 `peaks code detect-job` 调用并以 `allow-remedy-command` 放行。解析刻意收窄:分隔符、引号/注释/heredoc 提及、反引号与 `$(` 仍然关闭;豁免不写 `job-shape.json`。
|
|
39
|
+
- `peaks code detect-job --is-job false` 的 `--suggested-job-id` 变为可选,默认 `single-task`;`--is-job true` 仍必填,显式 id 仍优先。
|
|
40
|
+
|
|
41
|
+
### 2. Ledger 必有决策,gate 必报 exit code(`d08cf12f`,backlog §17.1 (3)+(4))
|
|
42
|
+
|
|
43
|
+
- `peaks job init` 创建 ledger 后,若 session 没有 `job-shape.json`,写入一条 provisional 决策(`isJob: true`、job id、请求的 strategy、`confidence: medium`,rationale 标注 provisional)。已有决策只读不覆盖;不可读文件以 `invalid-existing` 上报并给出带 `--force` 的 remedy;写失败同样显式上报。
|
|
44
|
+
- 打印的 provisional remedy 被集成测试逐字执行,保证它不是一条会失败的命令。
|
|
45
|
+
- `gate-step-08` 的两条 block 路径现在在 JSON envelope 中携带 `exitCode: 2`,并在 stderr 中明确写出 `exit 2`。
|
|
46
|
+
|
|
47
|
+
### 3. 证据与测试
|
|
48
|
+
|
|
49
|
+
- 两个切片合计:单测 38 项、集成 38 项;`tsc --noEmit`、`pnpm build`、repo/staged gate 全绿。
|
|
50
|
+
- code review 对第二个切片曾给出 BLOCK(`runJobInit` 超 50 行),修复后 PASS-WITH-FINDINGS;Karpathy review 两个切片均为 pass(各经过一轮修复:`$(`/反引号与 `--force` remedy);security audit `warn`(仅 LOW,均是已知的 §16 单段路径缺口与非逃逸面);perf audit pass。
|
|
51
|
+
- CI run `39253585358`(`c7947285`)全绿后才发版。
|
|
52
|
+
|
|
53
|
+
### 4. 残留(非阻塞,已记录)
|
|
54
|
+
|
|
55
|
+
- 窄解析的 fail-closed 情形、2s stdin timeout 无自动化测试、schema 不接受的 job id、跨 job 的 `suggestedJobId` 保留、`isJob:false` + 新 ledger 不拒绝、并发 `JOB_SHAPE_ALREADY_DECIDED` 分支未测、PowerShell native exit 2→1 映射。
|
|
56
|
+
|
|
3
57
|
## 4.1.8 — 2026-10-19(24h backlog 清扫:25 个切片,棱镜与证据链收紧,测试判定重新成为代码属性)
|
|
4
58
|
|
|
5
59
|
**版本级别**: 未发布区间 `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 调用前拒绝),升级路径均已覆盖。
|
|
@@ -75,6 +75,7 @@ import { registerSliceReviewCommands } from './slice-review-commands.js';
|
|
|
75
75
|
import { registerSmokeCommands } from './smoke-commands.js';
|
|
76
76
|
import { registerSopCommands } from './sop-commands.js';
|
|
77
77
|
import { registerStatusLineCommands } from './statusline-commands.js';
|
|
78
|
+
import { registerStratTactCommands } from './strat-tact-commands.js';
|
|
78
79
|
import { registerSpillDemoCommand } from './spill-demo-command.js';
|
|
79
80
|
import { registerSubAgentCommands } from './sub-agent-commands.js';
|
|
80
81
|
import { registerSubAgentShutdownCommands } from './sub-agent-shutdown-commands.js';
|
|
@@ -174,6 +175,7 @@ const REGISTRATIONS = [
|
|
|
174
175
|
['dashboard-commands', registerDashboardCommands],
|
|
175
176
|
['best-practice-scan-command', registerBestPracticeScanCommand],
|
|
176
177
|
['mut-commands', registerMutCommands],
|
|
178
|
+
['strat-tact-commands', registerStratTactCommands],
|
|
177
179
|
['fixture-commands', registerFixtureCommands],
|
|
178
180
|
['reviewer-commands', registerReviewerCommands],
|
|
179
181
|
['ide-commands', registerIdeCommands],
|
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
.
|
|
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(
|
|
54
|
-
printResult(io, fail('code.detect-job', 'INVALID_FLAG', `--suggested-job-id must match /^[a-z0-9][a-z0-9-]{2,40}$/ (got "${
|
|
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
|
|
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
|
-
|
|
84
|
-
|
|
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
|
-
|
|
87
|
-
|
|
88
|
-
|
|
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,16 @@
|
|
|
1
|
+
import type { ProgramIO } from '../cli-helpers.js';
|
|
2
|
+
import { type AstGateContext } from '../../services/rd/ast-gate.js';
|
|
3
|
+
import { type ImplOutput, type StrategyOutput } from '../../services/rd/types.js';
|
|
4
|
+
export declare class CommandRefusal extends Error {
|
|
5
|
+
readonly code: string;
|
|
6
|
+
readonly remedy: string;
|
|
7
|
+
constructor(code: string, remedy: string, message: string);
|
|
8
|
+
}
|
|
9
|
+
export declare function emitOk(io: ProgramIO, json: boolean, payload: Record<string, unknown>, human: string[]): void;
|
|
10
|
+
/** Run an action body, turning a named refusal into the CLI's error surface. */
|
|
11
|
+
export declare function guarded(io: ProgramIO, json: boolean, command: string, body: () => Promise<void>): Promise<void>;
|
|
12
|
+
/** Resolve `--out` and enforce the one-axis layout. */
|
|
13
|
+
export declare function requireSessionAxis(project: string, sessionId: string, out: string): string;
|
|
14
|
+
export declare function readStrategy(path: string): Promise<StrategyOutput>;
|
|
15
|
+
export declare function readImpl(path: string): Promise<ImplOutput>;
|
|
16
|
+
export declare function parseAstContext(raw: string | undefined): AstGateContext;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the STRAT → TACT producer commands (backlog §16 / §9.2).
|
|
3
|
+
*
|
|
4
|
+
* Split out of `strat-tact-commands.ts` for the repo's 300-line source cap.
|
|
5
|
+
* Pure orchestration helpers: refusal plumbing, the one-axis path guard, and
|
|
6
|
+
* the artifact readers that re-verify a signed JSON document before trusting
|
|
7
|
+
* it. The service layer stays the single implementation of both stages.
|
|
8
|
+
*/
|
|
9
|
+
import { readFile } from 'node:fs/promises';
|
|
10
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
11
|
+
import { fail } from 'peaks-loop-shared/result';
|
|
12
|
+
import { isUnsafePathInput } from '../../shared/path-safety.js';
|
|
13
|
+
import { AstGateContextSchema } from '../../services/rd/ast-gate.js';
|
|
14
|
+
import { canonicalSha256 } from '../../services/rd/canonical-hash.js';
|
|
15
|
+
import { ImplOutputSchema, StrategyOutputSchema } from '../../services/rd/types.js';
|
|
16
|
+
const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
17
|
+
const JSON_SUFFIX = '.json';
|
|
18
|
+
/** Short sig prefix shown in a mismatch message; the full digest stays in the artifact. */
|
|
19
|
+
const SIG_PREVIEW_LEN = 12;
|
|
20
|
+
export class CommandRefusal extends Error {
|
|
21
|
+
code;
|
|
22
|
+
remedy;
|
|
23
|
+
constructor(code, remedy, message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.remedy = remedy;
|
|
27
|
+
this.name = 'CommandRefusal';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function emitOk(io, json, payload, human) {
|
|
31
|
+
if (json) {
|
|
32
|
+
io.stdout(JSON.stringify({ ok: true, ...payload }));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
io.stdout(human.join('\n'));
|
|
36
|
+
}
|
|
37
|
+
function refuse(io, json, command, r) {
|
|
38
|
+
process.exitCode = 1;
|
|
39
|
+
if (json) {
|
|
40
|
+
io.stdout(JSON.stringify(fail(command, r.code, r.message, { remedy: r.remedy }, [r.remedy])));
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
io.stderr(`${r.code}: ${r.message} — ${r.remedy}\n`);
|
|
44
|
+
}
|
|
45
|
+
/** Run an action body, turning a named refusal into the CLI's error surface. */
|
|
46
|
+
export async function guarded(io, json, command, body) {
|
|
47
|
+
try {
|
|
48
|
+
await body();
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
if (err instanceof CommandRefusal) {
|
|
52
|
+
refuse(io, json, command, err);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Resolve `--out` and enforce the one-axis layout. */
|
|
59
|
+
export function requireSessionAxis(project, sessionId, out) {
|
|
60
|
+
// The canonical traversal guard PLUS the stricter single-segment regex: the
|
|
61
|
+
// former is what the runtime-id scanner recognises, the latter also rejects
|
|
62
|
+
// backslashes and a leading dot that the traversal guard alone would admit.
|
|
63
|
+
if (isUnsafePathInput(sessionId) || !SESSION_ID_RE.test(sessionId)) {
|
|
64
|
+
throw new CommandRefusal('INVALID_SESSION_ID', 'Use the session id that names .peaks/_runtime/<sid>/ (letters, digits, dot, dash, underscore).', `invalid --session-id: ${sessionId}`);
|
|
65
|
+
}
|
|
66
|
+
const sessionRoot = resolve(project, '.peaks', '_runtime', sessionId);
|
|
67
|
+
const absolute = isAbsolute(out) ? resolve(out) : resolve(project, out);
|
|
68
|
+
const rel = relative(sessionRoot, absolute);
|
|
69
|
+
if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
70
|
+
throw new CommandRefusal('ONE_AXIS_VIOLATION', `Pass --out .peaks/_runtime/${sessionId}/rd/<file>; artifacts are written only on the session axis.`, `--out must live under .peaks/_runtime/${sessionId}/ (got ${absolute})`);
|
|
71
|
+
}
|
|
72
|
+
return absolute;
|
|
73
|
+
}
|
|
74
|
+
async function readJsonFile(path, notFoundCode, invalidJsonCode, remedy) {
|
|
75
|
+
let raw;
|
|
76
|
+
try {
|
|
77
|
+
raw = await readFile(path, 'utf8');
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
throw new CommandRefusal(notFoundCode, remedy, `${path} could not be read: ${err instanceof Error ? err.message : String(err)}`);
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(raw);
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
throw new CommandRefusal(invalidJsonCode, remedy, `${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Recompute the digest over the RAW parsed JSON, before any schema strip.
|
|
91
|
+
* Order matters: an unknown field added to a signed artifact must change the
|
|
92
|
+
* digest (and therefore refuse), not be silently dropped by the schema.
|
|
93
|
+
*/
|
|
94
|
+
function assertArtifactDigest(raw, path, codes, remedy) {
|
|
95
|
+
if (raw === null || typeof raw !== 'object') {
|
|
96
|
+
throw new CommandRefusal(codes.invalid, remedy, `${path} is not a JSON object`);
|
|
97
|
+
}
|
|
98
|
+
const declared = raw.sha256;
|
|
99
|
+
const recomputed = canonicalSha256(raw);
|
|
100
|
+
if (declared !== recomputed) {
|
|
101
|
+
throw new CommandRefusal(codes.mismatch, remedy, `sha256 mismatch at ${path} (declared=${String(declared).slice(0, SIG_PREVIEW_LEN)}… ` +
|
|
102
|
+
`recomputed=${recomputed.slice(0, SIG_PREVIEW_LEN)}…)`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** The markdown sibling is the human-readable anchor; both must carry the same sig. */
|
|
106
|
+
async function requireStrategyMarkdown(jsonPath, sha256) {
|
|
107
|
+
const markdownPath = jsonPath.endsWith(JSON_SUFFIX)
|
|
108
|
+
? jsonPath.slice(0, -JSON_SUFFIX.length)
|
|
109
|
+
: jsonPath;
|
|
110
|
+
let markdown;
|
|
111
|
+
try {
|
|
112
|
+
markdown = await readFile(markdownPath, 'utf8');
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
throw new CommandRefusal('STRATEGY_MARKDOWN_NOT_FOUND', 'Re-run peaks strat write; it writes strategy.md next to the <out>.json sibling.', `strategy markdown not found at ${markdownPath} (${err instanceof Error ? err.message : String(err)})`);
|
|
116
|
+
}
|
|
117
|
+
const declared = /STRAT\.sig:\s*([a-f0-9]{64})/.exec(markdown)?.[1];
|
|
118
|
+
if (declared !== sha256) {
|
|
119
|
+
throw new CommandRefusal('STRATEGY_SIG_MISMATCH', `Re-run peaks strat write to regenerate both the markdown and its JSON sibling (${jsonPath}).`, `strategy markdown signature at ${markdownPath} is ${declared ?? '<missing>'} but the JSON ` +
|
|
120
|
+
`declares ${sha256.slice(0, SIG_PREVIEW_LEN)}…`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export async function readStrategy(path) {
|
|
124
|
+
const remedy = 'Re-run peaks strat write; --strategy expects the JSON sibling it wrote.';
|
|
125
|
+
const raw = await readJsonFile(path, 'STRATEGY_NOT_FOUND', 'INVALID_STRATEGY_JSON', remedy);
|
|
126
|
+
assertArtifactDigest(raw, path, { invalid: 'INVALID_STRATEGY', mismatch: 'STRAT_SIG_MISMATCH' }, remedy);
|
|
127
|
+
const parsed = StrategyOutputSchema.safeParse(raw);
|
|
128
|
+
if (!parsed.success) {
|
|
129
|
+
throw new CommandRefusal('INVALID_STRATEGY', remedy, `${path} does not match StrategyOutput: ${parsed.error.message}`);
|
|
130
|
+
}
|
|
131
|
+
await requireStrategyMarkdown(path, parsed.data.sha256);
|
|
132
|
+
return parsed.data;
|
|
133
|
+
}
|
|
134
|
+
export async function readImpl(path) {
|
|
135
|
+
const remedy = 'Re-run peaks tact write; --artifact expects the impl.json it wrote.';
|
|
136
|
+
const raw = await readJsonFile(path, 'IMPL_NOT_FOUND', 'INVALID_IMPL_JSON', remedy);
|
|
137
|
+
assertArtifactDigest(raw, path, { invalid: 'INVALID_IMPL', mismatch: 'IMPL_SIG_MISMATCH' }, remedy);
|
|
138
|
+
const parsed = ImplOutputSchema.safeParse(raw);
|
|
139
|
+
if (!parsed.success) {
|
|
140
|
+
throw new CommandRefusal('INVALID_IMPL', remedy, `${path} does not match ImplOutput: ${parsed.error.message}`);
|
|
141
|
+
}
|
|
142
|
+
return parsed.data;
|
|
143
|
+
}
|
|
144
|
+
export function parseAstContext(raw) {
|
|
145
|
+
if (raw === undefined) {
|
|
146
|
+
return { deps: {}, docSummaries: [] };
|
|
147
|
+
}
|
|
148
|
+
const remedy = 'Pass --ast-context as JSON matching { deps, docSummaries }, or omit it for the empty context.';
|
|
149
|
+
const parsed = AstGateContextSchema.safeParse(readJsonOrRefuse(raw, 'INVALID_AST_CONTEXT', remedy, '--ast-context'));
|
|
150
|
+
if (!parsed.success) {
|
|
151
|
+
throw new CommandRefusal('INVALID_AST_CONTEXT', remedy, `--ast-context does not match AstGateContext: ${parsed.error.message}`);
|
|
152
|
+
}
|
|
153
|
+
return parsed.data;
|
|
154
|
+
}
|
|
155
|
+
function readJsonOrRefuse(raw, code, remedy, path) {
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(raw);
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
throw new CommandRefusal(code, remedy, `${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
161
|
+
}
|
|
162
|
+
}
|