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,8 +1,8 @@
1
1
  import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
2
- import { existsSync } from 'node:fs';
3
2
  import { dirname, join } from 'node:path';
4
3
  import { isDirectory, listDirectories } from 'peaks-loop-shared/fs';
5
4
  import { checkPrerequisites, DEFAULT_REQUEST_TYPE, isRequestType, VALID_REQUEST_TYPES } from './artifact-prerequisites.js';
5
+ import { markQaInitiated } from './qa-initiated-marker.js';
6
6
  import { ensureSession, getSessionIdCanonical } from '../session/session-manager.js';
7
7
  // removed with the change-id axis. The change-id binding file is
8
8
  // gone; request-artifact callers pass `options.sessionId` explicitly
@@ -147,7 +147,7 @@ export async function createRequestArtifact(options) {
147
147
  const content = renderTemplate(options.role, options.requestId, sessionId, sessionSlug, timestamp,
148
148
  // `null`, not the default: an untyped request records no type, so the
149
149
  // reader's substitution stays visible as a substitution.
150
- options.requestType ?? null);
150
+ { requestType: options.requestType ?? null, projectRoot: options.projectRoot });
151
151
  if (options.apply !== true) {
152
152
  // session-axis dir (`.peaks/_runtime/<sid>/`). Pre-resolved here
153
153
  // so dry-run output reports the canonical scope location.
@@ -166,14 +166,10 @@ export async function createRequestArtifact(options) {
166
166
  await mkdir(dirname(path), { recursive: true });
167
167
  await writeFile(path, content, 'utf8');
168
168
  // Create QA initiated marker so rd:qa-handoff gate can verify QA was invoked.
169
- // The marker lives under the SESSION dir (canonical post-F3 home).
169
+ // The writer is shared with `peaks request mark-qa-initiated`, the in-order
170
+ // path for a QA role that wrote its artifact before this command ran.
170
171
  if (options.role === 'qa') {
171
- const qaDir = runtimeRoot(options.projectRoot).join(guardRuntimeSegment(sessionId, 'session id'), guardRuntimeSegment('qa', 'role'));
172
- const initiatedPath = join(qaDir, '.initiated');
173
- if (!existsSync(initiatedPath)) {
174
- await mkdir(qaDir, { recursive: true });
175
- await writeFile(initiatedPath, '', 'utf8');
176
- }
172
+ await markQaInitiated({ projectRoot: options.projectRoot, sessionId });
177
173
  }
178
174
  return {
179
175
  role: options.role,
@@ -403,7 +399,7 @@ export async function transitionRequestArtifact(options) {
403
399
  if (lintReport !== null && !lintReport.ok) {
404
400
  const errors = lintReport.findings.filter((f) => f.severity === 'error');
405
401
  if (errors.length > 0) {
406
- throw new LintGateError(options.role, options.newState, errors);
402
+ throw new LintGateError(options.role, options.newState, errors, lintReport.path);
407
403
  }
408
404
  }
409
405
  }
@@ -31,7 +31,8 @@ export declare class LintGateError extends Error {
31
31
  readonly newState: RequestArtifactState;
32
32
  readonly errorCount: number;
33
33
  readonly findings: ReadonlyArray<LintGateFinding>;
34
- constructor(role: RequestArtifactRole, newState: RequestArtifactState, findings: ReadonlyArray<LintGateFinding>);
34
+ readonly path: string;
35
+ constructor(role: RequestArtifactRole, newState: RequestArtifactState, findings: ReadonlyArray<LintGateFinding>, path: string);
35
36
  }
36
37
  export declare class TypeSanityViolationError extends Error {
37
38
  readonly code = "TYPE_SANITY_VIOLATION";
@@ -1,3 +1,4 @@
1
+ import { unmetPrerequisiteMessage } from './prerequisite-checks.js';
1
2
  export const ALLOWED_STATES_PER_ROLE = {
2
3
  prd: ['draft', 'confirmed-by-user', 'handed-off', 'blocked'],
3
4
  ui: ['draft', 'direction-locked', 'handed-off', 'blocked'],
@@ -22,7 +23,7 @@ export class PrerequisitesNotSatisfiedError extends Error {
22
23
  */
23
24
  warnings;
24
25
  constructor(role, newState, sessionId, missing, warnings = []) {
25
- super(`Cannot transition ${role} to ${newState}: ${missing.length} unmet requirement${missing.length === 1 ? '' : 's'} under .peaks/_runtime/${sessionId}/`);
26
+ super(unmetPrerequisiteMessage(role, newState, sessionId, missing));
26
27
  this.name = 'PrerequisitesNotSatisfiedError';
27
28
  this.role = role;
28
29
  this.newState = newState;
@@ -37,14 +38,16 @@ export class LintGateError extends Error {
37
38
  newState;
38
39
  errorCount;
39
40
  findings;
40
- constructor(role, newState, findings) {
41
- super(`Cannot transition ${role} to ${newState}: ${findings.length} lint error(s) found in artifact. ` +
41
+ path;
42
+ constructor(role, newState, findings, path) {
43
+ super(`Cannot transition ${role} to ${newState}: ${findings.length} lint error(s) found in ${path}. ` +
42
44
  'Fix lint errors or use --allow-incomplete to bypass.');
43
45
  this.name = 'LintGateError';
44
46
  this.role = role;
45
47
  this.newState = newState;
46
48
  this.findings = findings;
47
49
  this.errorCount = findings.length;
50
+ this.path = path;
48
51
  }
49
52
  }
50
53
  export class TypeSanityViolationError extends Error {
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Backlog §17.1 fix (3) — the provisional Job-shape decision `peaks job init`
3
+ * leaves behind.
4
+ *
5
+ * WHY. `peaks job init` writes `job/<jid>/state.json`, and the Step 0.8 gate
6
+ * reads that ledger with no `job-shape.json` as "`peaks code detect-job` was
7
+ * skipped" — every Bash call in the session is then refused, and the printed
8
+ * remedy is itself a Bash call. The gate cannot tell "the LLM forgot" from
9
+ * "the tooling created a ledger first", so `job init` records the one decision
10
+ * its own ledger implies: isJob=true for this job, at medium confidence,
11
+ * labelled provisional so a reader knows nobody judged the prompt.
12
+ *
13
+ * ORDER: ledger first, decision second (the PRD's chosen order). A decision
14
+ * with no ledger would point at a job that does not exist; a ledger with no
15
+ * decision is exactly the state a later `detect-job` corrects.
16
+ *
17
+ * NEVER OVERWRITES. An existing `job-shape.json` — `isJob: true` or `false`,
18
+ * written by the LLM or by an earlier `job init`, parseable or not — is left
19
+ * byte-identical. Any other failure (an id the decision schema refuses, a
20
+ * read-only runtime dir) is RETURNED rather than thrown: the ledger is already
21
+ * on disk, so the caller must report both facts accurately.
22
+ */
23
+ import { type JobStrategy } from './job-shape-decision.js';
24
+ export interface ProvisionalDecisionInput {
25
+ readonly jobId: string;
26
+ readonly strategy: JobStrategy;
27
+ }
28
+ export type ProvisionalDecisionOutcome = {
29
+ readonly written: true;
30
+ readonly path: string;
31
+ } | {
32
+ readonly written: false;
33
+ readonly path: string;
34
+ readonly reason: 'already-decided';
35
+ } | {
36
+ readonly written: false;
37
+ readonly path: string;
38
+ readonly reason: 'invalid-existing' | 'write-failed';
39
+ readonly error: string;
40
+ };
41
+ /**
42
+ * Ensure `.peaks/_runtime/<sessionId>/job-shape.json` exists, writing a
43
+ * provisional decision only when the path is empty.
44
+ *
45
+ * An existing file is classified by reading it, never by overwriting it: a
46
+ * readable decision is `already-decided`, and an unreadable one is
47
+ * `invalid-existing` so the caller can surface the corruption and the
48
+ * `--force` remedy. The writer's own `JOB_SHAPE_ALREADY_DECIDED` on a race is
49
+ * folded into `already-decided` — the winner's decision stands.
50
+ */
51
+ export declare function ensureProvisionalJobShapeDecision(projectRoot: string, sessionId: string, input: ProvisionalDecisionInput): ProvisionalDecisionOutcome;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Backlog §17.1 fix (3) — the provisional Job-shape decision `peaks job init`
3
+ * leaves behind.
4
+ *
5
+ * WHY. `peaks job init` writes `job/<jid>/state.json`, and the Step 0.8 gate
6
+ * reads that ledger with no `job-shape.json` as "`peaks code detect-job` was
7
+ * skipped" — every Bash call in the session is then refused, and the printed
8
+ * remedy is itself a Bash call. The gate cannot tell "the LLM forgot" from
9
+ * "the tooling created a ledger first", so `job init` records the one decision
10
+ * its own ledger implies: isJob=true for this job, at medium confidence,
11
+ * labelled provisional so a reader knows nobody judged the prompt.
12
+ *
13
+ * ORDER: ledger first, decision second (the PRD's chosen order). A decision
14
+ * with no ledger would point at a job that does not exist; a ledger with no
15
+ * decision is exactly the state a later `detect-job` corrects.
16
+ *
17
+ * NEVER OVERWRITES. An existing `job-shape.json` — `isJob: true` or `false`,
18
+ * written by the LLM or by an earlier `job init`, parseable or not — is left
19
+ * byte-identical. Any other failure (an id the decision schema refuses, a
20
+ * read-only runtime dir) is RETURNED rather than thrown: the ledger is already
21
+ * on disk, so the caller must report both facts accurately.
22
+ */
23
+ import { existsSync } from 'node:fs';
24
+ import { join } from 'node:path';
25
+ import { JobShapeDecisionError, JOB_SHAPE_ALREADY_DECIDED, JOB_SHAPE_FILE_NAME, readJobShapeDecision, writeJobShapeDecision } from './job-shape-decision.js';
26
+ function provisionalRationale(jobId) {
27
+ return (`Provisional decision written by \`peaks job init\` when it created the Job ledger for ` +
28
+ `"${jobId}": a ledger existed before any Job-shape decision was recorded. The job is ` +
29
+ `treated as Job-shaped so the Step 0.8 gate can allow. Re-record it with ` +
30
+ `\`peaks code detect-job --is-job true --suggested-job-id ${jobId} --force\` once the shape is known.`);
31
+ }
32
+ /**
33
+ * Ensure `.peaks/_runtime/<sessionId>/job-shape.json` exists, writing a
34
+ * provisional decision only when the path is empty.
35
+ *
36
+ * An existing file is classified by reading it, never by overwriting it: a
37
+ * readable decision is `already-decided`, and an unreadable one is
38
+ * `invalid-existing` so the caller can surface the corruption and the
39
+ * `--force` remedy. The writer's own `JOB_SHAPE_ALREADY_DECIDED` on a race is
40
+ * folded into `already-decided` — the winner's decision stands.
41
+ */
42
+ export function ensureProvisionalJobShapeDecision(projectRoot, sessionId, input) {
43
+ const path = join(projectRoot, '.peaks', '_runtime', sessionId, JOB_SHAPE_FILE_NAME);
44
+ if (existsSync(path)) {
45
+ try {
46
+ readJobShapeDecision(projectRoot, sessionId);
47
+ return { written: false, path, reason: 'already-decided' };
48
+ }
49
+ catch (err) {
50
+ if (err instanceof JobShapeDecisionError) {
51
+ return { written: false, path, reason: 'invalid-existing', error: err.message };
52
+ }
53
+ throw err;
54
+ }
55
+ }
56
+ try {
57
+ writeJobShapeDecision(projectRoot, sessionId, {
58
+ isJob: true,
59
+ rationale: provisionalRationale(input.jobId),
60
+ suggestedJobId: input.jobId,
61
+ suggestedStrategy: input.strategy,
62
+ confidence: 'medium',
63
+ prompt: `provisional:peaks job init:${input.jobId}`
64
+ });
65
+ return { written: true, path };
66
+ }
67
+ catch (err) {
68
+ // A concurrent writer won the race after the check above; its decision is
69
+ // the one that stands, so this is the same outcome as "already decided".
70
+ if (err instanceof JobShapeDecisionError && err.code === JOB_SHAPE_ALREADY_DECIDED) {
71
+ return { written: false, path, reason: 'already-decided' };
72
+ }
73
+ return {
74
+ written: false,
75
+ path,
76
+ reason: 'write-failed',
77
+ error: err instanceof Error ? err.message : String(err)
78
+ };
79
+ }
80
+ }
@@ -32,14 +32,22 @@
32
32
  * The gate never blocks on the ABSENCE of a decision alone: it runs on
33
33
  * every Bash call in every session, so a normal non-Job session must
34
34
  * keep passing through case (c).
35
+ * Before any of a–c, one exemption: when the hook payload's command is a
36
+ * real `peaks code detect-job` invocation, the gate allows with
37
+ * `allow-remedy-command`. The printed remedy is itself a Bash call, so a
38
+ * gate that blocks it deadlocks the session that needs it. The parse is
39
+ * narrow — a leading env assignment is allowed, the executable tokens
40
+ * must be `peaks`, `code`, `detect-job` in order, and a compound line is
41
+ * not the remedy. A command that only MENTIONS the verb in a quoted
42
+ * string, a comment, or a here-document is not an invocation.
35
43
  *
36
44
  * Karpathy §2 (Simplicity First): no LLM call inside. The regex is the FIRST
37
45
  * time peaks-loop accepts hardcoded keywords — explicitly scoped as a
38
46
  * *fail-closed backup* (case 3), NOT a primary judgement. The LLM still owns
39
47
  * the semantic call via `peaks code detect-job`.
40
48
  */
49
+ import { type Step08Progress } from './step-08-session-readers.js';
41
50
  export declare const STEP_08_GATE_FILE_NAME: "job-shape.json";
42
- export declare const STEP_08_PROGRESS_FILE_NAME: "progress.json";
43
51
  /**
44
52
  * Fail-closed backup regex — see module docstring case 3 for why this
45
53
  * exists. Kept short and explicit; if the prompt mentions any of these
@@ -53,14 +61,6 @@ export declare const STEP_08_PROGRESS_FILE_NAME: "progress.json";
53
61
  * until all done → until all done
54
62
  */
55
63
  export declare const STEP_08_BACKUP_REGEX: RegExp;
56
- export interface Step08Progress {
57
- readonly jobId: string;
58
- readonly done: number;
59
- readonly total: number;
60
- readonly currentSlice: string;
61
- readonly lastCommitSha: string | null;
62
- readonly updatedAt: string;
63
- }
64
64
  export type Step08PromptSource = 'flag' | 'last-prompt-file' | 'stdin-empty';
65
65
  export type Step08Verdict = {
66
66
  readonly kind: 'allow-job';
@@ -68,6 +68,14 @@ export type Step08Verdict = {
68
68
  readonly progress: Step08Progress | null;
69
69
  } | {
70
70
  readonly kind: 'allow-single';
71
+ } | {
72
+ /**
73
+ * The Bash command being gated IS the remedy this gate prints. Named
74
+ * separately so the transcript cannot confuse it with a command in a
75
+ * session that had already recorded a decision.
76
+ */
77
+ readonly kind: 'allow-remedy-command';
78
+ readonly reason: string;
71
79
  } | {
72
80
  readonly kind: 'block-missing-decision';
73
81
  readonly promptSource: Step08PromptSource;
@@ -80,16 +88,20 @@ export type Step08Verdict = {
80
88
  readonly ledgerJobIds: readonly string[];
81
89
  readonly reason: string;
82
90
  };
83
- export declare function runtimeSessionDir(projectRoot: string, sessionId: string): string;
84
91
  export interface EvaluateStep08Input {
85
92
  readonly projectRoot: string;
86
93
  readonly sessionId: string;
87
94
  /**
88
95
  * Explicit prompt text. When omitted, falls back to
89
- * `.peaks/_runtime/<sid>/txt/last-prompt.txt`, then to stdin (the
90
- * caller passes stdin verbatim — usually empty in tests).
96
+ * `.peaks/_runtime/<sid>/txt/last-prompt.txt`. Stdin carries the PreToolUse
97
+ * payload, not the prompt, and is read only when this is omitted.
91
98
  */
92
99
  readonly prompt?: string;
100
+ /**
101
+ * The Bash command the PreToolUse payload carried, when one was supplied.
102
+ * Used only for the remedy exemption — it never feeds the prompt regex.
103
+ */
104
+ readonly command?: string;
93
105
  }
94
106
  export interface EvaluateStep08Result {
95
107
  readonly allow: boolean;
@@ -32,19 +32,24 @@
32
32
  * The gate never blocks on the ABSENCE of a decision alone: it runs on
33
33
  * every Bash call in every session, so a normal non-Job session must
34
34
  * keep passing through case (c).
35
+ * Before any of a–c, one exemption: when the hook payload's command is a
36
+ * real `peaks code detect-job` invocation, the gate allows with
37
+ * `allow-remedy-command`. The printed remedy is itself a Bash call, so a
38
+ * gate that blocks it deadlocks the session that needs it. The parse is
39
+ * narrow — a leading env assignment is allowed, the executable tokens
40
+ * must be `peaks`, `code`, `detect-job` in order, and a compound line is
41
+ * not the remedy. A command that only MENTIONS the verb in a quoted
42
+ * string, a comment, or a here-document is not an invocation.
35
43
  *
36
44
  * Karpathy §2 (Simplicity First): no LLM call inside. The regex is the FIRST
37
45
  * time peaks-loop accepts hardcoded keywords — explicitly scoped as a
38
46
  * *fail-closed backup* (case 3), NOT a primary judgement. The LLM still owns
39
47
  * the semantic call via `peaks code detect-job`.
40
48
  */
41
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
42
- import { join } from 'node:path';
43
49
  import { readJobShapeDecision, JobShapeDecisionError, JOB_SHAPE_NOT_DECIDED } from './job-shape-decision.js';
44
50
  import { describeNextSlice } from '../job/job-progress-store.js';
45
- import { isExpectedFsMiss } from '../../shared/fs-utils.js';
51
+ import { ledgerJobIds, readProgressIfAny, readPromptFromLastPromptFile } from './step-08-session-readers.js';
46
52
  export const STEP_08_GATE_FILE_NAME = 'job-shape.json';
47
- export const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
48
53
  /**
49
54
  * Fail-closed backup regex — see module docstring case 3 for why this
50
55
  * exists. Kept short and explicit; if the prompt mentions any of these
@@ -58,98 +63,6 @@ export const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
58
63
  * until all done → until all done
59
64
  */
60
65
  export const STEP_08_BACKUP_REGEX = /直到|全部|until all done|disavow cost|不用考虑费用|all of them/i;
61
- export function runtimeSessionDir(projectRoot, sessionId) {
62
- return join(projectRoot, '.peaks', '_runtime', sessionId);
63
- }
64
- function progressPath(projectRoot, sessionId, jid) {
65
- // The progress file lives under job/<jid>/progress.json. The jid
66
- // comes from job-shape.json (decision.suggestedJobId) — there is
67
- // exactly one canonical jid per session under Job mode, so we read
68
- // the matching path directly rather than enumerating the job/ dir.
69
- // (Rotating mode spawns new jids but only one is "active" at a time;
70
- // the active jid is the latest write to job-shape.json.)
71
- return join(runtimeSessionDir(projectRoot, sessionId), 'job', jid, STEP_08_PROGRESS_FILE_NAME);
72
- }
73
- function readProgressIfAny(projectRoot, sessionId, jid) {
74
- const path = progressPath(projectRoot, sessionId, jid);
75
- if (!existsSync(path))
76
- return null;
77
- try {
78
- const raw = readFileSync(path, 'utf8');
79
- const parsed = JSON.parse(raw);
80
- if (typeof parsed.jobId === 'string' &&
81
- typeof parsed.done === 'number' &&
82
- typeof parsed.total === 'number' &&
83
- typeof parsed.currentSlice === 'string' &&
84
- typeof parsed.updatedAt === 'string') {
85
- return {
86
- jobId: parsed.jobId,
87
- done: parsed.done,
88
- total: parsed.total,
89
- currentSlice: parsed.currentSlice,
90
- lastCommitSha: typeof parsed.lastCommitSha === 'string' ? parsed.lastCommitSha : null,
91
- updatedAt: parsed.updatedAt
92
- };
93
- }
94
- return null;
95
- }
96
- catch (err) {
97
- // P1 site (S6, 2026-09-15) — same correction as `readPromptFromLastPromptFile`
98
- // below: corrupt progress.json stays loud, and a failure that is not an
99
- // fs miss (module-load ReferenceError, TypeError from a bad field, …)
100
- // propagates instead of reading as "no progress yet".
101
- if (err instanceof SyntaxError)
102
- throw err;
103
- if (!isExpectedFsMiss(err))
104
- throw err;
105
- return null;
106
- }
107
- }
108
- function readPromptFromLastPromptFile(projectRoot, sessionId) {
109
- const path = join(runtimeSessionDir(projectRoot, sessionId), 'txt', 'last-prompt.txt');
110
- if (!existsSync(path))
111
- return '';
112
- try {
113
- return readFileSync(path, 'utf8');
114
- }
115
- catch (err) {
116
- // P1 site (S6, 2026-09-15). This catch was bare — it bound nothing and
117
- // swallowed every error class. The sibling reads in this file had been
118
- // narrowed; this one had not, so the ONE path that feeds the step-08
119
- // backup regex was also the one that could not tell "no prompt file" from
120
- // "the module is broken". On the platform this gate exists for, that is
121
- // the difference between blocking a disavowal prompt and silently
122
- // allowing it. Missing/unreadable text is an empty prompt; anything else
123
- // propagates.
124
- if (!isExpectedFsMiss(err))
125
- throw err;
126
- return '';
127
- }
128
- }
129
- /**
130
- * Job ids this session owns a ledger for, sorted.
131
- *
132
- * A ledger is `job/<jid>/state.json`, which only `peaks job init` writes, and
133
- * `job-shape.json` is written by `peaks code detect-job` and by nothing else —
134
- * so a ledger with no decision is the decision step having been skipped.
135
- */
136
- function ledgerJobIds(projectRoot, sessionId) {
137
- const jobDir = join(runtimeSessionDir(projectRoot, sessionId), 'job');
138
- if (!existsSync(jobDir))
139
- return [];
140
- let names;
141
- try {
142
- names = readdirSync(jobDir);
143
- }
144
- catch (err) {
145
- if (!isExpectedFsMiss(err))
146
- throw err;
147
- return [];
148
- }
149
- return names
150
- .filter((name) => existsSync(join(jobDir, name, 'state.json')))
151
- .sort((left, right) => left.localeCompare(right));
152
- }
153
66
  /**
154
67
  * The reason a Job ledger with no decision is refused — it names both commands,
155
68
  * so the reader sees WHICH step was skipped.
@@ -159,7 +72,44 @@ function noDecisionWithLedgerReason(ledger) {
159
72
  return (`No Job-shape decision was recorded for this session, but it owns a Job ledger (${paths}). ` +
160
73
  'That means `peaks job init` ran and `peaks code detect-job` did not, so every ' +
161
74
  'Job-mode step this gate keys on was skipped. Record the verdict with ' +
162
- '`peaks code detect-job --is-job true|false ...`, then retry.');
75
+ '`peaks code detect-job --is-job false --rationale <text>` (its id defaults to ' +
76
+ '`single-task`), or `peaks code detect-job --is-job true --rationale <text> ' +
77
+ '--suggested-job-id <slug>`, then retry.');
78
+ }
79
+ const DETECT_JOB_TOKENS = ['peaks', 'code', 'detect-job'];
80
+ const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/;
81
+ const REMEDY_COMMAND_REASON = 'The Bash command being run IS the `peaks code detect-job` remedy this gate asks ' +
82
+ 'for when a Job ledger exists without a recorded decision. Allowing it breaks the ' +
83
+ 'deadlock: the remedy is a Bash call and this hook sees every one.';
84
+ /** Quotes group; a separator (`;`, `&`, `|`, `<`, `>`, newline) stands alone. */
85
+ const SHELL_TOKEN_RE = /'[^']*'|"[^"]*"|[^\s;|&<>\n]+|[;|&<>\n]/g;
86
+ /**
87
+ * Whether the command the hook is gating is the remedy this gate prints.
88
+ * Narrow on purpose — no shell parsing: the executable tokens must be
89
+ * `peaks code detect-job`, optionally behind a simple `NAME=value` env
90
+ * assignment. A quoted mention is not an invocation, and neither is a
91
+ * compound line, a comment, a here-document body, or anything carrying a
92
+ * backtick or `$(` — command substitution could run a different command
93
+ * inside what looks like the remedy, so it keeps the gate closed.
94
+ *
95
+ * LIMIT: an env assignment whose value is itself quoted
96
+ * (`A="a b" peaks code detect-job`) is not recognised; the flat tokeniser
97
+ * splits it and the exemption fails closed. A bare `A=b` prefix works.
98
+ */
99
+ function isDetectJobInvocation(command) {
100
+ if (command.includes('`') || command.includes('$('))
101
+ return false;
102
+ const tokens = [];
103
+ for (const match of command.trim().matchAll(SHELL_TOKEN_RE)) {
104
+ const token = match[0];
105
+ if (token === '\n' || (token.length === 1 && ';|&<>'.includes(token)))
106
+ return false;
107
+ tokens.push(token.replace(/^(['"])(.*)\1$/, '$2'));
108
+ }
109
+ let index = 0;
110
+ while (index < tokens.length && ENV_ASSIGNMENT_RE.test(tokens[index] ?? ''))
111
+ index += 1;
112
+ return DETECT_JOB_TOKENS.every((token, offset) => tokens[index + offset] === token);
163
113
  }
164
114
  /** Pure evaluator — does NOT write, does NOT exit. The CLI wrapper reads `allow`. */
165
115
  export function evaluateStep08(input) {
@@ -185,6 +135,13 @@ export function evaluateStep08(input) {
185
135
  }
186
136
  /** `job-shape.json` is missing — see the module header for the three answers. */
187
137
  function decideWithoutJobShapeDecision(input) {
138
+ if (input.command !== undefined && isDetectJobInvocation(input.command)) {
139
+ return {
140
+ allow: true,
141
+ verdict: { kind: 'allow-remedy-command', reason: REMEDY_COMMAND_REASON },
142
+ nextSliceLine: null
143
+ };
144
+ }
188
145
  const promptText = input.prompt ?? readPromptFromLastPromptFile(input.projectRoot, input.sessionId);
189
146
  const promptSource = input.prompt !== undefined
190
147
  ? 'flag'
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Step 0.8 gate — the session's on-disk inputs.
3
+ *
4
+ * Extracted from `step-08-gate.ts` when the remedy exemption pushed that file
5
+ * past the 300-line cap. Each reader answers ONE question about the session
6
+ * directory; the gate keeps the decision.
7
+ */
8
+ export interface Step08Progress {
9
+ readonly jobId: string;
10
+ readonly done: number;
11
+ readonly total: number;
12
+ readonly currentSlice: string;
13
+ readonly lastCommitSha: string | null;
14
+ readonly updatedAt: string;
15
+ }
16
+ export declare function readProgressIfAny(projectRoot: string, sessionId: string, jid: string): Step08Progress | null;
17
+ export declare function readPromptFromLastPromptFile(projectRoot: string, sessionId: string): string;
18
+ /**
19
+ * Job ids this session owns a ledger for, sorted.
20
+ *
21
+ * A ledger is `job/<jid>/state.json`, which only `peaks job init` writes.
22
+ * `peaks code detect-job` writes the deliberate `job-shape.json`; since backlog
23
+ * §17.1 fix (3) `peaks job init` also writes a PROVISIONAL one right after the
24
+ * ledger. A ledger with no decision is therefore a ledger from before that fix
25
+ * or a provisional write that failed — not proof the decision step was skipped.
26
+ */
27
+ export declare function ledgerJobIds(projectRoot: string, sessionId: string): string[];
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Step 0.8 gate — the session's on-disk inputs.
3
+ *
4
+ * Extracted from `step-08-gate.ts` when the remedy exemption pushed that file
5
+ * past the 300-line cap. Each reader answers ONE question about the session
6
+ * directory; the gate keeps the decision.
7
+ */
8
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { isExpectedFsMiss } from '../../shared/fs-utils.js';
11
+ const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
12
+ function runtimeSessionDir(projectRoot, sessionId) {
13
+ return join(projectRoot, '.peaks', '_runtime', sessionId);
14
+ }
15
+ function progressPath(projectRoot, sessionId, jid) {
16
+ // The progress file lives under job/<jid>/progress.json. The jid
17
+ // comes from job-shape.json (decision.suggestedJobId) — there is
18
+ // exactly one canonical jid per session under Job mode, so we read
19
+ // the matching path directly rather than enumerating the job/ dir.
20
+ // (Rotating mode spawns new jids but only one is "active" at a time;
21
+ // the active jid is the latest write to job-shape.json.)
22
+ return join(runtimeSessionDir(projectRoot, sessionId), 'job', jid, STEP_08_PROGRESS_FILE_NAME);
23
+ }
24
+ export function readProgressIfAny(projectRoot, sessionId, jid) {
25
+ const path = progressPath(projectRoot, sessionId, jid);
26
+ if (!existsSync(path))
27
+ return null;
28
+ try {
29
+ const raw = readFileSync(path, 'utf8');
30
+ const parsed = JSON.parse(raw);
31
+ if (typeof parsed.jobId === 'string' &&
32
+ typeof parsed.done === 'number' &&
33
+ typeof parsed.total === 'number' &&
34
+ typeof parsed.currentSlice === 'string' &&
35
+ typeof parsed.updatedAt === 'string') {
36
+ return {
37
+ jobId: parsed.jobId,
38
+ done: parsed.done,
39
+ total: parsed.total,
40
+ currentSlice: parsed.currentSlice,
41
+ lastCommitSha: typeof parsed.lastCommitSha === 'string' ? parsed.lastCommitSha : null,
42
+ updatedAt: parsed.updatedAt
43
+ };
44
+ }
45
+ return null;
46
+ }
47
+ catch (err) {
48
+ // P1 site (S6, 2026-09-15) — same correction as `readPromptFromLastPromptFile`
49
+ // below: corrupt progress.json stays loud, and a failure that is not an
50
+ // fs miss (module-load ReferenceError, TypeError from a bad field, …)
51
+ // propagates instead of reading as "no progress yet".
52
+ if (err instanceof SyntaxError)
53
+ throw err;
54
+ if (!isExpectedFsMiss(err))
55
+ throw err;
56
+ return null;
57
+ }
58
+ }
59
+ export function readPromptFromLastPromptFile(projectRoot, sessionId) {
60
+ const path = join(runtimeSessionDir(projectRoot, sessionId), 'txt', 'last-prompt.txt');
61
+ if (!existsSync(path))
62
+ return '';
63
+ try {
64
+ return readFileSync(path, 'utf8');
65
+ }
66
+ catch (err) {
67
+ // P1 site (S6, 2026-09-15). This catch was bare — it bound nothing and
68
+ // swallowed every error class. The sibling reads in this file had been
69
+ // narrowed; this one had not, so the ONE path that feeds the step-08
70
+ // backup regex was also the one that could not tell "no prompt file" from
71
+ // "the module is broken". On the platform this gate exists for, that is
72
+ // the difference between blocking a disavowal prompt and silently
73
+ // allowing it. Missing/unreadable text is an empty prompt; anything else
74
+ // propagates.
75
+ if (!isExpectedFsMiss(err))
76
+ throw err;
77
+ return '';
78
+ }
79
+ }
80
+ /**
81
+ * Job ids this session owns a ledger for, sorted.
82
+ *
83
+ * A ledger is `job/<jid>/state.json`, which only `peaks job init` writes.
84
+ * `peaks code detect-job` writes the deliberate `job-shape.json`; since backlog
85
+ * §17.1 fix (3) `peaks job init` also writes a PROVISIONAL one right after the
86
+ * ledger. A ledger with no decision is therefore a ledger from before that fix
87
+ * or a provisional write that failed — not proof the decision step was skipped.
88
+ */
89
+ export function ledgerJobIds(projectRoot, sessionId) {
90
+ const jobDir = join(runtimeSessionDir(projectRoot, sessionId), 'job');
91
+ if (!existsSync(jobDir))
92
+ return [];
93
+ let names;
94
+ try {
95
+ names = readdirSync(jobDir);
96
+ }
97
+ catch (err) {
98
+ if (!isExpectedFsMiss(err))
99
+ throw err;
100
+ return [];
101
+ }
102
+ return names
103
+ .filter((name) => existsSync(join(jobDir, name, 'state.json')))
104
+ .sort((left, right) => left.localeCompare(right));
105
+ }
@@ -1,3 +1,4 @@
1
+ import { spawn as childProcessSpawn } from 'node:child_process';
1
2
  /**
2
3
  * lease by shelling out to `peaks worktree spawn` (avoid re-implementing
3
4
  * the lease-write + git-worktree-add sequence in this file). The CLI
@@ -15,7 +16,7 @@ export declare function spawnWorktreeLease(args: {
15
16
  rid: string;
16
17
  role: string;
17
18
  purpose: string;
18
- }): Promise<{
19
+ }, spawnImplOverride?: typeof childProcessSpawn): Promise<{
19
20
  leaseId: string;
20
21
  path: string;
21
22
  branch: string;
@@ -36,6 +37,6 @@ export declare function spawnContainerLease(args: {
36
37
  rid: string;
37
38
  role: string;
38
39
  purpose: string;
39
- }): Promise<{
40
+ }, spawnImplOverride?: typeof childProcessSpawn): Promise<{
40
41
  leaseId: string;
41
42
  }>;