@tinkered/cli 0.30.1 → 0.31.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/README.md CHANGED
@@ -20,6 +20,7 @@ GitHub release; the
20
20
 
21
21
  ```text
22
22
  tinker check [root] [--json]
23
+ tinker graph [root] [--write]
23
24
  tinker skill list
24
25
  tinker skill load <skill>
25
26
  ```
@@ -38,6 +39,8 @@ bun --bun tinker check
38
39
  the cast gate.
39
40
  2. **rules:** Tinker's rules, then the app's
40
41
  other lint.
42
+ 3. **graph:** the graph of the code must match
43
+ `tinker.graph`.
41
44
 
42
45
  - Only the first stage that fails prints.
43
46
  - At most 5 findings print.
@@ -86,6 +89,94 @@ A tool with no config is skipped, and the
86
89
  `tinker check: not done`, with exit 2: only a
87
90
  run of every stage can say OK.
88
91
 
92
+ ## The graph
93
+
94
+ `tinker graph` prints the app's graph. It has one
95
+ line per operation (ADR 0161). The line holds
96
+ facts:
97
+
98
+ - `exits`: each way out, as the exit stage names
99
+ them;
100
+ - `reads`: each cell read, and how;
101
+ - `writes`: each cell write, and how;
102
+ - `calls`: each operation it runs.
103
+
104
+ ```text
105
+ issue.move.do exits{gone,moved,stale}
106
+ reads{issues.list.of} writes{issues.list.set}
107
+ calls{issues.inTeam}
108
+ ```
109
+
110
+ - A name is the label, never a local name.
111
+ - The sets hold all the code of `run`, callbacks
112
+ too. They do not say which exit a write is on.
113
+ - A dep written in place, in a `const`, or spread
114
+ from one reads the same.
115
+ - A dep taken apart in the body,
116
+ `const { list } = deps`, reads the same as one
117
+ taken apart in the parameters.
118
+ - A bare cell dep, `all: issues`, gives `run` its
119
+ value: that reads `issues.list.get` each run.
120
+ - The graph reads `src` and `cmds` only.
121
+
122
+ The graph is facts only. It never judges them.
123
+ The reader judges: a person or an LLM reads the
124
+ line and its diff, and asks if the change is
125
+ meant.
126
+
127
+ An empty set means "none". A `?` in a set means
128
+ "the graph could not see here": it never guesses.
129
+ A set gets `?` when the code can touch a dep in a
130
+ way the graph cannot follow:
131
+
132
+ - a dep handed on: passed to a function, put in
133
+ an array or an object, or given another name;
134
+ - the deps handed on whole, a rest
135
+ `{ a, ...others }` taken from them, or a key
136
+ the graph cannot read, such as `{ [key]: x }`;
137
+ - a call on a dep the graph does not know, such
138
+ as `list.watch(…)`;
139
+ - a dep the graph cannot name: a member of a
140
+ capsule or a contract (`seaApi["clock.now"]`),
141
+ a cell whose label is not written as a string,
142
+ an `atScope` or `atNamespace` controller;
143
+ - a tag dep that holds a unit (ADR 0151), through
144
+ any edge: an operation gives `calls{?}`; a
145
+ cell, a view or a read gives `reads{?}`, and a
146
+ cell `writes{?}` too;
147
+ - a `run` passed by name, not written in place.
148
+ With a dep the graph cannot name, every set
149
+ gets `?`.
150
+
151
+ The `?` goes in each set that dep can touch: a
152
+ cell in `reads` and `writes`, a read in `reads`,
153
+ an operation in `calls`. For a dep the graph
154
+ cannot name, its type in `run` says which.
155
+
156
+ A tag that holds a union of unit kinds, or a held
157
+ cell that `run` never uses, may show no `?`.
158
+
159
+ The graph reads each op's own body. A resource's
160
+ own code is not read: a write inside a
161
+ resource's value does not show.
162
+
163
+ `tinker graph --write` writes the graph to
164
+ `tinker.graph`. Commit that file. Then the check
165
+ builds the graph again and compares. Each line
166
+ that differs is a finding at the operation:
167
+
168
+ ```text
169
+ src/issues/ops.server.ts:80 tinker/graph
170
+ issue.move.do: writes{issues.list.set},
171
+ tinker.graph says writes{}
172
+ ```
173
+
174
+ - Meant the change? Run `--write` again. The
175
+ reviewer reads the diff of the file.
176
+ - Did not mean it? Fix the code.
177
+ - No `tinker.graph` is one finding, when the app
178
+ has an operation.
179
+
89
180
  ## The tests and the exits
90
181
 
91
182
  An exit is one way out of an operation: each
@@ -100,9 +191,9 @@ Name the test command in `tinker.json`:
100
191
 
101
192
  Then the check runs two more stages:
102
193
 
103
- 3. **tests:** the command. Red tests print the
194
+ 4. **tests:** the command. Red tests print the
104
195
  end of their output.
105
- 4. **exits:** each exit that the types declare
196
+ 5. **exits:** each exit that the types declare
106
197
  and no test reached is a finding.
107
198
 
108
199
  ```text
@@ -233,6 +324,14 @@ Intent finds them (ADR 0143).
233
324
  a finding: `export … from "…"`, of values or
234
325
  types, or `export { name }` of an imported
235
326
  name (ADR 0160).
327
+ - `tinker/link` — a page has no plain `<a>` to
328
+ a path in the app: `/issues`, `./next`. A
329
+ click loads the whole page, so the app state
330
+ is lost. Use the router's `Link`.
331
+ A server path, such as `/auth/login`: add `rel="external"`.
332
+ A link to another site or to a file, `#top`,
333
+ a download, a new tab, or what the rule
334
+ cannot read passes.
236
335
 
237
336
  A page file is a file in `src/` with no `.server`
238
337
  in its name.
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as main } from "./main-DmBjD1BM.mjs";
2
+ import { t as main } from "./main-BAo7SB-T.mjs";
3
3
  //#region src/cli.ts
4
4
  if (import.meta.main) {
5
5
  const { code, out, err } = main(process.argv.slice(2), process.cwd());
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
+ import ts from "typescript-api";
1
2
  //#region src/rules.d.ts
2
3
  /** Tinker's own rules: `check` finds them in the app's files. */
3
- declare const own: readonly ["tinker/plain", "tinker/one-wire", "tinker/react-state", "tinker/gap", "tinker/barrel"];
4
+ declare const own: readonly ["tinker/plain", "tinker/one-wire", "tinker/react-state", "tinker/gap", "tinker/barrel", "tinker/link"];
4
5
  //#endregion
5
6
  //#region src/check.d.ts
6
7
  declare namespace Check {
@@ -102,10 +103,10 @@ export declare function isError<N extends Errors.Name>(value: unknown, kind: N):
102
103
  //#region src/tools.d.ts
103
104
  declare namespace Tools {
104
105
  /**
105
- * A stage of `tinker check`: `types` runs first, `rules` only once it is clean, and `exits`
106
- * only once the app's tests pass.
106
+ * A stage of `tinker check`: `types` runs first, `rules` only once it is clean, `graph` only
107
+ * once the rules are, and `exits` only once the app's tests pass.
107
108
  */
108
- type Stage = "types" | "rules" | "exits";
109
+ type Stage = "types" | "rules" | "graph" | "exits";
109
110
  /** A run of the app's tests: its exit status, all it said, and the exits no test reached. */
110
111
  type Tested = {
111
112
  status: number | null;
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as check, r as isError, t as main } from "./main-DmBjD1BM.mjs";
1
+ import { n as check, r as isError, t as main } from "./main-BAo7SB-T.mjs";
2
2
  export { check, isError, main };
@@ -1,4 +1,4 @@
1
- import { existsSync, globSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
1
+ import { existsSync, globSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join, matchesGlob, relative, resolve } from "node:path";
3
3
  import ts from "typescript-api";
4
4
  import { IntentCoreError, listIntentSkills, loadIntentSkill } from "@tanstack/intent/core";
@@ -124,7 +124,7 @@ function labelOf(options) {
124
124
  if (!label || !ts.isPropertyAssignment(label)) return void 0;
125
125
  return ts.isStringLiteralLike(label.initializer) ? label.initializer.text : void 0;
126
126
  }
127
- function exitsIn(checker, source, path) {
127
+ function operationsIn(checker, source, path) {
128
128
  const operation = coreOperation(source);
129
129
  const found = [];
130
130
  if (!operation) return found;
@@ -136,35 +136,41 @@ function exitsIn(checker, source, path) {
136
136
  if (!label || !run) return;
137
137
  const returned = returnOf(checker, run);
138
138
  const line = source.getLineAndCharacterOfPosition(node.getStart()).line + 1;
139
- for (const exit of returned ? exitsOf(checker, returned) : []) found.push({
139
+ const exits = returned ? exitsOf(checker, returned) : [];
140
+ found.push({
140
141
  path,
141
142
  line,
142
143
  label,
143
- exit
144
+ options,
145
+ run,
146
+ exits
144
147
  });
145
148
  };
146
149
  visit(source);
147
150
  return found;
148
151
  }
149
152
  /**
150
- * Each exit the app's operations declare, read from the types of the app's own `tsconfig.json`.
151
- * An app with no `tsconfig.json` declares none.
153
+ * The app's operations, read with the types of the app's own `tsconfig.json`. An app with no
154
+ * `tsconfig.json` has none.
152
155
  */
153
- function declaredExits(root) {
156
+ function readOperations(root) {
154
157
  const config = join(root, "tsconfig.json");
155
- if (!existsSync(config)) return [];
158
+ if (!existsSync(config)) return void 0;
156
159
  const parsed = ts.getParsedCommandLineOfConfigFile(config, {}, {
157
160
  ...ts.sys,
158
161
  onUnRecoverableConfigFileDiagnostic: () => void 0
159
162
  });
160
- if (!parsed) return [];
163
+ if (!parsed) return void 0;
161
164
  const program = ts.createProgram(parsed.fileNames, parsed.options);
162
165
  const checker = program.getTypeChecker();
163
- return program.getSourceFiles().flatMap((source) => {
164
- const path = relative(root, source.fileName).replaceAll("\\", "/");
165
- if (source.isDeclarationFile || !appCode.test(path) || testFile.test(path)) return [];
166
- return exitsIn(checker, source, path);
167
- });
166
+ return {
167
+ checker,
168
+ operations: program.getSourceFiles().flatMap((source) => {
169
+ const path = relative(root, source.fileName).replaceAll("\\", "/");
170
+ if (source.isDeclarationFile || !appCode.test(path) || testFile.test(path)) return [];
171
+ return operationsIn(checker, source, path);
172
+ })
173
+ };
168
174
  }
169
175
  /** Where a page test leaves its store's text: one `.json` file a test file, under the app. */
170
176
  const pageExits = ".tinker/exits";
@@ -187,10 +193,10 @@ const said = {
187
193
  refused: "refuses",
188
194
  [plain]: "returns"
189
195
  };
190
- /** A finding for each declared exit that no test reached. */
191
- function unreached(root, file) {
196
+ /** A finding for each exit in `declared` that no test reached. */
197
+ function unreached(root, file, declared) {
192
198
  const reached = reachedIn(root, file);
193
- return declaredExits(root).filter(({ label, exit }) => !reached.has(`${label}\t${exit}`)).map(({ path, line, label, exit }) => ({
199
+ return declared.filter(({ label, exit }) => !reached.has(`${label}\t${exit}`)).map(({ path, line, label, exit }) => ({
194
200
  path,
195
201
  line,
196
202
  rule: "tinker/exit",
@@ -294,6 +300,94 @@ function applyGaps(findings, sources, doc) {
294
300
  };
295
301
  }
296
302
  //#endregion
303
+ //#region src/link.ts
304
+ /** A scheme, as in `https:`, `mailto:` or `tel:`: the link leaves the app. */
305
+ const scheme = /^[a-z][\w+.-]*:/i;
306
+ /**
307
+ * A path that ends in a file name, as `/llms.txt` or `/sea.html?room=1`: the server sends a file,
308
+ * and no route of the router answers it. A route with a dot, as `/v1.2`, passes too: the price of
309
+ * a rule that reads no route list.
310
+ */
311
+ const file = /^[^?#]*\.\w+(?:[?#]|$)/;
312
+ /**
313
+ * The text of a value written out: a string, in braces or not, or a template literal with `…` for
314
+ * each substitution. A template that starts with a substitution cannot be read: no text.
315
+ */
316
+ function textOf$1(value) {
317
+ const written = value && ts.isJsxExpression(value) ? value.expression : value;
318
+ if (!written) return;
319
+ if (ts.isStringLiteral(written) || ts.isNoSubstitutionTemplateLiteral(written)) return written.text;
320
+ if (!ts.isTemplateExpression(written) || !written.head.text) return;
321
+ return written.head.text + written.templateSpans.map(({ literal }) => `…${literal.text}`).join("");
322
+ }
323
+ /**
324
+ * A page inside the app: `/issues`, `./next`, `?page=2`. Not `//host`, `#top`, a scheme, or a
325
+ * file. An empty `href` cannot be read, so it is no finding.
326
+ */
327
+ function isPage(href) {
328
+ if (href === "" || href.startsWith("//") || href.startsWith("#")) return false;
329
+ return !scheme.test(href) && !file.test(href);
330
+ }
331
+ /**
332
+ * An attribute the `<a>` has whose text passes `says`, or whose text the rule cannot read. A
333
+ * target or rel that is partly read (a template with a gap) counts as read.
334
+ */
335
+ function saysOrUnread(attributes, name, says) {
336
+ if (!attributes.has(name)) return false;
337
+ const text = textOf$1(attributes.get(name));
338
+ return text === void 0 || says(text);
339
+ }
340
+ /**
341
+ * `download`, `target="_blank"` or `rel="external"`: the link means to leave the page. A
342
+ * `target` or `rel` the rule cannot read passes, as an `href` it cannot read does.
343
+ */
344
+ function leaves(attributes) {
345
+ return attributes.has("download") || saysOrUnread(attributes, "target", (target) => target === "_blank") || saysOrUnread(attributes, "rel", (rel) => rel.split(/\s+/).includes("external"));
346
+ }
347
+ /**
348
+ * The attributes of one `<a>`, or none when it has a spread: the spread may hold a `target` or
349
+ * `rel` the rule cannot read.
350
+ */
351
+ function attributesOf(link) {
352
+ const attributes = /* @__PURE__ */ new Map();
353
+ for (const attribute of link.attributes.properties) {
354
+ if (!ts.isJsxAttribute(attribute)) return;
355
+ attributes.set(attribute.name.getText(), attribute.initializer);
356
+ }
357
+ return attributes;
358
+ }
359
+ /** The `href` of an `<a>` that is a finding: written out, a page inside the app, and it stays. */
360
+ function inAppHref(node) {
361
+ if (!ts.isJsxOpeningElement(node) && !ts.isJsxSelfClosingElement(node)) return;
362
+ if (node.tagName.getText() !== "a") return;
363
+ const attributes = attributesOf(node);
364
+ if (!attributes) return;
365
+ const href = textOf$1(attributes.get("href"));
366
+ return href !== void 0 && isPage(href) && !leaves(attributes) ? href : void 0;
367
+ }
368
+ /**
369
+ * `tinker/link`: a plain `<a href>` to a path inside the app does a full page load, so app state
370
+ * is lost (CUJ eval run 5: 3 of 10 writers). The router's `Link` moves without one. It borrows
371
+ * the scope of Next.js `no-html-link-for-pages`: only a link to a page of the app, so a link to a
372
+ * file passes. What the rule cannot read is no finding: the rule does not guess.
373
+ */
374
+ function findLink({ path, text }) {
375
+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
376
+ const findings = [];
377
+ const visit = (node) => {
378
+ const href = inAppHref(node);
379
+ if (href !== void 0) findings.push({
380
+ path,
381
+ line: source.getLineAndCharacterOfPosition(node.getStart()).line + 1,
382
+ rule: "tinker/link",
383
+ what: `\`${href}\`: a plain <a href> to an in-app path reloads the page`
384
+ });
385
+ ts.forEachChild(node, visit);
386
+ };
387
+ visit(source);
388
+ return findings;
389
+ }
390
+ //#endregion
297
391
  //#region src/page.ts
298
392
  /** The banned hooks, by the name of the hook React exports. */
299
393
  const hooks = /* @__PURE__ */ new Set([
@@ -1317,6 +1411,7 @@ function readApp(root) {
1317
1411
  const found = [
1318
1412
  ...findPlain(app, config.plain?.entries ?? {}),
1319
1413
  ...page.flatMap(findPage),
1414
+ ...page.filter(({ path }) => path.endsWith("x")).flatMap(findLink),
1320
1415
  ...app.filter(({ path }) => appCode.test(path)).flatMap(findBarrel)
1321
1416
  ];
1322
1417
  return {
@@ -1346,6 +1441,394 @@ function check(root) {
1346
1441
  };
1347
1442
  }
1348
1443
  //#endregion
1444
+ //#region src/graph.ts
1445
+ /** The app's committed graph, at its root (ADR 0161). */
1446
+ const graphFile = "tinker.graph";
1447
+ const writeKinds = [
1448
+ "set",
1449
+ "update",
1450
+ "delete"
1451
+ ];
1452
+ const readKinds = [
1453
+ "get",
1454
+ "of",
1455
+ "where"
1456
+ ];
1457
+ /** A dep that reads one part of a keyed cell: `issues.where({ teamId })`. */
1458
+ const partKinds = ["of", "where"];
1459
+ /** The call kinds that run an operation a dep names. */
1460
+ const runKinds = ["run", "settle"];
1461
+ /** The `const` a name stands for, through an import. */
1462
+ function declarationOf(checker, symbol) {
1463
+ if (!symbol) return void 0;
1464
+ const declaration = (symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol).valueDeclaration;
1465
+ return declaration && ts.isVariableDeclaration(declaration) ? declaration : void 0;
1466
+ }
1467
+ /** The Core function a call names, by Core's own name for it: `data`, `operation`. */
1468
+ function coreName({ expression }) {
1469
+ const local = expression.getText();
1470
+ const item = coreImports(expression.getSourceFile()).find(({ name }) => name.text === local);
1471
+ return item && (item.propertyName ?? item.name).text;
1472
+ }
1473
+ /** The unit a name holds, when it is a `const` made by a Core call with a literal label. */
1474
+ function unitAt(checker, symbol) {
1475
+ const call = declarationOf(checker, symbol)?.initializer;
1476
+ if (!call || !ts.isCallExpression(call)) return void 0;
1477
+ const [options] = call.arguments;
1478
+ const label = options && ts.isObjectLiteralExpression(options) ? labelOf(options) : void 0;
1479
+ const made = coreName(call);
1480
+ return label && made ? {
1481
+ made,
1482
+ label,
1483
+ call
1484
+ } : void 0;
1485
+ }
1486
+ /** What a tag holds: the `T` of the `Tag.Handle<T>` its call makes, which `def` carries. */
1487
+ function heldOf(checker, call) {
1488
+ const def = checker.getTypeAtLocation(call).getProperty("def");
1489
+ return def && checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(def, call));
1490
+ }
1491
+ /** The unit a dep reads a part of: `issues.where({ teamId })`. */
1492
+ function partOf(checker, value) {
1493
+ if (!ts.isPropertyAccessExpression(value.expression)) return void 0;
1494
+ const read = value.expression.name.text;
1495
+ const unit = unitAt(checker, checker.getSymbolAtLocation(value.expression.expression));
1496
+ return unit && partKinds.includes(read) ? {
1497
+ ...unit,
1498
+ read
1499
+ } : void 0;
1500
+ }
1501
+ const bareOf = (unit) => unit && {
1502
+ ...unit,
1503
+ bare: true
1504
+ };
1505
+ /**
1506
+ * The unit a dep's value names: an operation, an edge of a unit (a cell's `controller`, a tag's
1507
+ * `required`), or a part of a cell. `record` keeps only the calls each kind of unit has.
1508
+ */
1509
+ function unitOf(checker, value) {
1510
+ if (ts.isIdentifier(value)) return bareOf(unitAt(checker, checker.getSymbolAtLocation(value)));
1511
+ if (ts.isCallExpression(value)) return partOf(checker, value);
1512
+ if (!ts.isPropertyAccessExpression(value)) return void 0;
1513
+ return unitAt(checker, checker.getSymbolAtLocation(value.expression));
1514
+ }
1515
+ /** The unit a dep's declaration names: `list: issues.controller`, or `{ inTeam }`. */
1516
+ function depUnit(checker, declaration) {
1517
+ if (declaration && ts.isShorthandPropertyAssignment(declaration)) return bareOf(unitAt(checker, checker.getShorthandAssignmentValueSymbol(declaration)));
1518
+ return declaration && ts.isPropertyAssignment(declaration) ? unitOf(checker, declaration.initializer) : void 0;
1519
+ }
1520
+ const allSets = [
1521
+ "reads",
1522
+ "writes",
1523
+ "calls"
1524
+ ];
1525
+ /** The mark of a fact the graph could not see: never a guess at the fact. */
1526
+ const unseen = "?";
1527
+ /** What each call the graph knows on an operation or a cell adds. */
1528
+ function touchesOf({ made, label, read }) {
1529
+ const touches = /* @__PURE__ */ new Map();
1530
+ const add = (kinds, set, fact) => {
1531
+ for (const kind of kinds) touches.set(kind, {
1532
+ set,
1533
+ fact: fact(kind)
1534
+ });
1535
+ };
1536
+ if (made === "operation") add(runKinds, "calls", () => label);
1537
+ else if (read) add(["get"], "reads", () => `${label}.${read}`);
1538
+ else {
1539
+ add(readKinds, "reads", (kind) => `${label}.${kind}`);
1540
+ add(writeKinds, "writes", (kind) => `${label}.${kind}`);
1541
+ }
1542
+ return touches;
1543
+ }
1544
+ /**
1545
+ * The sets a dep the graph cannot name may hide facts in, by its type in `run`: `settle` runs an
1546
+ * operation, `set` writes a cell, `get` reads one.
1547
+ */
1548
+ function hidesOf(type) {
1549
+ if (type?.getProperty("settle")) return ["calls"];
1550
+ if (type?.getProperty("set")) return ["reads", "writes"];
1551
+ return type?.getProperty("get") ? ["reads"] : [];
1552
+ }
1553
+ /** The type a dep has in `run`: a controller, a reader, or a value. */
1554
+ function slotOf(checker, param, key) {
1555
+ const slot = param && checker.getTypeAtLocation(param).getProperty(key);
1556
+ return slot && checker.getTypeOfSymbolAtLocation(slot, slot.valueDeclaration ?? param);
1557
+ }
1558
+ /**
1559
+ * The sets a tag may hide facts in, by what it holds (ADR 0151), through any edge: a cell may be
1560
+ * read and written, an operation run, a view or a read read. A plain value or a resource holds
1561
+ * no fact the graph reads: a resource's own code is not read.
1562
+ */
1563
+ function heldHides(held) {
1564
+ if (held?.getProperty("mode")) return ["reads", "writes"];
1565
+ if (held?.getProperty("run")) return ["calls"];
1566
+ return held?.getProperty("kind") ? ["reads"] : [];
1567
+ }
1568
+ /** A dep whose unit the graph cannot name: it hides in `hides`. */
1569
+ const unnamed = (hides) => ({
1570
+ touches: /* @__PURE__ */ new Map(),
1571
+ hides,
1572
+ named: false
1573
+ });
1574
+ /** A dep on an operation or a cell: a bare cell gives `run` its value, read on each run. */
1575
+ function namedDep(unit) {
1576
+ if (unit.bare && unit.made === "data") return {
1577
+ touches: /* @__PURE__ */ new Map(),
1578
+ hides: [],
1579
+ named: true,
1580
+ value: `${unit.label}.get`
1581
+ };
1582
+ const touches = touchesOf(unit);
1583
+ const sets = [...touches.values()].map(({ set }) => set);
1584
+ return {
1585
+ touches,
1586
+ hides: allSets.filter((set) => sets.includes(set)),
1587
+ named: true
1588
+ };
1589
+ }
1590
+ /**
1591
+ * A dep, from the declaration that names its unit. A tag hides by what it holds, through any
1592
+ * edge. Any other dep but an operation or a cell is read by its type in `run`: a dep the graph
1593
+ * cannot name may be anything.
1594
+ */
1595
+ function depOf(checker, key, param) {
1596
+ const unit = depUnit(checker, key.valueDeclaration);
1597
+ if (unit?.made === "tag") return unnamed(heldHides(heldOf(checker, unit.call)));
1598
+ return unit?.made === "operation" || unit?.made === "data" ? namedDep(unit) : unnamed(hidesOf(slotOf(checker, param, key.name)));
1599
+ }
1600
+ /**
1601
+ * Each dep of an operation by its key, from the type of its `depends`. A dep written in place,
1602
+ * in a `const`, or spread from one is a property of that type, and its declaration names its
1603
+ * unit. `param` is `run`'s first parameter: its type says what each dep is.
1604
+ */
1605
+ function depsOf(checker, options, param) {
1606
+ const depends = checker.getTypeAtLocation(options).getProperty("depends");
1607
+ const keys = depends ? checker.getTypeOfSymbolAtLocation(depends, options).getProperties() : [];
1608
+ const deps = /* @__PURE__ */ new Map();
1609
+ for (const key of keys) deps.set(key.name, depOf(checker, key, param));
1610
+ return deps;
1611
+ }
1612
+ /** A binding's key as text: a name or a string. Any other key the graph cannot read. */
1613
+ function keyText(key) {
1614
+ return ts.isIdentifier(key) || ts.isStringLiteral(key) ? key.text : void 0;
1615
+ }
1616
+ /** `name` is the value a `const { … } = name` takes apart. */
1617
+ function destructured(name) {
1618
+ const { parent } = name;
1619
+ return ts.isVariableDeclaration(parent) && parent.initializer === name;
1620
+ }
1621
+ /** Call `see` on every name in the node's code, a callback's body too. */
1622
+ function eachName(node, see) {
1623
+ const visit = (child) => {
1624
+ if (ts.isIdentifier(child)) see(child);
1625
+ ts.forEachChild(child, visit);
1626
+ };
1627
+ visit(node);
1628
+ }
1629
+ /** The method a call names on `node`: `list.set(…)` gives `set`. */
1630
+ function calledOn(node) {
1631
+ const { parent } = node;
1632
+ if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node) return void 0;
1633
+ return ts.isCallExpression(parent.parent) && parent.parent.expression === parent ? parent.name.text : void 0;
1634
+ }
1635
+ /**
1636
+ * Reads the code of one `run`: every use of its deps, through the checker's symbols. A dep is
1637
+ * bound by the first parameter, or by `const { a, b: c } = deps` in the body. A use the graph
1638
+ * cannot follow (passed on, assigned, spread, a method it does not know) adds `?` to each set
1639
+ * the dep may hide facts in.
1640
+ */
1641
+ var Reader = class {
1642
+ facts = {
1643
+ reads: /* @__PURE__ */ new Set(),
1644
+ writes: /* @__PURE__ */ new Set(),
1645
+ calls: /* @__PURE__ */ new Set()
1646
+ };
1647
+ checker;
1648
+ deps;
1649
+ bound = /* @__PURE__ */ new Map();
1650
+ whole;
1651
+ constructor(checker, deps, param) {
1652
+ this.checker = checker;
1653
+ this.deps = deps;
1654
+ for (const { value } of deps.values()) if (value) this.facts.reads.add(value);
1655
+ if (param && ts.isIdentifier(param.name)) this.whole = checker.getSymbolAtLocation(param.name);
1656
+ else if (param) this.bind(param.name);
1657
+ }
1658
+ /** Every dep could hide facts: `run` handed them all on. */
1659
+ hideAll() {
1660
+ for (const dep of this.deps.values()) this.hide(dep);
1661
+ }
1662
+ /**
1663
+ * A `run` passed by name: no code to read. A dep the graph names hides by its unit; one it
1664
+ * cannot name may hide anything, so every set gets `?`.
1665
+ */
1666
+ hideRun() {
1667
+ this.hideAll();
1668
+ if (![...this.deps.values()].every(({ named }) => named)) for (const set of allSets) this.facts[set].add(unseen);
1669
+ return this.facts;
1670
+ }
1671
+ hide({ hides }) {
1672
+ for (const set of hides) this.facts[set].add(unseen);
1673
+ }
1674
+ /** Bind each name a destructure of the deps gives. */
1675
+ bind(name) {
1676
+ if (!ts.isObjectBindingPattern(name)) return this.hideAll();
1677
+ for (const element of name.elements) this.bindElement(element);
1678
+ }
1679
+ /**
1680
+ * A rest takes every dep, and the graph cannot read a computed key: both hide every dep. A
1681
+ * nested pattern takes its dep apart.
1682
+ */
1683
+ bindElement({ dotDotDotToken, propertyName, name }) {
1684
+ const key = keyText(propertyName ?? name);
1685
+ if (dotDotDotToken || key === void 0) return this.hideAll();
1686
+ const dep = this.deps.get(key);
1687
+ if (!dep) return;
1688
+ const symbol = ts.isIdentifier(name) ? this.checker.getSymbolAtLocation(name) : void 0;
1689
+ if (symbol) this.bound.set(symbol, dep);
1690
+ else this.hide(dep);
1691
+ }
1692
+ useDep(node, dep) {
1693
+ if (!dep) return;
1694
+ const kind = calledOn(node);
1695
+ const touch = kind === void 0 ? void 0 : dep.touches.get(kind);
1696
+ if (touch) this.facts[touch.set].add(touch.fact);
1697
+ else this.hide(dep);
1698
+ }
1699
+ /** A use of the deps param: a member, a destructure (bound first), or a hand-off. */
1700
+ useWhole(name) {
1701
+ const { parent } = name;
1702
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === name) return this.useDep(parent, this.deps.get(parent.name.text));
1703
+ if (!destructured(name)) this.hideAll();
1704
+ }
1705
+ isWhole(name) {
1706
+ const symbol = this.checker.getSymbolAtLocation(name);
1707
+ return symbol !== void 0 && symbol === this.whole;
1708
+ }
1709
+ use(name) {
1710
+ const { parent } = name;
1711
+ if (ts.isBindingElement(parent)) return;
1712
+ const symbol = ts.isShorthandPropertyAssignment(parent) ? this.checker.getShorthandAssignmentValueSymbol(parent) : this.checker.getSymbolAtLocation(name);
1713
+ if (!symbol) return;
1714
+ if (symbol === this.whole) return this.useWhole(name);
1715
+ this.useDep(name, this.bound.get(symbol));
1716
+ }
1717
+ /**
1718
+ * Every use in the node's code, a callback's body too. Each destructure of the deps binds
1719
+ * first, so a use the code reads before it (in a callback) still counts.
1720
+ */
1721
+ read(node) {
1722
+ eachName(node, (name) => {
1723
+ if (destructured(name) && this.isWhole(name)) this.bind(name.parent.name);
1724
+ });
1725
+ eachName(node, (name) => this.use(name));
1726
+ return this.facts;
1727
+ }
1728
+ };
1729
+ /** The function an operation's `run` is, when it is written in place. */
1730
+ function functionOf(run) {
1731
+ if (ts.isMethodDeclaration(run)) return run;
1732
+ if (!ts.isPropertyAssignment(run)) return void 0;
1733
+ const value = run.initializer;
1734
+ return ts.isArrowFunction(value) || ts.isFunctionExpression(value) ? value : void 0;
1735
+ }
1736
+ /** What one operation's `run` touches. A `run` written elsewhere may touch any of its deps. */
1737
+ function factsOf(checker, { options, run }) {
1738
+ const fn = functionOf(run);
1739
+ const [param] = fn?.parameters ?? [];
1740
+ const reader = new Reader(checker, depsOf(checker, options, param), param);
1741
+ return fn?.body ? reader.read(fn.body) : reader.hideRun();
1742
+ }
1743
+ const listed = (name, items) => `${name}{${[...items].sort().join(",")}}`;
1744
+ /**
1745
+ * The app's graph, from its code: one line per operation, sorted by label in code-unit order,
1746
+ * the same on every machine. `exits` are the words of ADR 0159.
1747
+ */
1748
+ function graphOf(root) {
1749
+ const app = readOperations(root);
1750
+ if (!app) return [];
1751
+ return app.operations.map((operation) => {
1752
+ const { reads, writes, calls } = factsOf(app.checker, operation);
1753
+ const { path, line, label, exits } = operation;
1754
+ return {
1755
+ path,
1756
+ line,
1757
+ label,
1758
+ exits,
1759
+ parts: [
1760
+ listed("exits", exits),
1761
+ listed("reads", reads),
1762
+ listed("writes", writes),
1763
+ listed("calls", calls)
1764
+ ]
1765
+ };
1766
+ }).sort((a, b) => a.label < b.label ? -1 : 1);
1767
+ }
1768
+ /** The graph as `tinker.graph` holds it: one line per operation, and an end of line after each. */
1769
+ function graphText(lines) {
1770
+ return lines.map(({ label, parts }) => `${[label, ...parts].join(" ")}\n`).join("");
1771
+ }
1772
+ /**
1773
+ * Each line of the committed file by its label, and its line number. A line may end in `\r`: a
1774
+ * checkout on Windows can give the file those ends.
1775
+ */
1776
+ function linesIn(text) {
1777
+ const lines = /* @__PURE__ */ new Map();
1778
+ text.split("\n").forEach((row, index) => {
1779
+ const [label, ...parts] = row.trim().split(" ");
1780
+ if (label) lines.set(label, {
1781
+ line: index + 1,
1782
+ parts
1783
+ });
1784
+ });
1785
+ return lines;
1786
+ }
1787
+ /** What a code line says that the file's line does not: each part that differs. */
1788
+ function changed(code, file) {
1789
+ return code.flatMap((part, index) => {
1790
+ const said = file[index] ?? "nothing";
1791
+ return part === said ? [] : [`${part}, ${graphFile} says ${said}`];
1792
+ });
1793
+ }
1794
+ /**
1795
+ * A `tinker/graph` finding for each line where `code`, the graph `graphOf` read, and
1796
+ * `tinker.graph` differ (ADR 0161). A code line points at its operation; a line only the file
1797
+ * has points at the file. An app with no operation needs no file.
1798
+ */
1799
+ function graphFindings(root, code) {
1800
+ const path = join(root, graphFile);
1801
+ const rule = "tinker/graph";
1802
+ if (!existsSync(path)) {
1803
+ const what = `there is no ${graphFile}: run \`tinker graph --write\` and commit it`;
1804
+ return code.length ? [{
1805
+ path: graphFile,
1806
+ line: 1,
1807
+ rule,
1808
+ what
1809
+ }] : [];
1810
+ }
1811
+ const file = linesIn(readFileSync(path, "utf8"));
1812
+ const found = code.flatMap(({ path, line, label, parts }) => {
1813
+ const said = file.get(label);
1814
+ file.delete(label);
1815
+ const diff = said ? changed(parts, said.parts) : [`not in ${graphFile}`];
1816
+ return diff.length ? [{
1817
+ path,
1818
+ line,
1819
+ rule,
1820
+ what: `${label}: ${diff.join("; ")}`
1821
+ }] : [];
1822
+ });
1823
+ const gone = [...file].map(([label, { line }]) => ({
1824
+ path: graphFile,
1825
+ line,
1826
+ rule,
1827
+ what: `${label}: in ${graphFile}, not in the code`
1828
+ }));
1829
+ return [...found, ...gone];
1830
+ }
1831
+ //#endregion
1349
1832
  //#region src/rules.ts
1350
1833
  /** Tinker's own rules: `check` finds them in the app's files. */
1351
1834
  const own = [
@@ -1353,7 +1836,8 @@ const own = [
1353
1836
  "tinker/one-wire",
1354
1837
  "tinker/react-state",
1355
1838
  "tinker/gap",
1356
- "tinker/barrel"
1839
+ "tinker/barrel",
1840
+ "tinker/link"
1357
1841
  ];
1358
1842
  /** A lint rule that is a gate, by its lint code: its Tinker rule id. It belongs to `types`. */
1359
1843
  const gates = {
@@ -1376,7 +1860,8 @@ const rules = [.../* @__PURE__ */ new Set([
1376
1860
  ...own,
1377
1861
  ...Object.values(gates),
1378
1862
  ...Object.values(taught),
1379
- "tinker/exit"
1863
+ "tinker/exit",
1864
+ "tinker/graph"
1380
1865
  ])];
1381
1866
  //#endregion
1382
1867
  //#region src/skills.ts
@@ -1769,7 +2254,7 @@ function runTools(root, sources) {
1769
2254
  * read. A page test leaves its exits in `pageExits`, which is emptied first, so an old run says
1770
2255
  * nothing. A red run names no exit: its tests are the finding.
1771
2256
  */
1772
- function runTests(root, command) {
2257
+ function runTests(root, command, declared) {
1773
2258
  const folder = mkdtempSync(join(tmpdir(), "tinker-exits-"));
1774
2259
  const file = join(folder, "exits.tsv");
1775
2260
  const env = {
@@ -1788,7 +2273,7 @@ function runTests(root, command) {
1788
2273
  maxBuffer: 1 << 28
1789
2274
  });
1790
2275
  const output = `${done.error ? `${done.error.message}\n` : ""}${done.stdout ?? ""}${done.stderr ?? ""}`;
1791
- const missed = done.status === 0 ? unreached(root, file) : [];
2276
+ const missed = done.status === 0 ? unreached(root, file, declared) : [];
1792
2277
  rmSync(folder, {
1793
2278
  recursive: true,
1794
2279
  force: true
@@ -1808,13 +2293,19 @@ function tail(output) {
1808
2293
  }
1809
2294
  const usage = `usage:
1810
2295
  tinker check [root] [--json]
2296
+ tinker graph [root] [--write]
1811
2297
  tinker skill list
1812
2298
  tinker skill load <skill>
1813
2299
 
1814
2300
  check runs the app's types (tsc, the kind gate, the cast gate), then its rules (Tinker's
1815
- rules and the app's other lint), then its tests when tinker.json names their command: each
1816
- exit an operation declares must be reached by a test. Only the first stage that fails prints. Each finding
1817
- prints its fix. "tinker check: OK" and exit 0 is the only sign that the work is done.
2301
+ rules and the app's other lint), then its graph (the code's graph must match tinker.graph),
2302
+ then its tests when tinker.json names their command: each exit an operation declares must be
2303
+ reached by a test. Only the first stage that fails prints. Each finding prints its fix.
2304
+ "tinker check: OK" and exit 0 is the only sign that the work is done.
2305
+
2306
+ graph prints the app's graph: one line per operation, with its exits and what its run reads,
2307
+ writes and calls. The lines are facts; the reader judges them. --write writes them to
2308
+ tinker.graph, for the app to commit.
1818
2309
  `;
1819
2310
  /** One line per gaps row: marked lines over the row's count, as `G3 5/5`. */
1820
2311
  function gapLine(gaps) {
@@ -1853,7 +2344,8 @@ function failed(root, stage, found, gaps) {
1853
2344
  * Report the stages in order: the rules stage prints only when the types stage is clean. Tinker's
1854
2345
  * own rules read the config, so they run first: a bad config stops the run before the tools.
1855
2346
  * The gap rule allows a marked Tinker finding of either stage, never a `tsc` or other lint
1856
- * error; its own findings are rules.
2347
+ * error; its own findings are rules. The graph stage runs no app code, so it comes before the
2348
+ * tests (ADR 0161); no gap allows a graph finding.
1857
2349
  */
1858
2350
  function stages(root) {
1859
2351
  const { sources, found, doc, tests } = readApp(root);
@@ -1875,11 +2367,26 @@ function stages(root) {
1875
2367
  if (types.length) return failed(root, "types", types, []);
1876
2368
  const broken = findings.filter((item) => !typed.has(item));
1877
2369
  if (broken.length) return failed(root, "rules", broken, gaps);
1878
- const ran = [...tools.ran, `rules (${sources.length} files)`];
1879
- if (tools.skipped.length) return {
2370
+ return afterRules(root, {
2371
+ ran: [...tools.ran, `rules (${sources.length} files)`],
2372
+ skipped: tools.skipped,
2373
+ gaps,
2374
+ ...tests ? { tests } : {}
2375
+ });
2376
+ }
2377
+ /**
2378
+ * The stages after clean rules: the graph, then the tests and their exits. `ran` names the
2379
+ * graph only when the app has an operation: an app with none needs no `tinker.graph`.
2380
+ */
2381
+ function afterRules(root, { ran, skipped, gaps, tests }) {
2382
+ const graph = graphOf(root);
2383
+ const changed = graphFindings(root, graph);
2384
+ if (changed.length) return failed(root, "graph", changed, gaps);
2385
+ if (graph.length) ran.push(`graph (${graph.length} operations)`);
2386
+ if (skipped.length) return {
1880
2387
  kind: "incomplete",
1881
2388
  ran,
1882
- skipped: tools.skipped,
2389
+ skipped,
1883
2390
  gaps
1884
2391
  };
1885
2392
  if (!tests) return {
@@ -1887,7 +2394,12 @@ function stages(root) {
1887
2394
  ran,
1888
2395
  gaps
1889
2396
  };
1890
- const tested = runTests(root, tests);
2397
+ const tested = runTests(root, tests, graph.flatMap(({ path, line, label, exits }) => exits.map((exit) => ({
2398
+ path,
2399
+ line,
2400
+ label,
2401
+ exit
2402
+ }))));
1891
2403
  if (tested.status !== 0) return {
1892
2404
  kind: "red",
1893
2405
  output: tail(tested.output),
@@ -1994,6 +2506,27 @@ function checkCommand(root, json) {
1994
2506
  };
1995
2507
  }
1996
2508
  }
2509
+ /** Print the app's graph, or write it to `tinker.graph` with `--write`. */
2510
+ function graphCommand(root, write) {
2511
+ if (!existsSync(root)) return {
2512
+ code: 2,
2513
+ out: "",
2514
+ err: `tinker graph: no folder at ${root}\n`
2515
+ };
2516
+ const lines = graphOf(root);
2517
+ const text = graphText(lines);
2518
+ if (!write) return {
2519
+ code: 0,
2520
+ out: text,
2521
+ err: ""
2522
+ };
2523
+ writeFileSync(join(root, graphFile), text);
2524
+ return {
2525
+ code: 0,
2526
+ out: `wrote ${graphFile}: ${lines.length} operations\n`,
2527
+ err: ""
2528
+ };
2529
+ }
1997
2530
  function skillCommand(root, args) {
1998
2531
  const [action, use, ...rest] = args;
1999
2532
  try {
@@ -2021,27 +2554,34 @@ function skillCommand(root, args) {
2021
2554
  err: usage
2022
2555
  };
2023
2556
  }
2557
+ /** The one flag each command takes: `--json` prints data, `--write` writes the file. */
2558
+ function flagOf(command) {
2559
+ if (command === "check") return "--json";
2560
+ return command === "graph" ? "--write" : void 0;
2561
+ }
2024
2562
  /**
2025
2563
  * The command, without the process: `argv` is what follows the program name, and `cwd` is
2026
2564
  * the folder a relative root starts from. Exit 0 is done, 1 is a finding, 2 is a call, a
2027
2565
  * config or a tool the command cannot use.
2028
2566
  */
2029
2567
  function main(argv, cwd) {
2030
- const json = argv.includes("--json");
2031
- const [command, ...args] = argv.filter((arg) => arg !== "--json");
2032
- if (args.some((arg) => arg.startsWith("-"))) return {
2568
+ const [command = "", ...args] = argv.filter((arg) => !arg.startsWith("-"));
2569
+ const flag = flagOf(command);
2570
+ const on = argv.some((arg) => arg === flag);
2571
+ if (argv.some((arg) => arg.startsWith("-") && arg !== flag)) return {
2033
2572
  code: 2,
2034
2573
  out: "",
2035
2574
  err: usage
2036
2575
  };
2037
- if (command === "skill" && !json) return skillCommand(cwd, args);
2576
+ if (command === "skill") return skillCommand(cwd, args);
2038
2577
  const [root = ".", ...rest] = args;
2039
- if (command !== "check" || rest.length) return {
2578
+ if (!flag || rest.length) return {
2040
2579
  code: 2,
2041
2580
  out: "",
2042
2581
  err: usage
2043
2582
  };
2044
- return checkCommand(resolve(cwd, root), json);
2583
+ const at = resolve(cwd, root);
2584
+ return command === "graph" ? graphCommand(at, on) : checkCommand(at, on);
2045
2585
  }
2046
2586
  //#endregion
2047
2587
  export { check as n, isError as r, main as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkered/cli",
3
- "version": "0.30.1",
3
+ "version": "0.31.1",
4
4
  "description": "The tinker command: one check that corrects the writer (types, then rules, each finding with its fix from the skill), and the skills.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,14 +37,14 @@
37
37
  "devDependencies": {
38
38
  "@stryker-mutator/core": "^10.0.0",
39
39
  "@stryker-mutator/vitest-runner": "^10.0.0",
40
- "@tinkered/core": "^0.30.1",
40
+ "@tinkered/core": "^0.31.1",
41
41
  "@types/node": "^26.1.1",
42
42
  "vite-plus": "1.0.0",
43
43
  "vitest": "5.0.1",
44
44
  "zod": "^4.0.0"
45
45
  },
46
46
  "peerDependencies": {
47
- "@tinkered/core": "^0.30.1",
47
+ "@tinkered/core": "^0.31.1",
48
48
  "vite-plus": "^1.0.0"
49
49
  },
50
50
  "peerDependenciesMeta": {