@bendyline/gezel-script-stdlib 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/gezel-script-stdlib",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "Standard gate-script library packed into the app. Plain defineScript sources resolved in place by the script runner (scope: 'standard'); read-only, trusted, versioned with the app.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -41,7 +41,7 @@
41
41
  "!scripts/**/*.test.ts"
42
42
  ],
43
43
  "dependencies": {
44
- "@bendyline/gezel-sdk": "1.0.6"
44
+ "@bendyline/gezel-sdk": "1.0.8"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "^24.13.3",
@@ -0,0 +1,87 @@
1
+ import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
2
+ import { codebaseReviewReport, gateResult, workspaceFromGezel } from '@bendyline/gezel-sdk/checks';
3
+
4
+ export const meta = defineScript({
5
+ name: 'checkCodebaseReviewReport',
6
+ description:
7
+ 'Gate: a comprehensive codebase review is well-formed — the findings JSON parses, every finding cites a REAL workspace file with a severity, title, and concrete remediation (critical/high pinned to a line; fabricated paths are named), the report carries the required consultant sections with a per-dimension Scorecard table, systemic themes analyze root cause + blast radius once there is enough material, and the executive summary matches the open severity. Report and findings are read from the artifacts drawer; cited files are verified against the workspace.',
8
+ kind: 'gate',
9
+ inputs: {
10
+ file: {
11
+ type: 'string',
12
+ description: 'Artifact path of the review report markdown.',
13
+ required: true,
14
+ },
15
+ findings: {
16
+ type: 'string',
17
+ description: 'Artifact path of the machine-readable findings JSON.',
18
+ required: true,
19
+ },
20
+ minThemes: {
21
+ type: 'number',
22
+ description: 'Systemic themes required once findings ≥ themeThreshold.',
23
+ default: 2,
24
+ integer: true,
25
+ min: 0,
26
+ },
27
+ themeThreshold: {
28
+ type: 'number',
29
+ description: 'Findings count at/above which systemic-theme synthesis is required.',
30
+ default: 3,
31
+ integer: true,
32
+ min: 0,
33
+ },
34
+ minScorecardRows: {
35
+ type: 'number',
36
+ description: 'Minimum dimension rows the Scorecard table must carry.',
37
+ default: 4,
38
+ integer: true,
39
+ min: 1,
40
+ },
41
+ },
42
+ outputs: {
43
+ decision: { type: 'string', description: "'approve' or 'reject'." },
44
+ message: { type: 'string', description: 'What passed, or the concrete gap to fix.' },
45
+ },
46
+ requires: ['artifacts.read', 'workspace.read'],
47
+ } as const);
48
+
49
+ const input = gezel.input as InferredInput<typeof meta>;
50
+
51
+ function cleanArtifactPath(raw: unknown, label: string): string {
52
+ const value = String(raw ?? '')
53
+ .replace(/\\+/g, '/')
54
+ .replace(/^\.?\/+/, '')
55
+ .replace(/^artifacts\/+/i, '')
56
+ .trim();
57
+ if (!value) throw new Error(`${label} must be a non-empty artifact path.`);
58
+ if (value.includes('{{')) {
59
+ throw new Error(`${label} still contains an uninterpolated placeholder: ${value}`);
60
+ }
61
+ return value;
62
+ }
63
+
64
+ const reportFile = cleanArtifactPath(input.file, 'file');
65
+ const findingsFile = cleanArtifactPath(input.findings, 'findings');
66
+
67
+ // The deliverables live in the artifacts drawer; the files they cite live in
68
+ // the workspace. Two surfaces, one check — `workspaceFromGezel` covers the
69
+ // citation side, and the drawer side only ever needs `read`.
70
+ const drawer = {
71
+ read: async (file: string) => {
72
+ try {
73
+ return await gezel.artifacts.read(file);
74
+ } catch {
75
+ return null;
76
+ }
77
+ },
78
+ list: async () => [],
79
+ };
80
+
81
+ const r = await codebaseReviewReport(drawer, workspaceFromGezel(gezel), reportFile, {
82
+ findings: findingsFile,
83
+ minThemes: input.minThemes,
84
+ themeThreshold: input.themeThreshold,
85
+ minScorecardRows: input.minScorecardRows,
86
+ });
87
+ gezel.output(gateResult(r.ok, r.detail));
@@ -0,0 +1,93 @@
1
+ import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
2
+ import { gateResult, mergeCorpusCoverageShards } from '@bendyline/gezel-sdk/checks';
3
+
4
+ export const meta = defineScript({
5
+ name: 'checkCorpusCoverageProvenance',
6
+ description:
7
+ 'Gate: every published corpus batch has one exact coverage-N.json shard, and the merged run ledger is byte-semantically identical to the deterministic union of those shards. Prevents a parent from inventing coverage for missing child work.',
8
+ kind: 'gate',
9
+ inputs: {
10
+ batchesFile: {
11
+ type: 'string',
12
+ description: 'Artifact path of the runtime-published batch array.',
13
+ required: true,
14
+ },
15
+ shardDir: {
16
+ type: 'string',
17
+ description: 'Artifact directory containing coverage-N.json shards.',
18
+ required: true,
19
+ },
20
+ ledgerFile: {
21
+ type: 'string',
22
+ description: 'Artifact path of the merged run ledger to verify.',
23
+ required: true,
24
+ },
25
+ pullRequest: { type: 'string', description: 'Expected pull request number in the ledger.' },
26
+ },
27
+ outputs: {
28
+ decision: { type: 'string', description: "'approve' or 'reject'." },
29
+ message: { type: 'string', description: 'What passed, or the concrete provenance gap.' },
30
+ },
31
+ requires: ['artifacts.read'],
32
+ } as const);
33
+
34
+ const input = gezel.input as InferredInput<typeof meta>;
35
+
36
+ function cleanPath(raw: string, label: string): string {
37
+ const value = raw
38
+ .replace(/\\+/g, '/')
39
+ .replace(/^\.?\/+/, '')
40
+ .replace(/^artifacts\/+/i, '')
41
+ .replace(/\/+$/, '')
42
+ .trim();
43
+ if (!value || value.split('/').includes('..')) {
44
+ throw new Error(`${label} must be a safe artifact-relative path.`);
45
+ }
46
+ return value;
47
+ }
48
+
49
+ const batchesFile = cleanPath(input.batchesFile, 'batchesFile');
50
+ const shardDir = cleanPath(input.shardDir, 'shardDir');
51
+ const ledgerFile = cleanPath(input.ledgerFile, 'ledgerFile');
52
+ const pullRequest = input.pullRequest === undefined ? undefined : Number(input.pullRequest);
53
+ if (pullRequest !== undefined && (!Number.isInteger(pullRequest) || pullRequest < 1)) {
54
+ throw new Error('pullRequest must be a positive integer when supplied.');
55
+ }
56
+ const batchesContent = await gezel.artifacts.read(batchesFile).catch(() => null);
57
+ if (batchesContent === null) {
58
+ gezel.output(gateResult(false, `${batchesFile} is missing; provenance cannot be verified.`));
59
+ } else {
60
+ const entries = await gezel.artifacts.list(shardDir, { recursive: true }).catch(() => []);
61
+ const shards = await Promise.all(
62
+ entries
63
+ .map((entry) => entry.path.replace(/\\+/g, '/'))
64
+ .filter((path) => /(?:^|\/)coverage-\d+\.json$/.test(path))
65
+ .sort()
66
+ .map(async (path) => ({ path, content: await gezel.artifacts.read(path) })),
67
+ );
68
+ const merged = mergeCorpusCoverageShards(batchesContent, shards, {
69
+ ...(pullRequest !== undefined ? { pullRequest } : {}),
70
+ requireComplete: true,
71
+ batchesFile,
72
+ });
73
+ if (!merged.ok || !merged.ledger) {
74
+ gezel.output(gateResult(false, merged.detail));
75
+ } else {
76
+ const ledgerContent = await gezel.artifacts.read(ledgerFile).catch(() => null);
77
+ let actual: unknown = null;
78
+ try {
79
+ actual = ledgerContent === null ? null : JSON.parse(ledgerContent);
80
+ } catch {
81
+ actual = null;
82
+ }
83
+ const matches = JSON.stringify(actual) === JSON.stringify(merged.ledger);
84
+ gezel.output(
85
+ gateResult(
86
+ matches,
87
+ matches
88
+ ? merged.detail
89
+ : `${ledgerFile} is not the deterministic union of the validated coverage shards. Do not add paths by hand; let mergeCorpusCoverage rebuild it on the next activation.`,
90
+ ),
91
+ );
92
+ }
93
+ }
@@ -0,0 +1,255 @@
1
+ import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
2
+ import { gateResult } from '@bendyline/gezel-sdk/checks';
3
+
4
+ /**
5
+ * Fix-review gate (the enforceable `evaluate` step of the tactical fleet):
6
+ * the reviewer's artifact at `<task.dir>/review.md` is well-formed and its
7
+ * verdict actually routes the loop. `Verdict: PASS` advances; a well-formed
8
+ * `Verdict: REVISE` rejects WITH `goto` back to the fix step, carrying the
9
+ * findings as the prescriptive message; a malformed report rejects in place
10
+ * so the reviewer repairs the report rather than the fixer thrashing.
11
+ *
12
+ * Anti-fabrication: every file the review cites must exist — probed by
13
+ * reading each path (workspace, the task's diffpack overlay when drafting,
14
+ * or the artifacts drawer), never by trusting a listing (listings truncate
15
+ * and skip dotfiles; see core/checks/workspace-exists.ts).
16
+ */
17
+ export const meta = defineScript({
18
+ name: 'checkFixReview',
19
+ description:
20
+ 'Gate: a fix/improvement review artifact is well-formed — a `Verdict: PASS` or `Verdict: REVISE` line, severities from critical/major/minor/nit, every cited file exists (workspace, draft overlay, or artifacts), critical/major findings force REVISE — and a REVISE verdict routes the task back to the fix step with the findings as the message.',
21
+ kind: 'gate',
22
+ inputs: {
23
+ taskRef: {
24
+ type: 'string',
25
+ description: 'The task under review (auto-filled by the runtime when this gate runs).',
26
+ },
27
+ reviewPath: {
28
+ type: 'string',
29
+ description:
30
+ "Review artifact path in the artifacts drawer. Defaults to '<task.dir>/review.md'.",
31
+ },
32
+ findingsPath: {
33
+ type: 'string',
34
+ description:
35
+ 'Optional machine-readable findings JSON (artifacts drawer). When present, its entries must agree with the findings table.',
36
+ },
37
+ fixStepId: {
38
+ type: 'string',
39
+ description: "Step to route a REVISE verdict back to. Defaults to 'fix'.",
40
+ },
41
+ },
42
+ outputs: {
43
+ decision: { type: 'string', description: "'approve' or 'reject'." },
44
+ message: { type: 'string', description: 'What passed, or the concrete gaps / findings.' },
45
+ // `goto` (the fix step to re-activate on a well-formed REVISE) is
46
+ // deliberately NOT declared: every declared output field is REQUIRED by
47
+ // the runner's coerceOutput, and the approve path emits no goto — the
48
+ // first PASS verdict in the wild paused the task with `output is
49
+ // missing declared field "goto"`. Undeclared fields pass through to the
50
+ // GateScriptResult parse untouched.
51
+ },
52
+ requires: ['tasks.read', 'artifacts.read', 'workspace.read'],
53
+ } as const);
54
+
55
+ const SEVERITIES = new Set(['critical', 'major', 'minor', 'nit']);
56
+
57
+ interface TaskView {
58
+ num?: number;
59
+ artifactDir?: string;
60
+ diffpackId?: string;
61
+ }
62
+
63
+ const input = gezel.input as InferredInput<typeof meta>;
64
+
65
+ /** Strip citation decoration so `./src/x.ts`, `a/src/x.ts`, `src/x.ts` compare equal. */
66
+ function normPath(p: string): string {
67
+ return p
68
+ .trim()
69
+ .replace(/^`|`$/g, '')
70
+ .replace(/^\.\//, '')
71
+ .replace(/^[ab]\//, '')
72
+ .replace(/\\/g, '/');
73
+ }
74
+
75
+ const task = (await gezel.task.get(input.taskRef ?? '').catch(() => null)) as TaskView | null;
76
+ const taskDir = task?.artifactDir ?? (task?.num !== undefined ? `tasks/${task.num}` : undefined);
77
+ const reviewPath = input.reviewPath ?? (taskDir ? `${taskDir}/review.md` : undefined);
78
+ const fixStepId = input.fixStepId ?? 'fix';
79
+
80
+ /**
81
+ * A cited path exists when it reads from ANY surface the review may talk
82
+ * about: the live workspace, this task's diffpack draft overlay (a drafting
83
+ * run's fix exists only there), or the artifacts drawer (repro/validation
84
+ * notes). A bare sibling name additionally resolves relative to the
85
+ * review's own folder — a reviewer naturally writes "see `fix-notes.md`"
86
+ * for the evidence doc beside the review, and rejecting that as a
87
+ * fabricated path failed a flawless PASS verdict (wild-caught, trial 5).
88
+ * Read-probes, never listings.
89
+ */
90
+ async function citedPathExists(path: string, reviewDir: string): Promise<boolean> {
91
+ if ((await gezel.fs.read(path).catch(() => null)) !== null) return true;
92
+ if (task?.diffpackId) {
93
+ const drafted = await gezel.artifacts
94
+ .read(`diffpacks/${task.diffpackId}/after/${path}`)
95
+ .catch(() => null);
96
+ if (drafted !== null) return true;
97
+ }
98
+ if ((await gezel.artifacts.read(path).catch(() => null)) !== null) return true;
99
+ if (!path.includes('/') && reviewDir) {
100
+ if ((await gezel.artifacts.read(`${reviewDir}/${path}`).catch(() => null)) !== null) {
101
+ return true;
102
+ }
103
+ }
104
+ return false;
105
+ }
106
+
107
+ if (!reviewPath) {
108
+ gezel.output(
109
+ gateResult(
110
+ false,
111
+ 'This gate could not resolve the review artifact path — pass `reviewPath` explicitly (usually `{{task.dir}}/review.md`).',
112
+ ),
113
+ );
114
+ } else {
115
+ const report = await gezel.artifacts.read(reviewPath).catch(() => null);
116
+ if (report === null) {
117
+ gezel.output(
118
+ gateResult(
119
+ false,
120
+ `The review has not been written yet — write it to the artifact ${reviewPath} with one write_artifact call, ending with a \`Verdict: PASS\` or \`Verdict: REVISE\` line.`,
121
+ ),
122
+ );
123
+ } else {
124
+ const gaps: string[] = [];
125
+ const verdictMatch = /Verdict:\s*(PASS|REVISE)\b/i.exec(report);
126
+ if (!verdictMatch) {
127
+ gaps.push(
128
+ 'the review must end with a `Verdict: PASS` or `Verdict: REVISE` line (exactly one of those two words)',
129
+ );
130
+ }
131
+
132
+ // Findings table (optional on PASS, expected on REVISE): header row with
133
+ // Severity + File columns, walked for vocabulary + citations.
134
+ const lines = report.split('\n');
135
+ const headerIdx = lines.findIndex((l) => /^\s*\|/.test(l) && /\|\s*Severity\s*\|/i.test(l));
136
+ const rows: { severity: string; file: string; problem: string; fix: string; line: number }[] =
137
+ [];
138
+ if (headerIdx >= 0) {
139
+ const headers = lines[headerIdx]!.split('|').map((c) => c.trim().toLowerCase());
140
+ const sevCol = headers.indexOf('severity');
141
+ const fileCol = headers.indexOf('file');
142
+ const problemCol = headers.findIndex((h) => h === 'problem' || h === 'finding');
143
+ const fixCol = headers.findIndex((h) => h === 'fix' || h === 'recommendation');
144
+ for (let i = headerIdx + 1; i < lines.length; i++) {
145
+ const line = lines[i]!;
146
+ if (!/^\s*\|/.test(line)) break;
147
+ if (/^\s*\|[\s|:-]+\|\s*$/.test(line)) continue;
148
+ const cells = line.split('|').map((c) => c.trim());
149
+ rows.push({
150
+ severity: (cells[sevCol] ?? '').toLowerCase(),
151
+ file: cells[fileCol] ?? '',
152
+ problem: problemCol >= 0 ? (cells[problemCol] ?? '') : '',
153
+ fix: fixCol >= 0 ? (cells[fixCol] ?? '') : '',
154
+ line: i + 1,
155
+ });
156
+ }
157
+ }
158
+
159
+ const badSeverities = rows.filter((r) => r.severity !== '' && !SEVERITIES.has(r.severity));
160
+ if (badSeverities.length > 0) {
161
+ gaps.push(
162
+ `severity must be one of critical/major/minor/nit — fix: ${badSeverities
163
+ .map((r) => `"${r.severity}" (review line ${r.line})`)
164
+ .join(', ')}`,
165
+ );
166
+ }
167
+
168
+ // Citation floor: every File cell and every backtick path:line citation
169
+ // must resolve somewhere real.
170
+ const cited = new Set<string>();
171
+ for (const r of rows) {
172
+ const cell = normPath(r.file.replace(/:\d+(-\d+)?$/, ''));
173
+ if (cell && cell !== '-' && cell !== '—') cited.add(cell);
174
+ }
175
+ for (const m of report.matchAll(/`([^`\s]+?\.[A-Za-z0-9]{1,8})(?::\d+(?:-\d+)?)?`/g)) {
176
+ const p = m[1];
177
+ if (p) cited.add(normPath(p));
178
+ }
179
+ const reviewDir = reviewPath.includes('/')
180
+ ? reviewPath.slice(0, reviewPath.lastIndexOf('/'))
181
+ : '';
182
+ const unresolved: string[] = [];
183
+ for (const p of cited) {
184
+ if (!(await citedPathExists(p, reviewDir))) unresolved.push(p);
185
+ }
186
+ if (unresolved.length > 0) {
187
+ gaps.push(
188
+ `these cited files do not exist in the workspace, this task's change proposal, or the artifacts drawer (cite real paths exactly): ${unresolved.join(', ')}`,
189
+ );
190
+ }
191
+
192
+ // Optional machine handoff: the findings JSON a fix step consumes must
193
+ // agree with the table the human reads.
194
+ if (input.findingsPath) {
195
+ const findingsRaw = await gezel.artifacts.read(input.findingsPath).catch(() => null);
196
+ if (findingsRaw === null) {
197
+ gaps.push(
198
+ `the findings JSON is missing — write the same findings as a JSON array to the artifact ${input.findingsPath}`,
199
+ );
200
+ } else {
201
+ try {
202
+ const parsed = JSON.parse(findingsRaw) as unknown;
203
+ if (!Array.isArray(parsed)) {
204
+ gaps.push(`${input.findingsPath} must be a JSON ARRAY of finding objects`);
205
+ } else if (headerIdx >= 0 && parsed.length !== rows.length) {
206
+ gaps.push(
207
+ `${input.findingsPath} lists ${parsed.length} finding(s) but the review table has ${rows.length} — they must agree row for row`,
208
+ );
209
+ }
210
+ } catch {
211
+ gaps.push(`${input.findingsPath} is not valid JSON`);
212
+ }
213
+ }
214
+ }
215
+
216
+ const verdict = verdictMatch?.[1]?.toUpperCase();
217
+ const blocking = rows.filter((r) => r.severity === 'critical' || r.severity === 'major');
218
+ if (verdict === 'PASS' && blocking.length > 0) {
219
+ gaps.push(
220
+ `the verdict says PASS but ${blocking.length} critical/major finding(s) are listed (line(s) ${blocking
221
+ .map((r) => r.line)
222
+ .join(', ')}) — either downgrade them with justification or change the verdict to REVISE`,
223
+ );
224
+ }
225
+ if (verdict === 'REVISE' && rows.length === 0) {
226
+ gaps.push(
227
+ 'the verdict says REVISE but the findings table names nothing to fix — a fixer cannot act on an empty revision request; list the concrete findings',
228
+ );
229
+ }
230
+
231
+ if (gaps.length > 0) {
232
+ gezel.output(gateResult(false, `The review is not ready — ${gaps.join('; ')}.`));
233
+ } else if (verdict === 'REVISE') {
234
+ const summary = rows
235
+ .slice(0, 6)
236
+ .map(
237
+ (r) =>
238
+ `- [${r.severity || 'finding'}] ${r.file}${r.problem ? ` — ${r.problem}` : ''}${r.fix ? ` → ${r.fix}` : ''}`,
239
+ )
240
+ .join('\n');
241
+ gezel.output({
242
+ decision: 'reject',
243
+ goto: fixStepId,
244
+ message: `Reviewer verdict: REVISE. Address these findings, then bring the work back through review:\n${summary}${rows.length > 6 ? `\n…and ${rows.length - 6} more in ${reviewPath}.` : ''}`,
245
+ });
246
+ } else {
247
+ gezel.output(
248
+ gateResult(
249
+ true,
250
+ `review ${reviewPath} is well-formed: verdict PASS, ${rows.length} finding(s), ${cited.size} cited path(s) all real`,
251
+ ),
252
+ );
253
+ }
254
+ }
255
+ }
@@ -0,0 +1,102 @@
1
+ import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
2
+
3
+ /**
4
+ * Make the project's index as fresh as it can get, then publish the honest
5
+ * readiness snapshot as an artifact — the ENSURE half of "this craftbook
6
+ * depends on a current index".
7
+ *
8
+ * Meant as an `onEnter` hook on a review craftbook's first step: the
9
+ * runtime re-scans the static index, drives the AI tiers (embed, shadows,
10
+ * summaries, per-file reviews) with a bounded awake-time wait, and lands
11
+ * the resulting report at `outFile` before the model's first turn. The
12
+ * report separates what IS current from what CAN become current — on a
13
+ * crew with no Boekwachter the AI-review counts can never drain, and a
14
+ * review that waited on them would hang forever. The consuming step reads
15
+ * the artifact and cites its coverage numbers and caveats instead of
16
+ * assuming the index is complete.
17
+ *
18
+ * Never rejects for ordinary states (unstaffed crew, paused job, expired
19
+ * budget): those are recorded in the report's `notes`. A throw here means
20
+ * infrastructure — and step hooks are logged-and-swallowed, so the
21
+ * consuming prompt must treat a missing artifact as "freshness unknown",
22
+ * not as permission to invent coverage.
23
+ */
24
+
25
+ export const meta = defineScript({
26
+ name: 'ensureIndexFresh',
27
+ description:
28
+ "Action: bring the project's static + AI index as up to date as it can get within an awake-time budget, then publish the readiness snapshot (coverage counts, achievable tiers, caveats) as a JSON artifact for the consuming step to cite.",
29
+ kind: 'action',
30
+ inputs: {
31
+ outFile: {
32
+ type: 'string',
33
+ description:
34
+ 'Artifact path to write the readiness report to (e.g. {{workPath}}/review/index-readiness.json).',
35
+ required: true,
36
+ },
37
+ waitBudgetSeconds: {
38
+ type: 'number',
39
+ description:
40
+ 'Awake-time budget to wait for the AI tiers, in seconds (default 180, capped service-side below the script run timeout). 0 = refresh the static index and snapshot without waiting.',
41
+ integer: true,
42
+ min: 0,
43
+ },
44
+ reviews: {
45
+ type: 'boolean',
46
+ description: 'Also wait for the per-file AI review tier (default true).',
47
+ },
48
+ },
49
+ outputs: {
50
+ ok: { type: 'boolean', description: 'True when the report artifact was written.' },
51
+ outFile: { type: 'string', description: 'Artifact path that was written.' },
52
+ staticState: { type: 'string', description: 'Structural index state after the ensure pass.' },
53
+ drained: {
54
+ type: 'boolean',
55
+ description: 'Every achievable index tier drained inside the budget.',
56
+ },
57
+ aiAchievable: {
58
+ type: 'boolean',
59
+ description: 'The AI tiers can progress at all (staffed, enabled, not paused).',
60
+ },
61
+ notes: { type: 'number', description: 'Number of coverage caveats recorded in the report.' },
62
+ },
63
+ requires: ['index.refresh', 'artifacts.write'],
64
+ } as const);
65
+
66
+ const input = gezel.input as InferredInput<typeof meta>;
67
+
68
+ function fail(message: string): never {
69
+ throw new Error(message);
70
+ }
71
+
72
+ const outFile = String(input.outFile ?? '')
73
+ .replace(/\\+/g, '/')
74
+ .replace(/^\.?\/+/, '')
75
+ .replace(/^artifacts\/+/i, '')
76
+ .trim();
77
+ if (!outFile) fail('outFile must be a non-empty artifact-relative path.');
78
+ if (outFile.split('/').includes('..')) fail("outFile must not contain '..' segments.");
79
+ // An uninterpolated placeholder means the craftbook's param wiring is broken;
80
+ // writing a `{{workPath}}/…` literal would strand the artifact where no gate
81
+ // or reader will ever look.
82
+ if (outFile.includes('{{')) {
83
+ fail(`outFile still contains an uninterpolated placeholder: ${outFile}`);
84
+ }
85
+
86
+ const report = await gezel.index.ensureFresh({
87
+ ...(typeof input.waitBudgetSeconds === 'number'
88
+ ? { waitBudgetMs: input.waitBudgetSeconds * 1000 }
89
+ : {}),
90
+ ...(typeof input.reviews === 'boolean' ? { reviews: input.reviews } : {}),
91
+ });
92
+
93
+ await gezel.artifacts.write(outFile, `${JSON.stringify(report, null, 2)}\n`);
94
+
95
+ gezel.output({
96
+ ok: true,
97
+ outFile,
98
+ staticState: report.staticState,
99
+ drained: report.wait.drained,
100
+ aiAchievable: report.aiTier.achievable,
101
+ notes: report.notes.length,
102
+ });
@@ -0,0 +1,83 @@
1
+ import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
2
+ import { mergeCorpusCoverageShards } from '@bendyline/gezel-sdk/checks';
3
+
4
+ export const meta = defineScript({
5
+ name: 'mergeCorpusCoverage',
6
+ description:
7
+ 'Action: deterministically merge the coverage-N.json shards that exactly match their published corpus batches into one provenance-stamped run ledger. Missing shards produce an in-progress ledger; malformed or out-of-batch shards fail closed.',
8
+ kind: 'action',
9
+ inputs: {
10
+ batchesFile: {
11
+ type: 'string',
12
+ description: 'Artifact path of the runtime-published batch array.',
13
+ required: true,
14
+ },
15
+ shardDir: {
16
+ type: 'string',
17
+ description: 'Artifact directory containing coverage-N.json shards.',
18
+ required: true,
19
+ },
20
+ outFile: {
21
+ type: 'string',
22
+ description: 'Artifact path for the deterministic merged ledger.',
23
+ required: true,
24
+ },
25
+ pullRequest: { type: 'string', description: 'Pull request number to stamp in the ledger.' },
26
+ },
27
+ outputs: {
28
+ ok: { type: 'boolean', description: 'True when a valid ledger was written.' },
29
+ outFile: { type: 'string', description: 'Artifact path written.' },
30
+ expectedBatches: { type: 'number', description: 'Published batch count.' },
31
+ mergedBatches: { type: 'number', description: 'Validated shard count merged.' },
32
+ missingBatches: { type: 'json', description: 'Batch numbers still missing.' },
33
+ complete: { type: 'boolean', description: 'True when every batch shard was present.' },
34
+ },
35
+ requires: ['artifacts.read', 'artifacts.write'],
36
+ } as const);
37
+
38
+ const input = gezel.input as InferredInput<typeof meta>;
39
+
40
+ function cleanPath(raw: string, label: string): string {
41
+ const value = raw
42
+ .replace(/\\+/g, '/')
43
+ .replace(/^\.?\/+/, '')
44
+ .replace(/^artifacts\/+/i, '')
45
+ .replace(/\/+$/, '')
46
+ .trim();
47
+ if (!value || value.split('/').includes('..')) {
48
+ throw new Error(`${label} must be a safe artifact-relative path.`);
49
+ }
50
+ return value;
51
+ }
52
+
53
+ const batchesFile = cleanPath(input.batchesFile, 'batchesFile');
54
+ const shardDir = cleanPath(input.shardDir, 'shardDir');
55
+ const outFile = cleanPath(input.outFile, 'outFile');
56
+ const pullRequest = input.pullRequest === undefined ? undefined : Number(input.pullRequest);
57
+ if (pullRequest !== undefined && (!Number.isInteger(pullRequest) || pullRequest < 1)) {
58
+ throw new Error('pullRequest must be a positive integer when supplied.');
59
+ }
60
+ const batchesContent = await gezel.artifacts.read(batchesFile);
61
+ const entries = await gezel.artifacts.list(shardDir, { recursive: true });
62
+ const shards = await Promise.all(
63
+ entries
64
+ .map((entry) => entry.path.replace(/\\+/g, '/'))
65
+ .filter((path) => /(?:^|\/)coverage-\d+\.json$/.test(path))
66
+ .sort()
67
+ .map(async (path) => ({ path, content: await gezel.artifacts.read(path) })),
68
+ );
69
+ const merged = mergeCorpusCoverageShards(batchesContent, shards, {
70
+ ...(pullRequest !== undefined ? { pullRequest } : {}),
71
+ batchesFile,
72
+ });
73
+ if (!merged.ok || !merged.content || !merged.ledger) throw new Error(merged.detail);
74
+
75
+ await gezel.artifacts.write(outFile, merged.content);
76
+ gezel.output({
77
+ ok: true,
78
+ outFile,
79
+ expectedBatches: merged.expectedBatches,
80
+ mergedBatches: merged.mergedBatches,
81
+ missingBatches: merged.missingBatches,
82
+ complete: merged.ledger.complete,
83
+ });
@@ -1,14 +1,15 @@
1
1
  import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
2
2
 
3
3
  /**
4
- * Publish a connector corpus's own batch manifest as a fanout input artifact.
4
+ * Publish a connector corpus's batch manifest as a fanout input artifact,
5
+ * enriched with the exact current artifact record paths for every batch.
5
6
  *
6
7
  * A declarative fanout reads `spawn.overFile` — a JSON array, one entry per
7
8
  * child. When the corpus already ships that array (the `github-pulls`
8
9
  * connector writes deterministic 25-file batches into its manifest), asking a
9
- * model to retype it is pure loss: the paths are the gate keys for every child
10
- * reviewer, and token emission is the wrong transport for data that already
11
- * exists on disk.
10
+ * model to retype it is pure loss: the paths and record identities are the gate
11
+ * keys for every child reviewer, and token emission is the wrong transport for
12
+ * data that already exists on disk.
12
13
  *
13
14
  * Wild-caught on a 509-file pull request. The batch array is 25 KB — roughly
14
15
  * 7.3k tokens of arguments — against a 6144-token per-turn cap, so the write
@@ -25,7 +26,7 @@ import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
25
26
  export const meta = defineScript({
26
27
  name: 'publishCorpusBatches',
27
28
  description:
28
- "Action: copy a connector corpus manifest's batch array into a fanout-input artifact, verbatim, with completeness checks against the manifest's own file total.",
29
+ "Action: publish a connector corpus manifest's batch array into a fanout-input artifact, adding exact record paths from the writer identity sidecar and checking completeness against the manifest's own file total.",
29
30
  kind: 'action',
30
31
  inputs: {
31
32
  corpusDir: {
@@ -61,6 +62,10 @@ export const meta = defineScript({
61
62
  outFile: { type: 'string', description: 'Artifact path that was written.' },
62
63
  batches: { type: 'number', description: 'Number of batch entries published.' },
63
64
  paths: { type: 'number', description: 'Total distinct paths across every batch.' },
65
+ records: {
66
+ type: 'number',
67
+ description: 'Total exact per-file artifact record paths attached to the batches.',
68
+ },
64
69
  bytes: { type: 'number', description: 'Size of the written artifact in bytes.' },
65
70
  },
66
71
  requires: ['artifacts.read', 'artifacts.write'],
@@ -93,7 +98,11 @@ const manifestSuffix = String(input.manifestSuffix ?? '-files.json');
93
98
  const itemsField = String(input.itemsField ?? 'batches');
94
99
  const totalField = input.totalField === undefined ? 'totalFiles' : String(input.totalField);
95
100
 
96
- const entries = await gezel.artifacts.list(corpusDir, { recursive: true });
101
+ // The changed-file directory can hold thousands of records, while a recursive
102
+ // artifact listing is deliberately bounded. Manifests are small overview
103
+ // attachments, so search only that subtree and never enumerate the corpus.
104
+ const manifestDir = `${corpusDir}/attachments`;
105
+ const entries = await gezel.artifacts.list(manifestDir, { recursive: true }).catch(() => []);
97
106
  const candidates = entries
98
107
  .map((entry) => entry.path.replace(/\\+/g, '/'))
99
108
  .filter((path) => path.endsWith(manifestSuffix))
@@ -136,6 +145,7 @@ interface Batch {
136
145
  start: number;
137
146
  end: number;
138
147
  paths: string[];
148
+ records: string[];
139
149
  }
140
150
 
141
151
  function isPositiveInt(value: unknown): value is number {
@@ -143,7 +153,7 @@ function isPositiveInt(value: unknown): value is number {
143
153
  }
144
154
 
145
155
  const seenPaths = new Set<string>();
146
- const batches: Batch[] = itemsRaw.map((item, index) => {
156
+ const parsedBatches: Omit<Batch, 'records'>[] = itemsRaw.map((item, index) => {
147
157
  const where = `${itemsField}[${index}] of artifacts/${manifestPath}`;
148
158
  if (typeof item !== 'object' || item === null || Array.isArray(item)) {
149
159
  fail(`${where} is not an object.`);
@@ -201,6 +211,80 @@ if (totalField !== '') {
201
211
  }
202
212
  }
203
213
 
214
+ // Join manifest paths to the writer-owned filenames without listing the
215
+ // `files/` directory. `_flags.json` is a compact identity sidecar keyed by the
216
+ // stable record hash; unlike an ordinal reconstructed from manifest order, it
217
+ // stays correct when a PR refresh reorders, adds, or removes changed paths.
218
+ const filesRaw = manifestFields.files;
219
+ if (!Array.isArray(filesRaw) || filesRaw.length !== seenPaths.size) {
220
+ fail(
221
+ `artifacts/${manifestPath} must carry one files[] identity for each of its ${seenPaths.size} distinct batch paths.`,
222
+ );
223
+ }
224
+ const recordHashByPath = new Map<string, string>();
225
+ for (let index = 0; index < filesRaw.length; index += 1) {
226
+ const where = `files[${index}] of artifacts/${manifestPath}`;
227
+ const item = filesRaw[index];
228
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
229
+ fail(`${where} is not an object.`);
230
+ }
231
+ const fields = item as Record<string, unknown>;
232
+ const path = fields.path;
233
+ const recordHash = fields.recordHash;
234
+ if (typeof path !== 'string' || !seenPaths.has(path)) {
235
+ fail(`${where} has no path claimed by the published batches.`);
236
+ }
237
+ if (typeof recordHash !== 'string' || !/^[0-9a-f]{8}$/.test(recordHash)) {
238
+ fail(`${where} has no eight-character lowercase recordHash.`);
239
+ }
240
+ if (recordHashByPath.has(path)) fail(`${where} repeats the manifest path '${path}'.`);
241
+ recordHashByPath.set(path, recordHash);
242
+ }
243
+
244
+ const sidecarPath = `${corpusDir}/files/_flags.json`;
245
+ const sidecarRaw = await gezel.artifacts.read(sidecarPath).catch(() => null);
246
+ if (sidecarRaw === null) {
247
+ fail(
248
+ `artifacts/${sidecarPath} is missing. Re-sync the pull-request corpus with this Gezel version before launching the review.`,
249
+ );
250
+ }
251
+ let sidecar: unknown;
252
+ try {
253
+ sidecar = JSON.parse(sidecarRaw);
254
+ } catch (err) {
255
+ fail(
256
+ `artifacts/${sidecarPath} is not valid JSON (${err instanceof Error ? err.message : String(err)}).`,
257
+ );
258
+ }
259
+ if (typeof sidecar !== 'object' || sidecar === null || Array.isArray(sidecar)) {
260
+ fail(`artifacts/${sidecarPath} must contain a JSON object.`);
261
+ }
262
+ const sidecarFields = sidecar as Record<string, unknown>;
263
+ const recordsByPath = new Map<string, string>();
264
+ for (const [path, recordHash] of recordHashByPath) {
265
+ const identity = sidecarFields[recordHash];
266
+ const file =
267
+ typeof identity === 'object' && identity !== null && !Array.isArray(identity)
268
+ ? (identity as Record<string, unknown>).file
269
+ : undefined;
270
+ if (
271
+ typeof file !== 'string' ||
272
+ file.includes('/') ||
273
+ file.includes('\\') ||
274
+ !file.endsWith(`--${recordHash}.md`)
275
+ ) {
276
+ fail(
277
+ `artifacts/${sidecarPath} has no valid current filename for '${path}' (${recordHash}). Re-sync the corpus before reviewing it.`,
278
+ );
279
+ }
280
+ recordsByPath.set(path, `${corpusDir}/files/${file}`);
281
+ }
282
+
283
+ const batches: Batch[] = parsedBatches.map((batch) => ({
284
+ ...batch,
285
+ records: batch.paths.map((path) => recordsByPath.get(path)!),
286
+ }));
287
+
204
288
  const content = `${JSON.stringify(batches, null, 2)}\n`;
205
289
  await gezel.artifacts.write(outFile, content);
206
290
 
@@ -210,5 +294,6 @@ gezel.output({
210
294
  outFile,
211
295
  batches: batches.length,
212
296
  paths: seenPaths.size,
297
+ records: recordsByPath.size,
213
298
  bytes: content.length,
214
299
  });