@skillstech/thunderlang 1.3.0 → 1.4.1
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/CHANGELOG.md +87 -0
- package/dist/core.cjs +4868 -1068
- package/dist/index.cjs +3676 -189
- package/dist/learn.cjs +6444 -1275
- package/package.json +18 -1
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +23 -0
- package/src/core.d.ts +45 -0
- package/src/core.mjs +15 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +4 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/learn-lessons.mjs +145 -0
- package/src/learn.mjs +17 -0
- package/src/libraries.mjs +22 -1
- package/src/model.mjs +22 -1
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/react/reading.css +119 -0
- package/src/react/reading.d.mts +15 -0
- package/src/react/reading.mjs +87 -0
- package/src/read.mjs +37 -1
- package/src/reading-layout.d.mts +40 -0
- package/src/reading-layout.mjs +112 -0
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +16 -2
- package/src/steps.mjs +13 -1
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +178 -0
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/learn-lessons.mjs
CHANGED
|
@@ -544,6 +544,69 @@ const AGENT_RUN = (() => {
|
|
|
544
544
|
] }] }] }, null, 2);
|
|
545
545
|
})();
|
|
546
546
|
|
|
547
|
+
// ── Changing real code safely ──────────────────────────────────────────────────────────────────────────────────
|
|
548
|
+
// Three tools for code that already runs in several services: is every record limited to its caller, one rule
|
|
549
|
+
// changed everywhere it is written, and a record of the evidence for a change. Every answer is worked out by the
|
|
550
|
+
// tool itself on the lesson's files (accessFlow, writeRuleAcross, assemblePassport and checkPassport in ./core).
|
|
551
|
+
|
|
552
|
+
const INVOICES_API = `import express from "express";
|
|
553
|
+
import { db } from "./db";
|
|
554
|
+
|
|
555
|
+
const app = express();
|
|
556
|
+
|
|
557
|
+
app.get("/invoices/:id", async (req, res) => {
|
|
558
|
+
const invoice = await db.invoice.findFirst({
|
|
559
|
+
where: { id: req.params.id, tenantId: req.user.tenantId },
|
|
560
|
+
});
|
|
561
|
+
res.json(invoice);
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
app.get("/receipts/:id", async (req, res) => {
|
|
565
|
+
const receipt = await db.receipt.findUnique({ where: { id: req.params.id } });
|
|
566
|
+
res.json(receipt);
|
|
567
|
+
});
|
|
568
|
+
`;
|
|
569
|
+
|
|
570
|
+
const INVOICES_DB = `import { PrismaClient } from "@prisma/client";
|
|
571
|
+
|
|
572
|
+
export const db = new PrismaClient();
|
|
573
|
+
`;
|
|
574
|
+
|
|
575
|
+
const SHIP_WEB = `export function shippingFee(subtotal: number): number {
|
|
576
|
+
if (subtotal >= 50) return 0;
|
|
577
|
+
return 5.99;
|
|
578
|
+
}
|
|
579
|
+
`;
|
|
580
|
+
|
|
581
|
+
const SHIP_ORDERS = `public static class Shipping
|
|
582
|
+
{
|
|
583
|
+
public static decimal ShippingFee(decimal subtotal)
|
|
584
|
+
{
|
|
585
|
+
if (subtotal >= 50m) return 0m;
|
|
586
|
+
return 5.99m;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
`;
|
|
590
|
+
|
|
591
|
+
const SHIP_BILLING = `def shipping_fee(subtotal):
|
|
592
|
+
if subtotal >= 50:
|
|
593
|
+
return 0
|
|
594
|
+
return 5.99
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def coupon_allowed(subtotal):
|
|
598
|
+
if subtotal >= 50:
|
|
599
|
+
return True
|
|
600
|
+
return False
|
|
601
|
+
`;
|
|
602
|
+
|
|
603
|
+
const SHIP_TEST = `from receipt import shipping_fee
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def test_a_45_dollar_order_pays_shipping():
|
|
607
|
+
assert shipping_fee(45) == 5.99
|
|
608
|
+
`;
|
|
609
|
+
|
|
547
610
|
export const WRITE_LESSONS = [
|
|
548
611
|
{
|
|
549
612
|
slug: "first-program",
|
|
@@ -699,4 +762,86 @@ export const WRITE_LESSONS = [
|
|
|
699
762
|
{ q: "The refund did not go through. Was the customer refunded?", a: "Thunder can't know: the record shows the requests failed, not what the payment service did. It says the step may have partly happened, so a person checks." },
|
|
700
763
|
],
|
|
701
764
|
},
|
|
765
|
+
{
|
|
766
|
+
slug: "access-check",
|
|
767
|
+
part: "write",
|
|
768
|
+
concept: "Ownership: every record a request asks for must belong to the person asking",
|
|
769
|
+
title: "Does every route keep each customer's records to them?",
|
|
770
|
+
idea: "A web route that looks up a record by the id in the address must also check that the record belongs to the caller, or anyone can read anyone's invoice by changing a number. thunder read ./api --access follows each request through the code into the database and gives every route one verdict: guarded, unguarded, or cannot tell. Each verdict points to its lines. Thunder says unguarded only when it followed every step; when something is out of reach (a file it was not given), it says cannot tell and names what stopped it.",
|
|
771
|
+
picture: "A hotel desk. One clerk checks that the room key belongs to the guest before handing it over; the other hands any key to whoever names a room number.",
|
|
772
|
+
commands: ["thunder read ./api --access"],
|
|
773
|
+
files: [{ language: "typescript", label: "api/routes.ts", code: INVOICES_API }, { language: "typescript", label: "api/db.ts", code: INVOICES_DB }],
|
|
774
|
+
access: true,
|
|
775
|
+
show: "run",
|
|
776
|
+
quiz: [
|
|
777
|
+
{ prompt: "Which route lets one customer read another customer's record?", choices: ["GET /receipts/:id", "GET /invoices/:id", "Neither"], expect: "GET /receipts/:id",
|
|
778
|
+
explain: "The receipts lookup uses only the id from the address. The invoices lookup also requires tenantId to be the caller's own, so a different customer's id finds nothing.",
|
|
779
|
+
check: ({ access }) => { const u = access.routes.filter((r) => r.verdict === 'unguarded'); return u.length === 1 ? `${u[0].method} ${u[0].path}` : u.length ? 'Both' : 'Neither'; } },
|
|
780
|
+
{ prompt: "Thunder is given routes.ts but not db.ts. What does it say about GET /receipts/:id?", choices: ["Cannot tell: db comes from a file it was not given", "Unguarded", "Guarded"], expect: "Cannot tell: db comes from a file it was not given",
|
|
781
|
+
explain: "Without db.ts, Thunder cannot see that db is the database, so it cannot follow the lookup. It names what stopped it instead of guessing either way.",
|
|
782
|
+
check: ({ accessOf }) => { const r = accessOf([0]).routes.find((x) => x.path === '/receipts/:id'); return r.verdict === 'cannot tell' && /outside these files/.test(r.why) ? 'Cannot tell: db comes from a file it was not given' : r.verdict === 'unguarded' ? 'Unguarded' : 'Guarded'; } },
|
|
783
|
+
],
|
|
784
|
+
questions: [
|
|
785
|
+
{ q: "Every route says guarded. Is the app safe?", a: "Each route limits the record it hands back to the caller, on the paths Thunder followed. That is one important check, not all of security: sign-in itself, what a role may do, and data that leaks through other means are separate questions." },
|
|
786
|
+
{ q: "Why is cannot tell better than a guess?", a: "A wrong guarded hides a leak; a wrong unguarded wastes your time and teaches you to ignore warnings. Cannot tell, with what stopped it, tells you exactly where to look." },
|
|
787
|
+
],
|
|
788
|
+
},
|
|
789
|
+
{
|
|
790
|
+
slug: "change-everywhere",
|
|
791
|
+
part: "write",
|
|
792
|
+
concept: "One business rule, written in several services, changed together",
|
|
793
|
+
title: "Change one rule in every service at once",
|
|
794
|
+
idea: "Free shipping from $50 is often written three times: the cart page (TypeScript), the orders service (C#), and billing's receipt (Python). Change one and forget another, and customers see one price and pay another. thunder write web orders billing finds every copy of the rule, shows the plan, and with --write changes all of them or none, touching only the rule's characters. A rule that only looks the same is listed for you to check by hand, never changed, and tests are never edited.",
|
|
795
|
+
picture: "Changing a price on the shelf tag, the till, and the receipt printer together, instead of hoping someone remembers the other two.",
|
|
796
|
+
commands: ["thunder write web orders billing --decision shippingFee --rule 1 --when \"subtotal >= 40\"", "thunder write web orders billing --decision shippingFee --rule 1 --when \"subtotal >= 40\" --write"],
|
|
797
|
+
files: [
|
|
798
|
+
{ language: "typescript", label: "web/shipping.ts", code: SHIP_WEB },
|
|
799
|
+
{ language: "csharp", label: "orders/Shipping.cs", code: SHIP_ORDERS },
|
|
800
|
+
{ language: "python", label: "billing/receipt.py", code: SHIP_BILLING },
|
|
801
|
+
{ language: "python", label: "billing/test_receipt.py", code: SHIP_TEST },
|
|
802
|
+
],
|
|
803
|
+
across: { decision: "shippingFee", rule: 1, when: "subtotal >= 40" },
|
|
804
|
+
show: "run",
|
|
805
|
+
quiz: [
|
|
806
|
+
{ prompt: "Free shipping moves from $50 to $40. How many files does Thunder change?", choices: ["3", "4", "1"], expect: "3",
|
|
807
|
+
explain: "The shipping rule in each service: shipping.ts, Shipping.cs, and receipt.py. The test file is never edited.",
|
|
808
|
+
check: ({ across }) => String(new Set(across.plan.map((p) => `${p.part}/${p.file}`)).size) },
|
|
809
|
+
{ prompt: "coupon_allowed also says subtotal >= 50. What does Thunder do with it?", choices: ["Lists it to check by hand", "Changes it to 40 too"], expect: "Lists it to check by hand",
|
|
810
|
+
explain: "It has the same limit, but its name shares no word with shippingFee, so it is probably a different rule (the coupon minimum) that happens to use $50. Thunder lists it and leaves it alone.",
|
|
811
|
+
check: ({ across }) => (across.notIncluded.some((n) => n.decision === 'coupon_allowed') ? 'Lists it to check by hand' : 'Changes it to 40 too') },
|
|
812
|
+
{ prompt: "The test expects a $45 order to pay $5.99. After the change, what is true?", choices: ["The test will fail and needs a person to update it", "Thunder updates the test"], expect: "The test will fail and needs a person to update it",
|
|
813
|
+
explain: "At $40, a $45 order ships free, so the test's expectation is now wrong. Thunder never edits tests: a test that disagrees is how you find out what the change means.",
|
|
814
|
+
check: ({ across }) => (across.files['billing/test_receipt.py'] === undefined && across.ok ? 'The test will fail and needs a person to update it' : 'Thunder updates the test') },
|
|
815
|
+
],
|
|
816
|
+
questions: [
|
|
817
|
+
{ q: "Why all or nothing?", a: "Half a change is the problem you started with: two services disagreeing. If any copy cannot be changed exactly, no file changes and Thunder says which one and why." },
|
|
818
|
+
{ q: "The C# copy says 50m and the Python copy says 50. Why are they the same rule?", a: "Numbers are compared by value, and names as words (shippingFee, ShippingFee, and shipping_fee are the same name). Each copy keeps its own spelling: the C# becomes 40m." },
|
|
819
|
+
],
|
|
820
|
+
},
|
|
821
|
+
{
|
|
822
|
+
slug: "passport",
|
|
823
|
+
part: "write",
|
|
824
|
+
concept: "Evidence: what was checked, how, and what it does not cover",
|
|
825
|
+
title: "Keep the evidence for a change",
|
|
826
|
+
idea: "When you change code, a reviewer asks: what changed, how do you know it works, and what did you not check? thunder passport writes that down as a Software Passport. Each claim has its basis (a command and its exit code, or the source lines) and the files it depended on, by fingerprint. A failed test is recorded as failed, never as passed, and deployment, real outside services, several machines, and load are always listed as not verified. Later, thunder passport check marks each claim current, or stale when a file it depended on has changed since.",
|
|
827
|
+
picture: "A building inspection certificate: what was inspected, by what test, on which date, and a note that it no longer counts once someone moves a wall.",
|
|
828
|
+
commands: ["thunder passport web billing --run \"web: node --test\" --run \"billing: python3 -m pytest\"", "thunder passport check"],
|
|
829
|
+
files: [{ language: "typescript", label: "web/shipping.ts", code: SHIP_WEB }, { language: "python", label: "billing/receipt.py", code: SHIP_BILLING }],
|
|
830
|
+
passport: [
|
|
831
|
+
{ command: "node --test", part: "web", exitCode: 0, output: "1 passed" },
|
|
832
|
+
{ command: "python3 -m pytest", part: "billing", exitCode: 0, output: "1 passed" },
|
|
833
|
+
],
|
|
834
|
+
show: "run",
|
|
835
|
+
quiz: [
|
|
836
|
+
{ prompt: "After the passport is made, someone edits web/shipping.ts. Which claim turns stale?", choices: ["The web test run", "The billing test run", "Both"], expect: "The web test run",
|
|
837
|
+
explain: "Only the web tests depended on shipping.ts. Billing's claim depended on receipt.py, which did not change, so it stays current. Nothing is re-run: check compares fingerprints.",
|
|
838
|
+
check: ({ passportCheck }) => { const c = passportCheck({ 'web/shipping.ts': SHIP_WEB.replace('50', '45') }); const stale = c.items.filter((i) => i.freshness === 'stale'); return stale.length === 2 ? 'Both' : /in web/.test(stale[0]?.claim) ? 'The web test run' : 'The billing test run'; } },
|
|
839
|
+
{ prompt: "Every test passed. Does the passport say the change works in production?", choices: ["No: deployment is always listed as not verified", "Yes"], expect: "No: deployment is always listed as not verified",
|
|
840
|
+
explain: "Tests prove what they ran, on the machine they ran on. How it is deployed, real outside services, more than one machine, and heavy load are listed as not verified unless a claim covers them.",
|
|
841
|
+
check: ({ passport }) => (passport.unknowns.notVerified.some((x) => /^Deployment/.test(x)) ? 'No: deployment is always listed as not verified' : 'Yes') },
|
|
842
|
+
],
|
|
843
|
+
questions: [
|
|
844
|
+
{ q: "Why record a failed test instead of leaving it out?", a: "Leaving it out makes the passport look better than the truth. A reviewer needs to see the failure, and the passport says what it means: what that test covers is not verified." },
|
|
845
|
+
],
|
|
846
|
+
},
|
|
702
847
|
];
|
package/src/learn.mjs
CHANGED
|
@@ -13,6 +13,9 @@ import { compileCore } from './core/index.mjs';
|
|
|
13
13
|
import { runInProcess, testInProcess } from './core/engine-core.mjs';
|
|
14
14
|
import { pythonToCore } from './core/from-python.mjs';
|
|
15
15
|
import { explainRun } from './why.mjs';
|
|
16
|
+
import { accessFlow } from './flow/access.mjs';
|
|
17
|
+
import { writeRuleAcross } from './write-across.mjs';
|
|
18
|
+
import { assemblePassport, checkPassport } from './passport.mjs';
|
|
16
19
|
|
|
17
20
|
export const LEARN_SCHEMA = 'thunder-learn-v1';
|
|
18
21
|
export { READ_LESSONS, WRITE_LESSONS };
|
|
@@ -76,6 +79,20 @@ function writeContext(lesson) {
|
|
|
76
79
|
}
|
|
77
80
|
if (lesson.asCore) ctx.asCore = pythonToCore(file.code);
|
|
78
81
|
if (lesson.why) ctx.why = explainRun(file.code);
|
|
82
|
+
// Changing real code: each tool run on the lesson's files, labeled "part/file".
|
|
83
|
+
const parted = lesson.files.map((f) => { const i = f.label.indexOf('/'); return { part: f.label.slice(0, i), path: f.label.slice(i + 1), source: f.code }; });
|
|
84
|
+
if (lesson.access) {
|
|
85
|
+
ctx.accessOf = (which) => accessFlow((which ?? lesson.files.map((_, i) => i)).map((i) => ({ path: lesson.files[i].label, source: lesson.files[i].code })));
|
|
86
|
+
ctx.access = ctx.accessOf();
|
|
87
|
+
}
|
|
88
|
+
if (lesson.across) ctx.across = writeRuleAcross(parted, lesson.across);
|
|
89
|
+
if (lesson.passport) {
|
|
90
|
+
const parts = [...new Set(parted.map((f) => f.part))].map((name) => ({ name, files: parted.filter((f) => f.part === name).map(({ path, source }) => ({ path, source })) }));
|
|
91
|
+
const runs = lesson.passport.map((r) => ({ cwd: r.part, ...r }));
|
|
92
|
+
ctx.passport = assemblePassport({ parts, runs, builtAt: '2026-01-01T00:00:00.000Z', thunder: COMPILER_VERSION });
|
|
93
|
+
/** Check the passport after some files changed: { "part/file": new source }. */
|
|
94
|
+
ctx.passportCheck = (changed) => checkPassport(ctx.passport, { read: (part, file) => changed[`${part}/${file}`] ?? parted.find((f) => f.part === part && f.path === file)?.source });
|
|
95
|
+
}
|
|
79
96
|
return ctx;
|
|
80
97
|
}
|
|
81
98
|
|
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: /^(?:_?
|
|
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
|
-
|
|
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
|
+
|