am-i-done 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CLAUDE.md +36 -0
  2. package/LICENSE +21 -0
  3. package/README.md +339 -2
  4. package/bin/am-i-done.ts +5 -0
  5. package/bin/doing-it-wrong.ts +5 -0
  6. package/package.json +74 -4
  7. package/src/cache.ts +120 -0
  8. package/src/cli/am-i-done.ts +243 -0
  9. package/src/cli/doing-it-wrong.ts +52 -0
  10. package/src/cli/init.ts +111 -0
  11. package/src/config.ts +132 -0
  12. package/src/context.ts +20 -0
  13. package/src/engine/ast-corpus/jsx.js.txt +13 -0
  14. package/src/engine/ast-corpus/jsx.tsx.txt +3 -0
  15. package/src/engine/ast-corpus/plain.mjs.txt +4 -0
  16. package/src/engine/ast-corpus/syntax.ts.txt +44 -0
  17. package/src/engine/ast.ts +242 -0
  18. package/src/engine/engine.ts +202 -0
  19. package/src/engine/evaluate.ts +177 -0
  20. package/src/engine/files.ts +71 -0
  21. package/src/engine/fixtures.ts +119 -0
  22. package/src/engine/graph.ts +200 -0
  23. package/src/engine/mask.ts +245 -0
  24. package/src/engine/report.ts +59 -0
  25. package/src/engine/rule.ts +142 -0
  26. package/src/engine/suppress.ts +59 -0
  27. package/src/fingerprint.ts +54 -0
  28. package/src/index.ts +23 -0
  29. package/src/log.ts +115 -0
  30. package/src/modules.ts +49 -0
  31. package/src/output-guard.ts +58 -0
  32. package/src/rules/fixtures/no-as-any__cast.ts.fixture +3 -0
  33. package/src/rules/fixtures/no-as-any__clean.ts.fixture +4 -0
  34. package/src/rules/fixtures/no-as-any__jsx.tsx.fixture +4 -0
  35. package/src/rules/fixtures/no-empty-catch__empty.ts.fixture +12 -0
  36. package/src/rules/fixtures/no-empty-catch__handled.ts.fixture +4 -0
  37. package/src/rules/fixtures/no-focused-tests__clean.spec.ts.fixture +4 -0
  38. package/src/rules/fixtures/no-focused-tests__only.spec.ts.fixture +8 -0
  39. package/src/rules/fixtures/no-import-cycles__acyclic.ts.fixture +3 -0
  40. package/src/rules/fixtures/no-import-cycles__self.ts.fixture +4 -0
  41. package/src/rules/fixtures/no-raw-temp__helper.spec.ts.fixture +5 -0
  42. package/src/rules/fixtures/no-raw-temp__prod.ts.fixture +2 -0
  43. package/src/rules/fixtures/no-raw-temp__raw.spec.ts.fixture +8 -0
  44. package/src/rules/fixtures/no-skipped-tests__conditional.spec.ts.fixture +4 -0
  45. package/src/rules/fixtures/no-skipped-tests__no-issue.spec.ts.fixture +7 -0
  46. package/src/rules/fixtures/no-skipped-tests__skips.spec.ts.fixture +12 -0
  47. package/src/rules/fixtures/no-skipped-tests__suppressed.spec.ts.fixture +7 -0
  48. package/src/rules/fixtures/no-ts-expect-error__mentioned.ts.fixture +1 -0
  49. package/src/rules/fixtures/no-ts-expect-error__prod.ts.fixture +5 -0
  50. package/src/rules/fixtures/no-ts-ignore__directives.ts.fixture +10 -0
  51. package/src/rules/fixtures/no-ts-ignore__mentioned.ts.fixture +3 -0
  52. package/src/rules/fixtures/shell-injection__safe.ts.fixture +5 -0
  53. package/src/rules/fixtures/shell-injection__template.ts.fixture +7 -0
  54. package/src/rules/fixtures/test-uses-bun-test__helper.spec.ts.fixture +1 -0
  55. package/src/rules/fixtures/test-uses-bun-test__implicit.spec.ts.fixture +2 -0
  56. package/src/rules/fixtures/test-uses-bun-test__imported.spec.ts.fixture +2 -0
  57. package/src/rules/fixtures/test-uses-bun-test__vitest.test.ts.fixture +3 -0
  58. package/src/rules/no-as-any.rule.ts +14 -0
  59. package/src/rules/no-empty-catch.rule.ts +17 -0
  60. package/src/rules/no-focused-tests.rule.ts +13 -0
  61. package/src/rules/no-import-cycles.rule.ts +32 -0
  62. package/src/rules/no-raw-temp.rule.ts +42 -0
  63. package/src/rules/no-skipped-tests.rule.ts +20 -0
  64. package/src/rules/no-ts-expect-error.rule.ts +16 -0
  65. package/src/rules/no-ts-ignore.rule.ts +16 -0
  66. package/src/rules/shell-injection.rule.ts +18 -0
  67. package/src/rules/test-uses-bun-test.rule.ts +25 -0
  68. package/src/runner.ts +381 -0
  69. package/src/scheduler.ts +115 -0
  70. package/src/spawn.ts +209 -0
  71. package/src/spec-cache.ts +107 -0
  72. package/src/stage-process.ts +73 -0
  73. package/src/stages/builtin/bun-version.stage.ts +37 -0
  74. package/src/stages/builtin/lint.stage.ts +26 -0
  75. package/src/stages/builtin/rules.stage.ts +24 -0
  76. package/src/stages/builtin/test.stage.ts +52 -0
  77. package/src/stages/builtin/typecheck.stage.ts +12 -0
  78. package/src/stages/load.ts +89 -0
  79. package/src/stages/order.ts +68 -0
  80. package/src/tmp-preload.ts +16 -0
  81. package/src/tmp.ts +212 -0
  82. package/src/today.ts +5 -0
  83. package/src/types.ts +109 -0
  84. package/src/waivers.ts +49 -0
  85. package/templates/done.toml +23 -0
  86. package/templates/hooks/pre-commit +2 -0
  87. package/templates/hooks/pre-push +2 -0
  88. package/templates/rules/fixtures/todo-cites-issue__tracked.ts.fixture +2 -0
  89. package/templates/rules/fixtures/todo-cites-issue__untracked.ts.fixture +3 -0
  90. package/templates/rules/todo-cites-issue.rule.ts +17 -0
  91. package/templates/stages.md +18 -0
package/CLAUDE.md ADDED
@@ -0,0 +1,36 @@
1
+ # am-i-done
2
+
3
+ A definition-of-done gate for Bun projects: a stage runner (`am-i-done`) and a rule engine
4
+ (`doing-it-wrong`), plus `am-i-done/tmp`. Bun only; ships TypeScript source, no build.
5
+
6
+ ## Done means
7
+
8
+ `bun run am-i-done` passes. It runs this package on itself: bun-version, lint (Biome), the rules,
9
+ `bun check`, and `bun test --coverage` with a 100% line and function threshold (`bunfig.toml`).
10
+ Nothing is left uncovered or excluded to reach it; if a line cannot be covered, restructure it.
11
+
12
+ ## Layout
13
+
14
+ - `src/runner.ts`: runs a plan of stages: deadlines, rerun policy, `warnUntil`, output guard.
15
+ - `src/scheduler.ts`: pure; dependencies, path conflicts, core budget.
16
+ - `src/spawn.ts`: children in their own process groups, output to unlinked files, a watchdog.
17
+ - `src/stage-process.ts`: where a function stage runs, a `bun` process of its own.
18
+ - `src/stages/`: autoload (`load.ts`), derived order (`order.ts`), built-ins (`builtin/*.stage.ts`).
19
+ - `src/engine/`: rule DSL (`rule.ts`), dispatch and suppression (`evaluate.ts`, `suppress.ts`),
20
+ lexer (`mask.ts`), syntax trees (`ast.ts`, held to one shape across parsers by `ast.spec.ts` over
21
+ `ast-corpus/`), import graph (`graph.ts`), fixtures, liveness and the run (`engine.ts`), report.
22
+ - `src/rules/`: built-in rules; `src/rules/fixtures/` their fixtures.
23
+ - `src/fingerprint.ts`: hashing and git, shared by the caches. `src/cache.ts`: the local skip. `src/spec-cache.ts`: the per-spec cache the `test` stage uses. `src/tmp.ts`, `src/tmp-preload.ts`: the temp-file helper.
24
+ - `src/cli/`: the commands; `bin/` the two-line entry points.
25
+ - `templates/`: what `am-i-done init` copies.
26
+
27
+ ## Conventions
28
+
29
+ - `tsconfig.json` is as strict as TypeScript gets (`exactOptionalPropertyTypes`,
30
+ `noUncheckedIndexedAccess`, `noPropertyAccessFromIndexSignature`): consumers type-check this
31
+ source under their own settings, so it must pass the strictest.
32
+ - Every new rule ships fixtures: at least one that fires and one that does not.
33
+ - A parser upgrade that changes the tree fails `ast.spec.ts`; fix the normalizer in `ast.ts` with the
34
+ measured difference, never by loosening the comparison.
35
+ - Temp files come from `src/tmp.ts`, including in specs. Never `mkdtemp` or `tmpdir()`.
36
+ - Comments say why, not what. No issue numbers or names from other projects.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 theshadow27
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,340 @@
1
- # Temporary Holding Version
1
+ # am-i-done
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One command that says whether the work is finished.
4
+
5
+ ```
6
+ $ bun run am-i-done
7
+ [1/5] ✓ bun-version (0ms)
8
+ [2/5] ✓ lint (36ms)
9
+ [3/5] ✓ rules (32ms)
10
+ [4/5] ✓ typecheck (44ms)
11
+ [5/5] ✓ test (1s)
12
+ ✅ Done (1s)
13
+ ```
14
+
15
+ `am-i-done` is a definition of done for projects where agents write much of the code. It runs every
16
+ check the project has (types, lint, its own architecture rules, tests, anything else) in one gate
17
+ that a person, a git hook, an agent and CI all run the same way, and it is built to make passing
18
+ dishonestly hard: a check that silently stops checking fails, a test that only passes the second
19
+ time fails, and an exception to a rule has to say why and cite the issue that tracks it.
20
+
21
+ It grew out of the gate in [mcp-cli](https://github.com/theshadow27/mcp-cli), and has since been
22
+ copied into, and hardened in, more than half a dozen other projects. This package is those copies
23
+ merged into one, so they stop drifting apart, and in case it helps someone else.
24
+
25
+ Bun only (1.4.5 or later), on macOS and Linux: it ends process trees with POSIX process groups.
26
+ It ships TypeScript source, so you can read it in `node_modules`.
27
+
28
+ ## Quick start
29
+
30
+ ```sh
31
+ bun add -d am-i-done
32
+ bunx am-i-done init --hooks
33
+ bun run am-i-done
34
+ ```
35
+
36
+ `init` writes `done.toml`, an example rule with its fixtures, a `scripts/stages/` folder, two
37
+ package.json scripts, a `.gitignore` entry and (with `--hooks`) git hooks. It never overwrites a file
38
+ that exists.
39
+
40
+ The `am-i-done` script it adds is `bun install --frozen-lockfile --silent && am-i-done`. A fresh
41
+ checkout or worktree has no `node_modules`, so it has no `am-i-done` binary until it installs. With
42
+ nothing to install, that install returns in milliseconds.
43
+
44
+ ## What it runs
45
+
46
+ Stages, in an order derived from what each declares. The built-ins load where their tool is set up:
47
+
48
+ | Stage | Runs | When |
49
+ | ------------- | --------------------------------------------------------------------------- | ----------------------------- |
50
+ | `bun-version` | the running Bun equals `packageManager` | package.json pins `bun@x.y.z` |
51
+ | `lint` | `biome check --write --error-on-warnings` (check only in CI and pre-commit) | there is a `biome.json` |
52
+ | `typecheck` | `bun check --no-script` | there is a `tsconfig.json` |
53
+ | `rules` | the rule engine (below) | always |
54
+ | `test` | `bun test` | not in `pre-commit` |
55
+
56
+ A built-in whose tool is missing is left out, and every run says so (`left out: typecheck (no
57
+ tsconfig.json)`); one named in `[stages] load` must have its tool. `bun run am-i-done --list` prints
58
+ the plan. Modes pick stages: `--pre-commit`, `--pre-push`,
59
+ `--ci` (the default under CI), or `--mode <name>` for your own. `--only <stage>` and `--from <stage>`
60
+ rerun part of it; the failure message prints the exact command.
61
+
62
+ ### What makes it strict
63
+
64
+ - **Deadlines.** Each stage has a time limit (`timeout_seconds`, default 300) and so does the run
65
+ (`deadline_seconds`, default 1200). When one passes, the stage's whole process tree is killed,
66
+ grandchildren included, and the failure says which stage was running. A function stage runs in a
67
+ process of its own, so the same holds for one that blocks.
68
+ - **Nothing left running.** Processes a stage leaves behind are ended when it exits, with a warning.
69
+ If the gate itself is killed (a closed terminal, SIGKILL), a watchdog ends what it started.
70
+ - **No flakes.** A failing stage is run once more to see whether the failure repeats, and fails
71
+ either way: a test that passes only the second time is a bug, and the message says so.
72
+ `[run] rerun = "pass"` loosens this; `"off"` skips the second run.
73
+ - **Clean output.** A stage can declare lines that fail it even when it exits 0 (`failOnOutput`).
74
+ `test` fails on React's act() warnings; `lint` fails on Biome diagnostics `--write` left behind.
75
+ - **No silent passes.** Every rule must actually inspect something on a full run (below).
76
+ - **Nothing that does not block.** A failing stage or rule fails the run. The one exception is
77
+ `warnUntil: { date: "YYYY-MM-DD", reason: "… (#123)" }`: until that date it reports a warning,
78
+ then it blocks. The date is at most 90 days away, and the reason cites the issue that tracks it.
79
+
80
+ ### Agents
81
+
82
+ Under an agent harness (Claude Code sets `CLAUDECODE`; any other can set `AM_I_DONE_AI=1`) the console gets one line per stage
83
+ and the detail goes to `.am-i-done/run-*.log`, which is deleted when the run passes and named when it
84
+ fails. A passing run costs a few lines of context.
85
+
86
+ ### The local skip
87
+
88
+ A local rerun of a state that passed in the last hour is skipped. The state is HEAD and every
89
+ changed or untracked file git does not ignore (read from `git status`, so nothing is written to the
90
+ repository), plus Bun's version, the OS and time zone, what `bun install` resolved, every `.env*` file, the environment and the date, so any change runs the gate again. It
91
+ never applies in CI. `--no-cache` runs anyway; `[cache] skip = false` turns it off.
92
+
93
+ ### The spec cache (opt-in)
94
+
95
+ With `[cache] specs = true`, the `test` stage runs only the specs whose inputs changed since they
96
+ last passed. A spec's inputs are every project file it imports, transitively (JSON and other data
97
+ included), plus any project-local test preload, Bun's version, the lockfile, `bunfig.toml`,
98
+ `package.json`, `tsconfig.json`, `done.toml`, every `.env*` file and the environment. It cannot see
99
+ a file a spec reads without importing it (a fixture opened with `fs`), which is why it is off by
100
+ default. It never applies in CI, nor when the stage has arguments of its own, nor when
101
+ `bunfig.toml` measures coverage, which needs the whole suite.
102
+
103
+ ## Stages
104
+
105
+ Each `*.stage.ts` in `scripts/stages/` default-exports one stage:
106
+
107
+ ```ts
108
+ import type { Stage } from "am-i-done";
109
+
110
+ export default {
111
+ id: "build",
112
+ description: "The bundle builds",
113
+ command: "bun run build", // a string (split on spaces, no shell), an argv array, or an async function
114
+ phase: "test", // setup | check (default) | test | report
115
+ modes: ["default", "ci"], // absent: every mode
116
+ after: ["typecheck"], // within a phase; `before` works too
117
+ timeoutMs: 120_000,
118
+ } satisfies Stage;
119
+ ```
120
+
121
+ Phases run in order, and stages within a phase run side by side within the core budget unless
122
+ `after`/`before` or a `writes` conflict orders them (a fixer such as `lint --write` declares
123
+ `writes: ["*"]`). A project stage with a built-in's id replaces the built-in. Per-context behaviour
124
+ uses `ci`, `ai` and `sh`: `false` skips the stage there, and a function can rewrite its arguments.
125
+
126
+ A function stage is an `async` function that returns `true`, `false`, or
127
+ `{ success, error?, warnings?, output? }`; anything else fails. It receives `{ root, args, env,
128
+ logger, signal, context, mode, verbose, failOnOutput }`. It runs in a `bun` process of its own, which
129
+ imports its module, so its deadline ends it like any command and a `process.exit` in it ends only
130
+ it (and fails it). Its log is shown when it fails. A stage that remembers a pass of its own (a
131
+ cache) checks `failOnOutput` first. `spawnCaptured` (exported) runs a command with the same care.
132
+
133
+ ## Rules
134
+
135
+ `bun run doing-it-wrong` runs the rule engine on its own: the built-in rules plus every
136
+ `*.rule.ts` in `scripts/rules/`. `--list` shows them by category, `--rule <id>` runs one, and paths
137
+ narrow the files.
138
+
139
+ ```ts
140
+ import type { Rule } from "am-i-done";
141
+
142
+ export default {
143
+ id: "no-lodash",
144
+ type: "import", // or "pattern" (a global regex over code), or "check" (a function)
145
+ category: "architecture",
146
+ pattern: /^lodash/,
147
+ scold: "Use the standard library; lodash is not a dependency here.",
148
+ guidance: ["Array and Object methods cover most of it.", "Ask before adding a dependency."],
149
+ } satisfies Rule;
150
+ ```
151
+
152
+ A `pattern` rule ignores matches in comments and string literals (JSX text included) unless it
153
+ sets `scope: "all"` (or `"comments"`, for directives). `files` globs widen what a rule sees beyond source, so a rule over
154
+ `Dockerfile` or YAML is an ordinary rule. `tests: "exclude"` or `"only"` scope by test files.
155
+
156
+ A `check` rule returns `ctx.checked()` when it inspected the file and `ctx.skipped()` when the file
157
+ was out of scope. Its return type is a brand only the engine can mint, so a bare `return` does not
158
+ compile.
159
+
160
+ **Syntax trees.** A check rule that sets `ast: true` can call `ctx.ast()` for the file's tree, in
161
+ [TSESTree](https://typescript-eslint.io/packages/typescript-estree/) form (the ESTree dialect
162
+ typescript-eslint defines), with `range`, `loc` and `parent` on every node and the comments on the
163
+ program. It is parsed once per file and shared by every rule. The parser is TypeScript (through
164
+ typescript-estree) when the project's package.json declares `typescript`, else
165
+ [oxc](https://oxc.rs), which ships with this package; `[rules] parser` picks one. A spec holds the two to the same tree over a
166
+ syntax corpus and this package's own source, so a rule cannot tell which ran. `ctx.ast().raw` is the
167
+ escape hatch: `tsNode(node)` gives the TypeScript compiler node behind a tree node, and under oxc
168
+ `result` is oxc's own output. Runs where no rule sets `ast: true` load neither parser. `walk` and
169
+ the `TSESTree` types are exported from `am-i-done`.
170
+
171
+ ```ts
172
+ export default {
173
+ id: "no-default-class-export",
174
+ type: "check",
175
+ category: "conventions",
176
+ ast: true,
177
+ scold: "Export classes by name.",
178
+ guidance: ["`export class Foo`, then `import { Foo }`."],
179
+ check(ctx) {
180
+ for (const node of ctx.ast().program.body) {
181
+ if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ClassDeclaration") {
182
+ ctx.violated(node.loc.start.line, node.loc.start.column + 1, "export default class");
183
+ }
184
+ }
185
+ return ctx.checked();
186
+ },
187
+ } satisfies Rule;
188
+ ```
189
+
190
+ **The import graph.** `ctx.graph()` is the project's import graph, built once per run from Bun's
191
+ native import scanner, with no parser: `edges`, `importers(file)`, `closure(file)` and `cycles()`.
192
+ Relative imports resolve the way TypeScript's bundler resolution does (`.js` written for `.ts`,
193
+ `index` files); a workspace package resolves through Bun to the project file behind it.
194
+ `import type` is not an edge, since it never runs. The built-in `no-import-cycles` uses it.
195
+
196
+ **Liveness.** On a full run every rule must `checked()` at least `expected` files (default 1), and
197
+ every `anchors` predicate must find its marker somewhere in the tree. A rule whose target moved
198
+ fails loudly instead of passing as if the tree were clean. A rule with nothing to inspect yet sets
199
+ `expected: 0`.
200
+
201
+ **Fixtures.** Every rule needs at least one that fires, in
202
+ `scripts/rules/fixtures/<rule-id>__<scenario>.<ext>.fixture`, with `// @expect <n>` (default 0) and
203
+ optionally `// @path <path>` as comment lines of their own in its first lines. The path must be one
204
+ the rule looks at. They run on every run, so a rule that no longer catches what it was written for
205
+ fails. The `.fixture` suffix keeps
206
+ the type checker, linter and test runner away from code that is wrong on purpose.
207
+
208
+ **Suppression.** An exception says why, and where its removal is tracked:
209
+
210
+ ```ts
211
+ // doing-it-wrong-ignore no-skipped-tests: waits on the upstream fix (#123)
212
+ it.skip("parses the new format", () => {});
213
+ ```
214
+
215
+ It applies to its own line and the two below, in any comment syntax; in a script it must be a real
216
+ comment, not text in a string. `doing-it-wrong-ignore-file <rule-id>: <reason> (#123)` applies to
217
+ its whole file. A missing reason, a reason without an issue (with `[suppression] require_issue`, the
218
+ default), and a suppression that no longer suppresses anything are each a violation of their own.
219
+
220
+ ### Built-in rules
221
+
222
+ `no-as-any`, `no-ts-ignore`, `no-ts-expect-error` (outside tests), `no-empty-catch`,
223
+ `shell-injection`, `no-import-cycles`, `no-focused-tests`, `no-skipped-tests`, `test-uses-bun-test`,
224
+ `no-raw-temp`.
225
+ Turn them all off with `[rules] recommended = false`, or one with
226
+ `skip = [{ id = "no-as-any", reason = "… (#123)" }]`.
227
+
228
+ ## Temp files: `am-i-done/tmp`
229
+
230
+ Temp directories made by hand leak: a spec that throws before its cleanup, or a run that is killed,
231
+ leaves them behind, and they pile up unnoticed. `no-raw-temp` flags `mkdtemp`, `tmpdir()`, `/tmp/`
232
+ literals and `mktemp`, and points here:
233
+
234
+ ```ts
235
+ import { tmpDir, tmpScope } from "am-i-done/tmp";
236
+
237
+ using dir = tmpDir("cache-"); // removed when the scope ends, even on a throw
238
+ await using scope = tmpScope(); // many things, released together, newest first; every cleanup runs
239
+ const out = scope.dir("out-");
240
+ scope.defer(() => server.stop());
241
+ ```
242
+
243
+ `tmpFile(name)` gives a file path in a directory of its own, and `missingPath()` a path that must
244
+ still not exist when its scope ends. Everything lives under one root per process,
245
+ `$TMPDIR/amid-<pid>-XXXXXX`. The root is removed at exit, and a killed process's root is removed by
246
+ the next process that sees its pid is dead.
247
+
248
+ Add the preload so every test run sweeps first and cleans up after, naming any directory a spec
249
+ forgot to dispose (`AM_I_DONE_TMP_STRICT=1` makes that a failure):
250
+
251
+ ```toml
252
+ # bunfig.toml
253
+ [test]
254
+ preload = ["am-i-done/tmp/preload"]
255
+ ```
256
+
257
+ ## Configuration
258
+
259
+ `done.toml` at the project root. Every key is optional; these are the defaults.
260
+
261
+ ```toml
262
+ [run]
263
+ deadline_seconds = 1200 # the whole run; 0 disables
264
+ timeout_seconds = 300 # each stage, unless it sets timeoutMs; 0 disables
265
+ cores = 0 # 0: every available core
266
+ rerun = "diagnose" # "off" | "pass"
267
+ out_dir = ".am-i-done"
268
+ strip_env = ["NODE_ENV", "GIT_*"] # removed from every stage's environment
269
+
270
+ [stages]
271
+ recommended = true
272
+ load = [] # exactly these built-ins, instead of all
273
+ skip = [] # [{ id = "lint", reason = "… (#123)" }]
274
+ dirs = ["scripts/stages"]
275
+
276
+ [rules]
277
+ recommended = true
278
+ skip = [] # [{ id = "no-as-any", reason = "… (#123)" }]
279
+ dirs = ["scripts/rules"]
280
+ include = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"]
281
+ exclude = [] # in addition to .gitignore; node_modules is never scanned
282
+ categories = { architecture = "…", conventions = "…", testing = "…", config = "…" }
283
+ parser = "auto" # for ctx.ast(): the project's typescript, else oxc ("typescript", "oxc")
284
+
285
+ [suppression]
286
+ require_issue = true # every waiver (suppression, skip, warnUntil) cites an issue
287
+
288
+ [cache]
289
+ skip = true
290
+ max_age_minutes = 60
291
+ specs = false # run only specs whose imports changed since they passed
292
+ ```
293
+
294
+ `strip_env` exists because Bun loads `.env` into the gate's own process, so a `NODE_ENV=development`
295
+ there would reach `bun test`, which sets `test` only when the variable is unset. It also strips a git
296
+ hook's `GIT_DIR` and `GIT_INDEX_FILE`, which would otherwise point any git command a spec runs at the
297
+ hook's repository.
298
+
299
+ ## Wiring it in
300
+
301
+ **Git hooks.** `am-i-done init --hooks` writes `.githooks/pre-commit` (`bun run am-i-done --pre-commit`)
302
+ and `pre-push` (`--pre-push`), and runs `git config core.hooksPath .githooks`. Before a commit, lint
303
+ only checks: a fix there would land in the working tree while the commit takes the index, so it
304
+ fails and says how to fix and restage. Teammates run that
305
+ same `git config` once after cloning, or add `"prepare": "git config core.hooksPath .githooks"` to
306
+ package.json.
307
+
308
+ **CLAUDE.md** (or AGENTS.md). Tell agents the one command, and what not to do with it:
309
+
310
+ ```md
311
+ ## Definition of done
312
+
313
+ `bun run am-i-done` is the definition of done: run it before saying work is finished, and before
314
+ every commit. It runs typecheck, lint, the architecture rules and the tests.
315
+
316
+ - A failure prints the fix and a rerun command (`--only <stage>`); the full log path is printed too.
317
+ - Never loosen the gate to get past it: no `.skip`, no suppression without a reason and an issue,
318
+ no raised timeouts. If a rule is wrong, say so and propose changing the rule.
319
+ - `bun run doing-it-wrong --list` shows every rule; each failure explains itself.
320
+ - Temp files come from `am-i-done/tmp` (`using dir = tmpDir("x-")`), never `mkdtemp` or `/tmp`.
321
+ ```
322
+
323
+ **CI.**
324
+
325
+ ```yaml
326
+ - uses: oven-sh/setup-bun@v2
327
+ with: { bun-version-file: package.json }
328
+ - run: bun install --frozen-lockfile
329
+ - run: bun run am-i-done # --ci is implied when CI is set
330
+ ```
331
+
332
+ ## Status
333
+
334
+ 0.2: the runner, stage autoloading, the rule engine with syntax trees and the import graph, the local
335
+ skip, the spec cache, the temp-file helper. Planned: a host-wide lease so parallel worktrees do not
336
+ overload a machine, a CI skip for trees that passed before push, and more built-in rules.
337
+
338
+ ## License
339
+
340
+ MIT
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ import { amIDone, runCli } from "../src/cli/am-i-done.ts";
3
+ import { init } from "../src/cli/init.ts";
4
+
5
+ await runCli((argv, io) => (argv[0] === "init" ? init(argv.slice(1), io) : amIDone(argv, io)));
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ import { runCli } from "../src/cli/am-i-done.ts";
3
+ import { doingItWrong } from "../src/cli/doing-it-wrong.ts";
4
+
5
+ await runCli(doingItWrong);
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "am-i-done",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "A definition of done for agentic projects: one command that says whether the work is finished.",
5
+ "license": "MIT",
6
+ "author": "theshadow27 (https://github.com/theshadow27)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/theshadow27/am-i-done.git"
10
+ },
11
+ "homepage": "https://github.com/theshadow27/am-i-done#readme",
12
+ "bugs": "https://github.com/theshadow27/am-i-done/issues",
13
+ "keywords": [
14
+ "bun",
15
+ "ci",
16
+ "quality-gate",
17
+ "lint",
18
+ "agents",
19
+ "definition-of-done"
20
+ ],
21
+ "type": "module",
22
+ "packageManager": "bun@1.4.5",
23
+ "os": [
24
+ "darwin",
25
+ "linux"
26
+ ],
27
+ "engines": {
28
+ "bun": ">=1.4.5"
29
+ },
30
+ "exports": {
31
+ ".": "./src/index.ts",
32
+ "./tmp": "./src/tmp.ts",
33
+ "./tmp/preload": "./src/tmp-preload.ts",
34
+ "./package.json": "./package.json"
35
+ },
36
+ "bin": {
37
+ "am-i-done": "./bin/am-i-done.ts",
38
+ "doing-it-wrong": "./bin/doing-it-wrong.ts"
39
+ },
40
+ "files": [
41
+ "src",
42
+ "!src/**/*.spec.ts",
43
+ "!src/testing.ts",
44
+ "bin",
45
+ "templates",
46
+ "README.md",
47
+ "CLAUDE.md",
48
+ "LICENSE"
49
+ ],
50
+ "scripts": {
51
+ "am-i-done": "bun bin/am-i-done.ts",
52
+ "doing-it-wrong": "bun bin/doing-it-wrong.ts",
53
+ "typecheck": "bun check --no-script",
54
+ "lint": "biome check --write --error-on-warnings .",
55
+ "test": "bun test"
56
+ },
57
+ "dependencies": {
58
+ "@typescript-eslint/types": "8.74.0",
59
+ "@typescript-eslint/typescript-estree": "8.74.0",
60
+ "oxc-parser": "0.160.0",
61
+ "zod": "^4.6.7"
62
+ },
63
+ "devDependencies": {
64
+ "@biomejs/biome": "2.6.9",
65
+ "@types/bun": "1.4.5",
66
+ "typescript": "5.9.3"
67
+ },
68
+ "peerDependencies": {
69
+ "typescript": ">=5.0.0"
70
+ },
71
+ "peerDependenciesMeta": {
72
+ "typescript": {
73
+ "optional": true
74
+ }
75
+ }
76
+ }
package/src/cache.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { dotenvLines, envLines, fileHash, type Git, gitIn, sha } from "./fingerprint.ts";
4
+
5
+ /**
6
+ * The local skip: a run whose whole state matches a recent pass is not run again.
7
+ *
8
+ * The state is more than the source. A recorded pass is keyed on HEAD and the working tree's
9
+ * difference from it (tracked and untracked files git does not ignore, submodules too), Bun's
10
+ * version, the OS and time zone, the context and mode, what `bun install` resolved, every root
11
+ * `.env*` file, the caller's environment, and the date. Any change runs the gate. A pass is reused for at most `max_age_minutes`, never in CI, and
12
+ * only when the tree did not change while it ran (a fixer rewrote files): that run is not recorded.
13
+ *
14
+ * Not covered, by design: a hand-edited file inside node_modules (names and links are read, not
15
+ * contents), and gitignored build output a stage regenerates.
16
+ */
17
+
18
+ export const PASSES_FILE = "am-i-done-passes";
19
+ export const PASSES_KEPT = 50;
20
+
21
+ /** Fields before the path in a `git status --porcelain=v2` entry, by its kind. */
22
+ const FIELDS_BEFORE_PATH: Record<string, number> = { "1": 8, u: 10, "?": 1 };
23
+
24
+ /**
25
+ * The working tree's difference from HEAD: every changed, deleted or untracked file git does not
26
+ * ignore, with a hash of what is on disk now, and the same for each changed submodule. Read from
27
+ * `git status`, which writes nothing (a scratch-index `git add` would put every untracked file into
28
+ * the object store on every run).
29
+ */
30
+ export function worktreeState(git: Git, root: string): string | undefined {
31
+ const status = git.run(["status", "--porcelain=v2", "-z", "--untracked-files=all", "--no-renames"], {
32
+ GIT_OPTIONAL_LOCKS: "0",
33
+ });
34
+ if (status === undefined) return undefined;
35
+ const lines = status
36
+ .split("\0")
37
+ .filter(Boolean)
38
+ .map((entry) => {
39
+ const fields = entry.split(" ");
40
+ const path = fields.slice(FIELDS_BEFORE_PATH[fields[0] as string] ?? 1).join(" ");
41
+ const submodule = fields[0] !== "?" && fields[2]?.startsWith("S") === true;
42
+ const inner = submodule ? (worktreeState(gitIn(join(root, path)), join(root, path)) ?? "unreadable") : "";
43
+ return `${fields.slice(0, 2).join(" ")} ${path}=${submodule ? inner : fileHash(join(root, path))}`;
44
+ });
45
+ return sha([`head=${git.run(["rev-parse", "--verify", "-q", "HEAD"]) ?? "none"}`, ...lines.sort()].join("\n"));
46
+ }
47
+
48
+ const listing = (dir: string): string[] => (existsSync(dir) ? readdirSync(dir).sort() : []);
49
+
50
+ const entry = (dir: string, name: string): string => {
51
+ const path = join(dir, name);
52
+ return lstatSync(path).isSymbolicLink() ? `${name}->${readlinkSync(path)}` : name;
53
+ };
54
+
55
+ /**
56
+ * What `bun install` resolved, without reading every file: the root `node_modules` entries (one
57
+ * level into `@scope/`) with link targets, and the names in Bun's `.bun` store, which carry
58
+ * versions. Installs, upgrades and relinks change it.
59
+ */
60
+ export function nodeModulesFingerprint(root: string): string {
61
+ const nm = join(root, "node_modules");
62
+ if (!existsSync(nm)) return "absent";
63
+ const names = listing(nm).flatMap((name) =>
64
+ name.startsWith("@")
65
+ ? listing(join(nm, name)).map((inner) => `${name}/${entry(join(nm, name), inner)}`)
66
+ : [entry(nm, name)],
67
+ );
68
+ return sha([...names, "--", ...listing(join(nm, ".bun"))].join("\n"));
69
+ }
70
+
71
+ export interface StateInput {
72
+ context: string;
73
+ mode: string;
74
+ env: Record<string, string | undefined>;
75
+ today: string;
76
+ }
77
+
78
+ /** The key a pass is recorded under, or `undefined` when the tree cannot be read (so the run goes ahead). */
79
+ export function stateKey(root: string, git: Git, input: StateInput): string | undefined {
80
+ const tree = worktreeState(git, root);
81
+ if (tree === undefined) return undefined;
82
+ const parts = [
83
+ `tree=${tree}`,
84
+ `bun=${Bun.version}`,
85
+ `os=${process.platform}`,
86
+ `tz=${Intl.DateTimeFormat().resolvedOptions().timeZone}`,
87
+ `context=${input.context}`,
88
+ `mode=${input.mode}`,
89
+ `node_modules=${nodeModulesFingerprint(root)}`,
90
+ `dotenv=${sha(dotenvLines(root).join("\n"))}`,
91
+ `env=${sha(envLines(input.env).join("\0"))}`,
92
+ `date=${input.today}`,
93
+ ];
94
+ return sha(parts.join("\n")).slice(0, 32);
95
+ }
96
+
97
+ const passesPath = (git: Git): string | undefined => {
98
+ const dir = git.run(["rev-parse", "--path-format=absolute", "--git-dir"]);
99
+ return dir === undefined ? undefined : join(dir, PASSES_FILE);
100
+ };
101
+
102
+ /** Minutes since the newest pass under `key`, if it is younger than `maxAgeMs`. */
103
+ export function findPass(git: Git, key: string, now: Date, maxAgeMs: number): number | undefined {
104
+ const path = passesPath(git);
105
+ if (path === undefined || !existsSync(path)) return undefined;
106
+ const at = readFileSync(path, "utf8")
107
+ .split("\n")
108
+ .map((line) => line.split(" "))
109
+ .findLast(([k]) => k === key)?.[1];
110
+ const age = at === undefined ? Number.NaN : now.getTime() - Date.parse(at);
111
+ return age >= 0 && age <= maxAgeMs ? Math.floor(age / 60_000) : undefined;
112
+ }
113
+
114
+ /** Append a pass under `key`, keeping the newest {@link PASSES_KEPT}. */
115
+ export function recordPass(git: Git, key: string, now: Date): void {
116
+ const path = passesPath(git);
117
+ if (path === undefined) return;
118
+ const lines = existsSync(path) ? readFileSync(path, "utf8").split("\n").filter(Boolean) : [];
119
+ writeFileSync(path, `${[...lines, `${key} ${now.toISOString()}`].slice(-PASSES_KEPT).join("\n")}\n`);
120
+ }