@skillstech/thunderlang 1.3.0 → 1.4.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.
package/src/index.d.ts CHANGED
@@ -763,3 +763,6 @@ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPAR
763
763
  export type { ChangedCase, ChangedCases, WriteChange, RulePart } from './write.mjs';
764
764
  export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from './write-steps.mjs';
765
765
  export type { ThunderEdit, ThunderWriteResult, WriteProof } from './write-steps.mjs';
766
+ export { buildPassport, checkPassportOnDisk, accessEvidence } from './passport-fs.mjs';
767
+ export { PASSPORT_SCHEMA, assemblePassport, checkPassport, renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
768
+ export type { Passport, PassportEvidence, PassportCheck } from './passport.mjs';
package/src/index.mjs CHANGED
@@ -207,3 +207,6 @@ export { promoteDecision, PROMOTE_SCHEMA } from "./promote.mjs";
207
207
  // Thunder write: change a recovered rule and write exactly those characters back, verified by re-reading.
208
208
  export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from "./write.mjs";
209
209
  export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from "./write-steps.mjs";
210
+ // The Thunder Software Passport (docs/passport.md): build one from folders (git, runs) and check it on disk.
211
+ export { buildPassport, checkPassportOnDisk, accessEvidence } from './passport-fs.mjs';
212
+ export { PASSPORT_SCHEMA, assemblePassport, checkPassport, renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
package/src/libraries.mjs CHANGED
@@ -97,11 +97,24 @@ const CATALOG = [
97
97
  { re: /^fetch\s*\(/, say: (m, c) => { const a = splitTop(inside(c, c.indexOf('(')) ?? ''); const method = (a[1]?.match(/method\s*:\s*["'`](\w+)/i) || [])[1]?.toUpperCase() ?? 'GET'; return { says: `Sends a ${method} request to ${URL_WORDS(a[0])}`, does: 'ask' }; } },
98
98
  { re: /^(?:axios|http|httpClient|client|api|ky|got|superagent|request)\s*\.\s*(get|post|put|patch|delete|head)\s*\(/i, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
99
99
  { re: /^(?:requests|httpx|session|self\.session|aiohttp\.ClientSession\(\))\s*\.\s*(get|post|put|patch|delete)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
100
- { re: /^(?:_?httpClient|client|_client|HttpClient)\s*\.\s*(Get|Post|Put|Patch|Delete)(?:AsJson|FromJson|String)?Async\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
100
+ { re: /^(?:this\.)?(?:_?[Hh]ttp(?:Client)?|_?client|\w*HttpClient|_?\w+Client)\s*\.\s*(Get|Post|Put|Patch|Delete)(?:AsJson|FromJson|String)?Async\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
101
101
  { re: /^(?:restTemplate|webClient)\s*\.\s*(get|post|put|delete|patch)(?:ForObject|ForEntity)?\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
102
102
  { re: /^http\s*\.\s*(Get|Post|Head)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
103
103
  { re: /^reqwest\s*::\s*get\s*\(/, say: (m, c) => ({ says: `Sends a GET request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
104
104
 
105
+ // ── A new random ID: crypto.randomUUID(), uuid.uuid4(), Guid.NewGuid(), uuidv4(), UUID.randomUUID() ──
106
+ { re: /^(?:(?:globalThis\.|window\.)?crypto\.randomUUID|uuid\.uuid4|Guid\.NewGuid|uuidv4|uuid\.v4|UUID\.randomUUID|Uuid::new_v4)\s*\(\s*\)(?:\.(?:ToString|toString|hex)\(\)|\.hex)?$/, say: () => ({ says: 'a new random ID', does: 'calculate', value: true }) },
107
+
108
+ // ── .NET: a shared lookup table that makes an entry only once (ConcurrentDictionary.GetOrAdd) ──
109
+ // `byKey.GetOrAdd(key, _ => new Lazy<Task<T>>(() => Place(request))).Value`: later calls with the same key get the
110
+ // entry made the first time. The function that makes it is named when the code names one.
111
+ { re: /^(?:this\.)?(_?[A-Za-z]\w*)\s*\.\s*GetOrAdd\s*\(/, say: (m, c) => {
112
+ const args = splitTop(inside(c, c.indexOf('(', m.index + m[0].length - 1)) ?? '');
113
+ if (args.length !== 2) return null;
114
+ const made = [...args[1].matchAll(/\b([A-Za-z_]\w*)\s*\(/g)].map((x) => x[1]).filter((x) => !/^(?:new|Lazy|Task|ValueTask)$/.test(x)).pop();
115
+ return { says: `the entry for ${valueWords(args[0])} in ${words(m[1])}, made${made ? ` by ${words(made)}` : ''} if it is missing (a later call with the same ${valueWords(args[0]).replace(/^the [\w ]+'s /, '')} gets that same entry)`, does: 'find', value: true };
116
+ } },
117
+
105
118
  // ── Prisma ──
106
119
  { re: /^(?:this\.)?prisma\s*\.\s*(\w+)\s*\.\s*(findUnique|findUniqueOrThrow|findFirst|findFirstOrThrow|findMany|create|createMany|update|updateMany|upsert|delete|deleteMany|count|aggregate)\s*\(/, say: (m, c) => {
107
120
  const thing = words(m[1]), args = inside(c, c.indexOf('(', m.index + m[0].length - 1)) ?? '', whose = whereOf(args);
@@ -176,6 +189,14 @@ const CATALOG = [
176
189
 
177
190
  // ── JSON, files, time ──
178
191
  { re: /^JSON\s*\.\s*parse\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[1])} as JSON`, does: 'calculate' }) },
192
+ // An object written right there names its fields: JSON.stringify({ items: cart, coupon }) -> "Turns items (cart) and coupon into JSON text".
193
+ { re: /^JSON\s*\.\s*stringify\s*\(\s*\{/, say: (m, c) => {
194
+ const obj = inside(c, c.indexOf('{'));
195
+ const fields = obj == null ? null : splitTop(obj).filter((x) => x.trim()).map((x) => x.trim().match(/^([A-Za-z_$][\w$]*)(?:\s*:\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?))?$/));
196
+ if (!fields?.length || fields.some((f) => !f)) return null;
197
+ const said = fields.map((f) => (f[2] && f[2] !== f[1] ? `${words(f[1])} (${valueWords(f[2])})` : words(f[1])));
198
+ return { says: `Turns ${said.length === 1 ? said[0] : `${said.slice(0, -1).join(', ')} and ${said.at(-1)}`} into JSON text`, does: 'calculate' };
199
+ } },
179
200
  { re: /^JSON\s*\.\s*stringify\s*\(\s*([^,]+)/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON text`, does: 'calculate' }) },
180
201
  { re: /^json\s*\.\s*(loads|load)\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[2])} as JSON`, does: 'calculate' }) },
181
202
  { re: /^json\s*\.\s*(dumps|dump)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Turns ${valueWords(m[2])} into JSON text`, does: 'calculate' }) },
package/src/model.mjs CHANGED
@@ -14,6 +14,7 @@ import { psThings } from './powershell.mjs';
14
14
  import { splitLogic, closeOf, isCodeWords, balancedText } from './faithful.mjs';
15
15
  import { detailParts } from './meaning.mjs';
16
16
  import { linkSystem, callsSummary } from './system.mjs';
17
+ import { accessFlow, ownershipWords } from './flow/access.mjs';
17
18
 
18
19
  export const MODEL_SCHEMA = 'thunder-model-v1';
19
20
  /**
@@ -41,6 +42,8 @@ function startValue(expr, params = {}) {
41
42
  if (/^(True|true)$/.test(e)) return 'yes at first';
42
43
  if (/^(False|false)$/.test(e)) return 'no at first';
43
44
  if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
45
+ // A typed number (C# 0.08m, Java 10L, 2.5f): the number, without its type letter.
46
+ if (/^-?\d+(\.\d+)?(?:[mMfFdDlL]|[uU][lL]?|[lL][uU])$/.test(e)) return `${e.replace(/[a-zA-Z]+$/, '')} at first`;
44
47
  if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes(e)}" at first`;
45
48
  const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/) || e.match(/^(?:[A-Z]\w*)?\.([a-z]\w*)$/); // Swift: .onShelf
46
49
  if (en) return `${words(en[1])} at first`;
@@ -830,6 +833,21 @@ export function thunderModel(files, { name = 'app' } = {}) {
830
833
  }
831
834
  }
832
835
  } catch (e) { unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Screens could not be read: ${e.message}` }); }
836
+ // Ownership on web routes (src/flow/access.mjs): does a record chosen by the request get limited to the caller?
837
+ // Only for TypeScript/JavaScript routes; each route's member says its verdict in words.
838
+ const routeMembers = members.filter((m) => m.route && /^(typescript|javascript)$/i.test(m.language ?? ''));
839
+ if (routeMembers.length) {
840
+ try {
841
+ const access = accessFlow(files.filter((f) => /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(f.path)));
842
+ for (const r of access.routes) {
843
+ if (!r.verdict) continue;
844
+ const m = routeMembers.find((x) => x.file === r.file && x.route === `${r.method} ${r.path}`)
845
+ ?? routeMembers.find((x) => x.file === r.file && Math.abs((x.lines?.[0] ?? 0) - r.line) <= 2);
846
+ if (m) m.ownership = { verdict: r.verdict, says: ownershipWords(r), why: r.why, paths: r.paths };
847
+ }
848
+ model.access = { schema: access.schema, summary: access.summary };
849
+ } catch (e) { unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Ownership on routes could not be checked: ${e.message}` }); }
850
+ }
833
851
  return model;
834
852
  }
835
853
 
@@ -893,6 +911,7 @@ export function modelText(model, id, { note = null, full = false } = {}) {
893
911
  const lines = [`${m.label}${owner && m.kind !== 'setup' ? ` (${owner.label})` : ''}${m.kind === 'rule' ? ': a rule' : ''}`];
894
912
  if (m.when) lines.push(` ${m.when}`);
895
913
  else if (m.route) lines.push(` When someone calls ${m.route}`);
914
+ if (m.ownership) lines.push(` ${m.ownership.says}`);
896
915
  if (m.doc) lines.push(` Author's note: ${m.doc}`);
897
916
  if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(', ')}`);
898
917
  if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
@@ -1115,7 +1134,8 @@ export function readLevel(model, level, focus, { full = false } = {}) {
1115
1134
  const resource = thing?.kind === 'resource' ? thing : null;
1116
1135
  const thingCard = (t) => ({ id: t.id, label: t.label, ...(t.doc ? { doc: t.doc } : {}), knows: t.knows.map((k) => ({ label: k.label, ...(k.start ? { start: k.start } : {}) })), can: model.members.filter((m) => m.owner === t.id && m.kind !== 'setup' && !m.callback).map(short) });
1117
1136
  return { ...base, ...about,
1118
- ...(thing?.doc ?? model.files[0]?.purpose ? { purpose: thing?.doc ?? model.files[0]?.purpose } : {}),
1137
+ // (A file's own description describes that file: the whole app takes one only when it is one file.)
1138
+ ...((() => { const p = thing ? (thing.doc ?? model.files.find((f) => f.path === thing.file)?.purpose) : model.files.length === 1 ? model.files[0]?.purpose : null; return p ? { purpose: p } : {}; })()),
1119
1139
  things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === 'thing' && !t.screen)).map(thingCard),
1120
1140
  resources: (resource ? [resource] : thing ? [] : model.things.filter((t) => t.kind === 'resource')).map(resourceCard),
1121
1141
  ...(thing ? {} : { permissions: model.permissions ?? [], settings: model.settings ?? [], facts: model.facts ?? [] }),
@@ -1138,6 +1158,7 @@ export function readLevel(model, level, focus, { full = false } = {}) {
1138
1158
  // Calls and requests worth linking that could not be, with the reason (never guessed).
1139
1159
  notLinked: (model.notLinked ?? []).filter((x) => x.from === member.id),
1140
1160
  notExplained: steps.filter((s) => s.notExplained).length, uses, usedBy, tryable: !!member.rule, ...(member.rule ? { rule: member.rule } : {}),
1161
+ ...(member.ownership ? { ownership: member.ownership } : {}),
1141
1162
  source: 'Read from code by the Thunder compiler, with no AI.' };
1142
1163
  }
1143
1164
  if (lv.id === 'text') {
@@ -0,0 +1,101 @@
1
+ // thunder passport: the command line for the Thunder Software Passport (passport.mjs, passport-fs.mjs, docs/passport.md).
2
+ // thunder passport <folder…> [--base REV] [--head REV] [--run "cmd" | --run "part: cmd" …] [--purpose "…" | --purpose-file f]
3
+ // [--evidence f.json …] [--json | --md] [--out file] [--md-out file.md]
4
+ // thunder passport check <passport.json> [--part name=folder …] [--json]
5
+ import { readFileSync, writeFileSync } from 'node:fs';
6
+ import { dirname, resolve } from 'node:path';
7
+ import { buildPassport, checkPassportOnDisk } from './passport-fs.mjs';
8
+ import { renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
9
+ import { paint, useColor } from './term.mjs';
10
+
11
+ const USAGE = `usage: thunder passport <folder…> [--base REV] [--run "cmd" | --run "part: cmd" …] [--purpose "…" | --purpose-file f]
12
+ [--evidence result.json …] [--no-access] [--json | --md] [--out passport.json] [--md-out passport.md]
13
+ thunder passport check <passport.json> [--part name=folder …] [--json]
14
+ A passport records what is known about a feature or a change: its behavior, what it depends on and changes, the
15
+ evidence for each claim (with what it does not cover), and what is not verified. When this build has the ownership
16
+ check (thunder read --access), its verdicts join as evidence (--no-access leaves them out). Only git and the commands you pass
17
+ with --run are executed. Exit codes: 0 built, 1 a --run command failed (still recorded), 2 usage.`;
18
+
19
+ const say = (s) => console.log(paint(s, useColor()));
20
+
21
+ /** The ownership check (src/flow/access.mjs), when this build has it; null otherwise. */
22
+ async function loadAccess() {
23
+ try { const m = await import('./flow/access.mjs'); return typeof m.accessFlow === 'function' ? m.accessFlow : null; } catch { return null; }
24
+ }
25
+
26
+ export async function passportMain(argv) {
27
+ if (argv[0] === 'check') return checkMain(argv.slice(1));
28
+ const a = { _: [], base: null, head: null, run: [], purpose: null, purposeFile: null, evidence: [], json: false, md: false, out: null, mdOut: null, access: true };
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const x = argv[i];
31
+ const need = () => { const v = argv[++i]; if (v == null) throw new Error(`${x} needs a value.`); return v; };
32
+ try {
33
+ if (x === '--base') a.base = need();
34
+ else if (x === '--head') a.head = need();
35
+ else if (x === '--run') a.run.push(need());
36
+ else if (x === '--purpose') a.purpose = need();
37
+ else if (x === '--purpose-file') a.purposeFile = need();
38
+ else if (x === '--evidence') a.evidence.push(need());
39
+ else if (x === '--json') a.json = true;
40
+ else if (x === '--no-access') a.access = false;
41
+ else if (x === '--md') a.md = true;
42
+ else if (x === '--out') a.out = need();
43
+ else if (x === '--md-out') a.mdOut = need();
44
+ else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
45
+ else if (x.startsWith('--')) { console.error(`thunder passport: there is no option ${x}.\n${USAGE}`); return 2; }
46
+ else a._.push(x);
47
+ } catch (e) { console.error(`thunder passport: ${e.message}\n${USAGE}`); return 2; }
48
+ }
49
+ if (!a._.length) { console.error(`thunder passport: name the folders it describes (each one part, as for thunder trace).\n${USAGE}`); return 2; }
50
+ if (a.json && a.md) { console.error('thunder passport: choose --json or --md, not both.'); return 2; }
51
+ let purpose = null;
52
+ if (a.purposeFile) {
53
+ try { purpose = { text: readFileSync(a.purposeFile, 'utf8').trim().slice(0, 4000), source: a.purposeFile }; } catch { console.error(`thunder passport: couldn't read ${a.purposeFile}.`); return 2; }
54
+ } else if (a.purpose) purpose = { text: a.purpose, source: 'given with --purpose' };
55
+ const evidence = [];
56
+ for (const f of a.evidence) {
57
+ try { evidence.push(JSON.parse(readFileSync(f, 'utf8'))); } catch { console.error(`thunder passport: ${f} is not a JSON file Thunder can read.`); return 2; }
58
+ }
59
+ const relativeTo = a.out ? dirname(resolve(a.out)) : process.cwd();
60
+ let p;
61
+ const access = a.access ? await loadAccess() : null;
62
+ try { p = buildPassport({ parts: a._, base: a.base, head: a.head, run: a.run, purpose, evidence, access, relativeTo }); }
63
+ catch (e) { console.error(`thunder passport: ${e.message}`); return 2; }
64
+ if (a.mdOut) writeFileSync(a.mdOut, renderPassportMarkdown(p));
65
+ const failed = p.evidence.some((e) => e.kind === 'test-run' && e.status === 'failed');
66
+ const text = a.md ? renderPassportMarkdown(p) : `${JSON.stringify(p, null, 2)}\n`;
67
+ if (a.out) {
68
+ writeFileSync(a.out, a.md ? text : `${JSON.stringify(p, null, 2)}\n`);
69
+ if (!a.json) { say(renderPassportSummary(p)); say(`\nWrote ${a.out}. Check it later with: thunder passport check ${a.out}`); }
70
+ } else if (a.json) process.stdout.write(text);
71
+ else if (a.md) process.stdout.write(text);
72
+ else say(renderPassportSummary(p));
73
+ return failed ? 1 : 0;
74
+ }
75
+
76
+ function checkMain(argv) {
77
+ const a = { _: [], json: false, dirs: {} };
78
+ for (let i = 0; i < argv.length; i++) {
79
+ const x = argv[i];
80
+ if (x === '--json') a.json = true;
81
+ else if (x === '--part') { const m = String(argv[++i] ?? '').match(/^([^=]+)=(.+)$/); if (!m) { console.error('thunder passport check: --part needs name=folder.'); return 2; } a.dirs[m[1]] = m[2]; }
82
+ else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
83
+ else if (x.startsWith('--')) { console.error(`thunder passport check: there is no option ${x}.\n${USAGE}`); return 2; }
84
+ else a._.push(x);
85
+ }
86
+ if (a._.length !== 1) { console.error(`thunder passport check: name one passport file.\n${USAGE}`); return 2; }
87
+ let p;
88
+ try { p = JSON.parse(readFileSync(a._[0], 'utf8')); } catch { console.error(`thunder passport check: couldn't read ${a._[0]} as a passport.`); return 2; }
89
+ let r;
90
+ try { r = checkPassportOnDisk(p, { baseDir: dirname(resolve(a._[0])), dirs: a.dirs }); } catch (e) { console.error(`thunder passport check: ${e.message}`); return 2; }
91
+ if (a.json) { console.log(JSON.stringify(r, null, 2)); return 0; }
92
+ const L = [`Thunder passport check: ${r.current} current, ${r.stale} stale (nothing was re-run)`, ''];
93
+ for (const x of r.items) {
94
+ L.push(` ${x.freshness === 'current' ? '✓ current' : x.freshness === 'stale' ? '! stale' : '○ unknown'}: ${x.claim}`);
95
+ for (const c of x.changed) L.push(` ${c.part}/${c.file} ${c.now === 'missing' ? 'is gone' : 'changed since the passport was built'}`);
96
+ }
97
+ if (r.changedFiles.length) L.push('', `Files that changed since the passport was built: ${r.changedFiles.map((c) => `${c.part}/${c.file}${c.now === 'missing' ? ' (gone)' : ''}`).join(', ')}`);
98
+ if (r.stale) L.push('', 'Stale claims are not evidence about the code as it is now. Build a new passport to re-run them.');
99
+ say(L.join('\n'));
100
+ return 0;
101
+ }
@@ -0,0 +1,9 @@
1
+ import type { Passport, PassportCheck, PassportEvidence } from './passport.mjs';
2
+ export function buildPassport(options: {
3
+ parts: string[]; base?: string | null; head?: string | null; run?: string[];
4
+ purpose?: { text: string; source?: string } | null; evidence?: unknown[];
5
+ /** The ownership check (accessFlow from src/flow/access.mjs), run per part when given. */
6
+ access?: ((files: Array<{ path: string; source: string }>) => unknown) | null; relativeTo?: string; builtAt?: string; timeoutMs?: number;
7
+ }): Passport;
8
+ export function checkPassportOnDisk(passport: Passport, options?: { baseDir?: string; dirs?: Record<string, string> }): PassportCheck;
9
+ export function accessEvidence(report: unknown, partOf?: (file: string) => string | null): Array<Omit<PassportEvidence, 'id'>>;
@@ -0,0 +1,180 @@
1
+ // Thunder Software Passport, the Node side: read the parts (folders or repositories), what changed since a base
2
+ // commit, run the test commands you name, and hand everything to assemblePassport (passport.mjs, pure).
3
+ // Only git and the commands you pass with `run` are executed; nothing else is run, fetched, or sent anywhere.
4
+ import { execFileSync, spawnSync } from 'node:child_process';
5
+ import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
6
+ import { basename, join, resolve, relative } from 'node:path';
7
+ import { collectReadableFiles } from './read-repo-fs.mjs';
8
+ import { assemblePassport, checkPassport } from './passport.mjs';
9
+ import { COMPILER_VERSION } from './emit.mjs';
10
+
11
+ const git = (dir, args) => {
12
+ try { return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024 }); } catch { return null; }
13
+ };
14
+
15
+ const SKIP = new Set(['node_modules', '.git', 'bin', 'obj', 'dist', 'build', '__pycache__', '.venv', 'venv', 'target', '.next']);
16
+
17
+ /** Packages a part declares: package.json dependencies, requirements.txt, and .csproj PackageReference. */
18
+ function packagesIn(root) {
19
+ const out = [];
20
+ const walk = (dir, depth) => {
21
+ if (depth > 4) return;
22
+ let names = [];
23
+ try { names = readdirSync(dir).sort(); } catch { return; }
24
+ for (const n of names) {
25
+ if (SKIP.has(n)) continue;
26
+ const full = join(dir, n);
27
+ let st;
28
+ try { st = statSync(full); } catch { continue; }
29
+ if (st.isDirectory()) { walk(full, depth + 1); continue; }
30
+ const rel = relative(root, full).split('\\').join('/');
31
+ try {
32
+ if (n === 'package.json') {
33
+ const j = JSON.parse(readFileSync(full, 'utf8'));
34
+ for (const k of ['dependencies', 'devDependencies']) for (const [name, version] of Object.entries(j[k] ?? {})) out.push({ name, version: String(version), from: rel, ...(k === 'devDependencies' ? { dev: true } : {}) });
35
+ } else if (n === 'requirements.txt') {
36
+ for (const line of readFileSync(full, 'utf8').split('\n')) {
37
+ const m = line.replace(/#.*/, '').trim().match(/^([A-Za-z0-9_.-]+)\s*(.*)$/);
38
+ if (m) out.push({ name: m[1], ...(m[2] ? { version: m[2] } : {}), from: rel });
39
+ }
40
+ } else if (/\.csproj$/.test(n)) {
41
+ for (const m of readFileSync(full, 'utf8').matchAll(/<PackageReference\s+Include="([^"]+)"(?:\s+Version="([^"]+)")?/g)) out.push({ name: m[1], ...(m[2] ? { version: m[2] } : {}), from: rel });
42
+ }
43
+ } catch { /* a manifest Thunder cannot parse is not a package list */ }
44
+ }
45
+ };
46
+ walk(root, 0);
47
+ return out;
48
+ }
49
+
50
+ /** What changed in one part since `base` (committed and not), with each changed file's base version. */
51
+ function changesSince(root, base) {
52
+ const prefix = git(root, ['rev-parse', '--show-prefix'])?.trim() ?? '';
53
+ const diff = git(root, ['diff', '--unified=0', '--no-color', '--no-renames', base, '--', '.']) ?? '';
54
+ const byFile = new Map();
55
+ let cur = null;
56
+ for (const line of diff.split('\n')) {
57
+ let m;
58
+ if ((m = line.match(/^diff --git a\/(.+) b\/(.+)$/))) { cur = { file: m[2], ranges: [], status: 'changed' }; byFile.set(cur.file, cur); }
59
+ else if (cur && line.startsWith('new file mode')) cur.status = 'added';
60
+ else if (cur && line.startsWith('deleted file mode')) cur.status = 'removed';
61
+ else if (cur && (m = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/))) {
62
+ const start = Number(m[1]), n = m[2] === undefined ? 1 : Number(m[2]);
63
+ cur.ranges.push(n === 0 ? [Math.max(1, start), Math.max(1, start)] : [start, start + n - 1]);
64
+ }
65
+ }
66
+ for (const f of (git(root, ['ls-files', '--others', '--exclude-standard', '--', '.']) ?? '').split('\n').filter(Boolean)) {
67
+ const file = prefix + f;
68
+ if (!byFile.has(file)) byFile.set(file, { file, ranges: [], status: 'added' });
69
+ }
70
+ const out = [];
71
+ for (const c of byFile.values()) {
72
+ if (!c.file.startsWith(prefix)) continue;
73
+ const old = c.status === 'added' ? null : git(root, ['show', `${base}:${c.file}`]);
74
+ out.push({ file: c.file.slice(prefix.length), status: c.status, ranges: c.ranges, old: old == null || old.includes('\0') ? null : old });
75
+ }
76
+ return out.sort((a, b) => a.file.localeCompare(b.file));
77
+ }
78
+
79
+ /**
80
+ * Evidence items from a thunder-access-v1 report (the ownership check, src/flow/access.mjs, when present). One item
81
+ * per route that has a verdict. `partOf(file)` names the part a file is in when the report does not say.
82
+ */
83
+ export function accessEvidence(report, partOf = () => null) {
84
+ const words = { guarded: 'checks that the record belongs to the caller on every path', unguarded: 'has a path with no ownership check (every step was followed)', 'cannot tell': 'cannot be told: Thunder could not follow every step', 'cannot-tell': 'cannot be told: Thunder could not follow every step' };
85
+ return (report?.routes ?? []).filter((r) => r.verdict).map((r) => {
86
+ const part = r.part ?? partOf(r.file);
87
+ const files = [...new Set([r.file, ...(r.paths ?? []).flatMap((x) => (x.steps ?? []).map((st) => st.file))].filter(Boolean))];
88
+ return {
89
+ kind: 'access-flow', status: 'read',
90
+ claim: `${r.method && r.path ? `${r.method} ${r.path}` : r.route ?? 'A route'}${part ? ` in ${part}` : ''} ${words[r.verdict] ?? `has the verdict "${r.verdict}"`}.`,
91
+ basis: { schema: report.schema ?? 'thunder-access-v1', verdict: r.verdict, at: r.file ? `${part ? `${part}:` : ''}${r.file}${r.line ? `:${r.line}` : ''}` : null, why: r.why ?? null },
92
+ scope: 'Read from code by the ownership check; nothing was run. Only the frameworks and data libraries it supports, and only these files.',
93
+ inputs: part ? files.map((file) => ({ part, file })) : [],
94
+ };
95
+ });
96
+ }
97
+
98
+ /**
99
+ * Build a passport from folders on disk.
100
+ * parts: folder paths (each one part, named by its folder, as Thunder Trace takes them)
101
+ * base: a commit to compare with (a change); none for a snapshot
102
+ * head: must be the checked-out commit when given (the passport reads the files on disk)
103
+ * run: commands to run and record; "billing: python3 -m unittest" runs in the part named billing
104
+ * purpose: { text, source } (from --purpose or --purpose-file); never invented
105
+ * evidence: extra evidence (parsed JSON: a thunder-access-v1 result, or a list of evidence items)
106
+ * relativeTo: where part paths are recorded from (the passport's folder, so `check` finds them later)
107
+ */
108
+ export function buildPassport({ parts, base = null, head = null, run = [], purpose = null, evidence = [], access = null, relativeTo = process.cwd(), builtAt, timeoutMs = 20 * 60 * 1000 } = {}) {
109
+ if (!parts?.length) throw new Error('name at least one folder to describe.');
110
+ const names = new Set();
111
+ const read = parts.map((dir) => {
112
+ const root = resolve(dir);
113
+ let ok = false;
114
+ try { ok = statSync(root).isDirectory(); } catch { /* missing */ }
115
+ if (!ok) throw new Error(`${dir} is not a folder.`);
116
+ const name = basename(root);
117
+ if (names.has(name)) throw new Error(`two parts are called "${name}"; give folders with different names.`);
118
+ names.add(name);
119
+ const top = git(root, ['rev-parse', '--show-toplevel'])?.trim() ?? null;
120
+ const sha = top ? git(root, ['rev-parse', 'HEAD'])?.trim() || null : null;
121
+ const dirty = top ? !!git(root, ['status', '--porcelain', '--', '.'])?.trim() : false;
122
+ if (head && top) {
123
+ const want = git(root, ['rev-parse', '--verify', `${head}^{commit}`])?.trim();
124
+ if (!want) throw new Error(`${head} is not a commit in ${dir}.`);
125
+ if (want !== sha) throw new Error(`the passport reads the files on disk, and ${dir} is not at ${head}. Check out ${head} first.`);
126
+ }
127
+ let changes;
128
+ if (base) {
129
+ if (!top) throw new Error(`${dir} is not in a git repository, so there is no ${base} to compare with.`);
130
+ if (!git(root, ['rev-parse', '--verify', `${base}^{commit}`])?.trim()) throw new Error(`${base} is not a commit in ${dir}.`);
131
+ changes = changesSince(root, base);
132
+ }
133
+ const files = collectReadableFiles(root).map((f) => ({ path: f.path, source: f.source }));
134
+ return { name, root, path: relative(relativeTo, root).split('\\').join('/') || '.', sha, dirty, files, packages: packagesIn(root), ...(changes ? { changes } : {}) };
135
+ });
136
+
137
+ const runs = run.map((spec) => {
138
+ const m = String(spec).match(/^([A-Za-z0-9_.-]+):\s+(.+)$/);
139
+ const part = m && read.find((p) => p.name === m[1]) ? m[1] : null;
140
+ const command = part ? m[2] : String(spec);
141
+ const cwd = part ? read.find((p) => p.name === part).root : process.cwd();
142
+ const r = spawnSync(`(${command}) 2>&1`, { shell: true, cwd, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 });
143
+ const exitCode = r.status ?? (r.error || r.signal ? 1 : 0);
144
+ const output = `${r.stdout ?? ''}${r.error ? `\n(${r.error.message})` : ''}${r.signal ? `\n(stopped by ${r.signal})` : ''}`;
145
+ return { command, part, cwd: relative(relativeTo, cwd).split('\\').join('/') || '.', exitCode, output };
146
+ });
147
+
148
+ const extra = [];
149
+ // A file path names its part when exactly one part has it.
150
+ const partOf = (file) => { const hits = read.filter((p) => p.files.some((f) => f.path === file)); return hits.length === 1 ? hits[0].name : null; };
151
+ // The ownership check, when given (the CLI passes accessFlow when src/flow/access.mjs is there): run per part.
152
+ if (typeof access === 'function') {
153
+ for (const p of read) {
154
+ try { extra.push(...accessEvidence(access(p.files), () => p.name)); } catch { /* a part the check cannot read adds no evidence */ }
155
+ }
156
+ }
157
+ for (const e of evidence) {
158
+ if (e?.schema === 'thunder-access-v1') extra.push(...accessEvidence(e, partOf));
159
+ else if (Array.isArray(e)) extra.push(...e.filter((x) => x && x.kind && x.claim && x.basis && x.scope).map((x) => ({ status: 'read', ...x })));
160
+ }
161
+ const change = base ? { base: git(read[0].root, ['rev-parse', base])?.trim() ?? base, head: head ? read[0].sha : read[0].sha ? `${read[0].sha}${read.some((p) => p.dirty) ? ' (with uncommitted changes)' : ''}` : null } : null;
162
+ return assemblePassport({ parts: read, change, runs, purpose, extra, builtAt, thunder: COMPILER_VERSION });
163
+ }
164
+
165
+ /**
166
+ * Check a passport against the files on disk: each evidence item current or stale. Part folders are found from
167
+ * the paths the passport recorded, relative to `baseDir` (the passport's folder), unless `dirs` names them.
168
+ */
169
+ export function checkPassportOnDisk(passport, { baseDir = process.cwd(), dirs = {} } = {}) {
170
+ const where = new Map(passport.subject.parts.map((p) => [p.name, dirs[p.name] ? resolve(dirs[p.name]) : resolve(baseDir, p.path)]));
171
+ return checkPassport(passport, {
172
+ read: (part, file) => {
173
+ const root = where.get(part);
174
+ if (!root) return null;
175
+ const full = join(root, file);
176
+ try { return existsSync(full) ? readFileSync(full, 'utf8') : null; } catch { return null; }
177
+ },
178
+ });
179
+ }
180
+
@@ -0,0 +1,46 @@
1
+ // Types for the Thunder Software Passport (passport.mjs, passport-fs.mjs). Spec: docs/passport.md.
2
+ export const PASSPORT_SCHEMA: 'thunder-passport-v1';
3
+ export const ALWAYS_NOT_VERIFIED: string[];
4
+ export interface PassportInput { part: string; file: string; sha256: string | null }
5
+ export interface PassportEvidence {
6
+ id: string;
7
+ kind: 'test-run' | 'trace-link' | 'review' | 'accuracy-gate' | 'conformance' | 'access-flow' | string;
8
+ /** passed / failed: a command ran; read: read from code, nothing was run. */
9
+ status: 'passed' | 'failed' | 'read';
10
+ claim: string;
11
+ basis: { command?: string; cwd?: string; exitCode?: number; outputDigest?: string; outputTail?: string; from?: string; to?: string; base?: string; head?: string; [k: string]: unknown };
12
+ /** What this evidence does not cover. */
13
+ scope: string;
14
+ /** The files it depended on, by content hash; when one changes, the item is stale. */
15
+ inputs: PassportInput[];
16
+ }
17
+ export interface Passport {
18
+ schema: 'thunder-passport-v1';
19
+ subject: { kind: 'change' | 'feature'; parts: Array<{ name: string; path: string; sha: string | null; dirty: boolean }> };
20
+ purpose: { stated: boolean; text: string; source: string | null };
21
+ behavior: Array<{ part: string; file: string; lines: [number, number]; name: string; kind: string; change?: 'added' | 'changed' | 'removed'; text: string }>;
22
+ dependencies: { files: PassportInput[]; links: Array<{ kind: string; says: string; from: string; to: string }>; packages: Array<{ name: string; version?: string; from: string; dev?: boolean }>; services: Array<{ part: string; calls: string; at: string }> };
23
+ effects: Array<{ part: string; file: string; line: number; in: string; kind: 'reads' | 'writes' | 'sends' | 'deletes' | 'calls another part' | 'sends the person to'; says: string; how: 'detected' | 'observed' | 'declared'; basis: string }>;
24
+ evidence: PassportEvidence[];
25
+ unknowns: { notRead: Array<{ part: string; file: string; line: number; what: string }>; notLinked: Array<{ kind: string; call: string; at: string; why: string }>; untested: Array<{ part: string; what: string }>; notShown?: string; notVerified: string[] };
26
+ history: { base: string | null; head: string | null; changedFiles: Array<{ part: string; file: string; status: string }>; thunder: string | null; builtAt: string };
27
+ summary: { claims: number; passed: number; failed: number; readFromCode: number; unknowns: number; notVerified: number };
28
+ fingerprint: string;
29
+ }
30
+ export interface PassportCheck {
31
+ schema: 'thunder-passport-check-v1'; current: number; stale: number;
32
+ items: Array<{ id: string; kind: string; claim: string; freshness: 'current' | 'stale' | 'unknown'; changed: Array<{ part: string; file: string; now: 'changed' | 'missing' }> }>;
33
+ changedFiles: Array<{ part: string; file: string; now: 'changed' | 'missing' }>;
34
+ }
35
+ export function assemblePassport(input: {
36
+ parts: Array<{ name: string; path?: string; sha?: string | null; dirty?: boolean; files: Array<{ path: string; source: string }>; packages?: Passport['dependencies']['packages']; changes?: Array<{ file: string; status: 'added' | 'changed' | 'removed'; ranges: Array<[number, number]>; old?: string | null }> }>;
37
+ change?: { base: string; head: string | null } | null;
38
+ runs?: Array<{ command: string; part: string | null; cwd: string; exitCode: number; output: string }>;
39
+ purpose?: { text: string; source?: string } | null;
40
+ extra?: Array<Omit<PassportEvidence, 'id'>>;
41
+ builtAt?: string; thunder?: string | null;
42
+ }): Passport;
43
+ export function summarize(passport: Omit<Passport, 'summary' | 'fingerprint'>): Passport['summary'];
44
+ export function checkPassport(passport: Passport, options: { read: (part: string, file: string) => string | null }): PassportCheck;
45
+ export function renderPassportSummary(passport: Passport): string;
46
+ export function renderPassportMarkdown(passport: Passport): string;