@codedology/code-forge 0.8.0 → 0.10.0

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 (64) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +46 -7
  3. package/docs/reference/blocks.json +618 -1
  4. package/docs/reference/config.md +36 -0
  5. package/package.json +1 -1
  6. package/schema/code-forge.schema.json +89 -0
  7. package/skill/references/adapters/claude-code.md +1 -1
  8. package/skill/references/adapters/solo.md +2 -2
  9. package/skill/references/adapters/subprocess.md +12 -2
  10. package/skill/references/code.md +21 -7
  11. package/skill/references/ledger.md +2 -2
  12. package/skill/references/proof.md +77 -2
  13. package/skill/references/review.md +29 -4
  14. package/skill/references/security.md +5 -5
  15. package/skill/scripts/forge +1 -1
  16. package/skill/templates/coder-brief.md +4 -2
  17. package/src/autopilot/binnacle.mjs +9 -3
  18. package/src/cli/block.mjs +300 -33
  19. package/src/cli/jev.mjs +22 -3
  20. package/src/cli/keys.mjs +156 -21
  21. package/src/cli/proof.mjs +35 -7
  22. package/src/cli/review-file.mjs +264 -13
  23. package/src/cli/spawn.mjs +44 -3
  24. package/src/config/validate.mjs +320 -5
  25. package/src/doctor/index.mjs +7 -5
  26. package/src/doctor/local.mjs +116 -8
  27. package/src/doctor/probes.mjs +38 -0
  28. package/src/engines/builders/codex.mjs +44 -4
  29. package/src/engines/sandbox-dirs.mjs +257 -0
  30. package/src/keys/store.mjs +128 -21
  31. package/src/ledger/write.mjs +7 -1
  32. package/src/proof/junit.mjs +530 -0
  33. package/src/proof/red-green.mjs +57 -9
  34. package/src/proof/red-parse.mjs +2 -0
  35. package/src/proof/runners.mjs +472 -0
  36. package/src/proof/xcresult.mjs +285 -0
  37. package/src/review/answers.mjs +445 -0
  38. package/src/review/deletion.mjs +106 -0
  39. package/src/review/engine.mjs +117 -31
  40. package/src/review/fixloop.mjs +70 -28
  41. package/src/review/gate-check.mjs +378 -80
  42. package/src/review/lenses/A.md +1 -0
  43. package/src/review/lenses/B.md +1 -0
  44. package/src/review/lenses/full.md +1 -0
  45. package/src/review/lenses/quick.md +1 -0
  46. package/src/review/lenses/recheck.md +1 -0
  47. package/src/review/reopen.mjs +256 -0
  48. package/src/review/route.mjs +232 -0
  49. package/src/review/schema-fallback.mjs +77 -22
  50. package/src/review/session-retry.mjs +44 -9
  51. package/src/review/stop-exits.mjs +15 -0
  52. package/src/review/test-quality.mjs +201 -0
  53. package/src/review/verb-forms.mjs +39 -0
  54. package/src/session/spawn.mjs +39 -2
  55. package/src/state/block.mjs +13 -3
  56. package/src/state/config-snapshot.mjs +39 -0
  57. package/src/state/run.mjs +4 -0
  58. package/src/util/forbidden.mjs +11 -1
  59. package/src/util/tmp.mjs +16 -4
  60. package/src/worker/engine.mjs +75 -9
  61. package/src/worker/loop.mjs +82 -15
  62. package/src/worker/queue.mjs +265 -10
  63. package/src/worker/review-state.mjs +346 -51
  64. package/src/worker/ticket.mjs +9 -1
@@ -0,0 +1,285 @@
1
+ /**
2
+ * `xcresult` (red-green plan §1.6, B102): read the result bundle of an `xcodebuild test` run and
3
+ * classify the RED and GREEN steps of the `xcodebuild` runner adapter from it.
4
+ *
5
+ * The bundle is read with `xcrun xcresulttool get test-results tests --path <bundle>` (argv only,
6
+ * 60 s timeout, output capped at 8 MiB), and its JSON is mapped to the common `{tests}` shape of
7
+ * `junit.mjs`. The node shape is pinned by real captured output (Xcode 26.6, `test/fixtures/xcresult/`):
8
+ *
9
+ * {testNodes: [Test Plan → Unit test bundle | UI test bundle → Test Suite (→ Test Suite)…
10
+ * → Test Case → Failure Message]}
11
+ *
12
+ * A Test Case carries `nodeIdentifier` (`ClampXCTests/testCapsHigh()` for XCTest,
13
+ * `ClampSwiftTests/capsHigh()` for Swift Testing) and `result` (`Passed`, `Failed`, `Skipped`). Its
14
+ * id is `<bundle name>/<nodeIdentifier>`, e.g. `KitTests/ClampXCTests/testCapsHigh()`. A Test Plan
15
+ * with no children (a filter that selected nothing) is zero tests.
16
+ *
17
+ * Fail closed: no bundle, a bundle that is not a real directory, a failed or timed-out
18
+ * `xcresulttool`, output over 8 MiB, JSON that does not parse, two tests with the same id, and a
19
+ * failed check of what this reader uses make the result unreadable. It checks every node's
20
+ * `nodeType` (a known type) and its parent type (a known place), a Test Case's `result` (a known
21
+ * result) and `nodeIdentifier` (a non-empty string), a bundle's `name` (non-empty, no `/`), a
22
+ * Failure Message's `name` (a string, no children) and every `children` (a list). Any other key of a
23
+ * node or of the document (`devices`, `testPlanConfigurations`, `duration`, …) is not read and is
24
+ * ignored. An unreadable result never proves anything (RED is `RED_INVALID error`, GREEN is
25
+ * `NOT_GREEN`). Today
26
+ * that includes these xcresulttool node types: a parameterized Swift Testing test (`Arguments`),
27
+ * repetitions (`Repetition`, `Test Case Run`), a multi-destination or multi-configuration run
28
+ * (`Device`, `Test Plan Configuration`), `Runtime Warning`, `Source Code Reference`, `Attachment`,
29
+ * `Expression`, `Test Value`, and the result `Expected Failure`.
30
+ *
31
+ * A Failure Message (`<file>.swift:<line>: <text>`, the prefix optional) is an assertion only for
32
+ * these texts, as captured: `XCTAssert… failed` (but not `XCTAssert… failed: threw error`, a thrown
33
+ * error inside the assertion), XCTFail's `failed` and `failed - <message>`, and Swift Testing's
34
+ * `Expectation failed: …`. Every other text is an error: a thrown error (`failed: caught error: …`,
35
+ * `Caught error: …`), `Issue recorded: …`, a crash. A failed test is an assertion only when every
36
+ * one of its messages is one.
37
+ */
38
+
39
+ import { lstat } from 'node:fs/promises';
40
+ import path from 'node:path';
41
+ import { exec } from '../util/exec.mjs';
42
+ import { MAX_REPORT_BYTES, NO_REPORT, classifyGreen, classifyReport, swiftCompileError } from './junit.mjs';
43
+
44
+ /** `xcresulttool` may run this long before it is stopped. */
45
+ export const XCRESULTTOOL_TIMEOUT_MS = 60_000;
46
+
47
+ /** Which parent node type each known node type may have (`null` = the `testNodes` list). */
48
+ const NODE_PARENTS = Object.freeze({
49
+ 'Test Plan': [null],
50
+ 'Unit test bundle': ['Test Plan'],
51
+ 'UI test bundle': ['Test Plan'],
52
+ 'Test Suite': ['Unit test bundle', 'UI test bundle', 'Test Suite'],
53
+ 'Test Case': ['Test Suite'],
54
+ 'Failure Message': ['Test Case'],
55
+ });
56
+
57
+ /** A Test Case `result` this reader knows, and its common status. */
58
+ const RESULT_STATUS = Object.freeze({ Passed: 'passed', Failed: 'failed', Skipped: 'skipped' });
59
+
60
+ /** The optional `<file>.swift:<line>: ` prefix of a Failure Message. */
61
+ const MESSAGE_PREFIX = /^[^\n:]+\.swift:\d+: /;
62
+ /** The assertion texts, after the prefix (see the header). */
63
+ const ASSERTION_MESSAGES = Object.freeze([/^XCTAssert\w* failed(?!: threw error)/, /^failed - /, /^failed$/, /^Expectation failed: /]);
64
+
65
+ // eslint-disable-next-line no-control-regex
66
+ const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
67
+ /** `xcodebuild`'s own build-failure lines (`** BUILD FAILED **`, `** TEST BUILD FAILED **`). */
68
+ const BUILD_FAILED_LINE = /^\*\* (?:TEST )?BUILD FAILED \*\*[ \t\r]*$/m;
69
+ /** `xcodebuild test` (Xcode 26.6) on a test that does not compile prints this line, tab-indented, then `** TEST FAILED **`. */
70
+ const BUILD_CANCELLED_LINE = /^[ \t]*Testing cancelled because the build failed\.[ \t\r]*$/m;
71
+
72
+ /** @param {string} reason @returns {never} */
73
+ function unreadable(reason) {
74
+ const err = new Error(`report-unreadable: ${reason}`);
75
+ /** @type {any} */ (err).code = 'report-unreadable';
76
+ throw err;
77
+ }
78
+
79
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
80
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
81
+
82
+ /**
83
+ * Is a Failure Message text an assertion failure?
84
+ * @param {string} text @returns {'assertion' | 'error'}
85
+ */
86
+ export function failureMessageKind(text) {
87
+ const rest = String(text).replace(MESSAGE_PREFIX, '');
88
+ return ASSERTION_MESSAGES.some((p) => p.test(rest)) ? 'assertion' : 'error';
89
+ }
90
+
91
+ /**
92
+ * Read `xcresulttool get test-results tests` JSON.
93
+ * @param {string} text
94
+ * @returns {{tests: import('./junit.mjs').ReportTest[]}}
95
+ * @throws {Error} `code: 'report-unreadable'`; the message names the reason only, never content.
96
+ */
97
+ export function readXcresult(text) {
98
+ if (typeof text !== 'string') unreadable('the xcresulttool output is not text');
99
+ if (Buffer.byteLength(text, 'utf8') > MAX_REPORT_BYTES) unreadable('the xcresulttool output is over 8 MiB');
100
+ let doc;
101
+ try {
102
+ doc = JSON.parse(text);
103
+ } catch {
104
+ unreadable('the xcresulttool output is not JSON');
105
+ }
106
+ if (!isObject(doc) || !Array.isArray(doc.testNodes)) unreadable('the xcresulttool output has no testNodes list');
107
+
108
+ /** @type {import('./junit.mjs').ReportTest[]} */
109
+ const tests = [];
110
+ const seen = new Set();
111
+ /** @param {unknown} node @param {string | null} parent @param {string | null} bundle */
112
+ const walk = (node, parent, bundle) => {
113
+ if (!isObject(node)) unreadable('a test node that is not an object');
114
+ const type = node.nodeType;
115
+ if (typeof type !== 'string' || !Object.hasOwn(NODE_PARENTS, type)) unreadable('a node type this reader does not know');
116
+ if (!NODE_PARENTS[/** @type {keyof typeof NODE_PARENTS} */ (type)].includes(/** @type {any} */ (parent))) unreadable('a test node in the wrong place');
117
+ const children = node.children ?? [];
118
+ if (!Array.isArray(children)) unreadable('test node children that are not a list');
119
+ if (type === 'Failure Message') {
120
+ if (typeof node.name !== 'string') unreadable('a failure message without a text');
121
+ if (children.length > 0) unreadable('a failure message with children');
122
+ return;
123
+ }
124
+ let inBundle = bundle;
125
+ if (type === 'Unit test bundle' || type === 'UI test bundle') {
126
+ if (typeof node.name !== 'string' || node.name === '' || node.name.includes('/')) unreadable('a test bundle without a name');
127
+ inBundle = node.name;
128
+ }
129
+ if (type === 'Test Case') {
130
+ const ident = node.nodeIdentifier;
131
+ if (typeof ident !== 'string' || ident === '') unreadable('a test case without a nodeIdentifier');
132
+ const result = node.result;
133
+ if (typeof result !== 'string' || !Object.hasOwn(RESULT_STATUS, result)) unreadable('a test result this reader does not know');
134
+ const status = RESULT_STATUS[/** @type {keyof typeof RESULT_STATUS} */ (result)];
135
+ const kinds = children.map((child) => {
136
+ walk(child, 'Test Case', inBundle);
137
+ return failureMessageKind(/** @type {any} */ (child).name);
138
+ });
139
+ const id = `${inBundle}/${ident}`;
140
+ // one id twice (two bundles of one name, a repeated node) would let one result hide the other
141
+ if (seen.has(id)) unreadable('two test cases with the same id');
142
+ seen.add(id);
143
+ if (status === 'failed') tests.push({ id, status, kind: kinds.length > 0 && kinds.every((k) => k === 'assertion') ? 'assertion' : 'error' });
144
+ else if (kinds.length > 0) unreadable('a failure message on a test that did not fail');
145
+ else tests.push({ id, status });
146
+ return;
147
+ }
148
+ for (const child of children) walk(child, type, inBundle);
149
+ };
150
+ for (const node of doc.testNodes) walk(node, null, null);
151
+ return { tests };
152
+ }
153
+
154
+ /**
155
+ * `readXcresult` that never throws.
156
+ * @param {string} text @returns {import('./junit.mjs').ReportResult}
157
+ */
158
+ export function parseXcresult(text) {
159
+ try {
160
+ return readXcresult(text);
161
+ } catch (err) {
162
+ const message = err instanceof Error ? err.message : '';
163
+ return { unreadable: message.startsWith('report-unreadable: ') ? message.slice('report-unreadable: '.length) : 'the result bundle could not be read' };
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Read a result bundle with `xcresulttool`. Never throws. No bundle at the path is `NO_REPORT`; a
169
+ * symlink or any other non-directory is unreadable. A relative `bundle` is resolved against `cwd`
170
+ * once, and that one absolute path is both checked and read.
171
+ * @param {string} bundle @param {{cwd: string, env: NodeJS.ProcessEnv, timeoutMs?: number}} opts
172
+ * @returns {Promise<import('./junit.mjs').ReportResult>}
173
+ */
174
+ export async function loadXcresult(bundle, { cwd, env, timeoutMs = XCRESULTTOOL_TIMEOUT_MS }) {
175
+ const target = path.resolve(cwd, bundle);
176
+ let st;
177
+ try {
178
+ st = await lstat(target);
179
+ } catch (err) {
180
+ return /** @type {any} */ (err)?.code === 'ENOENT' ? NO_REPORT : { unreadable: 'the result bundle could not be opened' };
181
+ }
182
+ if (!st.isDirectory()) return { unreadable: 'the result bundle is not a directory' };
183
+ try {
184
+ const res = await exec(['xcrun', 'xcresulttool', 'get', 'test-results', 'tests', '--path', target], { cwd, env, timeoutMs, maxBufferBytes: MAX_REPORT_BYTES + 1 });
185
+ if (res.result !== 'ok' || res.code !== 0 || res.signal || res.timedOut) return { unreadable: 'xcresulttool failed' };
186
+ return parseXcresult(res.stdout);
187
+ } catch {
188
+ return { unreadable: 'xcresulttool failed' };
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Does the console text show that the test build failed? Colours are stripped first.
194
+ * @param {string} text @returns {boolean}
195
+ */
196
+ export function xcodeBuildFailed(text) {
197
+ const plain = String(text).replace(ANSI, '');
198
+ return BUILD_FAILED_LINE.test(plain) || BUILD_CANCELLED_LINE.test(plain);
199
+ }
200
+
201
+ /** @param {import('./junit.mjs').RunResult} run @returns {boolean} */
202
+ const exitedClean = (run) => run.code === 0 && !run.signal && !run.timedOut;
203
+
204
+ /**
205
+ * A scope is `<test_target>/<Suite>/`: two non-empty parts and the closing `/`. Without the `/`,
206
+ * `KitTests/Clamp` would also admit `KitTests/ClampMore/…`, so any other scope throws (the callers
207
+ * then classify fail closed).
208
+ * @param {unknown} scope @returns {asserts scope is string}
209
+ */
210
+ function checkScope(scope) {
211
+ if (typeof scope !== 'string' || !/^[^/]+\/[^/]+\/$/.test(scope)) throw new Error('an xcodebuild scope is <test_target>/<Suite>/');
212
+ }
213
+
214
+ /**
215
+ * Is any test of a readable result outside `scope` (`<test_target>/<Suite>/`)?
216
+ * @param {import('./junit.mjs').ReportResult} report @param {string} scope @returns {boolean}
217
+ * @throws {Error} a scope that is not `<test_target>/<Suite>/`
218
+ */
219
+ const ranOtherTests = (report, scope) => {
220
+ checkScope(scope);
221
+ return 'tests' in report && report.tests.some((t) => !t.id.startsWith(scope));
222
+ };
223
+
224
+ /**
225
+ * Classify the RED step of an `xcodebuild` run. Never throws. A `scope` that is not
226
+ * `<test_target>/<Suite>/` is `RED_INVALID error`. Then the first row that applies wins:
227
+ * - exit 0 and no readable result (no bundle, or an unreadable one) ⇒ `RED_INVALID error`: a clean
228
+ * exit with nothing to read says nothing about the test;
229
+ * - exit 0 and a readable result with a test outside `scope` (or only such tests) ⇒
230
+ * `RED_INVALID error` (the filter ran other tests): the test under proof did not run cleanly
231
+ * in scope, so a passing run is not `NOT_RED`;
232
+ * - exit 0 and a readable result with no test that ran ⇒ `RED_INVALID error` (the filter ran no
233
+ * test). This differs from `junit` and `swift`, where `classifyReport` reads any exit 0 as
234
+ * `NOT_RED`: `xcodebuild test` exits 0 when `-only-testing` selects nothing (a Swift Testing id
235
+ * without its `()`), so an empty run says nothing about the test and must not read as "it passed";
236
+ * - exit 0 otherwise ⇒ `NOT_RED`; a timeout or a signal ⇒ `RED_INVALID fatal`;
237
+ * - a failed run whose console shows a build failure, or that has no tests and a `swiftc` error
238
+ * ⇒ `RED_INVALID compile`;
239
+ * - a test outside `scope` ⇒ `RED_INVALID error` (the filter ran other tests);
240
+ * - else `classifyReport` (§1.1).
241
+ * Every invalid row this adds carries no failed data.
242
+ * @param {{run: import('./junit.mjs').RunResult, report: import('./junit.mjs').ReportResult, scope: string}} input
243
+ * @returns {import('./junit.mjs').JUnitRedParse}
244
+ */
245
+ export function classifyXcodeRed({ run, report, scope }) {
246
+ try {
247
+ checkScope(scope);
248
+ const base = classifyReport({ run, reports: [report], compileError: swiftCompileError });
249
+ /** @param {'compile' | 'error'} red_kind @param {string} reason @returns {import('./junit.mjs').JUnitRedParse} */
250
+ const invalid = (red_kind, reason) => ({ ...base, verdict: 'RED_INVALID', red_kind, failed: null, failed_tests: [], failed_ids: [], reason });
251
+ const readable = isObject(report) && Array.isArray(/** @type {any} */ (report).tests);
252
+ if (exitedClean(run)) {
253
+ if (!readable) return invalid('error', 'no readable test result');
254
+ if (readable && ranOtherTests(report, scope)) return invalid('error', 'the filter ran other tests');
255
+ if (readable && !(/** @type {any} */ (report).tests.some((/** @type {any} */ t) => t.status !== 'skipped'))) return invalid('error', 'the filter ran no test');
256
+ return base;
257
+ }
258
+ if (run.timedOut || run.signal) return base;
259
+ const output = `${run.stdout ?? ''}\n${run.stderr ?? ''}`;
260
+ if (xcodeBuildFailed(output)) return invalid('compile', 'the test did not build');
261
+ const noTests = report === NO_REPORT || (readable && /** @type {any} */ (report).tests.length === 0);
262
+ if (noTests && swiftCompileError(output)) return invalid('compile', 'the test did not compile');
263
+ if (readable && ranOtherTests(report, scope)) return invalid('error', 'the filter ran other tests');
264
+ return base;
265
+ } catch {
266
+ return { verdict: 'RED_INVALID', red_kind: 'error', framework: 'junit', failed: null, failed_tests: [], failed_ids: [], reason: 'no readable test result' };
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Classify the GREEN step of an `xcodebuild` run: `classifyGreen`, and `NOT_GREEN` when the result
272
+ * has a test outside `scope`. Never throws.
273
+ * @param {{run: import('./junit.mjs').RunResult, report: import('./junit.mjs').ReportResult, redFailed: string[], scope: string}} input
274
+ * @returns {import('./junit.mjs').JUnitGreenParse}
275
+ */
276
+ export function classifyXcodeGreen({ run, report, redFailed, scope }) {
277
+ try {
278
+ checkScope(scope);
279
+ const base = classifyGreen({ run, reports: [report], redFailed });
280
+ if (base.verdict === 'GREEN' && ranOtherTests(report, scope)) return { ...base, verdict: 'NOT_GREEN', reason: 'the filter ran other tests' };
281
+ return base;
282
+ } catch {
283
+ return { verdict: 'NOT_GREEN', failed: null, failed_tests: [], reason: 'no readable test result' };
284
+ }
285
+ }