@bendyline/gezel-script-stdlib 1.0.4 → 1.0.6

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.4",
3
+ "version": "1.0.6",
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.4"
44
+ "@bendyline/gezel-sdk": "1.0.6"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "^24.13.3",
@@ -0,0 +1,214 @@
1
+ import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
2
+
3
+ /**
4
+ * Publish a connector corpus's own batch manifest as a fanout input artifact.
5
+ *
6
+ * A declarative fanout reads `spawn.overFile` — a JSON array, one entry per
7
+ * child. When the corpus already ships that array (the `github-pulls`
8
+ * 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.
12
+ *
13
+ * Wild-caught on a 509-file pull request. The batch array is 25 KB — roughly
14
+ * 7.3k tokens of arguments — against a 6144-token per-turn cap, so the write
15
+ * was arithmetically impossible. Two cap-length attempts were rejected, a
16
+ * third landed valid-but-truncated JSON holding 10 of 21 batches, and the
17
+ * scope gate (json-valid + minBytes) passed it: 259 changed files would have
18
+ * been dropped from the review with no signal until the downstream merge gate
19
+ * deadlocked. Running this instead costs no model tokens and cannot truncate.
20
+ *
21
+ * Validation is deliberately strict and fails loudly — a batch file that is
22
+ * quietly wrong produces gates no child reviewer can ever pass.
23
+ */
24
+
25
+ export const meta = defineScript({
26
+ name: 'publishCorpusBatches',
27
+ 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
+ kind: 'action',
30
+ inputs: {
31
+ corpusDir: {
32
+ type: 'string',
33
+ description:
34
+ 'Artifact-relative directory the connector mirrored the corpus into (e.g. data/github-pull-requests/pr-33).',
35
+ required: true,
36
+ },
37
+ outFile: {
38
+ type: 'string',
39
+ description:
40
+ "Artifact path to write the batch array to. Must match the craftbook's `spawn.overFile`.",
41
+ required: true,
42
+ },
43
+ manifestSuffix: {
44
+ type: 'string',
45
+ description:
46
+ 'Filename suffix identifying the manifest inside the corpus (default: -files.json).',
47
+ },
48
+ itemsField: {
49
+ type: 'string',
50
+ description: 'Manifest field holding the batch array (default: batches).',
51
+ },
52
+ totalField: {
53
+ type: 'string',
54
+ description:
55
+ 'Manifest field holding the expected total item count the batches must cover (default: totalFiles). Set empty to skip the total cross-check.',
56
+ },
57
+ },
58
+ outputs: {
59
+ ok: { type: 'boolean', description: 'True when the artifact was written; failures throw.' },
60
+ manifest: { type: 'string', description: 'Artifact path of the manifest that was read.' },
61
+ outFile: { type: 'string', description: 'Artifact path that was written.' },
62
+ batches: { type: 'number', description: 'Number of batch entries published.' },
63
+ paths: { type: 'number', description: 'Total distinct paths across every batch.' },
64
+ bytes: { type: 'number', description: 'Size of the written artifact in bytes.' },
65
+ },
66
+ requires: ['artifacts.read', 'artifacts.write'],
67
+ } as const);
68
+
69
+ const input = gezel.input as InferredInput<typeof meta>;
70
+
71
+ function fail(message: string): never {
72
+ throw new Error(message);
73
+ }
74
+
75
+ function cleanPath(raw: unknown, label: string): string {
76
+ // A craftbook's `corpusScope` param is authored as `artifacts/data/...` for
77
+ // the model-facing prose; the drawer API is already scoped there, so the
78
+ // redundant prefix is stripped here exactly as read/write strip it.
79
+ const value = String(raw ?? '')
80
+ .replace(/\\+/g, '/')
81
+ .replace(/^\.?\/+/, '')
82
+ .replace(/^artifacts\/+/i, '')
83
+ .replace(/\/+$/, '')
84
+ .trim();
85
+ if (!value) fail(`${label} must be a non-empty artifact-relative path.`);
86
+ if (value.split('/').includes('..')) fail(`${label} must not contain '..' segments.`);
87
+ return value;
88
+ }
89
+
90
+ const corpusDir = cleanPath(input.corpusDir, 'corpusDir');
91
+ const outFile = cleanPath(input.outFile, 'outFile');
92
+ const manifestSuffix = String(input.manifestSuffix ?? '-files.json');
93
+ const itemsField = String(input.itemsField ?? 'batches');
94
+ const totalField = input.totalField === undefined ? 'totalFiles' : String(input.totalField);
95
+
96
+ const entries = await gezel.artifacts.list(corpusDir, { recursive: true });
97
+ const candidates = entries
98
+ .map((entry) => entry.path.replace(/\\+/g, '/'))
99
+ .filter((path) => path.endsWith(manifestSuffix))
100
+ .sort();
101
+ if (candidates.length === 0) {
102
+ fail(
103
+ `No '*${manifestSuffix}' manifest under artifacts/${corpusDir}. The connector corpus is missing or was never synced, so there is nothing to fan out over.`,
104
+ );
105
+ }
106
+ // Ambiguity is a real failure, not a coin flip: picking the wrong manifest
107
+ // would fan the crew out over the wrong pull request.
108
+ if (candidates.length > 1) {
109
+ fail(
110
+ `Found ${candidates.length} '*${manifestSuffix}' manifests under artifacts/${corpusDir}: ${candidates.join(', ')}. Narrow corpusDir to one record.`,
111
+ );
112
+ }
113
+ const manifestPath = candidates[0]!;
114
+
115
+ const raw = await gezel.artifacts.read(manifestPath);
116
+ let manifest: unknown;
117
+ try {
118
+ manifest = JSON.parse(raw);
119
+ } catch (err) {
120
+ fail(
121
+ `artifacts/${manifestPath} is not valid JSON (${err instanceof Error ? err.message : String(err)}).`,
122
+ );
123
+ }
124
+ if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {
125
+ fail(`artifacts/${manifestPath} must contain a JSON object.`);
126
+ }
127
+ const manifestFields = manifest as Record<string, unknown>;
128
+
129
+ const itemsRaw = manifestFields[itemsField];
130
+ if (!Array.isArray(itemsRaw) || itemsRaw.length === 0) {
131
+ fail(`artifacts/${manifestPath} has no non-empty '${itemsField}' array to fan out over.`);
132
+ }
133
+
134
+ interface Batch {
135
+ batchNumber: number;
136
+ start: number;
137
+ end: number;
138
+ paths: string[];
139
+ }
140
+
141
+ function isPositiveInt(value: unknown): value is number {
142
+ return typeof value === 'number' && Number.isInteger(value) && value > 0;
143
+ }
144
+
145
+ const seenPaths = new Set<string>();
146
+ const batches: Batch[] = itemsRaw.map((item, index) => {
147
+ const where = `${itemsField}[${index}] of artifacts/${manifestPath}`;
148
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
149
+ fail(`${where} is not an object.`);
150
+ }
151
+ const fields = item as Record<string, unknown>;
152
+ // `batchNumber` over `number`: a fanout child addresses its own fields as
153
+ // `{{key}}`, and launch params interpolate first — a book launched with a
154
+ // `number` param would shadow the batch's own.
155
+ const batchNumber = fields.batchNumber ?? fields.number;
156
+ if (!isPositiveInt(batchNumber)) fail(`${where} has no positive integer batchNumber.`);
157
+ if (batchNumber !== index + 1) {
158
+ fail(
159
+ `${where} has batchNumber ${batchNumber} at position ${index + 1}. Batch numbers must be 1..N in order — the fanout addresses children by this value.`,
160
+ );
161
+ }
162
+ const { start, end } = fields;
163
+ if (!isPositiveInt(start) || !isPositiveInt(end) || end < start) {
164
+ fail(`${where} has an invalid start/end ordinal range.`);
165
+ }
166
+ const pathsRaw = fields.paths;
167
+ if (
168
+ !Array.isArray(pathsRaw) ||
169
+ pathsRaw.length === 0 ||
170
+ pathsRaw.some((value) => typeof value !== 'string' || value.trim() === '')
171
+ ) {
172
+ fail(`${where} has no non-empty array of path strings.`);
173
+ }
174
+ const paths = pathsRaw as string[];
175
+ if (paths.length !== end - start + 1) {
176
+ fail(
177
+ `${where} spans ordinals ${start}-${end} (${end - start + 1} files) but carries ${paths.length} paths.`,
178
+ );
179
+ }
180
+ for (const path of paths) {
181
+ // Every path must land in exactly one batch: a duplicate silently double-
182
+ // reviews one file while the coverage arithmetic still looks complete.
183
+ if (seenPaths.has(path))
184
+ fail(`${where} repeats '${path}', which another batch already claims.`);
185
+ seenPaths.add(path);
186
+ }
187
+ return { batchNumber, start, end, paths };
188
+ });
189
+
190
+ if (totalField !== '') {
191
+ const expectedTotal = manifestFields[totalField];
192
+ if (!isPositiveInt(expectedTotal)) {
193
+ fail(
194
+ `artifacts/${manifestPath} has no positive integer '${totalField}' to verify batch coverage against (fail-closed).`,
195
+ );
196
+ }
197
+ if (seenPaths.size !== expectedTotal) {
198
+ fail(
199
+ `artifacts/${manifestPath} declares ${totalField}=${expectedTotal} but its ${itemsField} cover ${seenPaths.size} distinct paths. The manifest is internally inconsistent; fanning out over it would drop or duplicate work.`,
200
+ );
201
+ }
202
+ }
203
+
204
+ const content = `${JSON.stringify(batches, null, 2)}\n`;
205
+ await gezel.artifacts.write(outFile, content);
206
+
207
+ gezel.output({
208
+ ok: true,
209
+ manifest: manifestPath,
210
+ outFile,
211
+ batches: batches.length,
212
+ paths: seenPaths.size,
213
+ bytes: content.length,
214
+ });