@volter/twin-standard 1.0.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 (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +20 -0
  3. package/dist/src/check-sources.d.ts +33 -0
  4. package/dist/src/check-sources.js +128 -0
  5. package/dist/src/cli.d.ts +2 -0
  6. package/dist/src/cli.js +105 -0
  7. package/dist/src/derive.d.ts +2 -0
  8. package/dist/src/derive.js +349 -0
  9. package/dist/src/gate.d.ts +9 -0
  10. package/dist/src/gate.js +109 -0
  11. package/dist/src/grade.d.ts +30 -0
  12. package/dist/src/grade.js +36 -0
  13. package/dist/src/index.d.ts +7 -0
  14. package/dist/src/index.js +11 -0
  15. package/dist/src/lanes.d.ts +2 -0
  16. package/dist/src/lanes.js +33 -0
  17. package/dist/src/p3-rules.d.ts +8 -0
  18. package/dist/src/p3-rules.js +43 -0
  19. package/dist/src/protocol-3.d.ts +5 -0
  20. package/dist/src/protocol-3.js +721 -0
  21. package/dist/src/published.d.ts +13 -0
  22. package/dist/src/published.js +36 -0
  23. package/dist/src/spec-documents.d.ts +12 -0
  24. package/dist/src/spec-documents.js +61 -0
  25. package/dist/src/spec-ir-client.d.ts +20 -0
  26. package/dist/src/spec-ir-client.js +77 -0
  27. package/dist/src/spec-ir-commands.d.ts +38 -0
  28. package/dist/src/spec-ir-commands.js +38 -0
  29. package/dist/src/spec-ir-discovery.d.ts +11 -0
  30. package/dist/src/spec-ir-discovery.js +106 -0
  31. package/dist/src/spec-ir-graphql.d.ts +25 -0
  32. package/dist/src/spec-ir-graphql.js +46 -0
  33. package/dist/src/spec-ir-lines.d.ts +19 -0
  34. package/dist/src/spec-ir-lines.js +76 -0
  35. package/dist/src/spec-ir-proto.d.ts +80 -0
  36. package/dist/src/spec-ir-proto.js +339 -0
  37. package/dist/src/spec-ir.d.ts +104 -0
  38. package/dist/src/spec-ir.js +691 -0
  39. package/dist/src/spec-patches.d.ts +8 -0
  40. package/dist/src/spec-patches.js +24 -0
  41. package/dist/src/spec.d.ts +5 -0
  42. package/dist/src/spec.js +7 -0
  43. package/dist/src/types.d.ts +75 -0
  44. package/dist/src/types.js +4 -0
  45. package/dist/src/unit.d.ts +5 -0
  46. package/dist/src/unit.js +14 -0
  47. package/package.json +71 -0
  48. package/src/check-sources.ts +109 -0
  49. package/src/cli.ts +75 -0
  50. package/src/derive.ts +316 -0
  51. package/src/gate.ts +95 -0
  52. package/src/grade.ts +47 -0
  53. package/src/index.ts +12 -0
  54. package/src/lanes.ts +29 -0
  55. package/src/p3-rules.ts +44 -0
  56. package/src/protocol-3.ts +617 -0
  57. package/src/published.ts +37 -0
  58. package/src/spec-documents.ts +58 -0
  59. package/src/spec-ir-client.ts +86 -0
  60. package/src/spec-ir-commands.ts +50 -0
  61. package/src/spec-ir-discovery.ts +104 -0
  62. package/src/spec-ir-graphql.ts +64 -0
  63. package/src/spec-ir-lines.ts +76 -0
  64. package/src/spec-ir-proto.ts +289 -0
  65. package/src/spec-ir.ts +689 -0
  66. package/src/spec-patches.ts +23 -0
  67. package/src/spec.ts +8 -0
  68. package/src/types.ts +53 -0
  69. package/src/unit.ts +15 -0
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env bun
2
+ // derive — the derived-pack generator's build step (docs/contributing/architecture.md, "The derived pack"), the
3
+ // standard's own: the grade's `derived-reproducible` runs it, so every grader derives the same way. Reads a pack's
4
+ // vendored spec (`<pack>/spec/openapi.json[.gz]`), builds the spec IR (./spec-ir.ts) and writes the pack's
5
+ // `src/generated/`. Deterministic: a second run over the same spec writes the same bytes. Never hand-edit what it writes.
6
+ //
7
+ // Usage: twin-standard derive <pack dir> [--out <dir>] (twin-world: bun scripts/derive-pack.ts <vendor>)
8
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
9
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
10
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
11
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
12
+ });
13
+ }
14
+ return path;
15
+ };
16
+ import { parse as parseYaml } from 'yaml';
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { gunzipSync } from 'node:zlib';
20
+ import { CRUD_CLASSES, fromOpenAPI, fromSmithy, fromSwagger2, slug } from "./spec-ir.js";
21
+ import { fromCommandReplies } from "./spec-ir-lines.js";
22
+ import { fromProto, protoSchema, readProtoFiles } from "./spec-ir-proto.js";
23
+ import { fromRedisCommands } from "./spec-ir-commands.js";
24
+ import { fromClientCalls } from "./spec-ir-client.js";
25
+ import { discoveryMethods, fromDiscovery, isDiscovery } from "./spec-ir-discovery.js";
26
+ import { handlerCitations, quotedPage, urlsIn } from "./check-sources.js";
27
+ import { applySpecPatch } from "./spec-patches.js";
28
+ import { unitAt } from "./unit.js";
29
+ import { mergeDocuments, readSpecDocuments } from "./spec-documents.js";
30
+ import { p3RuleHits } from "./p3-rules.js";
31
+ const vendor = process.argv[2];
32
+ if (!vendor) {
33
+ console.error('usage: twin-standard derive <pack dir> [--out <dir>]');
34
+ process.exit(1);
35
+ }
36
+ const PKG = unitAt(vendor).dir;
37
+ // an OpenAPI document, an AWS Smithy JSON model (smithy.json), the RFC a line protocol is (rfcNNNN.txt), or the
38
+ // Protocol Buffers files an RPC service is published as (spec/proto/, every file the service imports), or the calls a
39
+ // vendor's own client makes where the vendor publishes no spec (client-ops.json, spec-ir-client.ts), or one API's several
40
+ // OpenAPI documents (spec/openapi/, read as their union: spec-documents.ts), or a Google API Discovery document
41
+ // (discovery.json, spec-ir-discovery.ts)
42
+ const rfc = existsSync(join(PKG, 'spec')) ? readdirSync(join(PKG, 'spec')).find((f) => /^rfc\d+\.txt$/.test(f)) : undefined;
43
+ const specPath = ['openapi.json.gz', 'openapi.json', 'openapi.yaml.gz', 'openapi.yaml', 'smithy.json.gz', 'smithy.json', 'discovery.json.gz', 'discovery.json', ...(rfc ? [rfc] : []), 'openapi', 'proto', 'commands', 'client-ops.json'].map((f) => join(PKG, 'spec', f)).find((p) => existsSync(p));
44
+ if (!specPath) {
45
+ console.error(`derive-pack: no spec at ${join(PKG, 'spec')}/openapi.{json,yaml}[.gz], smithy.json[.gz], rfcNNNN.txt, proto/, commands/ or client-ops.json`);
46
+ process.exit(1);
47
+ }
48
+ const rpcService = specPath.endsWith('/proto');
49
+ const severalDocuments = specPath.endsWith('/openapi');
50
+ // a command language's table, one vendored file per command (Redis's src/commands/*.json), with its version in SOURCE.md
51
+ const commandTable = specPath.endsWith('/commands');
52
+ const protoTree = (dir, at = '') => Object.fromEntries(readdirSync(join(dir, at), { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? Object.entries(protoTree(dir, join(at, e.name))) : e.name.endsWith('.proto') ? [[join(at, e.name), readFileSync(join(dir, at, e.name), 'utf8')]] : [])));
53
+ const bytes = rpcService || commandTable || severalDocuments ? Buffer.from('') : readFileSync(specPath);
54
+ const text = (specPath.endsWith('.gz') ? gunzipSync(bytes) : bytes).toString('utf8');
55
+ // an RFC's command-reply table and a service's .proto files are read into data first, so a patch corrects them as it
56
+ // corrects a JSON spec
57
+ const lineProtocol = specPath.endsWith('.txt');
58
+ const commandVersion = commandTable ? (/\*\*Version:\*\* `([^`]+)`/.exec(existsSync(join(PKG, 'spec', 'SOURCE.md')) ? readFileSync(join(PKG, 'spec', 'SOURCE.md'), 'utf8') : '')?.[1] ?? '') : '';
59
+ let doc = severalDocuments ? readSpecDocuments(join(PKG, 'spec')) : commandTable ? fromRedisCommands(Object.fromEntries(readdirSync(specPath).filter((f) => f.endsWith('.json')).sort().map((f) => [f, JSON.parse(readFileSync(join(specPath, f), 'utf8'))])), commandVersion) : rpcService ? readProtoFiles(protoTree(specPath)) : lineProtocol ? fromCommandReplies(text) : /\.ya?ml(\.gz)?$/.test(specPath) ? parseYaml(text) : JSON.parse(text);
60
+ // ── the evidence the pack cites ──────────────────────────────────────────────────────────────
61
+ // A source is a page check-sources (./check-sources.ts) fetched and recorded found (spec/sources.json), a quote
62
+ // that page holds, or `spec:<operationId or /json/pointer> "quote"`: words of the vendored spec itself
63
+ // (read before any patch, so a patch never vouches for itself).
64
+ const vendored = lineProtocol || commandTable ? structuredClone(doc) : JSON.parse(text.startsWith('{') ? text : JSON.stringify(doc));
65
+ /** An RFC's section by its number (`4.1.4`): its heading's line to the next heading's. */
66
+ const sectionOf = (n) => {
67
+ const at = text.search(new RegExp(`^${n.replace(/\./g, '\\.')}\\. `, 'm'));
68
+ if (at < 0)
69
+ return undefined;
70
+ const next = text.slice(at + 1).search(/^\d+(\.\d+)*\. {2}/m);
71
+ return next < 0 ? text.slice(at) : text.slice(at, at + 1 + next);
72
+ };
73
+ const sourcesPath = join(PKG, 'spec', 'sources.json');
74
+ const recorded = existsSync(sourcesPath) ? JSON.parse(readFileSync(sourcesPath, 'utf8')) : {};
75
+ const HTTP_METHODS = new Set(['get', 'put', 'post', 'delete', 'patch', 'head', 'options', 'trace']);
76
+ const specOps = new Map();
77
+ // an operation by its id: the spec's operationId, or the `method_path` slug the IR mints where the spec names none (QStash)
78
+ for (const d of severalDocuments ? Object.values(vendored.documents) : [vendored]) {
79
+ for (const [path, item] of Object.entries(d.paths ?? {})) {
80
+ for (const [method, o] of Object.entries(item)) {
81
+ if (!o || typeof o !== 'object' || !HTTP_METHODS.has(method))
82
+ continue;
83
+ const id = o.operationId;
84
+ specOps.set(typeof id === 'string' && id ? id : slug(method, path), o);
85
+ }
86
+ }
87
+ }
88
+ // a proto spec's rpc, message or enum is its declaring file's text, comments and all (Google documents each rpc and field
89
+ // in the comments above it): `spec:SearchUris "…"` checks the words there
90
+ // (the names are read from the file with its comments taken out: a comment's "the message of" names nothing)
91
+ if (rpcService)
92
+ for (const text of Object.values(protoTree(specPath)))
93
+ for (const m of text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '').matchAll(/\b(?:rpc|message|enum)\s+(\w+)/g))
94
+ if (!specOps.has(m[1]))
95
+ specOps.set(m[1], text);
96
+ // a JSON pointer into several documents reads their union (a schema only one of them has)
97
+ const pointed = severalDocuments ? mergeDocuments(vendored).doc : vendored;
98
+ // a Discovery document's methods are its operations, by their ids
99
+ if (isDiscovery(vendored))
100
+ for (const m of discoveryMethods(vendored.resources))
101
+ specOps.set(String(m.id), m);
102
+ // a spec node's words: its strings and its keys (a schema's property names are what it says)
103
+ const wordsIn = (node) => (typeof node === 'string' ? node : node && typeof node === 'object' ? Object.entries(node).map(([k, v]) => `${Array.isArray(node) ? '' : k} ${wordsIn(v)}`).join(' ') : '');
104
+ const bare = (s) => s.replace(/\s+/g, '');
105
+ // a JSON pointer into the spec, an operation by id, or (an RFC's) a section by number
106
+ const specNode = (ref) => (ref.startsWith('/') ? ref.split('/').slice(1).map((k) => k.replace(/~1/g, '/').replace(/~0/g, '~')).reduce((n, k) => n?.[k], severalDocuments && !ref.startsWith('/documents/') ? pointed : vendored) : lineProtocol && /^\d+(\.\d+)*$/.test(ref) ? sectionOf(ref) : specOps.get(ref));
107
+ /** Why a citation does not hold, or undefined when it does. */
108
+ function unheld(source) {
109
+ const spec = /^spec:(\S+)\s+"([\s\S]*)"$/.exec(source.trim());
110
+ if (spec && !spec[2].trim())
111
+ return `spec:${spec[1]} quotes nothing`;
112
+ if (spec) {
113
+ const node = specNode(spec[1]);
114
+ if (node === undefined)
115
+ return `the spec has nothing at ${spec[1]}`;
116
+ return bare(wordsIn(node)).includes(bare(spec[2].replace(/\\"/g, '"'))) ? undefined : `the spec at ${spec[1]} does not say "${spec[2]}"`;
117
+ }
118
+ const urls = urlsIn(source);
119
+ if (!urls.length)
120
+ return `"${source.slice(0, 60)}" names no page and no spec words`;
121
+ const dead = urls.filter((u) => recorded[u]?.status !== 200);
122
+ return dead.length ? dead.map((u) => `${u} is ${recorded[u] ? `answering ${recorded[u].status || 'nothing'}` : 'not checked'} (twin-standard check-sources ${vendor})`).join('; ') : undefined;
123
+ }
124
+ const evidence = [];
125
+ // every rule a handler writes carries its citation beside it (`// source:`), held as a transition's is
126
+ for (const c of handlerCitations(PKG)) {
127
+ const q = quotedPage(c.source);
128
+ // a quote is checked only in the two forms that say where it is; any other quote is refused, never passed unread
129
+ const trimmed = c.source.trim();
130
+ const loose = !q && (/^spec:/.test(trimmed) ? !/^spec:\S+\s+"[\s\S]*"$/.test(trimmed) : trimmed.includes('"'));
131
+ const held = loose ? `"${c.source.slice(0, 60)}" quotes words in no form a check reads (\`<url> "<quote>"\` or \`spec:<ref> "<quote>"\`)` : q ? (recorded[q.url]?.quotes?.[q.quote] === true ? undefined : `${q.url} does not hold "${q.quote}" as recorded (twin-standard check-sources ${vendor})`) : unheld(c.source);
132
+ if (held)
133
+ evidence.push(`semantics/${c.where}: ${held}`);
134
+ }
135
+ // Corrections to the vendor's spec, as data: RFC 6902 operations (add, replace, remove, move, copy)
136
+ // in spec/patches.json, applied before the IR so the vendored file stays the vendor's own bytes. Each says
137
+ // `why`, citing what shows the vendor differs from its spec (its docs, the spec's own example, a recording).
138
+ const patchPath = join(PKG, 'spec', 'patches.json');
139
+ if (existsSync(patchPath)) {
140
+ for (const p of JSON.parse(readFileSync(patchPath, 'utf8')).patches) {
141
+ if (!p.why?.trim()) {
142
+ console.error(`${vendor}: spec patch ${p.op} ${p.path} gives no why`);
143
+ process.exit(1);
144
+ }
145
+ {
146
+ const s = p.source;
147
+ const held = s?.spec ? unheld(`spec:${s.spec} "${s.quote}"`)
148
+ : s?.url ? (recorded[s.url]?.quotes?.[s.quote] === true ? undefined : `${s.url} does not hold "${s.quote}" as recorded`)
149
+ : urlsIn(p.why).length ? unheld(p.why) : 'it cites no page and quotes nothing';
150
+ if (held)
151
+ evidence.push(`spec patch ${p.op} ${p.path}: ${held}`);
152
+ }
153
+ applySpecPatch(doc, p);
154
+ }
155
+ }
156
+ // several documents of one API are read as their union once the patches have ruled every contradiction
157
+ if (severalDocuments) {
158
+ const { doc: merged, contradictions } = mergeDocuments(doc);
159
+ if (contradictions.length) {
160
+ console.error(`${vendor}: the documents contradict each other; a patch (citing what shows which holds) rules each:\n ${contradictions.join('\n ')}`);
161
+ process.exit(1);
162
+ }
163
+ doc = merged;
164
+ }
165
+ // --out <dir> writes the core elsewhere, touching nothing in the pack (the grader's reproducibility check)
166
+ const outAt = process.argv.indexOf('--out');
167
+ const out = outAt >= 0 && process.argv[outAt + 1] ? process.argv[outAt + 1] : join(PKG, 'src', 'generated');
168
+ mkdirSync(out, { recursive: true });
169
+ // A line protocol's surface is its commands and the replies each may answer; its manifest's transitions
170
+ // name commands and cite the RFC.
171
+ if (lineProtocol || commandTable) {
172
+ const spec = doc;
173
+ writeFileSync(join(out, 'surface.gen.json'), `${JSON.stringify({ generatedBy: 'scripts/derive-pack.ts', spec: specPath.split('/').pop(), ...spec })}\n`);
174
+ const manifestPath = join(PKG, 'src', 'manifest.ts');
175
+ if (existsSync(manifestPath)) {
176
+ const { manifest } = (await import(__rewriteRelativeImportExtension(manifestPath)));
177
+ for (const [name, decl] of Object.entries(manifest.resources)) {
178
+ for (const [field, m] of Object.entries(decl.state ?? {})) {
179
+ for (const tr of m.transitions) {
180
+ const held = unheld(String(tr.source ?? ''));
181
+ if (held)
182
+ evidence.push(`${name}.${field} ${tr.operation ?? tr.actor ?? ''} → ${tr.to ?? '(stays)'}: ${held}`);
183
+ if (tr.operation && !spec.commands.some((c) => c.id === tr.operation))
184
+ evidence.push(`${name}.${field}: a transition names ${tr.operation}, which the spec does not have`);
185
+ }
186
+ }
187
+ }
188
+ }
189
+ if (evidence.length) {
190
+ console.error(`${vendor}: ${evidence.length} citation(s) do not hold:\n ${[...new Set(evidence)].join('\n ')}`);
191
+ process.exit(1);
192
+ }
193
+ console.log(`${vendor}: spec ${spec.version}, ${spec.commands.length} commands${'anyCommand' in spec ? `; any command may answer ${spec.anyCommand.join(', ')}` : ''}`);
194
+ process.exit(0);
195
+ }
196
+ const ir = isDiscovery(doc) ? fromDiscovery(doc) : doc?.format === 'client' ? fromClientCalls(doc) : rpcService ? fromProto(doc) : /smithy\.json(\.gz)?$/.test(specPath) ? fromSmithy(doc) : doc?.swagger === '2.0' ? fromSwagger2(doc) : fromOpenAPI(doc);
197
+ // A spec that groups its operations by tag (Cloudflare's: nearly every path begins /accounts/{account_id}/, so the
198
+ // path's first segment names one family for thousands of operations) says so in spec/grouping.json, `{ "by": "tag" }`:
199
+ // each operation's family is then its first tag, as a file name (`Worker Script` is `worker-script`).
200
+ const grouping = existsSync(join(PKG, 'spec', 'grouping.json')) ? JSON.parse(readFileSync(join(PKG, 'spec', 'grouping.json'), 'utf8')) : {};
201
+ if (grouping.by === 'tag') {
202
+ // an operation the spec names no operationId for is found by its method and path, in the spec as corrected (an
203
+ // operation a patch adds carries its own tags: PostHog's person delete)
204
+ const byRoute = new Map();
205
+ for (const [path, item] of Object.entries(doc.paths ?? {})) {
206
+ for (const [method, op] of Object.entries(item ?? {}))
207
+ if (op && typeof op === 'object')
208
+ byRoute.set(`${method.toLowerCase()} ${path}`, op);
209
+ }
210
+ for (const o of ir.operations) {
211
+ const op = (specOps.get(o.id) ?? byRoute.get(`${o.method.toLowerCase()} ${o.path}`));
212
+ const tag = op?.tags?.[0];
213
+ if (tag)
214
+ o.family = tag.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
215
+ }
216
+ }
217
+ // A GraphQL API beside the REST one (spec/schema.graphql[.gz]) is a second wire over the same state.
218
+ const sdlPath = ['schema.graphql.gz', 'schema.graphql'].map((f) => join(PKG, 'spec', f)).find((p) => existsSync(p));
219
+ // the GraphQL wire's root fields (`mutation.issueArchive`), which a transition may name as a REST operation is named
220
+ const graphqlOperations = new Set();
221
+ if (sdlPath) {
222
+ const { fromGraphQL } = await import("./spec-ir-graphql.js");
223
+ const sdl = (sdlPath.endsWith('.gz') ? gunzipSync(readFileSync(sdlPath)) : readFileSync(sdlPath)).toString('utf8');
224
+ const gql = fromGraphQL(sdl);
225
+ for (const o of gql.operations)
226
+ graphqlOperations.add(o.id);
227
+ mkdirSync(out, { recursive: true });
228
+ writeFileSync(join(out, 'graphql.gen.json'), `${JSON.stringify({ generatedBy: 'scripts/derive-pack.ts', spec: sdlPath.split('/').pop(), ...gql })}\n`);
229
+ // the schema itself, for the pack's GraphQL wire to validate and execute against (imported lazily)
230
+ writeFileSync(join(out, 'graphql-sdl.gen.json'), `${JSON.stringify({ generatedBy: 'scripts/derive-pack.ts', sdl })}\n`);
231
+ const g = new Map();
232
+ for (const o of gql.operations)
233
+ g.set(o.class, (g.get(o.class) ?? 0) + 1);
234
+ console.log(` graphql: ${gql.operations.length} root fields, ${gql.resources.length} resources; ` + [...g].sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}=${v}`).join(' '));
235
+ }
236
+ // a proto unit's schema, for the kernel's protobuf codec and gRPC wire: fields by number, enums by number, rpcs by path
237
+ if (rpcService)
238
+ writeFileSync(join(out, 'proto.gen.json'), `${JSON.stringify({ generatedBy: 'scripts/derive-pack.ts', ...protoSchema(doc) })}\n`);
239
+ // Data, not code: the surface is JSON so it adds nothing to a typecheck and ships as an asset.
240
+ writeFileSync(join(out, 'surface.gen.json'), `${JSON.stringify({ generatedBy: 'scripts/derive-pack.ts', spec: specPath.split('/').pop(), ...ir })}\n`);
241
+ // The event types a vendor delivers, when its spec enumerates them where a webhook subscription names the events it
242
+ // wants (a request body's `enabled_events`): the pack records an event only under a type the vendor sends.
243
+ const eventTypes = new Set();
244
+ for (const item of Object.values((doc?.paths ?? {}))) {
245
+ for (const op of Object.values(item ?? {})) {
246
+ for (const media of Object.values((op?.requestBody?.content ?? {}))) {
247
+ for (const type of (media?.schema?.properties?.enabled_events?.items?.enum ?? []))
248
+ if (typeof type === 'string' && type !== '*')
249
+ eventTypes.add(type);
250
+ }
251
+ }
252
+ }
253
+ if (eventTypes.size)
254
+ writeFileSync(join(out, 'events.gen.json'), `${JSON.stringify({ generatedBy: 'scripts/derive-pack.ts', spec: specPath.split('/').pop(), types: [...eventTypes].sort() })}\n`);
255
+ // What the pack's UI needs to know about each resource its manifest declares: where it is listed,
256
+ // read, created and moved, which values its state fields take and which moves are legal from which,
257
+ // and which fields name another resource. Data the browser bundle reads; it never imports the manifest.
258
+ const manifestPath = join(PKG, 'src', 'manifest.ts');
259
+ if (existsSync(manifestPath)) {
260
+ const { manifest } = (await import(__rewriteRelativeImportExtension(manifestPath)));
261
+ const base = ir.basePath ?? '';
262
+ const ops = ir.operations.filter((o) => !(manifest.unmodeled ?? []).includes(o.id));
263
+ const ui = {};
264
+ for (const [name, decl] of Object.entries(manifest.resources)) {
265
+ const mine = ops.filter((o) => o.resource === name);
266
+ const pick = (cls) => mine.filter((o) => o.class === cls).sort((a, b) => a.path.length - b.path.length)[0];
267
+ const [list, retrieve, create] = [pick('list'), pick('retrieve'), pick('create')];
268
+ const moves = Object.entries(decl.state ?? {}).flatMap(([field, m]) => m.transitions.filter((t) => t.operation).map((t) => {
269
+ const o = mine.find((x) => x.id === t.operation);
270
+ return o ? { operation: o.id, method: o.method.toUpperCase(), path: (o.basePath ?? base) + o.path, field, from: t.from, ...(t.to !== undefined ? { to: t.to } : {}) } : undefined;
271
+ }).filter(Boolean));
272
+ ui[name] = {
273
+ ...(list ? { list: (list.basePath ?? base) + list.path } : {}),
274
+ ...(retrieve ? { retrieve: (retrieve.basePath ?? base) + retrieve.path } : {}),
275
+ ...(create ? { create: { path: (create.basePath ?? base) + create.path, encoding: create.bodyEncoding, body: create.body } } : {}),
276
+ actions: moves,
277
+ states: Object.fromEntries(Object.entries(decl.state ?? {}).map(([f, m]) => [f, [...new Set([String(m.initial), ...m.transitions.flatMap((t) => [...(t.from === '*' ? [] : t.from), ...(t.to !== undefined ? [t.to] : [])])])].sort()])),
278
+ embeds: decl.embeds ?? {},
279
+ };
280
+ }
281
+ writeFileSync(join(out, 'ui.gen.json'), `${JSON.stringify({ generatedBy: 'scripts/derive-pack.ts', resources: ui })}\n`);
282
+ // every transition cites what shows the vendor moves that way, and the citation holds
283
+ for (const [name, decl] of Object.entries(manifest.resources)) {
284
+ for (const [field, m] of Object.entries(decl.state ?? {})) {
285
+ for (const tr of m.transitions) {
286
+ const held = unheld(String(tr.source ?? ''));
287
+ if (held)
288
+ evidence.push(`${name}.${field} ${tr.operation ?? tr.actor ?? ''} → ${tr.to ?? '(stays)'}: ${held}`);
289
+ if (tr.operation && !ir.operations.some((o) => o.id === tr.operation) && !graphqlOperations.has(tr.operation))
290
+ evidence.push(`${name}.${field}: a transition names ${tr.operation}, which the spec does not have`);
291
+ }
292
+ }
293
+ }
294
+ if (evidence.length) {
295
+ console.error(`${vendor}: ${evidence.length} citation(s) do not hold:\n ${[...new Set(evidence)].join('\n ')}`);
296
+ process.exit(1);
297
+ }
298
+ // every state candidate of a resource the pack models is ruled on: a state field, or named not one
299
+ const unruled = ir.resources.flatMap((r) => {
300
+ const decl = manifest.resources[r.name];
301
+ return decl ? r.stateCandidates.filter((c) => !(c.field in (decl.state ?? {})) && !(decl.notState ?? []).includes(c.field)).map((c) => `${r.name}.${c.field}`) : [];
302
+ });
303
+ if (unruled.length) {
304
+ console.error(`${vendor}: the manifest does not rule on ${unruled.length} state candidate(s): ${unruled.join(', ')} (declare each a state field or list it in notState)`);
305
+ process.exit(1);
306
+ }
307
+ // a resource's refresh scope ("The real-system adapters", What a pack declares) names the list that enumerates it or
308
+ // its retrieve, or says why the vendor offers no read-back; whether every stored resource declares one is
309
+ // pack-standing's report, not this build's
310
+ // (a resource the spec names is read by its own list or retrieve; one the manifest names apart from the spec's, an RPC
311
+ // vendor's, by the list or read the scope names, with `items` where the answer holds them when the spec does not say)
312
+ const specNamed = new Set(ir.resources.map((r) => r.name));
313
+ const scopes = Object.entries(manifest.resources).flatMap(([name, decl]) => {
314
+ const r = decl.refresh;
315
+ if (!r)
316
+ return [];
317
+ const op = (id) => ir.operations.find((o) => o.id === id);
318
+ const ours = (o) => !specNamed.has(name) || o.resource === name;
319
+ if (r.list !== undefined) {
320
+ const o = op(r.list);
321
+ if (!(o?.class === 'list' && ours(o)))
322
+ return [`${name}: refresh.list ${r.list} is ${o ? `a ${o.class} of ${o.resource ?? 'no resource'}` : 'no operation of the spec'}, not a list of ${name}`];
323
+ return o.answers?.list || r.items ? [] : [`${name}: refresh.list ${r.list} answers no list the spec names; say where its items are (items)`];
324
+ }
325
+ if (r.get !== undefined) {
326
+ const o = op(r.get);
327
+ return o?.class === 'retrieve' && ours(o) ? [] : [`${name}: refresh.get ${r.get} is ${o ? `a ${o.class} of ${o.resource ?? 'no resource'}` : 'no operation of the spec'}, not the retrieve of ${name}`];
328
+ }
329
+ return typeof r.none === 'string' && r.none.trim() ? [] : [`${name}: refresh names no list, no get and no reason`];
330
+ });
331
+ if (scopes.length) {
332
+ console.error(`${vendor}: ${scopes.length} refresh scope(s) do not hold:\n ${scopes.join('\n ')}`);
333
+ process.exit(1);
334
+ }
335
+ // the architecture's mechanical rules over the pack's own code (./p3-rules.ts): a line breaking one records why, or
336
+ // the build stops
337
+ const hits = p3RuleHits(PKG);
338
+ if (hits.length) {
339
+ console.error(`${vendor}: ${hits.length} line(s) break a Protocol 3 rule (fix it, or record why on the line: // p3: <reason>):\n ${hits.map((h) => `${h.file}:${h.line}: ${h.rule}\n ${h.text}`).join('\n ')}`);
340
+ process.exit(1);
341
+ }
342
+ }
343
+ const counts = new Map();
344
+ for (const o of ir.operations)
345
+ counts.set(o.class, (counts.get(o.class) ?? 0) + 1);
346
+ const crud = ir.operations.filter((o) => CRUD_CLASSES.has(o.class)).length;
347
+ const candidates = ir.resources.reduce((n, r) => n + r.stateCandidates.length, 0);
348
+ console.log(`${vendor}: spec ${ir.version}, ${ir.operations.length} operations (${crud} crud), ${ir.resources.length} resources, ${candidates} state candidates`);
349
+ console.log(' ' + [...counts].sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}=${v}`).join(' '));
@@ -0,0 +1,9 @@
1
+ /** Every unit of a pack repository: each pack (a directory with a package.json) and each lane in it (a directory with
2
+ * its own src/manifest.ts and no package.json). */
3
+ export declare function unitsOf(repo: string): string[];
4
+ export declare function laneRootFailures(dir: string): string[];
5
+ /** Each unit's blocking form failures (empty when it may be in the repository). */
6
+ export declare function p3Gate(units: string[]): Promise<Array<{
7
+ unit: string;
8
+ failures: string[];
9
+ }>>;
@@ -0,0 +1,109 @@
1
+ // The gate — what may be in a Protocol 3 pack repository or catalog: every pack and lane passes the form
2
+ // section of the grade (docs/contributing/architecture.md, "The grade"), so nothing that is not Protocol 3 enters it:
3
+ // nothing outside the pack layout, no handler past its contract.
4
+ // The repository was made so that this holds (the owner, 2026-09-29: "this was WHY we created p3 so this can't
5
+ // happen"); this is what makes it hold. It runs before a commit (the pack repository's hook, on the units it touches),
6
+ // before a release (pack-release, on each pack it releases), and on every version submitted to the catalog
7
+ // (twin-catalog's check, on the published tarball) — each at the version of this package it pins, so all of them judge by
8
+ // one standard.
9
+ //
10
+ // twin-standard gate <pack repository> [<pack or lane dir>…]
11
+ //
12
+ // It blocks on every criterion of the form section; what a pack's walked life proves (no dead code among them) is the
13
+ // proof section's, which the gate does not read.
14
+ import { spawnSync } from 'node:child_process';
15
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import ts from 'typescript';
18
+ import { grade } from "./grade.js";
19
+ /** Every unit of a pack repository: each pack (a directory with a package.json) and each lane in it (a directory with
20
+ * its own src/manifest.ts and no package.json). */
21
+ export function unitsOf(repo) {
22
+ const units = [];
23
+ for (const name of readdirSync(repo).sort()) {
24
+ const dir = join(repo, name);
25
+ if (name.startsWith('.') || name === 'node_modules' || !statSync(dir).isDirectory() || !existsSync(join(dir, 'package.json')))
26
+ continue;
27
+ units.push(dir);
28
+ for (const sub of readdirSync(dir).sort()) {
29
+ const lane = join(dir, sub);
30
+ if (statSync(lane).isDirectory() && !existsSync(join(lane, 'package.json')) && existsSync(join(lane, 'src', 'manifest.ts')))
31
+ units.push(lane);
32
+ }
33
+ }
34
+ return units;
35
+ }
36
+ /** What a vendor whose every API is a lane may hold at its root: the package files, the vendor's life (journeys/), its
37
+ * generated facts, its lanes, and in src/ only its manifest (its lanes' routes, discovery and descriptor, as data), the
38
+ * fetch the kernel serves them by (createVendorFetch, generated) and the fixed serve factory, index and bin. Nothing
39
+ * routes by hand: only the fetch reaches a lane. A directory with no manifest and no lane is no Protocol 3 pack. */
40
+ const ROOT_ENTRIES = new Set(['README.md', 'package.json', 'LICENSE', 'CHANGELOG.md', 'tsconfig.json', 'tsconfig.build.json', 'gate.ts', 'census.json', 'vendor', 'journeys', 'generated', 'src', 'node_modules']);
41
+ const ROOT_SRC = new Set(['manifest.ts', 'fetch.ts', 'index.ts', 'cli.ts', 'server.ts']);
42
+ /** What the repository ignores (a build's dist/, a World's state) is no file of the pack, as protocol-3's layout reads it. */
43
+ function ignored(dir, names) {
44
+ if (!names.length)
45
+ return new Set();
46
+ const run = spawnSync('git', ['check-ignore', '--', ...names], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
47
+ return new Set(String(run.stdout ?? '').split('\n').filter(Boolean));
48
+ }
49
+ export function laneRootFailures(dir) {
50
+ const lanes = readdirSync(dir).filter((n) => existsSync(join(dir, n, 'src', 'manifest.ts')));
51
+ if (!lanes.length)
52
+ return ['layout: no src/manifest.ts and no lane: not a Protocol 3 pack'];
53
+ const stray = readdirSync(dir).filter((n) => !n.startsWith('.') && !ROOT_ENTRIES.has(n) && !lanes.includes(n));
54
+ const skip = ignored(dir, stray);
55
+ const outside = [
56
+ ...stray.filter((n) => !skip.has(n)),
57
+ ...(existsSync(join(dir, 'src')) ? readdirSync(join(dir, 'src')).filter((n) => !ROOT_SRC.has(n) && !n.endsWith('.d.ts') && n !== 'semantics').map((n) => `src/${n}`) : []),
58
+ // what the lanes share, and nothing else (architecture, "Pack layout": a vendor whose every API is a lane)
59
+ ...(existsSync(join(dir, 'src', 'semantics')) ? readdirSync(join(dir, 'src', 'semantics')).filter((n) => n !== 'shared.ts').map((n) => `src/semantics/${n}`) : []),
60
+ ];
61
+ const failures = outside.length ? [`layout: ${outside.length} outside the vendor's root (its lanes hold the rest): ${outside.slice(0, 8).join(', ')}${outside.length > 8 ? ` and ${outside.length - 8} more` : ''}`] : [];
62
+ // the vendor's front is declared and the kernel serves it: a manifest, and a fetch that is createVendorFetch over it
63
+ const src = (n) => (existsSync(join(dir, 'src', n)) ? readFileSync(join(dir, 'src', n), 'utf8') : '');
64
+ if (!src('manifest.ts'))
65
+ failures.push("layout: no src/manifest.ts: a vendor of lanes declares its lanes' routes, discovery and descriptor");
66
+ if (!/\bcreateVendorFetch\(/.test(src('fetch.ts')))
67
+ failures.push('layout: src/fetch.ts builds no createVendorFetch: the kernel routes a vendor\'s lanes from its manifest, nothing by hand');
68
+ // the root's own files hold to the pack contract as a unit's do (the grade's kernel-contract)
69
+ const beyond = [];
70
+ for (const n of existsSync(join(dir, 'src')) ? readdirSync(join(dir, 'src')).filter((x) => /\.tsx?$/.test(x) && !x.endsWith('.d.ts')) : []) {
71
+ // the file's imports as TypeScript reads them, as the grade's kernel-contract does
72
+ for (const from of ts.preProcessFile(readFileSync(join(dir, 'src', n), 'utf8'), true, true).importedFiles.map((i) => i.fileName)) {
73
+ // only the fetch reaches a lane (the kernel's routing), and the index each lane's manifest and generated surface
74
+ // (the kernel derives the vendor-backed half from them); the manifest is data, importing the contract's types alone
75
+ const laneData = n === 'index.ts' && /^\.\.\/[^/]+\/src\/(manifest\.ts|generated\/surface\.gen\.json)$/.test(from);
76
+ if (/^\.\.\/[^/]+\/src\//.test(from) && n !== 'fetch.ts' && !laneData) {
77
+ beyond.push(`src/${n} imports ${from}: only src/fetch.ts reaches a lane`);
78
+ continue;
79
+ }
80
+ if (n === 'manifest.ts' && from !== '@volter/world-core') {
81
+ beyond.push(`src/manifest.ts imports ${from}: the manifest is data`);
82
+ continue;
83
+ }
84
+ if (from.startsWith('.') || from === '@volter/world-core' || from === '@volter/world-ui')
85
+ continue;
86
+ if (n === 'cli.ts' && (from === '@volter/world-core/args' || from === '@volter/world-core/lifecycle'))
87
+ continue;
88
+ beyond.push(`src/${n} imports ${from}`);
89
+ }
90
+ }
91
+ return beyond.length ? [...failures, `kernel-contract: ${beyond.join('; ')}`] : failures;
92
+ }
93
+ /** Each unit's blocking form failures (empty when it may be in the repository). */
94
+ export async function p3Gate(units) {
95
+ const out = [];
96
+ for (const unit of units) {
97
+ // a vendor whose every API is a lane has no spec of its own: its lanes are graded, and its root is only the vendor's
98
+ // front (architecture, "Pack layout", "Other wires: lanes")
99
+ const lanesOnly = !existsSync(join(unit, 'spec')) && readdirSync(unit).some((n) => existsSync(join(unit, n, 'src', 'manifest.ts')));
100
+ if (lanesOnly || !existsSync(join(unit, 'src', 'manifest.ts'))) {
101
+ out.push({ unit, failures: laneRootFailures(unit) });
102
+ continue;
103
+ }
104
+ const grades = await grade(unit, { static: true, sections: ['form'] });
105
+ const form = Object.values(grades).flatMap((g) => g.criteria).filter((c) => !c.pass);
106
+ out.push({ unit, failures: form.map((c) => `${c.id}: ${c.reason}`) });
107
+ }
108
+ return out;
109
+ }
@@ -0,0 +1,30 @@
1
+ import type { ScoreReport, Standard } from './types.js';
2
+ /** The latest version of each standard. A new protocol, or a revision, replaces or joins this list. */
3
+ export declare const STANDARDS: Standard[];
4
+ export interface CriterionGrade {
5
+ id: string;
6
+ section: string;
7
+ asks: string;
8
+ pass: boolean;
9
+ reason: string;
10
+ }
11
+ export interface StandardGrade {
12
+ grade: number;
13
+ met: number;
14
+ total: number;
15
+ criteria: CriterionGrade[];
16
+ planned: string[];
17
+ }
18
+ export type GradeOptions = {
19
+ /** only the criteria that read the tree (the executed ones are the pack's typecheck and tests) */
20
+ static?: boolean;
21
+ /** only these sections (the catalog grades a submission's `form`) */
22
+ sections?: ReadonlyArray<'form' | 'proof' | 'soundness'>;
23
+ /** the unit's name when its directory does not say it (an unpacked tarball's `package/`) */
24
+ name?: string;
25
+ /** the customer life's report, recomputed by the caller, and why a walk gave none */
26
+ report?: ScoreReport | null;
27
+ walkError?: string;
28
+ };
29
+ /** Each standard's grade of the unit at `dir`, by `<standard>@<version>`. */
30
+ export declare function grade(dir: string, opts?: GradeOptions): Promise<Record<string, StandardGrade>>;
@@ -0,0 +1,36 @@
1
+ // The grader (docs/contributing/architecture.md, "The grade"): one engine that grades a unit — a pack, or a lane of one,
2
+ // in any repository or an unpacked published tarball — against the latest version of every standard this package
3
+ // holds. It trusts only stamped evidence; a committed score, count or index row is never an input. The proof section
4
+ // reads the customer life's report, which the caller recomputes and hands in (twin-world walks it on an in-memory World);
5
+ // without one, the proof criteria fail as unproven, never pass.
6
+ import { protocol3 } from "./protocol-3.js";
7
+ import { unitAt } from "./unit.js";
8
+ /** The latest version of each standard. A new protocol, or a revision, replaces or joins this list. */
9
+ export const STANDARDS = [protocol3];
10
+ /** Each standard's grade of the unit at `dir`, by `<standard>@<version>`. */
11
+ export async function grade(dir, opts = {}) {
12
+ const at = unitAt(dir);
13
+ const name = opts.name ?? at.name;
14
+ const unit = { name, vendor: name.split('/')[0], dir: at.dir, report: opts.report ?? null, ...(opts.walkError ? { walkError: opts.walkError } : {}) };
15
+ const grades = {};
16
+ for (const standard of STANDARDS) {
17
+ const criteria = [];
18
+ for (const c of standard.criteria) {
19
+ if (opts.static && c.executed)
20
+ continue;
21
+ if (opts.sections && !opts.sections.includes(c.section))
22
+ continue;
23
+ let result;
24
+ try {
25
+ result = await c.check(unit);
26
+ }
27
+ catch (e) {
28
+ result = { pass: false, reason: `the check threw: ${e.message.slice(0, 160)}` };
29
+ }
30
+ criteria.push({ id: c.id, section: c.section, asks: c.asks, ...result });
31
+ }
32
+ const met = criteria.filter((c) => c.pass).length;
33
+ grades[`${standard.id}@${standard.version}`] = { grade: criteria.length ? Math.floor((met / criteria.length) * 100) : 0, met, total: criteria.length, criteria, planned: standard.planned };
34
+ }
35
+ return grades;
36
+ }
@@ -0,0 +1,7 @@
1
+ export { grade, STANDARDS, type CriterionGrade, type GradeOptions, type StandardGrade } from './grade.js';
2
+ export { laneRootFailures, p3Gate, unitsOf } from './gate.js';
3
+ export { gatePublished, vendorOfPackage, type PublishedGate } from './published.js';
4
+ export { handlerName, protocol3, PLANNED } from './protocol-3.js';
5
+ export { sharingLanesIn } from './lanes.js';
6
+ export { unitAt } from './unit.js';
7
+ export type { Criterion, CriterionResult, GradeUnit, ScoreReport, Standard } from './types.js';
@@ -0,0 +1,11 @@
1
+ // @volter/twin-standard — the Protocol 3 standard (docs/contributing/architecture.md, "The grade"): the criteria a twin
2
+ // pack is judged by, the grader, the gate a pack repository and the catalog run, and the derivation the grade checks
3
+ // against. One package, versioned, so every place a pack is judged — its repository, its release, the catalog's review
4
+ // of a submission — judges by the same standard at the version it pins. Changing a criterion is a release of this
5
+ // package: a criterion's id never changes meaning, a changed criterion takes a new id and a new standard version.
6
+ export { grade, STANDARDS } from "./grade.js";
7
+ export { laneRootFailures, p3Gate, unitsOf } from "./gate.js";
8
+ export { gatePublished, vendorOfPackage } from "./published.js";
9
+ export { handlerName, protocol3, PLANNED } from "./protocol-3.js";
10
+ export { sharingLanesIn } from "./lanes.js";
11
+ export { unitAt } from "./unit.js";
@@ -0,0 +1,2 @@
1
+ /** The lanes over a vendor's state in the vendor's directory `pkg`, wherever its repository is. */
2
+ export declare function sharingLanesIn(pkg: string, vendor: string): string[];
@@ -0,0 +1,33 @@
1
+ // The lanes over a vendor's state (docs/contributing/architecture.md, "Pack layout"): a lane whose manifest names the
2
+ // vendor's service and that the vendor's serve factory serves (its server.ts, or its fixed fetch.ts when its manifest routes to the lane, imports the lane's src/). Such a lane is
3
+ // walked, measured and graded through the vendor's life; every other lane keeps its own.
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ /** The service a manifest names: the top-level `service:` of its exported manifest object. */
7
+ function serviceOf(manifestPath) {
8
+ const text = readFileSync(manifestPath, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
9
+ const body = /export\s+const\s+manifest\b[^=]*=\s*\{([\s\S]*)$/.exec(text)?.[1] ?? '';
10
+ // only the object's own first level: a nested object's `service` is not the manifest's
11
+ let depth = 0;
12
+ for (const m of body.matchAll(/[{}]|\bservice:\s*['"]([^'"]+)['"]/g)) {
13
+ if (m[0] === '{')
14
+ depth += 1;
15
+ else if (m[0] === '}') {
16
+ if (depth === 0)
17
+ break;
18
+ depth -= 1;
19
+ }
20
+ else if (depth === 0)
21
+ return m[1];
22
+ }
23
+ return undefined;
24
+ }
25
+ /** The lanes over a vendor's state in the vendor's directory `pkg`, wherever its repository is. */
26
+ export function sharingLanesIn(pkg, vendor) {
27
+ // the vendor serves a lane from its serve factory, or from its fixed fetch when its manifest routes to it
28
+ const serverText = ['server.ts', 'fetch.ts'].map((f) => join(pkg, 'src', f)).filter(existsSync).map((f) => readFileSync(f, 'utf8')).join('\n');
29
+ return (existsSync(pkg) ? readdirSync(pkg) : []).filter((l) => {
30
+ const manifest = join(pkg, l, 'src', 'manifest.ts');
31
+ return existsSync(manifest) && serviceOf(manifest) === vendor && new RegExp(`from ['"]\\.\\./${l}/src/`).test(serverText);
32
+ }).sort();
33
+ }
@@ -0,0 +1,8 @@
1
+ export type RuleHit = {
2
+ file: string;
3
+ line: number;
4
+ rule: string;
5
+ text: string;
6
+ };
7
+ /** Every line of a unit's `src/` that breaks a rule and does not record why. */
8
+ export declare function p3RuleHits(unit: string): RuleHit[];