peaks-loop 4.1.12 → 4.1.14

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 (76) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +118 -0
  3. package/dist/cli/commands/_register.js +2 -0
  4. package/dist/cli/commands/batch-commands.d.ts +6 -0
  5. package/dist/cli/commands/batch-commands.js +70 -0
  6. package/dist/cli/commands/batch-diagnose-command.d.ts +10 -0
  7. package/dist/cli/commands/batch-diagnose-command.js +196 -0
  8. package/dist/cli/commands/batch-diagnose-envelope.d.ts +25 -0
  9. package/dist/cli/commands/batch-diagnose-envelope.js +60 -0
  10. package/dist/cli/commands/batch-diagnose-record.d.ts +21 -0
  11. package/dist/cli/commands/batch-diagnose-record.js +51 -0
  12. package/dist/cli/commands/batch-item-input.d.ts +59 -0
  13. package/dist/cli/commands/batch-item-input.js +113 -0
  14. package/dist/cli/commands/batch-report-command.d.ts +22 -0
  15. package/dist/cli/commands/batch-report-command.js +199 -0
  16. package/dist/cli/commands/code-gate-command.d.ts +18 -0
  17. package/dist/cli/commands/code-gate-command.js +95 -32
  18. package/dist/cli/commands/core/skill-context-verdict.d.ts +16 -1
  19. package/dist/cli/commands/core/skill-context-verdict.js +38 -8
  20. package/dist/cli/commands/lint-commands.js +8 -0
  21. package/dist/cli/commands/lint-rules-command.d.ts +14 -0
  22. package/dist/cli/commands/lint-rules-command.js +44 -0
  23. package/dist/services/batch/batch-active-batch.d.ts +55 -0
  24. package/dist/services/batch/batch-active-batch.js +127 -0
  25. package/dist/services/batch/batch-context-reminder.d.ts +85 -0
  26. package/dist/services/batch/batch-context-reminder.js +201 -0
  27. package/dist/services/batch/batch-diagnosis-finding.d.ts +25 -0
  28. package/dist/services/batch/batch-diagnosis-finding.js +227 -0
  29. package/dist/services/batch/batch-diagnosis-report-store.d.ts +49 -0
  30. package/dist/services/batch/batch-diagnosis-report-store.js +133 -0
  31. package/dist/services/batch/batch-diagnosis-summary.d.ts +31 -0
  32. package/dist/services/batch/batch-diagnosis-summary.js +129 -0
  33. package/dist/services/batch/batch-diagnosis.d.ts +36 -0
  34. package/dist/services/batch/batch-diagnosis.js +107 -0
  35. package/dist/services/batch/batch-entry.d.ts +22 -0
  36. package/dist/services/batch/batch-entry.js +42 -0
  37. package/dist/services/batch/batch-fix-agent.d.ts +39 -0
  38. package/dist/services/batch/batch-fix-agent.js +126 -0
  39. package/dist/services/batch/batch-fix-types.d.ts +85 -0
  40. package/dist/services/batch/batch-fix-types.js +11 -0
  41. package/dist/services/batch/batch-fix.d.ts +15 -0
  42. package/dist/services/batch/batch-fix.js +229 -0
  43. package/dist/services/batch/batch-phase-advance.d.ts +45 -0
  44. package/dist/services/batch/batch-phase-advance.js +105 -0
  45. package/dist/services/batch/batch-progress-store.d.ts +52 -0
  46. package/dist/services/batch/batch-progress-store.js +219 -0
  47. package/dist/services/batch/batch-progress-types.d.ts +79 -0
  48. package/dist/services/batch/batch-progress-types.js +10 -0
  49. package/dist/services/batch/batch-recovery.d.ts +5 -0
  50. package/dist/services/batch/batch-recovery.js +24 -0
  51. package/dist/services/batch/batch-verify.d.ts +93 -0
  52. package/dist/services/batch/batch-verify.js +216 -0
  53. package/dist/services/code/auto-compact-decision.d.ts +17 -0
  54. package/dist/services/code/auto-compact-decision.js +6 -0
  55. package/dist/services/code/auto-compact-orchestrator.js +6 -0
  56. package/dist/services/code/batch-compaction-point.d.ts +45 -0
  57. package/dist/services/code/batch-compaction-point.js +99 -0
  58. package/dist/services/context/context-schema.d.ts +1 -1
  59. package/dist/services/hooks/pre-tool-code-gate.d.ts +33 -1
  60. package/dist/services/hooks/pre-tool-code-gate.js +67 -6
  61. package/dist/services/lint/curated-rule-reader.d.ts +37 -0
  62. package/dist/services/lint/curated-rule-reader.js +179 -0
  63. package/dist/services/lint/project-lint-declarations.d.ts +27 -0
  64. package/dist/services/lint/project-lint-declarations.js +217 -0
  65. package/dist/services/lint/project-lint-tool-detection.d.ts +14 -0
  66. package/dist/services/lint/project-lint-tool-detection.js +208 -0
  67. package/dist/services/lint/project-lint-tool-rules.d.ts +19 -0
  68. package/dist/services/lint/project-lint-tool-rules.js +199 -0
  69. package/dist/services/lint/rule-pre-read-types.d.ts +66 -0
  70. package/dist/services/lint/rule-pre-read-types.js +22 -0
  71. package/dist/services/lint/rule-pre-read.d.ts +20 -0
  72. package/dist/services/lint/rule-pre-read.js +145 -0
  73. package/dist/services/skill/skill-search-service.d.ts +3 -3
  74. package/package.json +5 -5
  75. package/skills/peaks-code/references/micro-cycle.md +13 -1
  76. package/skills/peaks-race-code/SKILL.md +40 -1
@@ -0,0 +1,59 @@
1
+ import { z } from 'zod';
2
+ import type { BatchItem } from '../../services/batch/batch-progress-types.js';
3
+ /**
4
+ * One item as the caller knows it.
5
+ *
6
+ * `files` and `riskSurface` are the measured results and are carried
7
+ * forward onto the record; the risk surface is bounded by the same number
8
+ * the race lane's own gate uses.
9
+ */
10
+ declare const batchItemInputSchema: z.ZodObject<{
11
+ id: z.ZodString;
12
+ label: z.ZodString;
13
+ symptom: z.ZodString;
14
+ status: z.ZodEnum<{
15
+ pending: "pending";
16
+ diagnosed: "diagnosed";
17
+ }>;
18
+ files: z.ZodOptional<z.ZodArray<z.ZodString>>;
19
+ riskSurface: z.ZodOptional<z.ZodNumber>;
20
+ }, z.core.$strip>;
21
+ export type BatchItemInput = z.infer<typeof batchItemInputSchema>;
22
+ /** The parsed item list, or the reason it could not be read. */
23
+ export type ParsedItems = {
24
+ readonly kind: 'ok';
25
+ readonly items: readonly BatchItemInput[];
26
+ } | {
27
+ readonly kind: 'invalid';
28
+ readonly message: string;
29
+ };
30
+ /** The options this command reads. */
31
+ export interface BatchDiagnoseOptions {
32
+ readonly rid?: string;
33
+ readonly project?: string;
34
+ readonly items?: string;
35
+ readonly itemsJson?: string;
36
+ readonly json?: boolean;
37
+ }
38
+ /**
39
+ * Read the caller's item list, from a file or from inline JSON.
40
+ *
41
+ * The two shapes are the same shape (`wave-plan` reads its slices the same
42
+ * way), and a refusal here names WHICH shape was wrong rather than throwing
43
+ * a parse error at the caller.
44
+ */
45
+ export declare function readItems(options: BatchDiagnoseOptions): ParsedItems;
46
+ /**
47
+ * Whether a recorded item still carries the question it has to be asked.
48
+ *
49
+ * An item without a symptom cannot be diagnosed: there is nothing to
50
+ * diagnose. It is named rather than dispatched with a substitute, because a
51
+ * prompt whose "Reported symptom" line holds the item's LABEL would ask the
52
+ * diagnostician the wrong question and report a confident answer to it.
53
+ */
54
+ export declare function hasSymptom(item: BatchItem): item is BatchItem & {
55
+ readonly symptom: string;
56
+ };
57
+ /** The record row for one item: what the caller measured, carried forward. */
58
+ export declare function toBatchItem(input: BatchItemInput): BatchItem;
59
+ export {};
@@ -0,0 +1,113 @@
1
+ // src/cli/commands/batch-item-input.ts
2
+ //
3
+ // The batch's item list as the CALLER knows it, and the record row it
4
+ // becomes.
5
+ //
6
+ // Split out of `batch-diagnose-command.ts` to honor the repo's file-size
7
+ // cap. The two share no logic: this one is the INPUT vocabulary and how it
8
+ // is read and validated; that one is the action.
9
+ //
10
+ // WHY THE CALLER SUPPLIES THE ITEMS. They are facts about the user's
11
+ // request that only the caller holds — the labels, the symptoms, and which
12
+ // of them have already been diagnosed. The CLI reads them; it does not
13
+ // invent them.
14
+ //
15
+ // WHY THE STATUS IS EXPLICIT. `diagnosed` means the file set was MEASURED
16
+ // and `pending` means a diagnostician still has to produce one. Nothing is
17
+ // inferred from an absent field, because an item whose diagnosis found NO
18
+ // files is still diagnosed — an absent `files` array would read as
19
+ // "not measured" and send it round the diagnosis loop again.
20
+ //
21
+ // WHY THE SYMPTOM IS CARRIED ON THE RECORD. The symptom is the item's
22
+ // INPUT, not a measurement: the diagnosis prompt is built from it, and the
23
+ // report the diagnostician produces is an answer to it. Keeping it on the
24
+ // record is what lets a batch that resumes after a compaction still ask the
25
+ // question.
26
+ import { readFileSync } from 'node:fs';
27
+ import { z } from 'zod';
28
+ import { RISK_SURFACE_MAX } from '../../services/race/pilot-gate-store.js';
29
+ /**
30
+ * One item as the caller knows it.
31
+ *
32
+ * `files` and `riskSurface` are the measured results and are carried
33
+ * forward onto the record; the risk surface is bounded by the same number
34
+ * the race lane's own gate uses.
35
+ */
36
+ const batchItemInputSchema = z.object({
37
+ id: z.string().min(1),
38
+ label: z.string().min(1),
39
+ symptom: z.string().min(1),
40
+ status: z.enum(['pending', 'diagnosed']),
41
+ files: z.array(z.string()).optional(),
42
+ riskSurface: z.number().int().min(1).max(RISK_SURFACE_MAX).optional()
43
+ });
44
+ const batchInputSchema = z.object({
45
+ items: z.array(batchItemInputSchema).min(1)
46
+ });
47
+ /**
48
+ * Read the caller's item list, from a file or from inline JSON.
49
+ *
50
+ * The two shapes are the same shape (`wave-plan` reads its slices the same
51
+ * way), and a refusal here names WHICH shape was wrong rather than throwing
52
+ * a parse error at the caller.
53
+ */
54
+ export function readItems(options) {
55
+ const inline = options.itemsJson;
56
+ const path = options.items;
57
+ if (inline === undefined && path === undefined) {
58
+ return { kind: 'invalid', message: 'no items supplied' };
59
+ }
60
+ let text;
61
+ if (inline !== undefined) {
62
+ text = inline;
63
+ }
64
+ else {
65
+ try {
66
+ text = readFileSync(path, 'utf8');
67
+ }
68
+ catch (error) {
69
+ const detail = error instanceof Error ? error.message : String(error);
70
+ return { kind: 'invalid', message: `cannot read the items file: ${detail}` };
71
+ }
72
+ }
73
+ let parsed;
74
+ try {
75
+ parsed = JSON.parse(text);
76
+ }
77
+ catch (error) {
78
+ const detail = error instanceof Error ? error.message : String(error);
79
+ return { kind: 'invalid', message: `the items are not valid JSON: ${detail}` };
80
+ }
81
+ const result = batchInputSchema.safeParse(parsed);
82
+ if (!result.success) {
83
+ return {
84
+ kind: 'invalid',
85
+ message: `the items do not match the expected shape: ${result.error.message}`
86
+ };
87
+ }
88
+ return { kind: 'ok', items: result.data.items };
89
+ }
90
+ /**
91
+ * Whether a recorded item still carries the question it has to be asked.
92
+ *
93
+ * An item without a symptom cannot be diagnosed: there is nothing to
94
+ * diagnose. It is named rather than dispatched with a substitute, because a
95
+ * prompt whose "Reported symptom" line holds the item's LABEL would ask the
96
+ * diagnostician the wrong question and report a confident answer to it.
97
+ */
98
+ export function hasSymptom(item) {
99
+ return typeof item.symptom === 'string' && item.symptom.length > 0;
100
+ }
101
+ /** The record row for one item: what the caller measured, carried forward. */
102
+ export function toBatchItem(input) {
103
+ const base = {
104
+ id: input.id,
105
+ label: input.label,
106
+ symptom: input.symptom,
107
+ status: input.status,
108
+ files: input.files ?? []
109
+ };
110
+ if (input.riskSurface === undefined)
111
+ return base;
112
+ return { ...base, riskSurface: input.riskSurface };
113
+ }
@@ -0,0 +1,22 @@
1
+ import { type ProgramIO } from '../cli-helpers.js';
2
+ /** The options both actions read. */
3
+ export interface BatchReportOptions {
4
+ readonly rid?: string;
5
+ readonly item?: string;
6
+ readonly file?: string;
7
+ readonly full?: boolean;
8
+ readonly project?: string;
9
+ readonly json?: boolean;
10
+ }
11
+ /**
12
+ * Land a diagnosis report on disk and answer with its summary.
13
+ *
14
+ * The summary is what the orchestrator keeps; the full report is on disk
15
+ * for the phase that needs the detail.
16
+ */
17
+ export declare function runBatchReportWrite(options: BatchReportOptions, io: ProgramIO): void;
18
+ /**
19
+ * Read a diagnosis report back — the summary by default, the whole report
20
+ * when the caller asks for it.
21
+ */
22
+ export declare function runBatchReportRead(options: BatchReportOptions, io: ProgramIO): void;
@@ -0,0 +1,199 @@
1
+ // src/cli/commands/batch-report-command.ts
2
+ //
3
+ // `peaks batch report` — landing a diagnosis report on disk and reading
4
+ // back the summary the orchestrator's window may hold.
5
+ //
6
+ // WHY THIS EXISTS. A batch produces one diagnosis report per item, and the
7
+ // orchestrator's window cannot hold all of them: twenty sub-agent reports
8
+ // cost ≈60 KB ≈15K tokens, and a batch produces N at once. So the report
9
+ // lands on disk, and the orchestrator's context keeps only the ≤2 KB
10
+ // summary — the conclusion, the MEASURED file set (the topology stage's
11
+ // only input), and a one-line sketch. The full report is read back on
12
+ // demand, when a phase needs the detail the summary left out.
13
+ //
14
+ // WHY THE ORCHESTRATOR WRITES THE REPORT RATHER THAN THE DIAGNOSTICIAN.
15
+ // The diagnosis phase is read-only on purpose: a diagnostician that also
16
+ // wrote files would be reporting a guess about what it changed, and the
17
+ // whole measurement premise of the batch would be gone. The report is the
18
+ // diagnostician's own words, so the party that HOLDS those words — the
19
+ // orchestrator — is the party that lands them.
20
+ //
21
+ // THE TWO ACTIONS. `write` lands a report and answers with its summary;
22
+ // `read` answers with the summary again, or with the whole report when the
23
+ // caller asks for it (`--full`).
24
+ import { readFileSync } from 'node:fs';
25
+ import { fail, ok } from 'peaks-loop-shared/result';
26
+ import { printResult } from '../cli-helpers.js';
27
+ import { readBatchDiagnosisReport, readBatchDiagnosisSummary, writeBatchDiagnosisReport } from '../../services/batch/batch-diagnosis-report-store.js';
28
+ import { REQUEST_ID_PATTERN } from '../../services/artifacts/request-artifact-service.js';
29
+ import { getCurrentSessionId } from '../../services/skills/skill-presence-service.js';
30
+ /**
31
+ * Resolve the preconditions.
32
+ *
33
+ * The rid names the batch and the item names the report; both become path
34
+ * segments, so both are checked here rather than deeper in the store.
35
+ */
36
+ function resolveReport(options) {
37
+ const projectRoot = options.project ?? process.cwd();
38
+ const rid = options.rid;
39
+ if (typeof rid !== 'string' || rid === '') {
40
+ return {
41
+ kind: 'refused',
42
+ code: 'MISSING_RID',
43
+ message: 'a batch belongs to a request, so --rid is required',
44
+ data: { rid: null, itemId: null },
45
+ nextActions: ['Re-run with --rid <rid> naming the request this batch belongs to.']
46
+ };
47
+ }
48
+ if (!REQUEST_ID_PATTERN.test(rid)) {
49
+ return {
50
+ kind: 'refused',
51
+ code: 'INVALID_RID',
52
+ message: `the request id "${rid}" is not a valid request id`,
53
+ data: { rid, itemId: null },
54
+ nextActions: [
55
+ 'A request id is letters, digits, dots, dashes and underscores (see REQUEST_ID_PATTERN).'
56
+ ]
57
+ };
58
+ }
59
+ const item = options.item;
60
+ if (typeof item !== 'string' || item === '') {
61
+ return {
62
+ kind: 'refused',
63
+ code: 'MISSING_ITEM',
64
+ message: 'a report belongs to an item, so --item is required',
65
+ data: { rid, itemId: null },
66
+ nextActions: ['Re-run with --item <id> naming the item this report is about.']
67
+ };
68
+ }
69
+ const sessionId = getCurrentSessionId(projectRoot);
70
+ if (sessionId === null) {
71
+ return {
72
+ kind: 'refused',
73
+ code: 'NO_SESSION',
74
+ message: `no peaks session is bound to ${projectRoot}, so the report cannot be stored`,
75
+ data: { rid, itemId: item },
76
+ nextActions: ['Run `peaks workspace init --project .` first, then re-run this command.']
77
+ };
78
+ }
79
+ return { kind: 'ready', ref: { projectRoot, sessionId, batchId: rid, itemId: item } };
80
+ }
81
+ /**
82
+ * The report text, or the reason it could not be read.
83
+ */
84
+ function readReportFile(file) {
85
+ try {
86
+ return { ok: true, text: readFileSync(file, 'utf8') };
87
+ }
88
+ catch (error) {
89
+ const detail = error instanceof Error ? error.message : String(error);
90
+ return { ok: false, message: `cannot read the report file: ${detail}` };
91
+ }
92
+ }
93
+ /** A refusal from the write action. */
94
+ function refuseWrite(input) {
95
+ const { io, asJson, ref, code, message, nextActions } = input;
96
+ printResult(io, fail('batch.report.write', code, message, { rid: ref.batchId, itemId: ref.itemId }, [
97
+ ...nextActions
98
+ ]), asJson);
99
+ process.exitCode = 1;
100
+ }
101
+ /** A refusal from the read action. */
102
+ function refuseRead(io, asJson, ref) {
103
+ printResult(io, fail('batch.report.read', 'NO_REPORT', 'this item has no diagnosis report yet', {
104
+ rid: ref.batchId,
105
+ itemId: ref.itemId
106
+ }, ['Land it first with `peaks batch report write`.']), asJson);
107
+ process.exitCode = 1;
108
+ }
109
+ /**
110
+ * The answer to a landed report: the summary, and the pointer to the rest.
111
+ *
112
+ * The full report is NOT in the answer — that is the whole point of the
113
+ * command: the window keeps the bounded form, and the full text is on
114
+ * disk for the phase that needs it.
115
+ */
116
+ function printWrittenReport(io, asJson, ref, report) {
117
+ printResult(io, ok('batch.report.write', {
118
+ rid: ref.batchId,
119
+ itemId: ref.itemId,
120
+ bytes: Buffer.byteLength(report, 'utf8'),
121
+ summary: readBatchDiagnosisSummary(ref)
122
+ }, [], [
123
+ 'The full report is on disk; the summary above is what the window keeps.',
124
+ 'Read the full report again with `peaks batch report read --full`.'
125
+ ]), asJson);
126
+ }
127
+ /**
128
+ * Land a diagnosis report on disk and answer with its summary.
129
+ *
130
+ * The summary is what the orchestrator keeps; the full report is on disk
131
+ * for the phase that needs the detail.
132
+ */
133
+ export function runBatchReportWrite(options, io) {
134
+ const asJson = options.json === true;
135
+ const resolved = resolveReport(options);
136
+ if (resolved.kind === 'refused') {
137
+ printResult(io, fail('batch.report.write', resolved.code, resolved.message, resolved.data, [
138
+ ...resolved.nextActions
139
+ ]), asJson);
140
+ process.exitCode = 1;
141
+ return;
142
+ }
143
+ const file = options.file;
144
+ if (typeof file !== 'string' || file === '') {
145
+ refuseWrite({
146
+ io,
147
+ asJson,
148
+ ref: resolved.ref,
149
+ code: 'MISSING_FILE',
150
+ message: 'the report text is read from a file',
151
+ nextActions: ['Re-run with --file <path> naming the file that holds the report text.']
152
+ });
153
+ return;
154
+ }
155
+ const read = readReportFile(file);
156
+ if (!read.ok) {
157
+ refuseWrite({
158
+ io,
159
+ asJson,
160
+ ref: resolved.ref,
161
+ code: 'UNREADABLE_FILE',
162
+ message: read.message,
163
+ nextActions: ['Point --file at a readable file holding the report text.']
164
+ });
165
+ return;
166
+ }
167
+ const report = read.text;
168
+ writeBatchDiagnosisReport(resolved.ref, report);
169
+ printWrittenReport(io, asJson, resolved.ref, report);
170
+ }
171
+ /**
172
+ * Read a diagnosis report back — the summary by default, the whole report
173
+ * when the caller asks for it.
174
+ */
175
+ export function runBatchReportRead(options, io) {
176
+ const asJson = options.json === true;
177
+ const resolved = resolveReport(options);
178
+ if (resolved.kind === 'refused') {
179
+ printResult(io, fail('batch.report.read', resolved.code, resolved.message, resolved.data, [
180
+ ...resolved.nextActions
181
+ ]), asJson);
182
+ process.exitCode = 1;
183
+ return;
184
+ }
185
+ const report = readBatchDiagnosisReport(resolved.ref);
186
+ if (report === null) {
187
+ refuseRead(io, asJson, resolved.ref);
188
+ return;
189
+ }
190
+ const summary = readBatchDiagnosisSummary(resolved.ref);
191
+ const full = options.full === true;
192
+ printResult(io, ok('batch.report.read', {
193
+ rid: resolved.ref.batchId,
194
+ itemId: resolved.ref.itemId,
195
+ bytes: Buffer.byteLength(report, 'utf8'),
196
+ summary,
197
+ ...(full ? { report } : {})
198
+ }, [], full ? [] : ['The summary is the bounded form; add --full for the whole report.']), asJson);
199
+ }
@@ -21,4 +21,22 @@
21
21
  */
22
22
  import type { Command } from 'commander';
23
23
  import { type ProgramIO } from '../cli-helpers.js';
24
+ /**
25
+ * The marker the gate leaves on stderr when it could not decide.
26
+ *
27
+ * The gate fails OPEN on a payload it cannot read, and that is deliberate: a
28
+ * blocked edit on every call would be worse than an allowed one. But a silent
29
+ * allow is invisible, and the failure it hides is the expensive kind — an
30
+ * acceptance that feeds the payload through a pipe (which some shells do not
31
+ * forward to the process at all) then "passes" every case while proving
32
+ * nothing. So the case says so, on the channel the harness already reads.
33
+ */
34
+ export declare const UNDECIDABLE_MARKER = "PEAKS_CODE_GATE_UNDECIDABLE";
35
+ /**
36
+ * How to feed the payload so that it arrives. A pipeline is not a delivery
37
+ * mechanism on every shell — a PowerShell pipeline to a native executable
38
+ * does not forward stdin at all — and then the gate reads no payload, allows
39
+ * everything, and the check passes vacuously.
40
+ */
41
+ export declare const PAYLOAD_DELIVERY_RECIPE: string;
24
42
  export declare function registerCodeGateCommand(program: Command, io: ProgramIO): void;
@@ -20,7 +20,7 @@
20
20
  * vendor-neutral — no vendor references in the source code itself.
21
21
  */
22
22
  import { addJsonOption, printResult } from '../cli-helpers.js';
23
- import { decideGateAction, extractFilePath } from '../../services/hooks/pre-tool-code-gate.js';
23
+ import { decideGateAction, extractFilePath, isGatedTool } from '../../services/hooks/pre-tool-code-gate.js';
24
24
  import { hasLeaseForCaller, resolveActiveSkillForCaller } from '../../services/audit/enforcers/active-skill-resolver.js';
25
25
  import { resolveCanonicalProjectRoot } from '../../services/config/config-service.js';
26
26
  import { pluckObject, pluckString } from '../../services/ide/hook-translator.js';
@@ -59,6 +59,81 @@ function resolveDriver(projectRoot, payload) {
59
59
  return null;
60
60
  return resolveActiveSkillForCaller(projectRoot, { callerId }).skill;
61
61
  }
62
+ /**
63
+ * The marker the gate leaves on stderr when it could not decide.
64
+ *
65
+ * The gate fails OPEN on a payload it cannot read, and that is deliberate: a
66
+ * blocked edit on every call would be worse than an allowed one. But a silent
67
+ * allow is invisible, and the failure it hides is the expensive kind — an
68
+ * acceptance that feeds the payload through a pipe (which some shells do not
69
+ * forward to the process at all) then "passes" every case while proving
70
+ * nothing. So the case says so, on the channel the harness already reads.
71
+ */
72
+ export const UNDECIDABLE_MARKER = 'PEAKS_CODE_GATE_UNDECIDABLE';
73
+ /**
74
+ * How to feed the payload so that it arrives. A pipeline is not a delivery
75
+ * mechanism on every shell — a PowerShell pipeline to a native executable
76
+ * does not forward stdin at all — and then the gate reads no payload, allows
77
+ * everything, and the check passes vacuously.
78
+ */
79
+ export const PAYLOAD_DELIVERY_RECIPE = 'feed the payload by FILE REDIRECTION (cmd /c "peaks code-gate < payload.json"), not through a pipe: ' +
80
+ 'a shell pipeline does not always forward stdin to the process, and then every case is allowed and the check proves nothing.';
81
+ /** Say, on stderr, that the gate could not decide — and still allow. */
82
+ function reportUndecidable(reason) {
83
+ process.stderr.write(`${UNDECIDABLE_MARKER}: ${reason}; allowing. ${PAYLOAD_DELIVERY_RECIPE}\n`);
84
+ }
85
+ /**
86
+ * The reason this payload cannot be judged, or `null` when it can.
87
+ *
88
+ * A payload that names a gated tool but no target path is the same "cannot
89
+ * decide" the empty payload is: there is no file to match against a family.
90
+ */
91
+ function undecidableReason(tool, input) {
92
+ if (!isGatedTool(tool))
93
+ return null;
94
+ if (extractFilePath(input).length > 0)
95
+ return null;
96
+ return 'the payload names a gated tool but no target path';
97
+ }
98
+ /** The payload as bytes, or `''` when stdin could not be read. */
99
+ async function readPayload() {
100
+ try {
101
+ return await readStdin();
102
+ }
103
+ catch {
104
+ // Empty / unreadable stdin → fail-open allow. The shell-script
105
+ // sibling does the same.
106
+ return '';
107
+ }
108
+ }
109
+ /** The payload as an object, or `null` when it is empty or malformed. */
110
+ function parsePayload(raw) {
111
+ if (raw.trim().length === 0)
112
+ return null;
113
+ let parsed = null;
114
+ try {
115
+ parsed = JSON.parse(raw);
116
+ }
117
+ catch {
118
+ // Malformed JSON → fail-open allow. Cannot decide safely.
119
+ parsed = null;
120
+ }
121
+ return parsed;
122
+ }
123
+ /** The verdict envelope, in the shape the `--dry-run` mode prints. */
124
+ function printDryRunVerdict(io, asJson, context) {
125
+ const { tool, input, verdict, undecidable } = context;
126
+ if (verdict.action === 'allow') {
127
+ printResult(io, ok('code.gate', { action: 'allow', tool, filePath: extractFilePath(input) }, [], undecidable === null ? [] : [PAYLOAD_DELIVERY_RECIPE]), asJson);
128
+ return;
129
+ }
130
+ printResult(io, fail('code.gate', 'PEAKS_CODE_PROHIBITED_DIRECT_EDIT', verdict.message, {
131
+ action: 'deny',
132
+ tool,
133
+ filePath: verdict.filePath,
134
+ reason: verdict.reason
135
+ }, ['use peaks sub-agent dispatch rd']), asJson);
136
+ }
62
137
  export function registerCodeGateCommand(program, io) {
63
138
  addJsonOption(program
64
139
  .command('code-gate')
@@ -68,48 +143,36 @@ export function registerCodeGateCommand(program, io) {
68
143
  'The gate blocks Edit/Write/MultiEdit on hard-blocked path families ' +
69
144
  '(src/, tests/unit/, tests/integration/, config/, bin/, scripts/) so the ' +
70
145
  'orchestrator is forced to dispatch via `peaks sub-agent dispatch rd`. ' +
71
- 'Allow-listed paths (.peaks/**, skills/**, docs/**) are NOT gated.')
146
+ 'Allow-listed paths (.peaks/**, skills/**, docs/**) are NOT gated. ' +
147
+ 'A payload the gate cannot read is ALLOWED (fail-open) and says so on ' +
148
+ 'stderr with PEAKS_CODE_GATE_UNDECIDABLE — ' +
149
+ 'feed the payload by FILE REDIRECTION, not through a pipe.')
72
150
  .option('--dry-run', 'emit JSON verdict to stdout instead of exit code; useful for tests')
73
151
  .option('--project <path>', 'project the driver lease is resolved against (default: current directory)')).action(async (opts) => {
74
- let raw = '';
75
- try {
76
- raw = await readStdin();
77
- }
78
- catch {
79
- // Empty / unreadable stdin → fail-open allow. The shell-script
80
- // sibling does the same.
81
- raw = '';
82
- }
83
- let parsed = null;
84
- try {
85
- parsed = raw.trim().length > 0 ? JSON.parse(raw) : null;
86
- }
87
- catch {
88
- // Malformed JSON → fail-open allow. Cannot decide safely.
89
- parsed = null;
90
- }
152
+ const parsed = parsePayload(await readPayload());
91
153
  if (parsed === null) {
154
+ reportUndecidable('no stdin payload');
92
155
  if (opts.dryRun === true) {
93
- printResult(io, ok('code.gate', { action: 'allow', reason: 'empty-or-malformed-payload' }, [], ['no stdin payload; allowing']), opts.json);
156
+ printResult(io, ok('code.gate', { action: 'allow', reason: 'empty-or-malformed-payload' }, [], ['no stdin payload; allowing', PAYLOAD_DELIVERY_RECIPE]), opts.json);
94
157
  return;
95
158
  }
96
159
  process.exit(0);
97
160
  }
98
161
  const tool = readToolName(parsed);
99
162
  const input = readToolInput(parsed);
100
- const verdict = decideGateAction(tool, input, resolveDriver(resolveCanonicalProjectRoot(opts.project ?? process.cwd()), parsed));
163
+ const undecidable = undecidableReason(tool, input);
164
+ if (undecidable !== null) {
165
+ reportUndecidable(undecidable);
166
+ }
167
+ // The project root is what the deny families are relative to, so it is
168
+ // resolved ONCE and used twice: to place the caller, and to relate an
169
+ // absolute target path to the project. A path spelled absolutely is the
170
+ // same file as the same path spelled relatively, and both must be judged
171
+ // the same way.
172
+ const projectRoot = resolveCanonicalProjectRoot(opts.project ?? process.cwd());
173
+ const verdict = decideGateAction(tool, input, resolveDriver(projectRoot, parsed), projectRoot);
101
174
  if (opts.dryRun === true) {
102
- if (verdict.action === 'allow') {
103
- printResult(io, ok('code.gate', { action: 'allow', tool, filePath: extractFilePath(input) }, [], []), opts.json);
104
- }
105
- else {
106
- printResult(io, fail('code.gate', 'PEAKS_CODE_PROHIBITED_DIRECT_EDIT', verdict.message, {
107
- action: 'deny',
108
- tool,
109
- filePath: verdict.filePath,
110
- reason: verdict.reason
111
- }, ['use peaks sub-agent dispatch rd']), opts.json);
112
- }
175
+ printDryRunVerdict(io, opts.json === true, { tool, input, verdict, undecidable });
113
176
  return;
114
177
  }
115
178
  if (verdict.action === 'deny') {
@@ -1,4 +1,5 @@
1
1
  import type { AutoCompactMode } from '../../../services/code/auto-compact-modes.js';
2
+ import { type BatchContextReminder } from '../../../services/batch/batch-context-reminder.js';
2
3
  /**
3
4
  * The loop-hygiene verdict attached to every ACTIVE `skill.presence` read.
4
5
  *
@@ -17,10 +18,24 @@ import type { AutoCompactMode } from '../../../services/code/auto-compact-modes.
17
18
  * Executing `peaks code auto-compact` stays the skill's own action — a
18
19
  * side effect here would fire on every single turn.
19
20
  *
21
+ * THE ONE WRITE. The batch reminder records the phase it last spoke in,
22
+ * so the batch says its reminder once per phase instead of once per turn.
23
+ * That marker is written only when the phase changed or when the batch
24
+ * spoke, and it lives in the batch's own directory under the session —
25
+ * never in the presence marker itself.
26
+ *
20
27
  * Failure swallows to `null`: the hygiene verdict is advisory and must
21
28
  * never be able to break the presence read itself.
29
+ *
30
+ * THE BATCH REMINDER IS CARRIED HERE TOO. A batch's context reminder (the
31
+ * ratio zone, the phase boundary) is another statement about the window,
32
+ * and it reaches the model through the same carrier — so a batch sentence
33
+ * cannot bypass the zero-pause contract by living somewhere else. The
34
+ * sentence itself is built by the batch module (it owns the wording); it
35
+ * is APPENDED here, and it states a fact rather than asking anybody to do
36
+ * anything.
22
37
  */
23
- export declare function buildContextVerdict(ratio: number, mode: AutoCompactMode): {
38
+ export declare function buildContextVerdict(ratio: number, mode: AutoCompactMode, batch?: BatchContextReminder | null): {
24
39
  context: {
25
40
  ratioPct: string;
26
41
  action: string;