peaks-loop 4.1.8 → 4.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +54 -0
  3. package/dist/cli/commands/_register.js +2 -0
  4. package/dist/cli/commands/code-gate-step-08-command.js +21 -11
  5. package/dist/cli/commands/code-gate-step-08-remedy.d.ts +17 -0
  6. package/dist/cli/commands/code-gate-step-08-remedy.js +76 -0
  7. package/dist/cli/commands/code-job-shape-commands.js +21 -5
  8. package/dist/cli/commands/job-init-status-commands.js +45 -5
  9. package/dist/cli/commands/strat-tact-command-helpers.d.ts +16 -0
  10. package/dist/cli/commands/strat-tact-command-helpers.js +162 -0
  11. package/dist/cli/commands/strat-tact-commands.d.ts +3 -0
  12. package/dist/cli/commands/strat-tact-commands.js +176 -0
  13. package/dist/services/code/job-shape-provisional.d.ts +51 -0
  14. package/dist/services/code/job-shape-provisional.js +80 -0
  15. package/dist/services/code/step-08-gate.d.ts +24 -12
  16. package/dist/services/code/step-08-gate.js +54 -97
  17. package/dist/services/code/step-08-session-readers.d.ts +27 -0
  18. package/dist/services/code/step-08-session-readers.js +105 -0
  19. package/dist/services/rd/ast-gate.d.ts +19 -12
  20. package/dist/services/rd/ast-gate.js +10 -0
  21. package/dist/services/rd/canonical-hash.d.ts +1 -0
  22. package/dist/services/rd/canonical-hash.js +38 -0
  23. package/dist/services/rd/impl.js +2 -8
  24. package/dist/services/rd/strategy.js +2 -8
  25. package/dist/services/rd/types.d.ts +10 -10
  26. package/dist/services/rd/types.js +21 -10
  27. package/package.json +5 -5
  28. package/skills/bee/peaks-rd/SKILL.md +25 -3
  29. package/skills/peaks-code/references/step-0-8-gate.md +2 -1
@@ -0,0 +1,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
+ }
@@ -1,16 +1,23 @@
1
+ import { z } from 'zod';
1
2
  import type { AstGateResult } from './types.js';
2
- export interface AstGateContext {
3
- readonly deps: Readonly<Record<string, {
4
- readonly version: string;
5
- readonly source: string;
6
- readonly resolved: string;
7
- }>>;
8
- readonly docSummaries: ReadonlyArray<{
9
- readonly dep: string;
10
- readonly version: string;
11
- readonly apis: ReadonlyArray<string>;
12
- }>;
13
- }
3
+ /**
4
+ * The locked-version context the gate compares against. The schema is the
5
+ * single source for both the type and the CLI's `--ast-context` validation —
6
+ * a malformed context is refused rather than silently read as empty.
7
+ */
8
+ export declare const AstGateContextSchema: z.ZodObject<{
9
+ deps: z.ZodRecord<z.ZodString, z.ZodObject<{
10
+ version: z.ZodString;
11
+ source: z.ZodString;
12
+ resolved: z.ZodString;
13
+ }, z.core.$strip>>;
14
+ docSummaries: z.ZodArray<z.ZodObject<{
15
+ dep: z.ZodString;
16
+ version: z.ZodString;
17
+ apis: z.ZodArray<z.ZodString>;
18
+ }, z.core.$strip>>;
19
+ }, z.core.$strip>;
20
+ export type AstGateContext = z.infer<typeof AstGateContextSchema>;
14
21
  export interface RunAstGateInput {
15
22
  readonly project: string;
16
23
  readonly changedFiles: ReadonlyArray<string>;
@@ -12,6 +12,16 @@
12
12
  */
13
13
  import { readFile } from 'node:fs/promises';
14
14
  import { join } from 'node:path';
15
+ import { z } from 'zod';
16
+ /**
17
+ * The locked-version context the gate compares against. The schema is the
18
+ * single source for both the type and the CLI's `--ast-context` validation —
19
+ * a malformed context is refused rather than silently read as empty.
20
+ */
21
+ export const AstGateContextSchema = z.object({
22
+ deps: z.record(z.string(), z.object({ version: z.string(), source: z.string(), resolved: z.string() })),
23
+ docSummaries: z.array(z.object({ dep: z.string(), version: z.string(), apis: z.array(z.string()) }))
24
+ });
15
25
  const IMPORT_RE = /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g;
16
26
  const CALL_RE = /\b([a-zA-Z_$][\w$]*)\s*\(/g;
17
27
  export async function runAstGate(input) {
@@ -0,0 +1 @@
1
+ export declare function canonicalSha256(content: object): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Canonical H8 digest shared by STRAT, TACT and the CLI verifiers.
3
+ *
4
+ * WHY one export: `writeStrategy`, `writeImpl` and the `peaks tact read|write`
5
+ * verifiers must compute the IDENTICAL digest, or an artifact signed by one
6
+ * side is refused by the other. Keeping the omit-`sha256` + sorted-keys rule
7
+ * in one place is what stops that drift.
8
+ *
9
+ * WHY A RECURSIVE SORT AND NOT `JSON.stringify(rest, Object.keys(rest).sort())`:
10
+ * the array-replacer form filters keys at EVERY nesting level, so a nested
11
+ * object whose keys are not top-level names serializes as `{}` — the digest
12
+ * then ignores `astGateResult`, `changedFiles[]` entries and
13
+ * `askUserQuestion` entirely. Measured: forging `impl.json#astGateResult`
14
+ * without touching `sha256` still verified. The sort must be applied by hand,
15
+ * per level, so every nested value is part of the digest.
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ function stableValue(value) {
19
+ if (Array.isArray(value)) {
20
+ return value.map(stableValue);
21
+ }
22
+ if (value === null || typeof value !== 'object') {
23
+ return value;
24
+ }
25
+ const source = value;
26
+ const sorted = {};
27
+ for (const key of Object.keys(source).sort()) {
28
+ sorted[key] = stableValue(source[key]);
29
+ }
30
+ return sorted;
31
+ }
32
+ export function canonicalSha256(content) {
33
+ const { sha256: _omit, ...rest } = content;
34
+ void _omit;
35
+ return createHash('sha256')
36
+ .update(JSON.stringify(stableValue(rest)))
37
+ .digest('hex');
38
+ }
@@ -7,15 +7,9 @@
7
7
  * H6 (CLI裁决): refuses to write when AST gate has violations —
8
8
  * LLM MUST auto-fix and re-run.
9
9
  */
10
- import { createHash } from 'node:crypto';
11
10
  import { writeFile, rename, unlink } from 'node:fs/promises';
11
+ import { canonicalSha256 } from './canonical-hash.js';
12
12
  import { ImplOutputSchema } from './types.js';
13
- function sha256Of(content) {
14
- const { sha256: _omit, ...rest } = content;
15
- void _omit;
16
- const canonical = JSON.stringify(rest, Object.keys(rest).sort());
17
- return createHash('sha256').update(canonical).digest('hex');
18
- }
19
13
  export async function writeImpl(input) {
20
14
  // Defense-in-depth: passed flag and violations[] must agree.
21
15
  // A caller passing passed=true with non-empty violations (lying input)
@@ -40,7 +34,7 @@ export async function writeImpl(input) {
40
34
  externalApiCalls: [...input.externalApiCalls],
41
35
  astGateResult: input.astGate
42
36
  };
43
- const sha256 = sha256Of(partial);
37
+ const sha256 = canonicalSha256(partial);
44
38
  const final = { ...partial, sha256 };
45
39
  ImplOutputSchema.parse(final);
46
40
  const tmp = `${input.out}.tmp`;
@@ -5,15 +5,9 @@
5
5
  * H8 (audit trail hashable): sig field embedded in strategy.md is the
6
6
  * sha256 of all OTHER content (chicken-and-egg avoided).
7
7
  */
8
- import { createHash } from 'node:crypto';
9
8
  import { writeFile, rename, unlink } from 'node:fs/promises';
9
+ import { canonicalSha256 } from './canonical-hash.js';
10
10
  import { StrategyOutputSchema } from './types.js';
11
- function sha256Of(content) {
12
- const { sha256: _omit, ...rest } = content;
13
- void _omit;
14
- const canonical = JSON.stringify(rest, Object.keys(rest).sort());
15
- return createHash('sha256').update(canonical).digest('hex');
16
- }
17
11
  export async function writeStrategy(input) {
18
12
  const partial = {
19
13
  version: '1.0',
@@ -25,7 +19,7 @@ export async function writeStrategy(input) {
25
19
  designRationale: input.designRationale,
26
20
  ...(input.askUserQuestion ? { askUserQuestion: input.askUserQuestion } : {})
27
21
  };
28
- const sha256 = sha256Of(partial);
22
+ const sha256 = canonicalSha256(partial);
29
23
  const final = { ...partial, sha256 };
30
24
  StrategyOutputSchema.parse(final);
31
25
  const body = [
@@ -16,8 +16,8 @@ export declare const StrategyOutputSchema: z.ZodObject<{
16
16
  askUserQuestion: z.ZodOptional<z.ZodObject<{
17
17
  question: z.ZodString;
18
18
  options: z.ZodArray<z.ZodString>;
19
- }, z.core.$strip>>;
20
- }, z.core.$strip>;
19
+ }, z.core.$strict>>;
20
+ }, z.core.$strict>;
21
21
  export type StrategyOutput = z.infer<typeof StrategyOutputSchema>;
22
22
  export declare const AstViolationSchema: z.ZodObject<{
23
23
  file: z.ZodString;
@@ -29,7 +29,7 @@ export declare const AstViolationSchema: z.ZodObject<{
29
29
  error: "error";
30
30
  warning: "warning";
31
31
  }>;
32
- }, z.core.$strip>;
32
+ }, z.core.$strict>;
33
33
  export declare const AstGateResultSchema: z.ZodObject<{
34
34
  passed: z.ZodBoolean;
35
35
  violations: z.ZodArray<z.ZodObject<{
@@ -42,14 +42,14 @@ export declare const AstGateResultSchema: z.ZodObject<{
42
42
  error: "error";
43
43
  warning: "warning";
44
44
  }>;
45
- }, z.core.$strip>>;
46
- }, z.core.$strip>;
45
+ }, z.core.$strict>>;
46
+ }, z.core.$strict>;
47
47
  export declare const ExternalApiCallSchema: z.ZodObject<{
48
48
  file: z.ZodString;
49
49
  line: z.ZodNumber;
50
50
  api: z.ZodString;
51
51
  version: z.ZodString;
52
- }, z.core.$strip>;
52
+ }, z.core.$strict>;
53
53
  export declare const ImplOutputSchema: z.ZodObject<{
54
54
  version: z.ZodLiteral<"1.0">;
55
55
  sha256: z.ZodString;
@@ -61,7 +61,7 @@ export declare const ImplOutputSchema: z.ZodObject<{
61
61
  line: z.ZodNumber;
62
62
  api: z.ZodString;
63
63
  version: z.ZodString;
64
- }, z.core.$strip>>;
64
+ }, z.core.$strict>>;
65
65
  astGateResult: z.ZodObject<{
66
66
  passed: z.ZodBoolean;
67
67
  violations: z.ZodArray<z.ZodObject<{
@@ -74,9 +74,9 @@ export declare const ImplOutputSchema: z.ZodObject<{
74
74
  error: "error";
75
75
  warning: "warning";
76
76
  }>;
77
- }, z.core.$strip>>;
78
- }, z.core.$strip>;
79
- }, z.core.$strip>;
77
+ }, z.core.$strict>>;
78
+ }, z.core.$strict>;
79
+ }, z.core.$strict>;
80
80
  export type ImplOutput = z.infer<typeof ImplOutputSchema>;
81
81
  export type AstViolation = z.infer<typeof AstViolationSchema>;
82
82
  export type AstGateResult = z.infer<typeof AstGateResultSchema>;
@@ -5,7 +5,8 @@
5
5
  * TACT.sig inputSig chain must reference STRAT.sig.
6
6
  */
7
7
  import { z } from 'zod';
8
- export const StrategyOutputSchema = z.object({
8
+ export const StrategyOutputSchema = z
9
+ .object({
9
10
  version: z.literal('1.0'),
10
11
  sha256: z.string().regex(/^[a-f0-9]{64}$/),
11
12
  generatedAt: z.string().datetime(),
@@ -18,27 +19,36 @@ export const StrategyOutputSchema = z.object({
18
19
  question: z.string(),
19
20
  options: z.array(z.string())
20
21
  })
22
+ .strict()
21
23
  .optional()
22
- });
23
- export const AstViolationSchema = z.object({
24
+ })
25
+ .strict();
26
+ export const AstViolationSchema = z
27
+ .object({
24
28
  file: z.string(),
25
29
  line: z.number().int(),
26
30
  api: z.string(),
27
31
  expectedVersion: z.string(),
28
32
  actualVersion: z.string(),
29
33
  severity: z.enum(['error', 'warning'])
30
- });
31
- export const AstGateResultSchema = z.object({
34
+ })
35
+ .strict();
36
+ export const AstGateResultSchema = z
37
+ .object({
32
38
  passed: z.boolean(),
33
39
  violations: z.array(AstViolationSchema)
34
- });
35
- export const ExternalApiCallSchema = z.object({
40
+ })
41
+ .strict();
42
+ export const ExternalApiCallSchema = z
43
+ .object({
36
44
  file: z.string(),
37
45
  line: z.number().int(),
38
46
  api: z.string(),
39
47
  version: z.string()
40
- });
41
- export const ImplOutputSchema = z.object({
48
+ })
49
+ .strict();
50
+ export const ImplOutputSchema = z
51
+ .object({
42
52
  version: z.literal('1.0'),
43
53
  sha256: z.string().regex(/^[a-f0-9]{64}$/),
44
54
  generatedAt: z.string().datetime(),
@@ -46,4 +56,5 @@ export const ImplOutputSchema = z.object({
46
56
  changedFiles: z.array(z.string()),
47
57
  externalApiCalls: z.array(ExternalApiCallSchema),
48
58
  astGateResult: AstGateResultSchema
49
- });
59
+ })
60
+ .strict();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peaks-loop",
3
- "version": "4.1.8",
3
+ "version": "4.1.10",
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.50",
133
+ "peaks-loop-shared-channel": "0.0.67",
134
+ "peaks-loop-shared": "0.0.99",
135
+ "peaks-loop-mut": "0.1.64"
136
136
  },
137
137
  "devDependencies": {
138
138
  "@changesets/cli": "2.31.1",
@@ -297,12 +297,34 @@ peaks-rd runs in two sub-stages:
297
297
  Hard constraint: TACT.sig cannot be written when the AST gate has violations.
298
298
  The LLM auto-fixes and retries (peaks-qa's 3-cycle repair cap).
299
299
 
300
+ Registered CLI surface (one-axis: `--session-id` required, every `--out` under
301
+ `.peaks/_runtime/<sid>/`):
302
+
303
+ ```bash
304
+ peaks strat write --project <repo> --session-id <sid> \
305
+ --out .peaks/_runtime/<sid>/rd/strategy.md \
306
+ --goal <text> --root-cause <text> --impact <paths...> --design <text> --json
307
+ # writes strategy.md + its JSON sibling (.peaks/_runtime/<sid>/rd/strategy.md.json)
308
+
309
+ peaks tact write --project <repo> --session-id <sid> \
310
+ --strategy .peaks/_runtime/<sid>/rd/strategy.md.json \
311
+ --out .peaks/_runtime/<sid>/rd/impl.json \
312
+ --changed-files <paths...> [--ast-context '<json>'] --json
313
+
314
+ peaks tact read --artifact .peaks/_runtime/<sid>/rd/impl.json --project <repo> --json
315
+ ```
316
+
317
+ `tact write` never accepts a raw `--input-sig`: it re-verifies the strategy
318
+ JSON's recomputed sha256 and refuses a tampered artifact. `tact read` does the
319
+ same for `impl.json` and prints `{ sha256, inputSig, changedFiles, astGateResult }`.
320
+
300
321
  Karpathy guidelines remain injected in both sub-stages.
301
322
 
302
- Public entry points (from `src/services/rd/rd-service.ts`):
323
+ Public entry points (from `src/services/rd/rd-service.ts`) are unchanged; the
324
+ commands above are thin wrappers over them:
303
325
 
304
- - `runStrategic(input: RunStrategicInput): Promise<StrategyOutput>` — strategy writer
305
- - `runTactical(input: RunTacticalInput): Promise<ImplOutput>` — runs AST gate then writes impl.json + TACT.sig chained to inputSig
326
+ - `runStrategic(input: RunStrategicInput): Promise<StrategyOutput>` — strategy writer (`peaks strat write`)
327
+ - `runTactical(input: RunTacticalInput): Promise<ImplOutput>` — runs AST gate then writes impl.json + TACT.sig chained to inputSig (`peaks tact write`)
306
328
 
307
329
  ## References
308
330
 
@@ -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.