@orthograph/cli 0.0.0-stage → 0.1.0-next.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.
Files changed (109) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +28 -2
  3. package/dist/main.d.ts +2 -0
  4. package/dist/main.js +318 -0
  5. package/dist/modules/add/internal/journeys.d.ts +3 -0
  6. package/dist/modules/add/internal/journeys.js +13 -0
  7. package/dist/modules/add/internal/names.d.ts +8 -0
  8. package/dist/modules/add/internal/names.js +9 -0
  9. package/dist/modules/add/internal/templates.d.ts +16 -0
  10. package/dist/modules/add/internal/templates.js +104 -0
  11. package/dist/modules/add/service.d.ts +2 -0
  12. package/dist/modules/add/service.js +27 -0
  13. package/dist/modules/add/types.d.ts +30 -0
  14. package/dist/modules/add/types.js +6 -0
  15. package/dist/modules/brief/service.d.ts +2 -0
  16. package/dist/modules/brief/service.js +48 -0
  17. package/dist/modules/brief/types.d.ts +16 -0
  18. package/dist/modules/brief/types.js +1 -0
  19. package/dist/modules/check/internal/blanks.d.ts +3 -0
  20. package/dist/modules/check/internal/blanks.js +11 -0
  21. package/dist/modules/check/internal/changes.d.ts +8 -0
  22. package/dist/modules/check/internal/changes.js +16 -0
  23. package/dist/modules/check/internal/drift.d.ts +4 -0
  24. package/dist/modules/check/internal/drift.js +25 -0
  25. package/dist/modules/check/internal/files.d.ts +8 -0
  26. package/dist/modules/check/internal/files.js +18 -0
  27. package/dist/modules/check/internal/ratchets.d.ts +7 -0
  28. package/dist/modules/check/internal/ratchets.js +17 -0
  29. package/dist/modules/check/internal/tools.d.ts +12 -0
  30. package/dist/modules/check/internal/tools.js +66 -0
  31. package/dist/modules/check/service.d.ts +2 -0
  32. package/dist/modules/check/service.js +37 -0
  33. package/dist/modules/check/types.d.ts +32 -0
  34. package/dist/modules/check/types.js +1 -0
  35. package/dist/modules/generate/service.d.ts +2 -0
  36. package/dist/modules/generate/service.js +18 -0
  37. package/dist/modules/generate/types.d.ts +13 -0
  38. package/dist/modules/generate/types.js +1 -0
  39. package/dist/modules/handoff/internal/find.d.ts +6 -0
  40. package/dist/modules/handoff/internal/find.js +29 -0
  41. package/dist/modules/handoff/service.d.ts +2 -0
  42. package/dist/modules/handoff/service.js +16 -0
  43. package/dist/modules/handoff/types.d.ts +17 -0
  44. package/dist/modules/handoff/types.js +2 -0
  45. package/dist/modules/model/internal/summary.d.ts +3 -0
  46. package/dist/modules/model/internal/summary.js +6 -0
  47. package/dist/modules/model/service.d.ts +2 -0
  48. package/dist/modules/model/service.js +9 -0
  49. package/dist/modules/model/types.d.ts +14 -0
  50. package/dist/modules/model/types.js +1 -0
  51. package/dist/modules/mounting/internal/age.d.ts +9 -0
  52. package/dist/modules/mounting/internal/age.js +47 -0
  53. package/dist/modules/mounting/internal/needs.d.ts +2 -0
  54. package/dist/modules/mounting/internal/needs.js +26 -0
  55. package/dist/modules/mounting/internal/scaffold.d.ts +3 -0
  56. package/dist/modules/mounting/internal/scaffold.js +27 -0
  57. package/dist/modules/mounting/service.d.ts +7 -0
  58. package/dist/modules/mounting/service.js +71 -0
  59. package/dist/modules/mounting/types.d.ts +28 -0
  60. package/dist/modules/mounting/types.js +6 -0
  61. package/dist/modules/new/internal/read.d.ts +6 -0
  62. package/dist/modules/new/internal/read.js +15 -0
  63. package/dist/modules/new/service.d.ts +2 -0
  64. package/dist/modules/new/service.js +28 -0
  65. package/dist/modules/new/types.d.ts +22 -0
  66. package/dist/modules/new/types.js +5 -0
  67. package/dist/modules/secrets/internal/argv.d.ts +3 -0
  68. package/dist/modules/secrets/internal/argv.js +27 -0
  69. package/dist/modules/secrets/service.d.ts +2 -0
  70. package/dist/modules/secrets/service.js +26 -0
  71. package/dist/modules/secrets/types.d.ts +23 -0
  72. package/dist/modules/secrets/types.js +1 -0
  73. package/dist/modules/ship/service.d.ts +2 -0
  74. package/dist/modules/ship/service.js +36 -0
  75. package/dist/modules/ship/types.d.ts +35 -0
  76. package/dist/modules/ship/types.js +1 -0
  77. package/dist/modules/staging/internal/address.d.ts +21 -0
  78. package/dist/modules/staging/internal/address.js +28 -0
  79. package/dist/modules/staging/internal/alchemy-bin.d.ts +3 -0
  80. package/dist/modules/staging/internal/alchemy-bin.js +12 -0
  81. package/dist/modules/staging/internal/app.d.ts +3 -0
  82. package/dist/modules/staging/internal/app.js +23 -0
  83. package/dist/modules/staging/internal/cloudflare.d.ts +2 -0
  84. package/dist/modules/staging/internal/cloudflare.js +47 -0
  85. package/dist/modules/staging/internal/config.d.ts +26 -0
  86. package/dist/modules/staging/internal/config.js +39 -0
  87. package/dist/modules/staging/internal/deploy.d.ts +3 -0
  88. package/dist/modules/staging/internal/deploy.js +50 -0
  89. package/dist/modules/staging/internal/destroy.d.ts +10 -0
  90. package/dist/modules/staging/internal/destroy.js +29 -0
  91. package/dist/modules/staging/internal/live.d.ts +2 -0
  92. package/dist/modules/staging/internal/live.js +33 -0
  93. package/dist/modules/staging/internal/plan.d.ts +28 -0
  94. package/dist/modules/staging/internal/plan.js +56 -0
  95. package/dist/modules/staging/internal/stack.d.ts +15 -0
  96. package/dist/modules/staging/internal/stack.js +24 -0
  97. package/dist/modules/staging/service.d.ts +7 -0
  98. package/dist/modules/staging/service.js +52 -0
  99. package/dist/modules/staging/types.d.ts +110 -0
  100. package/dist/modules/staging/types.js +9 -0
  101. package/dist/modules/telemetry/service.d.ts +2 -0
  102. package/dist/modules/telemetry/service.js +27 -0
  103. package/dist/modules/telemetry/types.d.ts +19 -0
  104. package/dist/modules/telemetry/types.js +1 -0
  105. package/dist/modules/watch/service.d.ts +2 -0
  106. package/dist/modules/watch/service.js +17 -0
  107. package/dist/modules/watch/types.d.ts +23 -0
  108. package/dist/modules/watch/types.js +1 -0
  109. package/package.json +36 -3
@@ -0,0 +1,104 @@
1
+ // What `add` writes. Every gap is a `Blueprint.todo` saying what belongs there.
2
+ import { Names } from "orthograph/server";
3
+ import { article, pascal, prefixOf } from "./names.js";
4
+ const header = `import { Blueprint } from "${Names.frontDoor}";`;
5
+ export const thingFiles = (thing) => {
6
+ const T = pascal(thing);
7
+ return [
8
+ {
9
+ path: `blueprint/things/${thing}/thing.ts`,
10
+ content: `${header}
11
+
12
+ export const ${T} = Blueprint.thing({
13
+ description: Blueprint.todo("what ${article(thing)} is, in one sentence"),
14
+ fields: {
15
+ id: Blueprint.id("${prefixOf(thing)}"),
16
+ },
17
+ });
18
+ `,
19
+ },
20
+ {
21
+ path: `blueprint/things/${thing}/machine.ts`,
22
+ content: `${header}
23
+ import { ${T} } from "./thing.ts";
24
+
25
+ // The states ${article(thing)} can be in, and the moves between them. Each move names the event it emits (events.ts).
26
+ export const machine = Blueprint.machine(${T}, {
27
+ states: Blueprint.todo("the states ${article(thing)} can be in, the first one where it starts"),
28
+ moves: {},
29
+ notFrom: { exit: 40 }, // the exit code when a move can't start from the state it's in
30
+ });
31
+ `,
32
+ },
33
+ {
34
+ path: `blueprint/things/${thing}/roles.ts`,
35
+ content: `${header}
36
+ import { ${T} } from "./thing.ts";
37
+
38
+ // Who a person is to ${article(thing)}. Rename the role to what it means.
39
+ export const holder = Blueprint.role(${T}, { rule: Blueprint.todo("when a person holds this role on ${article(thing)}") });
40
+ `,
41
+ },
42
+ {
43
+ path: `blueprint/things/${thing}/events.ts`,
44
+ content: `// What happened to ${article(thing)}, one event per move: \`export const ${T}Made = Blueprint.event({ ... })\`.
45
+ export {};
46
+ `,
47
+ },
48
+ {
49
+ path: `blueprint/things/${thing}/errors.ts`,
50
+ content: `// Refusals that depend on data: \`export class ${T}Missing extends Blueprint.error({ ... }, { exit: 40 }) {}\`.
51
+ // The machine's own refusal is generated and never written here.
52
+ export {};
53
+ `,
54
+ },
55
+ {
56
+ path: `blueprint/things/${thing}/invariants.ts`,
57
+ content: `// What stays true among many instances, one rule per export: \`export const oneHolder = Blueprint.invariant.unique(${T}.fields.name)\`.
58
+ export {};
59
+ `,
60
+ },
61
+ {
62
+ path: `blueprint/values/${thing}.ts`,
63
+ content: `// The values ${article(thing)}'s fields are made of: \`export const Amount = Blueprint.value(Blueprint.uint(128))\`.
64
+ export {};
65
+ `,
66
+ },
67
+ ];
68
+ };
69
+ export const operationFile = (thing, verb) => ({
70
+ path: `blueprint/things/${thing}/verbs/${verb}.ts`,
71
+ content: `${header}
72
+ import { ${pascal(thing)} } from "../thing.ts";
73
+
74
+ export default Blueprint.operation(${pascal(thing)}, {
75
+ description: Blueprint.todo("what ${verb} does to ${article(thing)}, in one sentence"),
76
+ payload: Blueprint.todo("what a caller sends"),
77
+ answer: Blueprint.todo("what ${verb} answers"),
78
+ allowed: Blueprint.todo("who may ${verb}"),
79
+ });
80
+ `,
81
+ });
82
+ export const readFile = (thing, verb) => ({
83
+ path: `blueprint/things/${thing}/verbs/${verb}.ts`,
84
+ content: `${header}
85
+ import { ${pascal(thing)} } from "../thing.ts";
86
+
87
+ // A read changes nothing, so it has no move and no handler: it answers from the ${thing}'s records.
88
+ export default Blueprint.read(${pascal(thing)}, {
89
+ by: "id",
90
+ fields: Blueprint.todo("the fields it answers"),
91
+ allowed: Blueprint.todo("who may read ${article(thing)}"),
92
+ });
93
+ `,
94
+ });
95
+ export const journeyFile = (title, file) => ({
96
+ path: `blueprint/journeys/${file}.ts`,
97
+ content: `${header}
98
+
99
+ export default Blueprint.journey(${JSON.stringify(title)}, {
100
+ cast: Blueprint.todo("who is in it, by role"),
101
+ steps: () => Blueprint.todo("the steps, each a call and its checks"),
102
+ });
103
+ `,
104
+ });
@@ -0,0 +1,2 @@
1
+ import { type AddApi } from "./types.ts";
2
+ export declare const Add: AddApi;
@@ -0,0 +1,27 @@
1
+ import { AddRefused } from "./types.js";
2
+ import { isThingName, kebab } from "./internal/names.js";
3
+ import { journeysOf } from "./internal/journeys.js";
4
+ import { journeyFile, operationFile, readFile, thingFiles } from "./internal/templates.js";
5
+ const verbName = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
6
+ const files = (what, name) => {
7
+ if (what === "journey") {
8
+ const file = kebab(name);
9
+ return file === "" ? new AddRefused({ message: "a journey needs a title" }) : [journeyFile(name, file)];
10
+ }
11
+ if (what === "thing")
12
+ return isThingName(name) ? thingFiles(name) : new AddRefused({ message: `"${name}" isn't a thing's name: lower case words joined by dashes` });
13
+ const [thing = "", verb = "", ...rest] = name.split(".");
14
+ if (rest.length > 0 || !isThingName(thing) || !verbName.test(verb))
15
+ return new AddRefused({ message: `"${name}" isn't <thing>.<verb>, like allowance.spend` });
16
+ return [what === "read" ? readFile(thing, verb) : operationFile(thing, verb)];
17
+ };
18
+ export const Add = {
19
+ plan: (what, name, exists) => {
20
+ const planned = files(what, name, exists);
21
+ if (planned instanceof AddRefused)
22
+ return planned;
23
+ const there = planned.filter((f) => exists(f.path));
24
+ return there.length > 0 ? new AddRefused({ message: `already there, so nothing was written: ${there.map((f) => f.path).join(", ")}` }) : planned;
25
+ },
26
+ journeys: journeysOf,
27
+ };
@@ -0,0 +1,30 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ /** One file `add` would write: its path from the project's root, and what goes in it. */
3
+ export interface Written {
4
+ readonly path: string;
5
+ readonly content: string;
6
+ }
7
+ export type What = "thing" | "operation" | "read" | "journey";
8
+ /** What `add journeys` writes, and the stubs it leaves because they are already there (and yours). */
9
+ export interface Planned {
10
+ readonly write: ReadonlyArray<Written>;
11
+ readonly there: ReadonlyArray<string>;
12
+ }
13
+ declare const AddRefused_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
14
+ readonly _tag: "AddRefused";
15
+ } & Readonly<A>;
16
+ /** The name doesn't fit what is being added, or a file it would write is already there. */
17
+ export declare class AddRefused extends AddRefused_base<{
18
+ readonly message: string;
19
+ }> {
20
+ }
21
+ export interface AddApi {
22
+ /**
23
+ * The files for `add <what> <name>`, never overwriting one that `exists`. A thing is `allowance`; an operation or a
24
+ * read is `allowance.spend`; a journey is its title, `"spend within an allowance"`.
25
+ */
26
+ readonly plan: (what: What, name: string, exists: (path: string) => boolean) => ReadonlyArray<Written> | AddRefused;
27
+ /** `add journeys <thing>`: a stub per path, role and declared error, writing only the missing ones (K16 e). */
28
+ readonly journeys: (model: Model, thing: string, exists: (path: string) => boolean) => Planned | AddRefused;
29
+ }
30
+ export {};
@@ -0,0 +1,6 @@
1
+ // Adding to a blueprint: `ortho add thing | operation | read | journey | journeys` writes declarations with blanks in them.
2
+ // A blank (`Blueprint.todo`) compiles, and `ortho check` names each one until it is filled.
3
+ import { Data } from "effect";
4
+ /** The name doesn't fit what is being added, or a file it would write is already there. */
5
+ export class AddRefused extends Data.TaggedError("AddRefused") {
6
+ }
@@ -0,0 +1,2 @@
1
+ import type { BriefApi } from "./types.ts";
2
+ export declare const Brief: BriefApi;
@@ -0,0 +1,48 @@
1
+ import { IDEMPOTENCY_CONFLICT } from "@orthograph/projections/shared";
2
+ const forbidden = [
3
+ "blueprint/**", "blueprint/journeys/**", "blueprint/starting-worlds/**", "journeys/**", "generated/**", "test/**",
4
+ ];
5
+ /** The nine evals, in their numbered order, as prove prints them. */
6
+ const EVALS = ["answer shape", "declared errors", "machine path", "events", "who may call", "steps", "performance", "coverage", "explainability"];
7
+ const of = (model, name, journeys) => {
8
+ const op = model.operations[name];
9
+ if (!op || op.kind !== "operation")
10
+ return { unknown: `${name} is not an operation with a handler: ${Object.values(model.operations).filter((o) => o.kind === "operation").map((o) => o.name).join(", ")}` };
11
+ const thing = model.things[op.thing];
12
+ const own = `things/${op.thing}/verbs/${op.verb}.ts`;
13
+ const calling = journeys.filter((j) => j.text.includes(own)).map((j) => j.path);
14
+ const declared = op.errors.map((e) => `${e} (exit ${thing.errors[e]?.exit ?? "?"})`);
15
+ // A reused request key (IdempotencyConflict) is met by the caller, not made by a handler: the brief names only what a handler might wrongly refuse.
16
+ const runtime = op.refusals.filter((r) => !op.errors.includes(r) && r !== IDEMPOTENCY_CONFLICT);
17
+ return {
18
+ lines: [
19
+ `brief ${name}`,
20
+ "",
21
+ `Write src/${op.thing}/${op.verb}.ts, and nothing else.`,
22
+ "",
23
+ "Read",
24
+ ` ${op.file} the declaration: payload, answer, move, steps, errors`,
25
+ ` generated/api/src/${op.thing}/${op.verb}.handler.ts what the handler is given and may return`,
26
+ ` generated/docs/${op.thing}/${op.verb}.md the same, in words, with every refusal`,
27
+ ` generated/docs/${op.thing}/index.md the ${op.thing}: fields, machine, roles`,
28
+ "",
29
+ "Do",
30
+ ...Object.values(op.steps).map((s) => ` run step ${s.name} (${s.type}) through steps.${s.name.split(".").pop()}(...)`),
31
+ ...(Object.values(op.steps).some((s) => s.type === "database")
32
+ ? [" a database step wraps one call of Records (yield* Records, from @orthograph/language-effect): find, insert or update. A move changes the machine's state only; a field changes only when you write it, as steps.x(records.update(Thing, id, { field: value }))"]
33
+ : []),
34
+ ...(op.move ? [` make the move with move(${op.move.to.length > 1 ? op.move.to.map((t) => `"${t}"`).join(" | ") : ""}): ${op.move.key}, emitting ${op.move.emits}`] : []),
35
+ ...(declared.length ? [` refuse with ${declared.join(", ")}, each after an Effect.logInfo saying why`] : []),
36
+ ...(runtime.length ? [` never refuse ${runtime.join(" or ")} yourself: the runtime does, before the handler runs`] : []),
37
+ "",
38
+ "Don't touch",
39
+ ...forbidden.map((f) => ` ${f}`),
40
+ "",
41
+ "Done when",
42
+ ` ortho prove --env local passes, with ${name}'s 9 evals: ${EVALS.join(", ")}`,
43
+ ...(calling.length ? [` and the journeys that call it: ${calling.join(", ")}`] : [` (no journey calls ${name} yet: coverage will fail until one does)`]),
44
+ " ortho check passes",
45
+ ],
46
+ };
47
+ };
48
+ export const Brief = { of, forbidden };
@@ -0,0 +1,16 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ /** A journey file and its text: the brief names the ones that call the operation. */
3
+ export interface JourneyFile {
4
+ readonly path: string;
5
+ readonly text: string;
6
+ }
7
+ export type Briefed = {
8
+ readonly lines: ReadonlyArray<string>;
9
+ } | {
10
+ readonly unknown: string;
11
+ };
12
+ export interface BriefApi {
13
+ readonly of: (model: Model, operation: string, journeys: ReadonlyArray<JourneyFile>) => Briefed;
14
+ /** Paths an agent writing a handler must never change. `check` and the `claude -p` session hold it to them. */
15
+ readonly forbidden: ReadonlyArray<string>;
16
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { Blank, CheckApi } from "../types.ts";
2
+ export declare const blanks: CheckApi["blanks"];
3
+ export declare const blankLines: (all: ReadonlyArray<Blank>) => ReadonlyArray<string>;
@@ -0,0 +1,11 @@
1
+ const TODO = /Blueprint\.todo(?:<[^>]*>)?\(\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`)?/g;
2
+ const ownerOf = (path) => /^blueprint\/things\/([^/]+)\//.exec(path)?.[1] ?? path.replace(/^blueprint\//, "").replace(/\.ts$/, "");
3
+ export const blanks = (files) => files.flatMap(({ path, text }) => text.split("\n").flatMap((line, i) => [...line.matchAll(TODO)].map((m) => ({ file: path, line: i + 1, owner: ownerOf(path), what: m[1] ? m[1].slice(1, -1) : "(no description)" }))));
4
+ export const blankLines = (all) => {
5
+ if (all.length === 0)
6
+ return ["blanks left 0"];
7
+ return [...new Set(all.map((b) => b.owner))].flatMap((owner) => {
8
+ const mine = all.filter((b) => b.owner === owner);
9
+ return [`${owner} has ${mine.length} blank${mine.length === 1 ? "" : "s"}`, ...mine.map((b) => ` ${b.file}:${b.line} ${b.what}`)];
10
+ });
11
+ };
@@ -0,0 +1,8 @@
1
+ import { Effect } from "effect";
2
+ import { type Model } from "@orthograph/compiler";
3
+ /**
4
+ * One line for each change that is not a patch, naming what changed and the bump it makes: `thing:allowance (states
5
+ * renumbered or removed: exhausted): major`. Nothing when nothing changed that matters, or when no model is checked in.
6
+ * These are what the next version will be made of (D3 #1), so they inform: they never fail the check.
7
+ */
8
+ export declare const changes: (root: string, model: Model) => Effect.Effect<ReadonlyArray<string>>;
@@ -0,0 +1,16 @@
1
+ // The changes part: what the blueprint now says against the model checked in under `generated/model/model.json`, and what each change means for the version.
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { Effect } from "effect";
5
+ import { Compare } from "@orthograph/compiler";
6
+ /**
7
+ * One line for each change that is not a patch, naming what changed and the bump it makes: `thing:allowance (states
8
+ * renumbered or removed: exhausted): major`. Nothing when nothing changed that matters, or when no model is checked in.
9
+ * These are what the next version will be made of (D3 #1), so they inform: they never fail the check.
10
+ */
11
+ export const changes = (root, model) => {
12
+ const file = join(root, "generated/model/model.json");
13
+ if (!existsSync(file))
14
+ return Effect.succeed([]);
15
+ return Effect.try({ try: () => JSON.parse(readFileSync(file, "utf8")), catch: (e) => e }).pipe(Effect.map((before) => Compare.release(before, model).changes.filter((c) => c.bump !== "patch")), Effect.map((found) => (found.length === 0 ? [] : [`changes ${found.length}`, ...found.map((c) => ` ${c.what}${c.detail ? ` (${c.detail})` : ""}: ${c.bump}`)])), Effect.orElseSucceed(() => []));
16
+ };
@@ -0,0 +1,4 @@
1
+ import { Effect } from "effect";
2
+ import type { Model } from "@orthograph/compiler";
3
+ import type { Finding } from "../types.ts";
4
+ export declare const drift: (root: string, model: Model) => Effect.Effect<ReadonlyArray<Finding>>;
@@ -0,0 +1,25 @@
1
+ // The drift part, which is also the rule no-edited-output: generated/ must be exactly what the blueprint renders.
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { basename, join, relative } from "node:path";
4
+ import { Cause, Effect } from "effect";
5
+ import { Render } from "@orthograph/generators/render";
6
+ import { allFiles } from "./files.js";
7
+ export const drift = (root, model) => Effect.gen(function* () {
8
+ // A projection that can't be loaded or won't render is drift too: nothing it should make can be compared.
9
+ // A projection that crashes on a model it has no rendering for (a chain-stored thing, until its language renders) is the same finding, never a crash of check.
10
+ const rendered = yield* Render.files({ name: basename(root), model, root }).pipe(Effect.catchCause((cause) => Effect.fail({ message: `can't render: ${Cause.pretty(cause).split("\n")[0] ?? "a projection failed"}` })), Effect.result);
11
+ if (rendered._tag === "Failure")
12
+ return [{ part: "drift", rule: "no-edited-output", file: "generated", message: rendered.failure.message }];
13
+ const wanted = rendered.success.filter((f) => !f.scaffold);
14
+ const edited = wanted.flatMap((f) => {
15
+ const at = join(root, f.path);
16
+ if (!existsSync(at))
17
+ return [{ part: "drift", rule: "no-edited-output", file: f.path, message: "is missing: run ortho generate" }];
18
+ return readFileSync(at, "utf8") === f.content ? [] : [{ part: "drift", rule: "no-edited-output", file: f.path, message: "differs from what the blueprint generates: never edit generated/, run ortho generate" }];
19
+ });
20
+ // Dot-folders under generated/ are tools' own state (wrangler's `.wrangler/`), never output.
21
+ const known = new Set(wanted.map((f) => f.path));
22
+ const orphans = allFiles(join(root, "generated")).map((f) => relative(root, f)).filter((p) => !known.has(p) && !p.split("/").some((part) => part.startsWith(".")))
23
+ .map((p) => ({ part: "drift", rule: "no-edited-output", file: p, message: "is in generated/ but the blueprint doesn't generate it" }));
24
+ return [...edited, ...orphans];
25
+ });
@@ -0,0 +1,8 @@
1
+ export declare const tsFiles: (dir: string) => ReadonlyArray<string>;
2
+ export declare const allFiles: (dir: string) => ReadonlyArray<string>;
3
+ export declare const textsUnder: (root: string, dir: string) => {
4
+ path: string;
5
+ text: string;
6
+ }[];
7
+ /** `node_modules/.bin/<name>` in the project or the nearest folder above it that has one. */
8
+ export declare const binOf: (root: string, name: string) => string | undefined;
@@ -0,0 +1,18 @@
1
+ // The project's files as check reads them, and the tools it runs, found the way a shell would: up from the project.
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ import { dirname, join, relative } from "node:path";
4
+ export const tsFiles = (dir) => existsSync(dir)
5
+ ? readdirSync(dir, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? tsFiles(join(dir, d.name)) : d.name.endsWith(".ts") ? [join(dir, d.name)] : []))
6
+ : [];
7
+ export const allFiles = (dir) => existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? allFiles(join(dir, d.name)) : [join(dir, d.name)])) : [];
8
+ export const textsUnder = (root, dir) => tsFiles(join(root, dir)).map((f) => ({ path: relative(root, f), text: readFileSync(f, "utf8") }));
9
+ /** `node_modules/.bin/<name>` in the project or the nearest folder above it that has one. */
10
+ export const binOf = (root, name) => {
11
+ for (let at = root;; at = dirname(at)) {
12
+ const bin = join(at, "node_modules/.bin", name);
13
+ if (existsSync(bin))
14
+ return bin;
15
+ if (dirname(at) === at)
16
+ return undefined;
17
+ }
18
+ };
@@ -0,0 +1,7 @@
1
+ import type { Finding } from "../types.ts";
2
+ export declare const ratchetsOf: (root: string) => Readonly<Record<string, number>>;
3
+ /** The findings no ratchet allows, and what the ratchets say. */
4
+ export declare const ratchet: (findings: ReadonlyArray<Finding>, allowed: Readonly<Record<string, number>>) => {
5
+ over: Finding[];
6
+ lines: string[];
7
+ };
@@ -0,0 +1,17 @@
1
+ // Ratchets: `.ortho/ratchets.json` holds how many findings of a rule a project still allows itself. A count may
2
+ // only go down: more findings than it allows fail, and fewer say the file should be lowered.
3
+ import { Names } from "orthograph/server";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ export const ratchetsOf = (root) => {
7
+ const file = join(root, Names.folder, "ratchets.json");
8
+ return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
9
+ };
10
+ /** The findings no ratchet allows, and what the ratchets say. */
11
+ export const ratchet = (findings, allowed) => {
12
+ const count = (rule) => findings.filter((f) => f.rule === rule).length;
13
+ const over = findings.filter((f) => count(f.rule) > (allowed[f.rule] ?? 0));
14
+ const lower = Object.entries(allowed).filter(([rule, n]) => count(rule) < n).map(([rule, n]) => ` ${rule} allows ${n} but has ${count(rule)}: lower it`);
15
+ const total = Object.values(allowed).reduce((a, b) => a + b, 0);
16
+ return { over, lines: [`ratchets ${total}`, ...lower] };
17
+ };
@@ -0,0 +1,12 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { ProjectFacts } from "@orthograph/lint";
3
+ import type { Finding } from "../types.ts";
4
+ export declare const RULES: readonly ["no-name-as-string", "refusal-has-log", "declared-errors-only", "no-wall-clock", "handler-matches-path", "no-old-names"];
5
+ /** The drift rules (M1.26, K16 f): the blueprint grew past a handler that is yours. Warnings, never failures. */
6
+ export declare const WARNINGS: readonly ["required-step-used", "outcome-chosen", "declared-error-named"];
7
+ export declare const types: (root: string) => ReadonlyArray<Finding>;
8
+ export declare const factsOf: (root: string, model: Model) => ProjectFacts;
9
+ export declare const rules: (root: string, model: Model) => {
10
+ readonly errors: ReadonlyArray<Finding>;
11
+ readonly warnings: ReadonlyArray<Finding>;
12
+ };
@@ -0,0 +1,66 @@
1
+ // The types and rules parts: tsc and oxlint, run for real on the project, their output read back as findings.
2
+ import { Names } from "orthograph/server";
3
+ import { spawnSync } from "node:child_process";
4
+ import { mkdirSync, writeFileSync } from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import { join, relative } from "node:path";
7
+ import { binOf, tsFiles } from "./files.js";
8
+ export const RULES = ["no-name-as-string", "refusal-has-log", "declared-errors-only", "no-wall-clock", "handler-matches-path", "no-old-names"];
9
+ /** The drift rules (M1.26, K16 f): the blueprint grew past a handler that is yours. Warnings, never failures. */
10
+ export const WARNINGS = ["required-step-used", "outcome-chosen", "declared-error-named"];
11
+ export const types = (root) => {
12
+ const tsc = binOf(root, "tsc");
13
+ if (!tsc)
14
+ return [{ part: "types", rule: "tsc", file: "tsconfig.json", message: "no tsc found in node_modules/.bin" }];
15
+ const run = spawnSync(tsc, ["-p", join(root, "tsconfig.json"), "--noEmit", "--pretty", "false"], { cwd: root, encoding: "utf8" });
16
+ const found = (run.stdout ?? "").split("\n").flatMap((l) => {
17
+ const m = /^(.+?)\((\d+),\d+\): error (TS\d+): (.*)$/.exec(l);
18
+ return m ? [{ part: "types", rule: m[3], file: m[1], line: Number(m[2]), message: m[4] }] : [];
19
+ });
20
+ return found.length === 0 && run.status !== 0 ? [failed("types", "tsc", "tsconfig.json", run)] : found;
21
+ };
22
+ export const factsOf = (root, model) => {
23
+ const ops = Object.values(model.operations);
24
+ const things = Object.values(model.things);
25
+ return {
26
+ root,
27
+ names: [...ops.map((o) => o.name), ...ops.flatMap((o) => Object.values(o.steps).map((s) => s.name)),
28
+ ...things.flatMap((t) => [...Object.keys(t.events), ...Object.keys(t.errors)])],
29
+ errors: things.flatMap((t) => Object.keys(t.errors)),
30
+ handlers: Object.fromEntries(ops.filter((o) => o.kind === "operation").map((o) => [`src/${o.thing}/${o.verb}.ts`, o.errors])),
31
+ requiredSteps: Object.fromEntries(ops.filter((o) => o.kind === "operation" && o.from.kind === "app").map((o) => [`src/${o.thing}/${o.verb}.ts`, Object.keys(o.steps).filter((key) => !o.steps[key]?.optional)])),
32
+ outcomes: Object.fromEntries(ops.filter((o) => o.kind === "operation" && o.from.kind === "app" && (o.move?.to.length ?? 0) > 1).map((o) => [`src/${o.thing}/${o.verb}.ts`, o.move.to])),
33
+ };
34
+ };
35
+ export const rules = (root, model) => {
36
+ const oxlint = binOf(root, "oxlint");
37
+ if (!oxlint)
38
+ return { errors: [{ part: "rules", rule: "oxlint", file: ".", message: "no oxlint found in node_modules/.bin" }], warnings: [] };
39
+ const plugin = createRequire(import.meta.url).resolve(`${Names.pkg("lint")}/plugin`);
40
+ const facts = factsOf(root, model);
41
+ const dir = join(root, Names.folder, "check");
42
+ mkdirSync(dir, { recursive: true });
43
+ // Only the ortho rules: the project's own lint config is its own business.
44
+ const config = {
45
+ jsPlugins: [plugin], categories: { correctness: "off" }, plugins: [],
46
+ rules: { ...Object.fromEntries(RULES.map((r) => [`ortho/${r}`, ["error", facts]])), ...Object.fromEntries(WARNINGS.map((r) => [`ortho/${r}`, ["warn", facts]])) },
47
+ };
48
+ writeFileSync(join(dir, "oxlintrc.json"), JSON.stringify(config, null, 2));
49
+ // Files named one by one: walking a folder applies every .gitignore above it, which would skip a project kept in one.
50
+ const targets = ["src", "blueprint"].flatMap((d) => tsFiles(join(root, d)).map((f) => relative(root, f)));
51
+ if (targets.length === 0)
52
+ return { errors: [], warnings: [] };
53
+ const run = spawnSync(oxlint, ["-c", join(dir, "oxlintrc.json"), "--no-ignore", "--format", "unix", ...targets], { cwd: root, encoding: "utf8" });
54
+ const errors = [];
55
+ const warnings = [];
56
+ for (const line of (run.stdout ?? "").split("\n")) {
57
+ const m = /^(.+?):(\d+):\d+: (.*) \[(Error|Warning)\/ortho\((.+?)\)\]$/.exec(line);
58
+ if (m)
59
+ (m[4] === "Error" ? errors : warnings).push({ part: "rules", rule: m[5], file: m[1], line: Number(m[2]), message: m[3] });
60
+ }
61
+ if (errors.length === 0 && run.status !== 0)
62
+ errors.push(failed("rules", "oxlint", ".", run));
63
+ return { errors, warnings };
64
+ };
65
+ /** A tool that exits non-zero without one finding it reports didn't run: that is a finding too, never a pass. */
66
+ const failed = (part, rule, file, run) => ({ part, rule, file, message: `${rule} failed (exit ${run.status}): ${`${run.stderr ?? ""}${run.stdout ?? ""}`.trim().split("\n")[0] ?? ""}` });
@@ -0,0 +1,2 @@
1
+ import type { CheckApi } from "./types.ts";
2
+ export declare const Check: CheckApi;
@@ -0,0 +1,37 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { Effect } from "effect";
4
+ import { Compiler, nodeSource } from "@orthograph/compiler";
5
+ import { blankLines, blanks } from "./internal/blanks.js";
6
+ import { textsUnder } from "./internal/files.js";
7
+ import { rules, types } from "./internal/tools.js";
8
+ import { changes } from "./internal/changes.js";
9
+ import { drift } from "./internal/drift.js";
10
+ import { ratchet, ratchetsOf } from "./internal/ratchets.js";
11
+ const part = (name, found) => found.length === 0
12
+ ? [`${name} ✔`]
13
+ : [`${name} ✘ ${found.length}`, ...found.map((f) => ` ${f.file}${f.line ? `:${f.line}` : ""} ${f.rule}: ${f.message}`)];
14
+ const run = (at) => Effect.gen(function* () {
15
+ // The real path: tools report files by it, so a root reached through a symlink (macOS /var) still matches.
16
+ const root = existsSync(at) ? realpathSync(at) : resolve(at);
17
+ const left = blanks(textsUnder(root, "blueprint"));
18
+ const compiled = yield* Compiler.model.pipe(Effect.provide(nodeSource(root)), Effect.result);
19
+ if (compiled._tag === "Failure") {
20
+ // Each problem names its files: the app's, and a plugin's package path with the mount that brought it in.
21
+ const problems = compiled.failure._tag === "BlueprintInvalid" ? compiled.failure.problems : [compiled.failure.message];
22
+ return { lines: [...blankLines(left), `model ✘ ${problems.length}`, ...problems.map((p) => ` ${p}`), "check ✘"], passed: false };
23
+ }
24
+ const model = { value: compiled.success };
25
+ const typed = yield* Effect.sync(() => types(root));
26
+ const ruled = yield* Effect.sync(() => rules(root, model.value));
27
+ const drifted = yield* drift(root, model.value);
28
+ const changed = yield* changes(root, model.value);
29
+ const ratchets = ratchet(ruled.errors, ratchetsOf(root));
30
+ const warnings = ruled.warnings.map((f) => ` warning: ${f.file}:${f.line} ${f.message}`);
31
+ const passed = left.length === 0 && typed.length === 0 && ratchets.over.length === 0 && drifted.length === 0;
32
+ return {
33
+ lines: [...blankLines(left), ...part("types", typed), ...part("rules", ratchets.over), ...warnings, ...part("drift", drifted), ...changed, ...ratchets.lines, passed ? "check ✔" : "check ✘"],
34
+ passed,
35
+ };
36
+ });
37
+ export const Check = { blanks, report: (all) => ({ lines: blankLines(all), passed: all.length === 0 }), run };
@@ -0,0 +1,32 @@
1
+ import type { Effect } from "effect";
2
+ /** One `Blueprint.todo` not filled yet: where it is and what it is waiting for. */
3
+ export interface Blank {
4
+ readonly file: string;
5
+ readonly line: number;
6
+ readonly what: string;
7
+ /** Whose it is: `allowance` for anything under its folder, else the file's own name. */
8
+ readonly owner: string;
9
+ }
10
+ /** One thing wrong, named by file (and line when there is one) and the rule or step that found it. */
11
+ export interface Finding {
12
+ readonly part: "types" | "rules" | "drift";
13
+ readonly rule: string;
14
+ readonly file: string;
15
+ readonly line?: number;
16
+ readonly message: string;
17
+ }
18
+ export interface Checked {
19
+ readonly lines: ReadonlyArray<string>;
20
+ readonly passed: boolean;
21
+ }
22
+ export interface CheckApi {
23
+ /** The blanks in a project's blueprint, given its files by path from the root. */
24
+ readonly blanks: (files: ReadonlyArray<{
25
+ readonly path: string;
26
+ readonly text: string;
27
+ }>) => ReadonlyArray<Blank>;
28
+ /** The lines `check` prints for blanks alone: `allowance has 3 blanks`, then each with its file and line. */
29
+ readonly report: (blanks: ReadonlyArray<Blank>) => Checked;
30
+ /** Every part, on the project at `root`. Reads files and runs tsc and oxlint; never writes outside `.ortho/`. */
31
+ readonly run: (root: string) => Effect.Effect<Checked>;
32
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { GenerateApi } from "./types.ts";
2
+ export declare const Generate: GenerateApi;
@@ -0,0 +1,18 @@
1
+ import { basename, dirname, resolve } from "node:path";
2
+ import { Effect } from "effect";
3
+ import { FsTree, flushChanges } from "nx/src/generators/tree.js";
4
+ import { Sync } from "@orthograph/generators/sync";
5
+ const kinds = { CREATE: "created", UPDATE: "updated", DELETE: "deleted" };
6
+ export const Generate = {
7
+ run: (root) => Effect.gen(function* () {
8
+ const abs = resolve(root);
9
+ const tree = new FsTree(dirname(abs), false);
10
+ yield* Sync.project(tree, basename(abs));
11
+ const changes = tree.listChanges();
12
+ yield* Effect.sync(() => flushChanges(dirname(abs), changes));
13
+ return changes.map((c) => ({ kind: kinds[c.type], path: c.path.slice(basename(abs).length + 1) }));
14
+ }),
15
+ lines: (changes) => changes.length === 0
16
+ ? ["nothing to change"]
17
+ : changes.map((c) => `${c.kind} ${c.path}${c.path.startsWith("src/") ? " (scaffold: yours from now on)" : ""}`),
18
+ };
@@ -0,0 +1,13 @@
1
+ import type { Effect } from "effect";
2
+ import type { ModelFailed } from "@orthograph/generators/sync";
3
+ /** One file the run changed: made, rewritten, or removed (an orphan in `generated/`). */
4
+ export interface Change {
5
+ readonly kind: "created" | "updated" | "deleted";
6
+ readonly path: string;
7
+ }
8
+ export interface GenerateApi {
9
+ /** Bring `root` in line with its blueprint, and say what changed: nothing, on a second run. */
10
+ readonly run: (root: string) => Effect.Effect<ReadonlyArray<Change>, ModelFailed>;
11
+ /** `created src/allowance/spend.ts (scaffold)`, one line per change, or `nothing to change`. */
12
+ readonly lines: (changes: ReadonlyArray<Change>) => ReadonlyArray<string>;
13
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ /** The first `node_modules/@orthograph/cli` with a package.json, from `from` up. */
2
+ export declare const installedCli: (from: string) => string | undefined;
3
+ /** The file the package's `ortho` bin names, when the package names one that exists. */
4
+ export declare const binOf: (dir: string) => string | undefined;
5
+ /** Whether two folders are one, links followed. */
6
+ export declare const same: (a: string, b: string) => boolean;
@@ -0,0 +1,29 @@
1
+ // Where the app's own CLI is installed, and the file its `ortho` bin runs.
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { Effect, Option } from "effect";
5
+ const CLI = "@orthograph/cli";
6
+ /** The first `node_modules/@orthograph/cli` with a package.json, from `from` up. */
7
+ export const installedCli = (from) => {
8
+ for (let dir = resolve(from);; dir = dirname(dir)) {
9
+ const candidate = join(dir, "node_modules", CLI);
10
+ if (existsSync(join(candidate, "package.json")))
11
+ return candidate;
12
+ if (dirname(dir) === dir)
13
+ return undefined;
14
+ }
15
+ };
16
+ /** The package's manifest, or nothing when it can't be read or parsed. */
17
+ const manifestOf = (dir) => Option.getOrUndefined(Effect.runSync(Effect.option(Effect.try(() => JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))))));
18
+ /** The file the package's `ortho` bin names, when the package names one that exists. */
19
+ export const binOf = (dir) => {
20
+ const manifest = manifestOf(dir);
21
+ if (manifest === undefined || manifest === null || typeof manifest !== "object")
22
+ return undefined;
23
+ const named = typeof manifest.bin === "string" ? manifest.bin : typeof manifest.bin === "object" && manifest.bin !== null ? manifest.bin["ortho"] : undefined;
24
+ // A `bin.ortho` that is not a string (a number, an object) is a package that can't be run, not a crash at startup.
25
+ const bin = typeof named === "string" ? named : undefined;
26
+ return manifest.name === CLI && bin !== undefined && existsSync(join(dir, bin)) ? join(dir, bin) : undefined;
27
+ };
28
+ /** Whether two folders are one, links followed. */
29
+ export const same = (a, b) => existsSync(a) && existsSync(b) && realpathSync(a) === realpathSync(b);
@@ -0,0 +1,2 @@
1
+ import type { HandoffApi } from "./types.ts";
2
+ export declare const Handoff: HandoffApi;