@skillstech/thunderlang 1.4.2 → 1.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skillstech/thunderlang",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "description": "Thunder™, the human programming language: the deterministic ThunderLang™ compiler, CLI, and Language Server. No AI required. Reads code in seventeen languages into Thunder, changes TypeScript, JavaScript, Python, and Go code from Thunder with a proof, compiles rules to six languages, and executes them: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/cli.mjs CHANGED
@@ -504,7 +504,7 @@ Read and understand code
504
504
  review <base-ref> [head-ref] [--format markdown|json] [--paths <glob,...>] [--out <file>]
505
505
  review in Thunder: what changed in meaning between two git commits (head: the working tree
506
506
  when omitted), as Markdown for a pull request comment; read from git, no network
507
- trace <folder…> [--json] [--out f] Thunder Trace: routes, requests, and events linked across repositories, cited repo@sha:file:line
507
+ trace <folder…> [--json] [--out f] Thunder Trace: routes, events, tables, and packages linked across repositories, cited repo@sha:file:line
508
508
  trace impact <thing | --diff [--base ref]> <folder…> what a change can affect in other repositories (one hop, ranked by risk)
509
509
  passport <folder…> [--base ref] [--run "part: cmd"…] [--purpose …] an evidence record: behavior, links, effects, evidence with its limits, what is not verified
510
510
  passport check <passport.json> which of its claims are still about the code as it is now (current or stale)
package/src/core.d.ts CHANGED
@@ -203,4 +203,4 @@ export function writeAcrossEvidence(result: WriteAcrossResult | { ok: false }):
203
203
 
204
204
  // What a reading shows and in what order (src/reading-layout.mjs).
205
205
  export { READING_LAYOUT_SCHEMA, READING_LABELS, readingLayout, thingCard, dataCard, ioBoxes, detailsLayout, flowEdgeLabel, memberSymbolId } from './reading-layout.mjs';
206
- export type { ReadingLayout, ThingCardLayout, DataCardLayout, IOBoxesLayout, DetailsLayout, When, KnowsLine, ThunderSymbolId } from './reading-layout.d.mts';
206
+ export type { ReadingLayout, ThingCardLayout, DataCardLayout, IOBoxesLayout, MemberEntryLayout, DetailsLayout, When, KnowsLine, ThunderSymbolId } from './reading-layout.d.mts';
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '1.4.2';
33
+ export const COMPILER_VERSION = '1.5.0';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
package/src/mcp.mjs CHANGED
@@ -265,12 +265,12 @@ const TOOLS = [
265
265
  },
266
266
  {
267
267
  name: 'intent_trace',
268
- description: 'ASK THUNDER TRACE BEFORE CHANGING CODE THAT OTHER REPOSITORIES USE (local only). Give the repository folders. With "thing" (a route like "POST /api/orders", an event name, or "repo:file[:line]") or "diff": true (the branch and uncommitted changes), it answers what the change can affect in the OTHER repositories: callers of a changed or removed route, listeners of a published event, ranked high/medium/low, one hop out, every item cited repo@sha:file:line. With neither, it gives the links between the repositories. Read from code; nothing is run; a call whose address is worked out when it runs is listed as not linked, never guessed.',
268
+ description: 'ASK THUNDER TRACE BEFORE CHANGING CODE THAT OTHER REPOSITORIES USE (local only). Give the repository folders. With "thing" (a route like "POST /api/orders", an event name, "table:orders", "setting:ORDERS_URL", "package:@acme/client", or "repo:file[:line]") or "diff": true (the branch and uncommitted changes), it answers what the change can affect in the OTHER repositories: callers of a changed or removed route, listeners of a published event, code that uses a changed, dropped, or removed table, other readers of a setting, dependents of a published package, ranked high/medium/low, one hop out, every item cited repo@sha:file:line. With neither, it gives the links between the repositories (HTTP, events, tables, packages) and what they share (settings, tables, package versions that differ). Read from code; nothing is run; a call whose address is worked out when it runs is listed as not linked, never guessed.',
269
269
  inputSchema: {
270
270
  type: 'object', required: ['paths'],
271
271
  properties: {
272
272
  paths: { type: 'array', minItems: 1, maxItems: 50, items: { ...str, description: 'a repository folder' } },
273
- thing: { ...str, description: 'what changes: "POST /api/orders", "order.placed", or "repo:src/file.ts:12"' },
273
+ thing: { ...str, description: 'what changes: "POST /api/orders", "order.placed", "table:orders", "setting:ORDERS_URL", "package:@acme/client", or "repo:src/file.ts:12"' },
274
274
  diff: { type: 'boolean', description: 'use the current changes (since the branch left main, plus uncommitted)' },
275
275
  base: { ...str, description: 'with diff: the commit or branch to compare against' },
276
276
  },
package/src/passport.mjs CHANGED
@@ -84,7 +84,11 @@ export function assemblePassport({ parts, change = null, runs = [], purpose = nu
84
84
 
85
85
  // Dependencies: every file read (with its hash), the links between the parts, packages, and services called.
86
86
  const trace = buildTrace(parts.map((p) => ({ name: p.name, sha: p.sha ?? null, dirty: !!p.dirty, files: p.files.filter((f) => !f.manifest) })));
87
- const links = trace.links.map((l) => ({ kind: l.kind, says: l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo}: ${l.method} ${l.path} (handled by ${l.to.label ?? l.route})` : `${l.from.repo} publishes ${l.event}, and ${l.to.repo} listens`, from: l.from.cite, to: l.to.cite }));
87
+ const linkSays = (l) => (l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo}: ${l.method} ${l.path} (handled by ${l.to.label ?? l.route})`
88
+ : l.kind === 'event' ? `${l.from.repo} publishes ${l.event}, and ${l.to.repo} listens`
89
+ : l.kind === 'data' ? `${l.from.repo} ${l.access} the ${l.table} table, which ${l.to.repo} creates`
90
+ : `${l.from.repo} depends on the package ${l.package}, which ${l.to.repo} publishes`);
91
+ const links = trace.links.map((l) => ({ kind: l.kind, says: linkSays(l), from: l.from.cite, to: l.to.cite }));
88
92
  const services = [];
89
93
  for (const r of trace.repos) for (const q of r.requests ?? []) if (q.base && q.base !== 'this app') services.push({ part: r.name, calls: `${q.method} ${q.base}${q.path}`, at: `${r.name}:${q.file}:${q.line}` });
90
94
 
@@ -105,7 +109,10 @@ export function assemblePassport({ parts, change = null, runs = [], purpose = nu
105
109
  for (const l of trace.links) {
106
110
  add({
107
111
  kind: 'trace-link', status: 'read',
108
- claim: l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo} with ${l.method} ${l.path}, and ${l.to.repo} handles it.` : `${l.from.repo} publishes "${l.event}", and ${l.to.repo} listens for it.`,
112
+ claim: l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo} with ${l.method} ${l.path}, and ${l.to.repo} handles it.`
113
+ : l.kind === 'event' ? `${l.from.repo} publishes "${l.event}", and ${l.to.repo} listens for it.`
114
+ : l.kind === 'data' ? `${l.from.repo} ${l.access} the ${l.table} table, and ${l.to.repo} creates it.`
115
+ : `${l.from.repo} depends on the package ${l.package}, and ${l.to.repo} publishes it.`,
109
116
  basis: { from: l.from.cite, to: l.to.cite, rules: `thunder-trace rules v${trace.rulesVersion}` },
110
117
  scope: 'Read from code; nothing was run. It does not show that the call succeeds or what it answers.',
111
118
  inputs: [inputOf(l.from.repo, l.from.file), inputOf(l.to.repo, l.to.file)],
@@ -109,8 +109,11 @@
109
109
  /* The Big Picture */
110
110
  .tl-big-picture { display: grid; gap: 24px; }
111
111
  .tl-bp-things { display: grid; gap: 20px; }
112
- .tl-bp-data { display: grid; gap: 16px; grid-template-columns: 1fr; }
113
- @media (min-width: 760px) { .tl-bp-data { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
112
+ .tl-bp-data { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 240px), 1fr)); }
113
+ .tl-bp-heading { margin: 0 0 8px !important; }
114
+ .tl-door-text { display: grid; gap: 2px; min-width: 0; }
115
+ .tl-door-doc { font-size: 13px; color: var(--tl-text-muted); }
116
+ .tl-ability.tl-selected { border-color: var(--tl-accent); }
114
117
  @media (max-width: 420px) {
115
118
  .tl-thing { padding: 18px; }
116
119
  .tl-card { padding: 16px; }
@@ -199,7 +202,7 @@
199
202
  .tl-cond { display: inline-flex; align-items: center; gap: 6px; }
200
203
  .tl-cond-q { color: var(--tl-text-body); }
201
204
  .tl-cond-and { color: var(--tl-text-quiet); margin-left: 2px; }
202
- .tl-ans { display: inline-block; padding: 1px 7px; border-radius: 6px; font-size: 12px; font-weight: 700; }
205
+ .tl-ans { display: inline-block; flex: none; white-space: nowrap; padding: 1px 7px; border-radius: 6px; font-size: 12px; font-weight: 700; }
203
206
  .tl-ans-yes { color: var(--tl-c-question); background: color-mix(in srgb, var(--tl-c-question) 12%, transparent); }
204
207
  .tl-ans-no { color: var(--tl-text-muted); background: color-mix(in srgb, var(--tl-c-unread) 14%, transparent); }
205
208
  .tl-ans-each { color: var(--tl-c-structure); background: color-mix(in srgb, var(--tl-c-structure) 12%, transparent); }
@@ -1,6 +1,6 @@
1
1
  import type { ReactElement, ReactNode } from 'react';
2
2
  import type { ThunderModel, Thing, Member } from '../model.d.mts';
3
- import type { ReadingLayout, ThingCardLayout, DataCardLayout, IOBoxesLayout, DetailsLayout, ThunderSymbolId } from '../reading-layout.d.mts';
3
+ import type { ReadingLayout, ThingCardLayout, DataCardLayout, IOBoxesLayout, MemberEntryLayout, DetailsLayout, ThunderSymbolId } from '../reading-layout.d.mts';
4
4
 
5
5
  export { readingLayout, thingCard, dataCard, ioBoxes, detailsLayout, flowEdgeLabel, READING_LABELS } from '../reading-layout.mjs';
6
6
  export type { ReadingLayout, ThingCardLayout, DataCardLayout, IOBoxesLayout, DetailsLayout, When, ThunderSymbolId } from '../reading-layout.d.mts';
@@ -108,6 +108,16 @@ export function IOBoxes({ card, model, member, onLine, onThing, headingLevel = 3
108
108
  : h('p', { className: 'tl-part-of' }, h(ThunderSymbol, { id: 'thing', size: 18 }), c.partOf.text)) : null);
109
109
  }
110
110
 
111
+ /** One action or rule on its own: its symbol, name, and doc; a button when the app can open it. */
112
+ function MemberDoor({ m, onOpen, selected }) {
113
+ const inner = h(Fragment, null,
114
+ h(ThunderSymbol, { id: m.symbol, size: 24 }),
115
+ h('span', { className: 'tl-door-text' }, h('span', { className: 'tl-ability-label' }, m.label), m.doc ? h('span', { className: 'tl-door-doc' }, m.doc) : null),
116
+ onOpen ? h('span', { className: 'tl-ability-go', 'aria-hidden': true }, '→') : null);
117
+ const cls = `tl-ability${selected ? ' tl-selected' : ''}`;
118
+ return onOpen ? h('button', { type: 'button', className: `${cls} tl-ability-button`, onClick: () => onOpen(m.id) }, inner) : h('div', { className: cls }, inner);
119
+ }
120
+
111
121
  /**
112
122
  * The Big Picture, zoomed by `focus` (see readingLayout): Things and Data, or, for an action or rule, its IO boxes.
113
123
  */
@@ -116,7 +126,9 @@ export function BigPicture({ model, layout, focus = null, onOpen, onLine, onThin
116
126
  return h('div', { className: 'tl-reading tl-big-picture' }, l.sections.map((s) => h('section', { key: s.id, className: `tl-bp-section tl-bp-${s.id}`, 'aria-label': s.heading },
117
127
  s.id === 'io'
118
128
  ? s.cards.map((c) => h(IOBoxes, { key: c.id, card: c, onLine, onThing, headingLevel: headingLevel + 1 }, children))
119
- : h('div', { className: s.id === 'things' ? 'tl-bp-things' : 'tl-bp-data' }, s.cards.map((c) => (c.kind === 'thing'
129
+ : s.id === 'actions'
130
+ ? h(Fragment, null, h(`h${headingLevel}`, { className: 'tl-section-label tl-bp-heading' }, s.heading), h('ul', { className: 'tl-abilities tl-bp-actions-list' }, s.cards.map((m) => h('li', { key: m.id }, h(MemberDoor, { m, onOpen, selected: m.id === selectedId })))))
131
+ : h('div', { className: s.id === 'things' ? 'tl-bp-things' : 'tl-bp-data' }, s.cards.map((c) => (c.kind === 'thing'
120
132
  ? h(ThingCard, { key: c.id, card: c, onOpen, selected: c.id === selectedId, headingLevel })
121
133
  : h(DataCard, { key: c.id, card: c, headingLevel: headingLevel + 1 })))))));
122
134
  }
@@ -22,8 +22,9 @@ const MANIFEST = /^(go\.mod|package\.json|tsconfig\.json|jsconfig\.json)$/;
22
22
  * go.mod, package.json, and tsconfig/jsconfig files that say which imports are this repo's own (for thunderModel's
23
23
  * calls across files); they are not code and are not read as code.
24
24
  */
25
+ // manifestNames: which manifest files `manifests` brings (Thunder Trace also wants requirements.txt and *.csproj).
25
26
  // templates: also bring Angular component templates (*.component.html), which screens read with their component.
26
- export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000, manifests = false, templates = false } = {}) {
27
+ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000, manifests = false, manifestNames = MANIFEST, templates = false } = {}) {
27
28
  const out = [];
28
29
  const walk = (dir) => {
29
30
  let names;
@@ -36,7 +37,7 @@ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400
36
37
  try { st = statSync(full); } catch { continue; }
37
38
  const path = relative(root, full).split('\\').join('/');
38
39
  if (st.isDirectory()) walk(full);
39
- else if (manifests && MANIFEST.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), manifest: true });
40
+ else if (manifests && manifestNames.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), manifest: true });
40
41
  else if (templates && /\.component\.html$/i.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), template: true });
41
42
  else if (readableLanguage(path) || (!name.includes('.') && shebangShell(full, st.size))) {
42
43
  // Oversized files are not loaded; readRepo lists them as skipped from their size.
@@ -4,7 +4,7 @@ export const READING_LAYOUT_SCHEMA: 'thunder-reading-layout-v1';
4
4
  export const READING_LABELS: Readonly<{
5
5
  thing: string; knows: string; can: string; starts: (label: string) => string; startsWithKnows: (label: string) => string;
6
6
  record: string; choices: string; recordSymbol: string; choicesSymbol: string; things: string; data: string;
7
- give: string; getBack: string; stops: string; givesNothing: string; getsNothing: string; partOf: (label: string) => string; io: string;
7
+ give: string; getBack: string; stops: string; givesNothing: string; getsNothing: string; partOf: (label: string) => string; io: string; actions: string;
8
8
  edges: Readonly<Record<'yes' | 'no' | 'each' | 'done' | 'error' | 'nested' | 'case', string>>;
9
9
  openLine: (line: number) => string; openRule: string;
10
10
  details: Readonly<{
@@ -35,10 +35,12 @@ export interface IOBoxesLayout {
35
35
  /** The Thing it belongs to, to link back to its card. */
36
36
  partOf: { id: string; text: string } | null;
37
37
  }
38
+ /** An action or rule that belongs to no Thing (a plain function), listed in the Big Picture as a door to open. */
39
+ export interface MemberEntryLayout { kind: 'member'; id: string; label: string; symbol: ThunderSymbolId; doc: string | null }
38
40
  export interface ReadingLayout {
39
41
  schema: 'thunder-reading-layout-v1';
40
42
  focus: { kind: 'app' | 'file' | 'thing' | 'member' | 'unknown'; id: string | null };
41
- sections: Array<{ id: 'things'; heading: string; cards: ThingCardLayout[] } | { id: 'data'; heading: string; cards: DataCardLayout[] } | { id: 'io'; heading: string; cards: IOBoxesLayout[] }>;
43
+ sections: Array<{ id: 'things'; heading: string; cards: ThingCardLayout[] } | { id: 'data'; heading: string; cards: DataCardLayout[] } | { id: 'io'; heading: string; cards: IOBoxesLayout[] } | { id: 'actions'; heading: string; cards: MemberEntryLayout[] }>;
42
44
  }
43
45
  export interface When { question: string; answer: string }
44
46
  export interface DetailsLayout {
@@ -25,6 +25,7 @@ export const READING_LABELS = Object.freeze({
25
25
  getsNothing: 'Nothing it hands back',
26
26
  partOf: (label) => `Part of ${label}`,
27
27
  io: 'What goes in and out',
28
+ actions: 'Actions and rules',
28
29
  // Flow: the words on each kind of edge. An edge label not listed here is shown as the compiler wrote it.
29
30
  edges: Object.freeze({ yes: 'Yes', no: 'No', each: 'For each', done: 'Done', error: 'If it fails', nested: 'Runs on its own', case: 'When' }),
30
31
  openLine: (line) => `line ${line}`,
@@ -149,18 +150,25 @@ export function detailsLayout(view) {
149
150
  };
150
151
  }
151
152
 
152
- const sectionsFor = (model, things) => {
153
+ /** An action or rule that belongs to no Thing (a plain function): a door to open, with its symbol and doc. */
154
+ const memberEntry = (m) => ({ kind: 'member', id: m.id, label: `${m.label}${m.yesNo ? '?' : ''}`, symbol: memberSymbolId(m), doc: m.doc ?? null });
155
+
156
+ const sectionsFor = (model, things, loose = []) => {
153
157
  const cards = things.filter((t) => t.kind === 'thing').map((t) => thingCard(model, t));
154
158
  const data = [...things.filter((t) => t.kind === 'record'), ...things.filter((t) => t.kind === 'choices')].map(dataCard);
159
+ const actions = loose.map(memberEntry);
155
160
  return [
156
161
  ...(cards.length ? [{ id: 'things', heading: READING_LABELS.things, cards }] : []),
157
162
  ...(data.length ? [{ id: 'data', heading: READING_LABELS.data, cards: data }] : []),
163
+ ...(actions.length ? [{ id: 'actions', heading: READING_LABELS.actions, cards: actions }] : []),
158
164
  ];
159
165
  };
166
+ const ownerless = (model, file) => model.members.filter((m) => !m.owner && (file == null || m.file === file));
160
167
 
161
168
  /**
162
169
  * The Big Picture, which zooms with what is in focus (the tabs stay Big Picture / Flow / Details / Text / Original):
163
- * no focus: every Thing, then every record, then every set of choices
170
+ * no focus: every Thing, then every record, then every set of choices, then the actions and rules that
171
+ * belong to no Thing (plain functions), each a door to open
164
172
  * a file's path: the same, for that file
165
173
  * a Thing's id: its card, then the Data in its file
166
174
  * an action or rule: its "You give it / You get back / It can stop with" boxes, with "Part of <Thing>"
@@ -169,7 +177,7 @@ const sectionsFor = (model, things) => {
169
177
  */
170
178
  export function readingLayout(model, { focus = null } = {}) {
171
179
  const base = { schema: READING_LAYOUT_SCHEMA };
172
- if (focus == null) return { ...base, focus: { kind: 'app', id: null }, sections: sectionsFor(model, model.things) };
180
+ if (focus == null) return { ...base, focus: { kind: 'app', id: null }, sections: sectionsFor(model, model.things, ownerless(model)) };
173
181
  const member = model.members.find((m) => m.id === focus);
174
182
  if (member) return { ...base, focus: { kind: 'member', id: focus }, sections: [{ id: 'io', heading: READING_LABELS.io, cards: [ioBoxes(model, member)] }] };
175
183
  const thing = model.things.find((t) => t.id === focus);
@@ -177,6 +185,6 @@ export function readingLayout(model, { focus = null } = {}) {
177
185
  const rest = model.things.filter((t) => t !== thing && t.file === thing.file && t.kind !== 'thing');
178
186
  return { ...base, focus: { kind: 'thing', id: focus }, sections: sectionsFor(model, [thing, ...rest]) };
179
187
  }
180
- if (model.files.some((f) => f.path === focus)) return { ...base, focus: { kind: 'file', id: focus }, sections: sectionsFor(model, model.things.filter((t) => t.file === focus)) };
188
+ if (model.files.some((f) => f.path === focus)) return { ...base, focus: { kind: 'file', id: focus }, sections: sectionsFor(model, model.things.filter((t) => t.file === focus), ownerless(model, focus)) };
181
189
  return { ...base, focus: { kind: 'unknown', id: focus }, sections: [] };
182
190
  }
package/src/trace-cli.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  // thunder trace: the command line for Thunder Trace (src/trace.mjs, docs/trace.md).
2
2
  // thunder trace <folder…> [--json] [--out graph.json] the links between repositories
3
- // thunder trace impact <thing> <folder…> [--json] what changing a route, event, or file can affect
3
+ // thunder trace impact <thing> <folder…> [--json] what changing a route, event, table, setting, package, or file can affect
4
4
  // thunder trace impact --diff [--base <ref>] <folder…> what the current changes (branch + uncommitted) can affect
5
5
  import { writeFileSync } from 'node:fs';
6
6
  import { buildTrace, renderTrace, traceImpact, traceImpactOf, renderImpact } from './trace.mjs';
7
7
  import { readRepoDir, gitChanges } from './trace-fs.mjs';
8
8
 
9
9
  const USAGE = `usage: thunder trace <folder> <folder> … [--json] [--out graph.json]
10
- thunder trace impact "<POST /api/orders | event name | repo:file[:line]>" <folder> … [--json]
10
+ thunder trace impact "<POST /api/orders | event name | table:orders | setting:KEY | package:name | repo:file[:line]>" <folder> … [--json]
11
11
  thunder trace impact --diff [--base <ref>] <folder> … [--json]
12
12
  Each folder is one repository. Nothing is run; links are read from code.`;
13
13
 
@@ -27,7 +27,7 @@ export function traceMain(argv) {
27
27
  const impact = a._[0] === 'impact';
28
28
  if (impact) a._.shift();
29
29
  const term = impact && !a.diff ? a._.shift() : null;
30
- if (impact && !a.diff && !term) { console.error(`thunder trace impact: name what changes (a route, an event, or repo:file), or use --diff.\n${USAGE}`); return 2; }
30
+ if (impact && !a.diff && !term) { console.error(`thunder trace impact: name what changes (a route, an event, table:name, setting:KEY, package:name, or repo:file), or use --diff.\n${USAGE}`); return 2; }
31
31
  if (!a._.length) { console.error(`thunder trace: give at least one repository folder.\n${USAGE}`); return 2; }
32
32
  let repos;
33
33
  try { repos = a._.map((d) => readRepoDir(d, { maxFiles: a.maxFiles })); } catch (e) { console.error(`thunder trace: ${e.message}`); return 2; }
@@ -0,0 +1,219 @@
1
+ // Thunder Trace, the data side: packages, settings, and tables each repository declares or uses. Browser-safe, no
2
+ // Node APIs. trace.mjs links them across repositories; this file only reads them, with the line each one is on.
3
+ //
4
+ // manifests (package.json, go.mod, requirements.txt, *.csproj) ──▶ packages: what a repository publishes, what it depends on
5
+ // code (process.env.KEY, os.getenv("KEY"), …) ──▶ settings: each setting key read, and where
6
+ // SQL files and SQL written in code ──▶ tables: created, altered, dropped, read, written
7
+ //
8
+ // Only what is written in the file counts. A setting key built from pieces, a table name inserted into SQL when it
9
+ // runs, or a package version decided by a lock file is not read, so it is never linked.
10
+
11
+ /** Line number (1-based) of a character offset. */
12
+ const lineAt = (text, index) => {
13
+ let n = 1;
14
+ for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
15
+ return n;
16
+ };
17
+ /** The 1-based line of the first line matching re, or null. */
18
+ const lineOf = (text, re) => {
19
+ const lines = text.split('\n');
20
+ for (let i = 0; i < lines.length; i++) if (re.test(lines[i])) return i + 1;
21
+ return null;
22
+ };
23
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
24
+ const baseName = (path) => path.split('/').pop();
25
+ const dirOf = (path) => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
26
+
27
+ // ── Packages ────────────────────────────────────────────────────────────────────────────────────────────
28
+
29
+ /** Is this file a package manifest Thunder Trace reads? */
30
+ export function isManifest(path) {
31
+ const n = baseName(path);
32
+ return n === 'package.json' || n === 'go.mod' || n === 'requirements.txt' || /\.csproj$/i.test(n);
33
+ }
34
+
35
+ /**
36
+ * What each manifest publishes and depends on.
37
+ * Gives back { publishes: [{ package, version?, file, line, root }], depends: [{ package, version?, dev?, file, line }] }.
38
+ * `root` is the folder the published package's code lives in (the manifest's folder).
39
+ */
40
+ export function packagesIn(files) {
41
+ const publishes = [], depends = [];
42
+ for (const f of files) {
43
+ if (!isManifest(f.path)) continue;
44
+ const text = String(f.source ?? '');
45
+ const n = baseName(f.path);
46
+ try {
47
+ if (n === 'package.json') {
48
+ const j = JSON.parse(text);
49
+ if (typeof j.name === 'string' && j.name.trim()) publishes.push({ package: j.name, ...(j.version ? { version: String(j.version) } : {}), file: f.path, line: lineOf(text, /^\s*"name"\s*:/), root: dirOf(f.path) });
50
+ for (const k of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
51
+ for (const [name, version] of Object.entries(j[k] ?? {})) {
52
+ depends.push({ package: name, version: String(version), ...(k === 'devDependencies' ? { dev: true } : {}), ...(k === 'peerDependencies' ? { peer: true } : {}), file: f.path, line: lineOf(text, new RegExp(`^\\s*"${esc(name)}"\\s*:`)) });
53
+ }
54
+ }
55
+ } else if (n === 'go.mod') {
56
+ const lines = text.split('\n');
57
+ let inRequire = false;
58
+ lines.forEach((raw, i) => {
59
+ const line = raw.replace(/\/\/.*$/, '').trim();
60
+ let m;
61
+ if ((m = line.match(/^module\s+(\S+)/))) publishes.push({ package: m[1], file: f.path, line: i + 1, root: dirOf(f.path) });
62
+ else if (/^require\s*\($/.test(line)) inRequire = true;
63
+ else if (inRequire && line === ')') inRequire = false;
64
+ else if ((m = inRequire ? line.match(/^(\S+)\s+(v\S+)/) : line.match(/^require\s+(\S+)\s+(v\S+)/))) depends.push({ package: m[1], version: m[2], file: f.path, line: i + 1 });
65
+ });
66
+ } else if (n === 'requirements.txt') {
67
+ text.split('\n').forEach((raw, i) => {
68
+ const line = raw.replace(/#.*/, '').trim();
69
+ if (!line || line.startsWith('-')) return; // -r other.txt, -e ., --index-url: not a package
70
+ const m = line.match(/^([A-Za-z0-9][A-Za-z0-9_.-]*)(?:\[[^\]]*\])?\s*(.*)$/);
71
+ if (m) depends.push({ package: m[1].toLowerCase().replace(/_/g, '-'), ...(m[2] ? { version: m[2].replace(/\s*;.*$/, '').trim() } : {}), file: f.path, line: i + 1 });
72
+ });
73
+ } else {
74
+ // .csproj: PackageReference (what it depends on) and PackageId (what it publishes, when it is packed).
75
+ for (const m of text.matchAll(/<PackageReference\s+Include="([^"]+)"(?:\s+Version="([^"]+)")?/g)) depends.push({ package: m[1], ...(m[2] ? { version: m[2] } : {}), file: f.path, line: lineAt(text, m.index) });
76
+ const id = text.match(/<PackageId>\s*([^<\s]+)\s*<\/PackageId>/);
77
+ if (id) publishes.push({ package: id[1], file: f.path, line: lineAt(text, id.index), root: dirOf(f.path) });
78
+ }
79
+ } catch { /* a manifest Thunder cannot parse is not a package list */ }
80
+ }
81
+ return { publishes, depends };
82
+ }
83
+
84
+ /** A version that names a place, not a version: it says nothing to compare across repositories. */
85
+ export const LOCAL_VERSION = /^(workspace:|file:|link:|portal:|\.{0,2}\/|git\+|github:|https?:)/;
86
+
87
+ // ── Settings ───────────────────────────────────────────────────────────────────────────────────────────
88
+
89
+ const KEY = '([A-Za-z_][A-Za-z0-9_]*)';
90
+ const Q = `["'\`]`;
91
+ const SETTING_READS = [
92
+ new RegExp(`\\bprocess\\.env\\.${KEY}`, 'g'),
93
+ new RegExp(`\\bprocess\\.env\\[\\s*${Q}${KEY}${Q}\\s*\\]`, 'g'),
94
+ new RegExp(`\\bimport\\.meta\\.env\\.${KEY}`, 'g'),
95
+ new RegExp(`\\bDeno\\.env\\.get\\(\\s*${Q}${KEY}${Q}`, 'g'),
96
+ new RegExp(`\\b(?:os\\.)?environ(?:\\.get)?\\s*[\\[(]\\s*${Q}${KEY}${Q}`, 'g'),
97
+ new RegExp(`\\bos\\.getenv\\(\\s*${Q}${KEY}${Q}`, 'g'),
98
+ new RegExp(`\\bos\\.(?:Getenv|LookupEnv)\\(\\s*"${KEY}"`, 'g'),
99
+ new RegExp(`\\bSystem\\.getenv\\(\\s*"${KEY}"`, 'g'),
100
+ new RegExp(`\\bEnvironment\\.GetEnvironmentVariable\\(\\s*"${KEY}"`, 'g'),
101
+ new RegExp(`\\bENV(?:\\.fetch\\(\\s*|\\[\\s*)${Q}${KEY}${Q}`, 'g'),
102
+ new RegExp(`\\benv::var(?:_os)?\\(\\s*"${KEY}"`, 'g'),
103
+ new RegExp(`\\bgetenv\\(\\s*${Q}${KEY}${Q}`, 'g'),
104
+ new RegExp(`\\$_ENV\\[\\s*${Q}${KEY}${Q}`, 'g'),
105
+ ];
106
+
107
+ /** Settings every service reads for itself, or the platform sets: two repositories reading PORT share nothing. */
108
+ export const isGenericSetting = (key) => GENERIC_SETTINGS.has(key) || /^(VERCEL_|EAS_BUILD|GITHUB_|RUNNER_|npm_|NETLIFY|RENDER_|RAILWAY_|FLY_|HEROKU_|AWS_LAMBDA_|K_SERVICE|KUBERNETES_)/.test(key);
109
+ export const GENERIC_SETTINGS = new Set(['NODE_ENV', 'PORT', 'HOST', 'HOSTNAME', 'HOME', 'PATH', 'PWD', 'USER', 'SHELL', 'TMPDIR', 'TEMP', 'TMP', 'TZ', 'LANG', 'CI', 'DEBUG', 'ENV', 'ENVIRONMENT', 'APP_ENV', 'LOG_LEVEL', 'LOGLEVEL', 'VERBOSE', 'GITHUB_ACTIONS', 'npm_package_version', 'ASPNETCORE_ENVIRONMENT', 'DOTNET_ENVIRONMENT', 'PYTHONPATH', 'GOPATH', 'JAVA_HOME', 'NODE_OPTIONS', 'CI_COMMIT_SHA']);
110
+
111
+ /** Each setting key read in code, with its line: [{ key, file, line }]. */
112
+ export function settingsIn(files) {
113
+ const out = [];
114
+ for (const f of files) {
115
+ if (isManifest(f.path) || /\.sql$/i.test(f.path)) continue;
116
+ const text = String(f.source ?? '');
117
+ if (!/env/i.test(text)) continue;
118
+ const seen = new Set();
119
+ for (const re of SETTING_READS) {
120
+ for (const m of text.matchAll(re)) {
121
+ const line = lineAt(text, m.index);
122
+ const k = `${m[1]}|${line}`;
123
+ if (seen.has(k)) continue;
124
+ seen.add(k);
125
+ out.push({ key: m[1], file: f.path, line });
126
+ }
127
+ }
128
+ }
129
+ return out.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.key.localeCompare(b.key));
130
+ }
131
+
132
+ // ── Tables ─────────────────────────────────────────────────────────────────────────────────────────────
133
+
134
+ const NAME = '((?:[`"\\[]?[A-Za-z_][\\w$]*[`"\\]]?\\.){0,2}[`"\\[]?[A-Za-z_][\\w$]*[`"\\]]?)';
135
+ // Words that can follow FROM / JOIN / INTO / UPDATE without being a table.
136
+ const NOT_TABLES = new Set(['select', 'set', 'where', 'values', 'dual', 'lateral', 'unnest', 'only', 'table', 'if', 'exists', 'not', 'the', 'a', 'an', 'my', 'your', 'this', 'that', 'each', 'all', 'json_table', 'information_schema', 'pg_catalog', 'sys']);
137
+
138
+ /** "public"."Orders" → { table: 'orders' (what links match on), name: 'public.Orders' (as written) }. */
139
+ export function tableName(raw) {
140
+ const name = raw.replace(/[`"[\]]/g, '');
141
+ return { table: name.split('.').pop().toLowerCase(), name };
142
+ }
143
+
144
+ /** Reads and writes in one piece of SQL, at character offset `at` of the file. */
145
+ function usesIn(sql, offsetOf, push) {
146
+ const re = new RegExp(`\\b(DELETE\\s+FROM|INSERT\\s+(?:OR\\s+\\w+\\s+)?INTO|MERGE\\s+INTO|UPDATE|FROM|JOIN)\\s+${NAME}(\\s*\\()?`, 'gi');
147
+ for (const m of sql.matchAll(re)) {
148
+ const kw = m[1].toUpperCase().replace(/\s+/g, ' ');
149
+ if (m[3] && (kw === 'FROM' || kw === 'JOIN')) continue; // FROM generate_series(…): a function, not a table
150
+ const { table, name } = tableName(m[2]);
151
+ if (NOT_TABLES.has(table) || NOT_TABLES.has(name.toLowerCase())) continue;
152
+ // UPDATE names a table only when SET follows (UPDATE t SET, UPDATE t AS x SET); not "FOR UPDATE" or "DO UPDATE SET".
153
+ if (kw === 'UPDATE' && (/\b(DO|FOR|KEY)\s*$/i.test(sql.slice(Math.max(0, m.index - 12), m.index)) || !/^\s*(?:(?:AS\s+)?\w+\s+)?SET\b/i.test(sql.slice(m.index + m[0].length)))) continue;
154
+ push({ table, name, access: kw === 'FROM' || kw === 'JOIN' ? 'reads' : 'writes', at: offsetOf(m.index) });
155
+ }
156
+ }
157
+
158
+ // A string is SQL only when it has a statement's shape, not just a SQL word first: "Delete your data from
159
+ // Profile" and "Update the app to continue" are sentences.
160
+ const SQL_SHAPES = [
161
+ /^\s*SELECT\b[\s\S]*?\bFROM\s/i,
162
+ /^\s*INSERT\s+(?:OR\s+\w+\s+)?INTO\s/i,
163
+ /^\s*UPDATE\s+[\w."`[\]]+\s+(?:(?:AS\s+)?\w+\s+)?SET\s/i,
164
+ /^\s*DELETE\s+FROM\s/i,
165
+ /^\s*WITH\s+(?:RECURSIVE\s+)?\w+\s+AS\s*\(/i,
166
+ /^\s*MERGE\s+INTO\s/i,
167
+ ];
168
+ const isSql = (text) => SQL_SHAPES.some((re) => re.test(text));
169
+ // SQL written in code: strings that start with a SQL verb. Single-line '…' and "…"; `…`, """…""", '''…''' may span lines.
170
+ const CODE_STRINGS = /"""([\s\S]*?)"""|'''([\s\S]*?)'''|`((?:\\[\s\S]|[^`\\])*)`|"((?:\\.|[^"\\\n])*)"|'((?:\\.|[^'\\\n])*)'/g;
171
+
172
+ /**
173
+ * Each table a file creates, alters, drops, reads, or writes: [{ table, name, access, file, line, lines? }].
174
+ * SQL files are read whole; in code, only strings that start with a SQL verb are read as SQL.
175
+ */
176
+ export function tablesIn(files) {
177
+ const out = [];
178
+ for (const f of files) {
179
+ if (isManifest(f.path)) continue;
180
+ const text = String(f.source ?? '');
181
+ const push = (u) => out.push({ table: u.table, name: u.name, access: u.access, file: f.path, line: lineAt(text, u.at), ...(u.end != null ? { lines: [lineAt(text, u.at), lineAt(text, u.end)] } : {}) });
182
+ if (/\.sql$/i.test(f.path)) {
183
+ const clean = text.replace(/--[^\n]*/g, (s) => ' '.repeat(s.length)).replace(/\/\*[\s\S]*?\*\//g, (s) => s.replace(/[^\n]/g, ' '));
184
+ const ddl = new RegExp(`\\b(CREATE(?:\\s+OR\\s+REPLACE)?(?:\\s+(?:TEMP|TEMPORARY|UNLOGGED|GLOBAL|LOCAL))*\\s+TABLE|ALTER\\s+TABLE|DROP\\s+TABLE)(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?(?:\\s+ONLY)?\\s+${NAME}`, 'gi');
185
+ const ddlSpans = [];
186
+ for (const m of clean.matchAll(ddl)) {
187
+ const { table, name } = tableName(m[2]);
188
+ if (NOT_TABLES.has(table)) continue;
189
+ const kw = m[1].toUpperCase();
190
+ if (/TEMP/.test(kw)) continue; // a temporary table belongs to one session, not to the schema
191
+ const end = clean.indexOf(';', m.index);
192
+ const stop = end < 0 ? clean.length : end;
193
+ ddlSpans.push([m.index, stop]);
194
+ push({ table, name, access: kw.startsWith('CREATE') ? 'creates' : kw.startsWith('ALTER') ? 'alters' : 'drops', at: m.index, end: stop });
195
+ }
196
+ // Views, functions, and data changes in SQL files read and write tables too (not inside the table definitions,
197
+ // where REFERENCES and defaults are not a use).
198
+ // GRANT … TO and REVOKE … FROM name roles, not tables (REVOKE ALL ON t FROM public).
199
+ const roles = [...clean.matchAll(/\b(?:GRANT|REVOKE)\b[^;]*/gi)].map((m) => [m.index, m.index + m[0].length]);
200
+ const skip = [...ddlSpans, ...roles];
201
+ usesIn(clean, (i) => i, (u) => { if (!skip.some(([a, b]) => u.at >= a && u.at <= b)) push(u); });
202
+ continue;
203
+ }
204
+ if (!/\b(SELECT|INSERT|UPDATE|DELETE|MERGE)\b/i.test(text)) continue;
205
+ for (const m of text.matchAll(CODE_STRINGS)) {
206
+ const body = m[1] ?? m[2] ?? m[3] ?? m[4] ?? m[5] ?? '';
207
+ if (!isSql(body)) continue;
208
+ const start = m.index + m[0].indexOf(body);
209
+ usesIn(body, (i) => start + i, push);
210
+ }
211
+ }
212
+ // The same table, file, line, and access once (a statement like UPDATE t … FROM t names it twice).
213
+ const seen = new Set();
214
+ return out.filter((t) => { const k = `${t.file}|${t.line}|${t.table}|${t.access}`; if (seen.has(k)) return false; seen.add(k); return true; })
215
+ .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.table.localeCompare(b.table));
216
+ }
217
+
218
+ /** Does this access define the table (rather than use it)? */
219
+ export const DEFINES = new Set(['creates', 'alters', 'drops']);
package/src/trace-fs.mjs CHANGED
@@ -6,6 +6,9 @@ import { statSync } from 'node:fs';
6
6
  import { collectReadableFiles } from './read-repo-fs.mjs';
7
7
  import { thunderModel } from './model.mjs';
8
8
  import { serviceFacts } from './system.mjs';
9
+ import { tablesIn } from './trace-data.mjs';
10
+
11
+ const TRACE_MANIFESTS = /^(go\.mod|package\.json|tsconfig\.json|jsconfig\.json|requirements\.txt|.+\.csproj)$/i;
9
12
 
10
13
  const git = (dir, args) => {
11
14
  try { return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 }); } catch { return null; }
@@ -20,7 +23,9 @@ export function readRepoDir(dir, { maxFiles = 5000 } = {}) {
20
23
  const top = git(root, ['rev-parse', '--show-toplevel'])?.trim();
21
24
  const sha = top ? git(root, ['rev-parse', 'HEAD'])?.trim() || null : null;
22
25
  const dirty = top ? !!git(root, ['status', '--porcelain'])?.trim() : false;
23
- return { name: basename(root), root, sha, dirty, files: collectReadableFiles(root, { maxFiles }) };
26
+ // Manifests come too: package.json, go.mod, requirements.txt, and *.csproj say which packages a repository
27
+ // publishes and depends on (they are not read as code).
28
+ return { name: basename(root), root, sha, dirty, files: collectReadableFiles(root, { maxFiles, manifests: true, manifestNames: TRACE_MANIFESTS }) };
24
29
  }
25
30
 
26
31
  /** The commit a branch started from: --base if given, else where HEAD left main/master (origin first), else HEAD. */
@@ -52,7 +57,9 @@ export function gitChanges(repo, base) {
52
57
  else if (cur && line.startsWith('deleted file mode')) cur.status = 'removed';
53
58
  else if (cur && (m = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/))) {
54
59
  const start = Number(m[1]), n = m[2] === undefined ? 1 : Number(m[2]);
55
- cur.ranges.push(n === 0 ? [Math.max(1, start), Math.max(1, start)] : [start, start + n - 1]);
60
+ // A pure deletion (+start,0) sits between line `start` and the next one: it touches what spans that gap (a
61
+ // statement or a function it was inside), not the line before it.
62
+ cur.ranges.push(n === 0 ? [start + 0.5, start + 0.5] : [start, start + n - 1]);
56
63
  }
57
64
  }
58
65
  for (const f of (git(dir, ['ls-files', '--others', '--exclude-standard', '--', '.']) ?? '').split('\n').filter(Boolean)) {
@@ -67,7 +74,7 @@ export function gitChanges(repo, base) {
67
74
  if (c.status !== 'added') {
68
75
  const old = git(dir, ['show', `${b}:${c.file}`]);
69
76
  if (old != null) {
70
- try { const files = [{ path: file, source: old }]; const f = serviceFacts(thunderModel(files), files); before = { routes: f.routes, listeners: f.listeners, publishes: f.publishes }; } catch { before = null; }
77
+ try { const files = [{ path: file, source: old }]; const f = serviceFacts(thunderModel(files), files); before = { routes: f.routes, listeners: f.listeners, publishes: f.publishes, tables: tablesIn(files) }; } catch { before = null; }
71
78
  }
72
79
  }
73
80
  changes.push({ repo: repo.name, file, ranges: c.ranges, status: c.status, ...(before ? { before } : {}) });