@skillstech/thunderlang 0.5.11 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +441 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
package/CHANGELOG.md CHANGED
@@ -1,3 +1,444 @@
1
+ # 1.0.3
2
+
3
+ - **Version:** ThunderLang now shares OpenThunder's version number, so the two always go together. 1.0.3 has the same contents as 0.5.12; nothing in the language or the compiler changed.
4
+
5
+ # 0.5.12
6
+
7
+ - **Fix:** a call through an instance made in the same file (`library = Library()` then `library.can_borrow(…)`; `const svc = new Service()` then `svc.canShip(…)`) links to the rule again, as in 0.5.11. Details "Rules it relies on" and Flow "Open the rule" depend on it. Reported by OpenThunder.
8
+
9
+ **Language: writing in Thunder** (`compiler/src/write-steps.mjs`; `thunderWrite` in `/core`; `thunder write <file>
10
+ --edit '<json>' [--apply] [--test "<cmd>"] [--candidate <file>]`). A person changes software in Thunder and the code is
11
+ written for them, then proven.
12
+ - **Thunder edits**, by function and step: `setValue`, `setCondition` (whole condition, comparison, one side,
13
+ negation, add or remove an `and`/`or` part), `addStep`, `removeStep`, `moveStep`, `addStop`, `removeStop`,
14
+ `addInput`, `removeInput`, `setGivesBack`, `rename` (an input, a name, or the function with its calls), and
15
+ `addFunction` (simple cases). Each is validated against the meaning tree; one that does not fit is refused with the
16
+ reason.
17
+ - **Written deterministically** for TypeScript, JavaScript, Python, and Go as a minimal patch: only the touched lines
18
+ (often characters) change; comments, quotes, indentation, and formatting stay byte for byte.
19
+ - **Otherwise `needs-ai`** with a self-contained instruction for an AI coding agent (the compiler makes no AI or
20
+ network call); code an AI wrote is checked by the same proof (`options.candidate`) and labeled **AI-written**.
21
+ - **Proven** by reading the changed files again: the edited steps equal the intended steps tree for tree, and every
22
+ other function means the same (identical trees, and `thunder same`). A patch that fails its proof is never returned
23
+ as written. `--test` runs a command on the change; `--apply` saves only then.
24
+ - On five audit repositories, 2,846 of 3,069 generated edits (92.7%) were written and proven, 210 needed AI, 13 were
25
+ refused (`scripts/write-sweep.mjs`).
26
+ - `/zoom` Details has **Change this**: change a limit or add a Stop on the sample and see the Thunder edit, the code
27
+ change, and the proof, computed in the browser; nothing is saved.
28
+ - `readCode(…, { allSteps: true })` also gives decisions their steps; `parseStatementSpans` gives each part's offsets.
29
+ - Fix: `thunder --help` is flushed before exit, so a long help is never cut off in a pipe.
30
+
31
+ **Fix (serious): `thunder same` could call different code "same".** It compared steps by their short words and
32
+ ignored the code of steps shown as code, so `x = a + b` and `x = a - b`, or `compute(o.items)` and
33
+ `compute(o.lines)`, were reported as the same. Steps are now also compared by a language-neutral signature of their
34
+ code (names in any convention, operators, values); when the words match but the code does not, the answer is "cannot
35
+ check: Thunder reads these the same, but the code differs at step N", with both lines. A faithful conversion across
36
+ languages is still proven the same.
37
+
38
+ **Language: the whole application, next two readers: Kubernetes YAML and Docker Compose (spec section 12).**
39
+ - **Kubernetes** (`.yaml`/`.yml` known by `apiVersion:` and `kind:` in its first lines; multi-document files and
40
+ `kind: List`): each resource is a Resource (`resourceType` the kind as written, `address` `Deployment/api` or
41
+ `Service/shop/web` in a namespace). Workloads (Deployment, StatefulSet, DaemonSet, Job, CronJob, Pod) know copies,
42
+ image, command, ports, settings (`secretKeyRef` only named), CPU and memory, health checks in words, the user they
43
+ run as, and their mounts; Services, Ingresses, ConfigMaps, Secrets (values never shown), PersistentVolumeClaims,
44
+ ServiceAccounts, NetworkPolicies (in words), autoscalers, Namespaces, and kustomizations are read too; other kinds
45
+ are still drawn, with their type as written.
46
+ - **Docker Compose** (`docker-compose.yml`, `compose.yaml`, `*.compose.yml`, `docker-compose.<name>.yml`): services,
47
+ named volumes, networks, secrets, and configs are Resources (`compose-service`, `services.web`). A service knows its
48
+ image or build folder, published ports and to whom, settings (`${VAR}` computed; secret-looking literals not shown),
49
+ env files, volumes, what it starts after, networks, health check, restarts, user, limits, and profiles.
50
+ - **Links** with file and line: a Service **sends to** the workloads its selector picks; an Ingress to its Services; a
51
+ setting that names a Service or Compose service exactly (`redis:6379`, `http://api:8080`) **sends to** it; ConfigMaps
52
+ and Secrets are **read from**; Namespaces and Compose networks are **run in**; service accounts, storage claims,
53
+ roles, `depends_on`, and named volumes are **used**. Links to resources in other files are drawn when the files are
54
+ read together (same folder first; another folder only when exactly one has it). A Compose `build:` is linked to that
55
+ folder's Dockerfile image by exact path, and a Kubernetes image to a Dockerfile whose folder has exactly its name.
56
+ - **Flow**: "Applying shop.yaml" (the order things are made) and "Starting compose.yaml" (networks and volumes, then
57
+ each service after what it waits for: "Builds and starts api (from ./api), once db is healthy"; "Is the profile
58
+ monitoring turned on?").
59
+ - **Permissions**: Role/ClusterRole rules ("can read (get, list, and watch) configmaps in the namespace shop") and
60
+ RoleBinding/ClusterRoleBinding ("The service account ci/deployer can do anything (cluster-admin) in the whole
61
+ cluster"), wide for `*` verbs or resources, cluster-admin, admin/edit cluster-wide, or a role given to everyone.
62
+ - **Facts**, two new kinds: `privileged-container` (`privileged: true`, SYS_ADMIN/ALL, host network/PID/IPC, the
63
+ Docker socket or the node's root mounted) and `no-resource-limits`; and `runs-as-root`, `image-not-pinned`,
64
+ `public-ingress` (NodePort, LoadBalancer, Ingress, a Compose port published on every address),
65
+ `secret-in-plain-env`, `secret-in-plain-config`, and `wide-permission`.
66
+ - Helm and other `{{ … }}` templates are listed as skipped with the reason, never read as YAML. The YAML reader has
67
+ `parseYamlDocs`: each document of a multi-document file parsed on its own, so one bad document does not hide the
68
+ rest. `readableFile(path, head)` is now given each file's first lines everywhere a repository is read.
69
+ - Read on real repositories: kubernetes/examples, GoogleCloudPlatform/microservices-demo, docker/awesome-compose, and
70
+ dockersamples/example-voting-app.
71
+ - thunderlang.dev/read has Kubernetes and Docker Compose in its picker, with a sample each.
72
+
73
+ **Language: the whole application, next two readers: Terraform and Bicep (spec section 12).**
74
+ - **Terraform** (`*.tf`): each `resource` is a Resource (`resourceType` exactly as written, `address`
75
+ `azurerm_storage_account.main`) that knows its arguments in words: a value only when the file writes it
76
+ ("Account tier: Standard"), a reference as what it names ("the location of the resource group rg (worked out when
77
+ it is applied)", `computed: true`), nested blocks summed up in a line, `lifecycle { prevent_destroy }` as
78
+ "Protected: Terraform refuses to destroy it". `data` sources are looked up (`existing: true`, "Looks up an existing
79
+ subscription, made elsewhere"); a `module` is a Resource of its own ("Uses the module …"). `count`/`for_each` read
80
+ "One for each item in the setting names"; `count = x ? 1 : 0` reads "one, only when …".
81
+ - **Bicep** (`*.bicep`): `resource` (`resourceType` 'Microsoft.Storage/storageAccounts', `address` the symbolic name),
82
+ nested resources (full type, `parent::child`), `existing`, `module`, `for` and `if (…)`, `targetScope`, and
83
+ `metadata description` as the file's purpose.
84
+ - **Links** with `file` and `line`: references, `depends_on`/`dependsOn`, and `parent`, as `runs-in`
85
+ (`resource_group_name`, `service_plan_id`, `serverFarmId`, `parent`, …), `reads-from` (data sources, `existing`),
86
+ `sends-to` (workspaces, endpoints), or `uses`; one link per pair, the most exact kind kept. A reference to a resource
87
+ in another `.tf` file of the same folder is linked once the folder is read together.
88
+ - **Flow**: one Steps card per file, the order things are created from those links ("Keeps what it made in an Azure
89
+ storage account", "Works in Azure", "Creates the resource group rg", "Creates the storage account main in the
90
+ resource group rg"), with a question for each conditional resource and "For each …" for repeated ones.
91
+ - **Permissions** (`role?` added): `azurerm_role_assignment`, Key Vault access policies, AWS IAM (inline JSON,
92
+ `jsonencode`, `aws_iam_policy_document`, trust policies, policy attachments), `google_*_iam_member`/`_binding`,
93
+ and Bicep `roleAssignments` with 48 built-in Azure role ids named (checked against Azure Verified Modules: Owner,
94
+ Contributor, Reader, Storage Blob Data Reader, Key Vault Secrets User, AcrPull, …), followed through a `var`.
95
+ Wide: Owner/Contributor/User Access Administrator on a subscription or management group, `roles/owner` or
96
+ `roles/editor` on a project, IAM `"*"` actions or changes on `Resource: "*"`, AdministratorAccess.
97
+ - **Settings** (`default?`, `type?`, `doc?`, `output?`, `from?`, `allowed?` added): `variable`/`param` (sensitive and
98
+ `@secure()` only named), `locals`/`var`, `output`. Text says "given when it is applied (westeurope unless told
99
+ otherwise)".
100
+ - **Facts**, new kinds: `storage-public`, `secret-in-plain-config`, `encryption-off`, `wide-permission`; and
101
+ `public-ingress` for security groups, NSG rules, and firewalls open to `0.0.0.0/0`, `*`, or `Internet` beyond ports
102
+ 80 and 443 (ICMP reads "ping").
103
+ - Small HCL and Bicep parsers (no dependency, linear): strings with `${…}`, heredocs, for expressions, multi-line
104
+ calls and ternaries, safe access and non-null assertions, lambdas, spreads, union types, decorators. A block or
105
+ declaration that cannot be parsed is listed in `unknowns` with its line ("Not read yet: …"); the rest of the file
106
+ is read.
107
+ - Read on real repositories: terraform-aws-vpc, terraform-aws-iam, terraform-google-network, two Azure Verified
108
+ Modules for Terraform, two Azure Samples, and all 1,880 Bicep files of the Azure Verified Modules: every file read.
109
+ - thunderlang.dev/read has Terraform and Bicep in its picker, with a sample each; a Resource card says when it is
110
+ looked up rather than made, and settings show their default and whether they are secret.
111
+
112
+ **Language: the whole application, first two readers: Dockerfiles and GitHub Actions workflows (spec section 12).**
113
+ - **Dockerfile**: each build stage is a Steps card ("Image build", or "The build stage" for `AS build`), its
114
+ instructions in words: "Starts from node:22-slim", "Starts from the build stage", "Copies package.json and
115
+ package-lock.json into the image", "Installs what it needs (npm ci)", "Sets NODE_ENV to production", "Opens port
116
+ 3000", "Runs as the user node", "Checks its health with …", and "Starts with …" last. `RUN` chains are split into
117
+ steps; continuation lines, heredocs, `# escape=`, `--mount=type=secret` (named only) are read.
118
+ - The image a Dockerfile makes is a **Resource** (`kind: 'resource'`, `resourceType: 'docker-image'`, `address:
119
+ 'image:<path>'`) that knows what it starts from, its working folder, ports, user, start command, health check, and
120
+ its ENV settings (a value only when the file writes it; a secret-looking one is never shown).
121
+ - **GitHub Actions**: each job is a pipeline member with a "When" badge (`route: { method: 'When', path }` and
122
+ `when`): "When someone pushes to main", "When a pull request is opened", "When someone starts it by hand", "On a
123
+ schedule: every day at 02:00 UTC" (else "On a schedule (cron …)"), several joined with "or". Steps: well-known
124
+ actions in words ("Gets the code", "Sets up Node 22", "Builds and pushes the image"), others "Uses owner/action";
125
+ `run:` one step per command ("Runs the tests", "Publishes the package to npm"; unknown commands "Runs `…`", kept
126
+ and counted as only named); `if:` as a question (steps sharing one share the question; `always()` is a note, not a
127
+ question); `needs:` as "After the Test job finishes"; a matrix as "For each …"; `environment:` as "Deploys to the
128
+ production environment (it may need someone's approval first)"; `exit 1` as a Stop; `continue-on-error` noted.
129
+ Shell `if`/`for`/`case`, `cmd || { …; exit 1; }`, `[ … ] && cmd`, heredocs, and quotes across lines are read.
130
+ - **Permissions** (`model.permissions[]`: `{ id, who, can, on, wide, why?, says, file, line }`): "This workflow can
131
+ read the code"; `write-all` is wide: "can change everything in the repository (wide)".
132
+ - **Settings** (`model.settings[]`: `{ name, source, secret, file, line }`): parameters, variables, secrets (named,
133
+ never shown), literals, and values worked out when it runs (`computed: true`). `${{ … }}` reads "worked out when it
134
+ runs"; `${{ secrets.X }}` reads "the secret X".
135
+ - **Facts** (`model.facts[]`, what the file says, not advice): `write-all-permissions`, `untrusted-trigger-with-secrets`,
136
+ `action-pinned-by-tag` (GitHub's own actions marked `firstParty`), `image-not-pinned`, `runs-as-root`,
137
+ `secret-in-plain-env`.
138
+ - Model, additive: `files[].category` ('application' | 'infrastructure' | 'delivery') and `files[].skipped` (why a
139
+ file could not be read); member kinds `pipeline` and `image-build`; links with `file` and `line`; Big Picture at app
140
+ scope has `resources`, `permissions`, `settings`, and `facts`; Text lists Permissions and Settings.
141
+ - `readableFile(path, head?)` (read-repo and /core) says which language or format a file is; `Dockerfile`,
142
+ `Dockerfile.*`, `*.dockerfile`, `Containerfile`, and `.github/workflows/*.yml|yaml` are read, and folder reading
143
+ no longer skips `.github`. Hooks are in place for Terraform, Bicep, Compose, Azure Pipelines, Helm, and Kubernetes.
144
+ - A small YAML reader (no dependency): block and flow collections, quoted and plain scalars, block scalars with
145
+ chomping, anchors, comments, and `${{ … }}` kept as text, line by line.
146
+ - Grammar: symbols `resource` (a block) and `permission` (a key), a `when` mark, elements Resource, Permission,
147
+ Setting, Pipeline, and Image build, and Dockerfile and GitHub Actions in LANGUAGES. thunderlang.dev draws a
148
+ Resource card, who can do what, and the settings; /read has a Dockerfile and a workflow sample.
149
+
150
+ **Language: the running system — what happened when it ran, on Thunder's pictures** (`compiler/src/running.mjs`,
151
+ `thunder runtime <folder>`). Evidence of a run is placed on the flows Thunder draws, so nobody needs to read a stack
152
+ trace or a log in the original language: per question, how many times each side was taken; per Stop, how many times
153
+ it happened with the error and message as seen; per ending, how many times it was reached; per action or rule, its
154
+ calls, failures, and average and slowest time, a Details sentence ("Ran 201 times; stopped with NotAvailable 117
155
+ times (58%), when Is the book's status on shelf? was No"), and the most-taken way through it.
156
+ - Sources, each an adapter to one event shape (`{ file, line, kind, side?, error?, message?, value?, durationMs?,
157
+ count? }`): proof by running's records (`fromTrace`), stack traces (`fromStack`: Python tracebacks and pytest
158
+ reports, Node/V8 stacks, Java with its causes, C#, Go panics), structured logs (`fromLogs`: JSON lines with a
159
+ file/line or function, including Python logging, Google Cloud's sourceLocation, ECS, zap's caller; an error's
160
+ stack in a log is read too), and OpenTelemetry spans (`fromOtlp`: OTLP/JSON with `code.filepath` / `code.lineno`
161
+ / `code.function` or the newer `code.file.path` / `code.line.number` / `code.function.name`, with the exception
162
+ event's stack).
163
+ - `explainError(model, stack)`: "Failed in Borrow, at “Adds book to student's books” (line 42): AttributeError: …;
164
+ it got there because Is the book's status on shelf? was Yes and Can borrow? was Yes. Called from …". The answers
165
+ that led there come from the flow as drawn and are left out when it does not show them.
166
+ - Honest by rule: counts only from evidence (no count is not zero); evidence that cannot be placed is listed as
167
+ **not matched** with the reason (spec section 13).
168
+ - `thunder runtime <folder> --traces <file|dir> [--stack <file>] [--logs <file>] [--otlp <file>] [--member <name>]
169
+ [--top n] [--json]` prints the flows in Thunder Text with counts ("- Ask: Is the book's status on shelf? (line
170
+ 36) (ran 201×: Yes 84, No 117)"), each error explained, and what was not matched.
171
+ - Site: Semantic Zoom's School library (Python) example has "What happened when it ran" at Flow and Details, from a
172
+ recorded sample run (labeled as one), with counts beside each node and on each side.
173
+ - `modelText(model, id, { note })` and `pathsOf(flow)` are exported for tools that draw their own overlays.
174
+
175
+ **Language: proof by running — readings are checked against what the code actually does** (`compiler/src/executed.mjs`,
176
+ `thunder verify --run <folder>`). Thunder runs real code (the project's own tests, and made-up inputs for functions
177
+ that look free of side effects), records which way every question went and how every call ended, and compares that
178
+ with the flow it drew: when a condition held, the side Thunder says it takes then must hold the next step that ran;
179
+ a loop must reach its "For each" steps; a `return` must be one of Thunder's endings (and a rule's answer the value
180
+ given back); a `raise` / `throw` must be a Stop of the error Thunder names; reaching the end needs a "Done". Each
181
+ member is **executed**, **contradicted** (with the question, side, and line), ran with nothing to check, or not run;
182
+ only a run writes `member.completeness.level = 'executed'` (`markExecuted`). Python uses `sys.monitoring` and `ast`
183
+ (3.12+, no packages); JavaScript uses V8's own debugger in-process (`node:inspector`), no dependencies.
184
+ - Release gate: `npm run accuracy:gate` (`compiler/scripts/accuracy-gate.mjs`, in CI) fails when a run contradicts
185
+ any reading of the fixtures (or configured repositories), when a step invents a value, or when a question's words
186
+ or Yes/No side disagree with the code's polarity (a new check in `scripts/accuracy.mjs`: 0 of 4,494 questions in
187
+ the eleven audit repositories).
188
+ - On real code (docs/accuracy.md): requests, urllib3, and werkzeug run by requests' 619-test suite, and Express by
189
+ its own 1,290 tests. The runs found reader bugs, now fixed: Python `try … else:` and `for` / `while … else:`
190
+ bodies were dropped from the picture; `with self.lock:` (no `as`) read "Calls with" and dropped every step inside
191
+ it; JavaScript `else if` rules were all placed on the first `if`'s line; a SQL CHECK / UNIQUE refusal was quoted as
192
+ if the database said those words (it is now described, not quoted).
193
+ - Decision nodes carry `whenTrue` ('yes' | 'no'): the side the code takes when its condition holds.
194
+
195
+ **Language: review in Thunder** (`compiler/src/review.mjs`, `thunder review`, spec section 14). A pull request is
196
+ shown by what it changed in meaning, in plain sentences, so it can be reviewed without reading the code diff.
197
+ `thunderReview(oldFiles, newFiles)` (exported from `/core`) pairs each action, rule, and function with its other
198
+ version (by file and name, by a name used once, by a route's code, or by meaning) and compares the ways it stops and
199
+ when ("Now stops with 403 Forbidden ("forbidden") when the x-admin-secret header is not the ADMIN_SECRET setting"),
200
+ rules by running both versions on every edge case ("the limit between Small fee and Big fee moved from 7 to 10 days
201
+ late", with the case 8 days late as evidence), inputs, what it gives back, what it changes or reaches (another
202
+ service, a payment, stored data), what it relies on, addresses, records and choices, new, removed, renamed, and moved
203
+ functions, imports, and code outside every function. Items are ordered risk, meaning, form, each with the before and
204
+ after. "Only the form changed" is said only when it is shown (same code apart from spacing and comments, consistent
205
+ renames of names the function declares, or a rule with the same answers on every edge case); when Thunder's words
206
+ read the same but the code differs, it says "Changed, check". Infrastructure and pipeline files are flagged to check,
207
+ not read. `thunder review <base-ref> [head-ref] [--json] [--out file]` reads both versions from git (no network) and
208
+ prints Markdown for a pull request comment; `.github/actions/thunder-review` posts and updates one comment with the
209
+ adopting repository's own token (not enabled on this repository). Decision nodes in the model now carry `holds` (each
210
+ side of a yes/no question as a statement) and Details' `when` entries a `says`, so sentences read "when the header is
211
+ not the setting" rather than quoting the question. /zoom shows a sample review computed by the compiler.
212
+
213
+ **Language: the whole system — calls across files and services** (`compiler/src/system.mjs`, in `/core`). The model
214
+ now links a step's call to the member it calls in another file, and a request or event to the code that handles it
215
+ (docs/spec.md, "The whole system"):
216
+ - **Calls across files**: `links[]` gains `kind: 'uses'` entries with `crossFile: true`, the target's `file`, and the
217
+ calling step's `line`, resolved through imports: JS/TS ES modules, CommonJS, re-exports, tsconfig path aliases,
218
+ workspace packages; Python absolute and relative imports and packages; Go packages (by `go.mod`) and the same
219
+ package's other files; Java/Kotlin imports by class, C# `using`, PHP `use`, Ruby class names, Rust `use crate::`.
220
+ Methods are followed through declared types (fields, constructor parameters, Go receivers), and overloads by how
221
+ many values a call gives. The calling flow node gets `uses` and `usesFile`, so Open → opens the other file.
222
+ - **Service calls**: `kind: 'sends-to'` links an HTTP request the library catalog recognizes to the route in this
223
+ repo with the same method and path (path parameters are wildcards; Next.js route files count), an event or queue
224
+ message to its listeners by name, and a Celery `delay()` to its task.
225
+ - **Never guessed**: `model.notLinked` lists what was worth linking and could not be, with the reason (external
226
+ package, dynamic import, computed URL, another service's host, no or two matching routes, an interface).
227
+ - **Views**: `readLevel(model, 'big-picture')` for the app adds `calls` (which areas call which, with examples) and
228
+ `notLinked`; `uses`/`usedBy` and Details' `reliesOn` say the file, service, and route; Details adds the member's
229
+ `notLinked`. The site shows "How the parts connect", "Open in orders.ts →", and the file of each link.
230
+ - `collectReadableFiles(root, { manifests: true })` also returns go.mod, package.json, and tsconfig/jsconfig files.
231
+ - On the eleven audit repositories, of calls whose name matches a function defined in another file, 47.8% are now
232
+ linked (55.5% where that name is defined only once in the repo; cobra 82%, gson 75%, formik 61%, requests 51%);
233
+ the rest are mostly calls on values whose type is not written down. Reading time is about 1.04× before overall.
234
+ - A comment with an apostrophe (`// it's`) no longer stretches a TypeScript class or interface over the functions
235
+ after it (they were wrongly owned by it, so their ids lose that owner); `lift.mjs` finds line numbers without
236
+ re-splitting the file each time.
237
+
238
+ **Language: JavaScript functions with no declaration of their own are items.** `exports.x = function`,
239
+ `module.exports.x =`, `obj.method = function`, `Foo.prototype.bar = function`, functions inside functions (the inner
240
+ `app` in Express's `createApplication`), object-literal methods, and anonymous callbacks (`app.use(function …)`,
241
+ `.then(function …)`, block-bodied arrows) are now items, named by what they are assigned to or
242
+ `<parent> › callback at line N` (items carry `assignedTo`, `callback`, `passedTo`). Prototype methods belong to their
243
+ Thing, and `function Foo()` is how a new Foo starts; an object given two or more methods (`res.json`, `res.send` on
244
+ `var res = Object.create(…)`) is a Thing. Declared functions keep their ids, and methods owned by assignment keep the
245
+ id they had. Test bodies (`describe`/`it` callbacks) stay tests; Big Picture does not list callbacks on their own.
246
+ On Express, the share of recorded executions Thunder can place on a member went from 71.9% to 99.7% (functions
247
+ drawn in lib/: 76 to 109).
248
+
249
+ **Language: no loss — every detail, one level down** (`compiler/src/meaning.mjs`, `compiler/src/round-trip.mjs`).
250
+ Thunder's words stay short, and nothing in the code is lost: every step now carries `expr`, its full meaning as a
251
+ small language-neutral tree (`thunder-expr-v1`): calls with their whole callee path and every argument, assignments
252
+ with their full target (index, keys) and value, conditions with every operand and negation, exact literals, object,
253
+ list, and JSX contents, lambdas (their body is the step's children), returns and throws with value, error type, and
254
+ message. What the reader cannot read exactly is `{ kind: 'code', text }`, never a guess.
255
+ - **Details** gives each step its `expr` and `detail`, what the short words leave out ("Calls save — with: order,
256
+ { validate: false }"). **Thunder Text** stays short; `modelText(model, id, { full: true })` (and Text with
257
+ `{ full: true }`) shows every argument and value. On the eleven audit repositories, a reader can now see 97.4% of
258
+ each step's code names in Details, against 59.5% in the short words (58% before, counted the old way).
259
+ - **Code → Thunder → code.** For TypeScript, JavaScript, Python, and Go, a step's tree is written back as code, read
260
+ again by the same reader, and compared: 99.4% of 9,965 steps come back exactly (every step that was read into a
261
+ tree; the rest are kept as code), none different. Conditions and values made of names and operators are also run
262
+ before and after on generated inputs (Node, Python): 1,069 run the same, none differently (Go is compared by tree
263
+ only). `scripts/accuracy.mjs` adds "names kept (Details)" and "steps round-trip exact" (and `--steps` to list
264
+ failures); 465 of 25,864 steps across all eleven repositories are still kept as code (docs/accuracy.md).
265
+ - **The faithfulness gate reads the tree**: a condition's negations and comparisons are counted from `expr` when it
266
+ parses (a TypeScript non-null `x!` is no longer a negation; operators inside strings never count), and
267
+ `wordsAgree(step)` checks that every number, quoted text, and "Calls X" in the words is in the tree (no step on the
268
+ eleven repositories disagrees).
269
+ - Reader fixes the tree found: `i++` at the end of a line (Go, JavaScript without semicolons) no longer swallows the
270
+ next statement; a one-line `if (x) { a(); }` no longer puts its block in its words; `case A: case B:` keeps both
271
+ labels in its tree; Kotlin `require(x) { "message" }` keeps its message.
272
+ - No existing test changed.
273
+
274
+ **Language: C, C++, and Swift.** Three more languages (with R, shell, and PowerShell below, seventeen in all). `.c` is C; `.cc`/`.cpp`/`.cxx`/`.hpp`/`.hh`/`.hxx`
275
+ are C++; a `.h` is C unless it uses classes, namespaces, templates, or `::` (C++ lines kept for C++ callers inside
276
+ `#ifdef __cplusplus` do not count); `.swift` is Swift. Pasted code is recognized too.
277
+ - **Functions.** C and C++ functions are found by walking scopes (file, namespaces, `extern "C"`, classes): return
278
+ types on their own line, `static`/`inline`, macros, templates, attributes, constructors with initializer lists,
279
+ destructors ("Clean up"), operators, and `Type::method` definitions (with the type they belong to). Swift `func`,
280
+ `init`, subscripts, computed properties, and Vapor routes (`app.get("orders", ":id") { req in … }`,
281
+ `routes.post(…, use: handler)`, literal `grouped(…)` prefixes). Doc comments: C/C++ `/* … */`, `/** … */`, `//`;
282
+ Swift `///`.
283
+ - **Steps.** C/C++: `malloc`/`calloc`/`new T[n]` ("Gets memory for 10 books as books"), `free`/`delete` ("Frees buf"),
284
+ `memcpy`/`strcpy`, `memset`, `strlen`, `strcmp(a, b) == 0` ("a is b"), `exit`/`abort`, `cout`/`printf`, `p->x`,
285
+ casts, declarations, designated initializers, labels and `goto`, `do … while` (also Allman style), endless loops,
286
+ range-for, `try`/`catch` by type, `throw;`, lambdas as their own sub-flow, `(void)x` skipped. A C/C++/Swift
287
+ `switch` is one question with one side per case; a C case without `break` says "then carries on into the next
288
+ case". Swift: `guard … else` ("If not: …" with the Stop inside), `if let`/`guard let` ("x is set"), `defer`,
289
+ `do`/`try`/`catch` by type, ranges (`0..<3` is "from 0 to 2"), enum cases (`.cancelled`), trailing closures,
290
+ one-expression bodies, `throw LibraryError.full`, Vapor `throw Abort(.notFound)` ("Fails with 404 Not Found").
291
+ C error returns stay what the code says ("Returns -1 early if fd is less than 0").
292
+ - **Things.** C `struct`/`typedef struct` (Data, or a Thing when functions take it first or are named after it, with
293
+ the type's name left out of the label) and `enum` (shared prefixes dropped); C++ `class`/`struct`/`enum class`,
294
+ methods outside the class (also in another file), constructors, initializer lists, and default member initializers
295
+ as starting values; Swift `class`/`struct`/`actor`/`enum`, `extension` methods (also in another file), `init`, stored
296
+ properties with defaults; `protocol` is a contract, not a Thing.
297
+ - Measured on redis (227 C files, 5,667 functions, 95% of steps explained), nlohmann/json and fmt (C++, 87–90%),
298
+ Alamofire and vapor (Swift, 92–96%), no reader errors; see the PR. The older readers are unchanged (the switch
299
+ grouping, `blockBrace`, and C/Swift wording run only for the new languages); `readableLanguage(path, source?)`
300
+ takes the source to decide a `.h`.
301
+ - thunderlang.dev says fourteen languages; /read has C, C++, and Swift samples, and the Original view colors them.
302
+
303
+ **Language: C, C++, and Swift held to the faithfulness bar.** The C, C++, and Swift readers pass the faithfulness
304
+ gate (`faithful.mjs`, below) and fix every false or misleading reading found in a hand
305
+ review of fmt, nlohmann/json, redis, Alamofire, and vapor (see docs/accuracy.md, "C, C++, and Swift"):
306
+ - **Text with values inside** (docs/spec.md): `printf`/`fprintf`/`snprintf`, `fmt::print`, `cout <<`, and Swift
307
+ interpolation keep every literal character and show each value as a «placeholder» (`"«dir»/alias «n»\n"`,
308
+ `«x as %5.2f»`); text whose values cannot be paired is shown as code.
309
+ - C/C++: macros in front of a return type are dropped (`FMT_CONSTEXPR void` gives back nothing; `auto f() -> T`
310
+ gives back T); `using` is no step; `*p = v` "Writes v where p points"; `+=` of a call adds; bit operators,
311
+ statement ternaries, and multi-name declarations are code; brace-less `for`/`while`/`if` (also nested, `++q`,
312
+ `*err = …`, `[[unlikely]]`) keep their bodies on the right side; `events[i].mask` and `c->argv[j]->ptr` keep their
313
+ index; `p != nullptr` and `!strcmp(a, b)` pass the gate; steps under `#if`/`#elif`/`#else` say which build runs
314
+ them; a block starting `p->x = …` is no longer cut as a lambda parameter; goto labels keep their names.
315
+ - Swift: a one-expression body (also a switch or if/else body, a trailing closure, a Vapor route closure) gives back
316
+ its value; `[Character]` parameters are inputs; a String property is never a yes/no rule; `Logger(…)` and Apple C
317
+ functions (`SecPolicyCreateSSL`) are not "writes a message"/"a new"; `guard case .x = event` asks about event;
318
+ `T.self is String.Type`; `for _ in xs`; code shown "not explained" is exactly as written.
319
+ - Regression tests: `test/faithfulness-c.test.mjs`, `-cpp`, `-swift` (one per false or misleading sample).
320
+
321
+ **Language: readings never say something false — the faithfulness gate** (`compiler/src/faithful.mjs`). A hand
322
+ review of 330 real readings found 57 false ones; re-graded after this change, none of them is false and 5 of the 53
323
+ misleading ones still are (docs/accuracy.md). Before Thunder shows words for code, it checks that the words keep
324
+ everything the code says, and shows the code (marked "not explained") when they cannot:
325
+ - Conditions are split at their top-level and / or, each part said on its own, and each part must keep its
326
+ negations (`!`, `not`, `!=`, `!==`, `is not`, `not in`, `unless`) and comparisons. Compound questions are asked as
327
+ written, so the Stop is always on the side the code takes (`!body || used` read "Body or used? No: stop"); only
328
+ `unless` flips a whole question. `=== null` and `=== undefined` are told apart, `typeof x === 'string'` reads "x
329
+ is text", PHP `is_string($x)` "x is text", `x instanceof Foo` "x is a Foo"; a question is asked by a rule's name
330
+ only when the condition is that call alone; `!==` before `null` no longer reads "! is empty".
331
+ - Values keep what they are made of: `headers[key] = v` reads "Stores v under key in headers" (it read "Sets headers
332
+ to …"); a returned `a && b` / `a || !b` keeps every part; multi-line returns and assignments are read whole (JSX
333
+ `return (` reads "what to show on screen"); `a or b` keeps its fallback; `*=`, `??=`, `||=`, `.=`, Go `append`
334
+ and PHP `$a[] =` say what they do; a call names a value only when it is the whole value; a returned function is
335
+ shown with its steps.
336
+ - Nothing is dropped or moved: a loop's `continue` / `break` are steps ("Skips to the next one", "Leaves the loop");
337
+ a brace-less `if (x)\n stmt;` keeps its statement; a C-like switch is one question with each case's steps under
338
+ it; Go `t.Fatal` / `t.Errorf` and Rust `cfg!` chains are no longer "Checks: …: nothing"; PHP `foreach ($a as $k =>
339
+ $v)` is a loop; `//` or PHP `#` inside a string no longer cuts the body short; a loop whose body could not be read
340
+ is shown as code; a function is drawn as a rule only when every statement was read into it (partial rules hid
341
+ later checks).
342
+ - `next(…)` passes an error on only in middleware (`(req, res, next)`, a route, a `NextFunction`); a .NET handler
343
+ delegate "returns the answer of the next handler"; a local helper named `next` is an ordinary call.
344
+ - Smaller fixes: messages are no longer cut at an inner quote; PHP `$a.$b` joins text (it read "the a's b"); Go
345
+ `return out, err` gives both back; Kotlin `?: return null`, `require`, abstract `fun`s; Ruby implicit last values,
346
+ `unless`, one-line blocks, `case … else`, `halt`; Python continued lines and bare `self.x`; destructured inputs;
347
+ a fetch `Request` / `Response` is an input outside web handlers.
348
+ - Tests updated where they encoded a lossy reading: "whether proxy and …" is now "whether proxy is set and …", a
349
+ keyed store reads "Stores True under arg in seen", a switch's cases hold their steps, and a value keeps its owner
350
+ ("otherwise the order's total", "Sets name to the user's name").
351
+
352
+ **Language: common libraries, read as what they do** (`compiler/src/libraries.mjs`). Calls into well-known libraries
353
+ read with their arguments instead of "Calls find unique": ORMs (Prisma, Mongoose, Sequelize, Django, SQLAlchemy,
354
+ Spring Data incl. derived names like `findByEmailAndActive`, Entity Framework, GORM, `database/sql`, ActiveRecord,
355
+ Eloquent and Laravel's query builder) say what they find, save, change, or remove and by what ("Finds the user whose
356
+ email is email"); HTTP clients name the method and address ("Sends a POST request to …/orders"); tokens, passwords,
357
+ caches, Stripe, email, background jobs, JSON, files, and the current time read in words. Go's `if err := <call>; err
358
+ != nil` says what could not be done ("If it cannot find the first user whose id is id").
359
+
360
+ **Language: inputs and outputs, read accurately.** Measured on eleven open-source repositories with the new
361
+ `scripts/accuracy.mjs` (see docs/accuracy.md):
362
+ - What goes in says where it comes from: "the x-admin-secret header", "force (in the address)", "email (sent in the
363
+ request)"; Details gives each input's kind when the code says it ("days late: a number", "request: a
364
+ PingResource"). Plumbing is decided by type when there is one, so `Handle(PingResource request, …)` takes a request.
365
+ - What comes back: an action's "You get back" lists every way it ends ("success (yes) and data (result); or it stops
366
+ with 403 or 500"); returned objects give their plain values; `yield` gives back one at a time; a redirect and
367
+ `next()` end the response ("Lets the request go on to the next step"); a bare `return` after a Stop is not a new
368
+ ending, and nothing after a Stop on the same path is listed as an ending.
369
+ - Conditions: `!==` reads "is not" (it read as a stray "!"); request and settings idioms read as words with their
370
+ names kept exactly (`req.headers['x-admin-secret'] !== process.env.ADMIN_SECRET`: "Is the x-admin-secret header
371
+ the ADMIN_SECRET setting?"); dynamic imports read "Loads … from ./lib/…".
372
+ - Text inside quotes is never changed (it was: "charset_normalizer" became "charset normalizer").
373
+
374
+ **Language: what a handler sends back.** A response sent to the caller reads as what the person gets back:
375
+ `res.json(user)` reads "Returns user" (not "Calls json"), `res.status(201).json(order)` "Returns order (201 Created)",
376
+ `res.sendStatus(204)` "Returns nothing (204 No Content)", `res.render('profile')` "Shows the profile page", across
377
+ Express, Fastify, Koa, Gin, ASP.NET (`Ok`, `CreatedAtAction`, `NoContent`), Spring (`ResponseEntity`), Flask
378
+ (`jsonify`), and FastAPI (`JSONResponse`). Their error forms (`NotFound(...)`, `ResponseEntity.notFound()`,
379
+ `res.sendStatus(404)`, Gin `c.JSON(http.StatusNotFound, …)`) are Stops with their status. Details lists them under
380
+ what it gives back and when.
381
+
382
+ **Language: R, Bash/POSIX shell, and PowerShell.** Thunder reads three more languages, each by its own module
383
+ (`rlang.mjs`, `shell.mjs`, `powershell.mjs`, with a shared phrasebook of command-line tools in `commands.mjs`) into
384
+ the same items as every other language.
385
+ - **R** (`.R`, `.r`): `name <- function(a, b = 3)` functions; `if`/`else if`/`else`, `return()` guards, and `switch()`
386
+ (with fall-through) as decisions; `for`/`while`/`repeat`, `stop()` as a Stop with its message, `warning()`,
387
+ `message()`, `tryCatch(error =, warning =, finally =)` as handlers and what always runs at the end, the implicit last
388
+ value; `library()` as setup; data-frame pipelines (`|>`, `%>%`) one verb at a time ("Keeps only the rows where total
389
+ is more than 100", "Groups the rows by region", "Sorts the rows by revenue, highest first"); `R6Class`,
390
+ `setRefClass`, and `setClass` as Things; roxygen `#'` as the author's note; plumber `#* @get /path` as actions;
391
+ testthat tests.
392
+ - **Shell** (`.sh`, `.bash`, `.zsh`, `.ksh`, and extensionless files with a shell shebang): a linear lexer and parser
393
+ for words, quotes, `$(…)`, heredocs, pipes, `&&`/`||`, `if`/`elif`/`else`, `for`, `while`/`until`, `case`, and
394
+ functions. Tests in words ("the file … exists", "x is empty", "is at least"), `exit N` as a Stop with the message
395
+ echoed to stderr right before it, `set -euo pipefail` as a note, `trap … EXIT` as what runs at the end,
396
+ `cmd || { …; exit 1; }` as a question, and docker, kubectl, helm, az, aws, gcloud, git, npm, curl, and file commands
397
+ by what they do. The script's own top-level code is one item named after the file. Shell has no classes, so it has
398
+ no Things (it is left out of `THING_LANGUAGES` on purpose).
399
+ - **PowerShell** (`.ps1`, `.psm1`): `function Verb-Noun` with `param()` inputs and their kinds, comment-based help
400
+ (`.SYNOPSIS`) as the author's note, `if`/`elseif`/`else` and `switch` as decisions, `foreach`, `ForEach-Object`,
401
+ `try`/`catch [Type]`/`finally`, `throw` as a Stop, `Write-Error` as a Stop only when errors are set to stop,
402
+ comparison operators in words, cmdlets by Verb-Noun ("Gets the Azure resource groups"), `class` and `enum` as Things
403
+ and Choices, Pode routes as actions, Pester tests.
404
+ - `readableLanguage(path, source)` reads an extensionless file as shell when its first line is a shell shebang;
405
+ `collectReadableFiles` looks at the first bytes of extensionless files to find them.
406
+ - Flows link a shell or PowerShell call to the function it runs (by the step's callee). Steps that write a message
407
+ or send an HTTP request get the "send" and "ask" shapes.
408
+ - `/read` has R, Shell (Bash), and PowerShell in its language picker, a sample for each, and editor colors for them.
409
+ - `scripts/language-audit.mjs` audits tidyverse/dplyr, nvm-sh/nvm, and PowerShell/PSScriptAnalyzer, and leaves a
410
+ script's own functions out of its top-level item's branch count. Spec section 9 updated.
411
+
412
+ **Language: R, shell, and PowerShell held to the faithfulness bar.** A hand review of 112 samples (nvm, neofetch,
413
+ posh-git, PSScriptAnalyzer, httr, dplyr) found 41 readings that stated something false (D) and 14 that misled (C);
414
+ after this change the same samples have 0 D and 0 C (each fix has a regression test in
415
+ `test/faithfulness-{shell,powershell,r}.test.mjs`).
416
+ - **Text with values inside** (spec section 9): quoted text keeps every literal character as written, escapes included,
417
+ and each inserted value is a `«…»` placeholder: a plain variable by its exact name (`"${NVM_DIR}/alias"` →
418
+ `"«NVM_DIR»/alias"`), anything else by its code (`«$1»`, `«${1-}»`, `«$(cat)»`). printf, sprintf, glue/cli, and
419
+ PowerShell `-f` pair each conversion with its argument (`«n as %5d»`); when they cannot be paired the step is shown
420
+ as code. Names are no longer turned into words inside quotes ("{nvm dir}", "{all the inputs}"), and quoted text is
421
+ never rewritten by the possessive pass (`liblzma.so` was "the liblzma's so", `binfmt_misc` "binfmt misc").
422
+ - **Shell**: `${x#p}`, `${x%%p}`, `${x/a/b}`, `${x:+w}`, `${#x[@]}`, `${x[0]}` say what they do (they read as the bare
423
+ variable before: "Sets version to version"); `${x:-d}` says "empty or not set", `${x-d}` "not set"; arithmetic
424
+ Thunder cannot say exactly (`?:`, commas inside conditions, `++` in a test) is shown as code; `a && b || c` runs `c`
425
+ when a or b failed (it was read as "only if a worked"); `test && a || b` is if/else only when `a` cannot fail; a bare
426
+ `return`/`exit` gives back the last command's code (it said "success"); `$1`…`$9` inside single quotes (awk) are not
427
+ inputs; `$(< file)` is the file's contents; case patterns are shown as written; `read -a … <<<`, `printf -v`.
428
+ - **commands.mjs**: `curl` sends to its address (not to the value after `--max-time`); `wget --version` / `curl
429
+ --version` download nothing; `find` with `!`, `-prune`, `-links` shows those tests as code instead of dropping them;
430
+ `head`/`tail -1` keep their count; `git config name` reads the setting; `choco -s .` is a source, not a package.
431
+ - **PowerShell**: conditions pass the faithfulness gate (`-not`, `-ne`, `-and`, `-or` counted like `!`, `!=`, `&&`,
432
+ `||`; otherwise the code is shown); arguments run to the next space (`-Color $s.X` no longer splits); `$_` in a catch
433
+ is "the error"; `$args[0]` is "the first input"; spaces inside quoted text are kept.
434
+ - **R**: calls not put into words keep every argument; `names(x) <- v` is "Sets the names of x"; `if`/`switch` used as
435
+ a value sets the variable on each side; `is.null` says "is NULL"; `cat` keeps escapes and its separator;
436
+ `!(a && b)` is shown as code, not rewritten.
437
+ - **Shared (ported from fix/faithfulness, identical code)**: `src/faithful.mjs`, `test/faithfulness-helpers.mjs`;
438
+ `askAsQuestion` asks a compound condition as written and a code condition as code, and asks by a rule's name only
439
+ when the condition is that call (`askedByRule`); words inside quotes, code, and placeholders are never the question's
440
+ verb ("^«COMMAND» is an alias for" is not split at "is"). `req`/`app` are plumbing only in web handlers.
441
+
1
442
  # 0.5.11
2
443
 
3
444
  **Language: choices among cases, and inner functions, in the flow.**