simt-dev 0.7.0 → 0.8.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 (235) hide show
  1. package/CHANGELOG.md +191 -870
  2. package/README.md +188 -213
  3. package/bin/simt.mjs +19 -55
  4. package/docs/decisions/ADR-014-workspace-is-configuration.md +2 -2
  5. package/docs/decisions/ADR-025-a-baseline-is-a-region-in-a-file-the-repo-owns.md +1 -1
  6. package/docs/decisions/ADR-026-a-config-without-a-region-is-a-file-the-repo-owns.md +1 -1
  7. package/docs/decisions/ADR-027-the-one-gitattributes-line-that-is-neither-dangerous-nor-empty.md +1 -1
  8. package/docs/decisions/ADR-028-a-base-file-is-a-floor-so-the-disagreement-it-cannot-repair-becomes-a-check.md +1 -1
  9. package/docs/decisions/ADR-029-the-pins-a-repository-declares-are-its-own.md +1 -1
  10. package/docs/decisions/ADR-030-what-a-plan-does-not-ship-is-a-decision-with-a-record.md +1 -1
  11. package/docs/decisions/ADR-048-a-baseline-carries-only-keys-a-reader-honours.md +1 -1
  12. package/docs/decisions/ADR-082-the-tracker-override-is-a-manifest-key.md +1 -1
  13. package/docs/decisions/ADR-099-the-release-verifies-served-bytes-and-the-formula-mirrors-them.md +1 -1
  14. package/docs/decisions/ADR-117-the-darwin-release-builds-on-supported-macos-15-runners-and-a-re-run-is-idempotent.md +81 -0
  15. package/docs/decisions/ADR-118-the-bench-corpus-is-keyed-on-history-is-append-only-and-is-portable-as-a-sealed-document.md +91 -0
  16. package/docs/decisions/ADR-119-the-environment-variable-points-into-a-workspace-the-repo-declared.md +90 -0
  17. package/docs/decisions/ADR-120-a-pre-push-whose-tree-is-already-proven-green-skips-the-test-gate-on-that-evidence.md +96 -0
  18. package/docs/decisions/ADR-122-the-shims-move-into-the-state-directory-and-the-legacy-directory-removes-itself.md +94 -0
  19. package/docs/decisions/ADR-123-a-surplus-positional-is-not-refused-because-arity-is-not-in-the-source.md +57 -0
  20. package/docs/decisions/ADR-124-the-manifest-has-a-schema-in-the-tool-and-its-unknown-keys-stay-the-repositorys.md +64 -0
  21. package/docs/decisions/ADR-125-a-shared-context-belongs-to-a-read-and-a-writer-reads-directly.md +65 -0
  22. package/docs/decisions/ADR-126-the-mcp-surface-stays-a-reader-so-there-is-no-write-path-to-build.md +68 -0
  23. package/docs/decisions/ADR-127-the-mcp-tool-list-is-written-by-hand-and-roots-is-not-asked-for.md +65 -0
  24. package/docs/decisions/ADR-128-a-research-plan-is-a-plan-and-the-tracker-reads-it.md +42 -0
  25. package/ecosystems/bun.json +6 -0
  26. package/ecosystems/cargo.json +25 -0
  27. package/ecosystems/composer.json +6 -0
  28. package/ecosystems/dart.json +24 -0
  29. package/ecosystems/deno.json +21 -0
  30. package/ecosystems/devcontainers.json +6 -0
  31. package/ecosystems/docker-compose.json +6 -0
  32. package/ecosystems/docker.json +6 -0
  33. package/ecosystems/dotnet.json +25 -0
  34. package/ecosystems/elixir.json +23 -0
  35. package/ecosystems/gitsubmodule.json +6 -0
  36. package/ecosystems/go.json +25 -0
  37. package/ecosystems/gradle.json +13 -0
  38. package/ecosystems/maven.json +23 -0
  39. package/ecosystems/node.json +25 -0
  40. package/ecosystems/python.json +20 -0
  41. package/ecosystems/ruby.json +23 -0
  42. package/ecosystems/swift.json +25 -0
  43. package/ecosystems/terraform.json +6 -0
  44. package/ecosystems/uv.json +6 -0
  45. package/harnesses/antigravity.json +162 -0
  46. package/harnesses/claude.json +206 -0
  47. package/harnesses/codex.json +136 -0
  48. package/harnesses/copilot.json +88 -0
  49. package/harnesses/cursor.json +140 -0
  50. package/harnesses/deepseek.json +99 -0
  51. package/harnesses/gemini.json +122 -0
  52. package/harnesses/opencode.json +173 -0
  53. package/package.json +12 -2
  54. package/rules/core.md +7 -0
  55. package/rules/mdc/intake-questions.mdc +8 -0
  56. package/rules/mdc/slice-commit.mdc +57 -4
  57. package/src/advice/advice.mjs +3 -2
  58. package/src/agenthooks/prompt.mjs +5 -2
  59. package/src/agenthooks/render.mjs +86 -180
  60. package/src/agenthooks/shim.mjs +1 -1
  61. package/src/agents/render.mjs +15 -18
  62. package/src/api.mjs +31 -0
  63. package/src/argv.mjs +48 -3
  64. package/src/bench/ablate.mjs +3 -4
  65. package/src/bench/adapters.json +163 -105
  66. package/src/bench/adapters.mjs +466 -0
  67. package/src/bench/arms.mjs +333 -0
  68. package/src/bench/grade.mjs +33 -73
  69. package/src/bench/graders.mjs +42 -0
  70. package/src/bench/mine.mjs +121 -475
  71. package/src/bench/probe-ledger.mjs +149 -0
  72. package/src/bench/probes.catalog.mjs +918 -0
  73. package/src/bench/probes.mjs +79 -1064
  74. package/src/bench/render.mjs +111 -0
  75. package/src/bench/report.mjs +120 -962
  76. package/src/bench/run.mjs +185 -802
  77. package/src/bench/variants.mjs +4 -5
  78. package/src/bench/workspace.mjs +160 -0
  79. package/src/brief/assemble.mjs +48 -15
  80. package/src/ci/dependabot.mjs +25 -55
  81. package/src/ci/workflow.mjs +30 -7
  82. package/src/cli.mjs +45 -0
  83. package/src/commands/agent.mjs +4 -13
  84. package/src/commands/agenthook.mjs +70 -40
  85. package/src/commands/bench.mjs +191 -18
  86. package/src/commands/brief.mjs +5 -4
  87. package/src/commands/ci.mjs +13 -14
  88. package/src/commands/compare.mjs +42 -42
  89. package/src/commands/completions.mjs +2 -6
  90. package/src/commands/decide.mjs +4 -4
  91. package/src/commands/distill.mjs +4 -3
  92. package/src/commands/docs.mjs +88 -0
  93. package/src/commands/doctor.mjs +11 -7
  94. package/src/commands/evidence.mjs +6 -9
  95. package/src/commands/explain.mjs +0 -1
  96. package/src/commands/gate.mjs +26 -25
  97. package/src/commands/graph.mjs +2 -3
  98. package/src/commands/harness.mjs +6 -5
  99. package/src/commands/help.mjs +168 -19
  100. package/src/commands/hooks.mjs +119 -49
  101. package/src/commands/ignore.mjs +13 -8
  102. package/src/commands/impact.mjs +8 -15
  103. package/src/commands/index.mjs +318 -193
  104. package/src/commands/init-scan.mjs +90 -0
  105. package/src/commands/init.mjs +124 -105
  106. package/src/commands/lease.mjs +73 -25
  107. package/src/commands/lessons.mjs +10 -9
  108. package/src/commands/local.mjs +3 -3
  109. package/src/commands/map.mjs +24 -14
  110. package/src/commands/mcp.mjs +2 -18
  111. package/src/commands/pack.mjs +9 -6
  112. package/src/commands/plan.mjs +6 -5
  113. package/src/commands/plugin.mjs +2 -2
  114. package/src/commands/prbody.mjs +3 -3
  115. package/src/commands/repoindex.mjs +12 -11
  116. package/src/commands/review.mjs +2 -2
  117. package/src/commands/rules.mjs +37 -16
  118. package/src/commands/shared.mjs +14 -19
  119. package/src/commands/skills.mjs +33 -32
  120. package/src/commands/skillscompile.mjs +7 -8
  121. package/src/commands/skillsinstall.mjs +7 -6
  122. package/src/commands/slice.mjs +220 -74
  123. package/src/commands/spec.mjs +167 -0
  124. package/src/commands/status.mjs +27 -18
  125. package/src/commands/sync.mjs +27 -25
  126. package/src/commands/tests.mjs +18 -21
  127. package/src/commands/tokens.mjs +21 -26
  128. package/src/commands/undo.mjs +5 -15
  129. package/src/commands/upgrade.mjs +15 -7
  130. package/src/commands/why.mjs +15 -21
  131. package/src/compare/hooksstate.mjs +2 -6
  132. package/src/compare/learn.mjs +3 -1
  133. package/src/compare/row.mjs +0 -2
  134. package/src/context.mjs +64 -0
  135. package/src/decisions/index-doc.mjs +46 -0
  136. package/src/decisions/index.mjs +3 -2
  137. package/src/diff.mjs +1 -1
  138. package/src/distill/distill.mjs +14 -1
  139. package/src/distill/engine.mjs +5 -1
  140. package/src/docs/commands.mjs +65 -0
  141. package/src/ecosystem/records.mjs +219 -0
  142. package/src/explain.mjs +31 -0
  143. package/src/gates/index.mjs +385 -0
  144. package/src/graph/compile.mjs +8 -4
  145. package/src/graph/load.mjs +6 -2
  146. package/src/graph/spec.mjs +10 -8
  147. package/src/harness/records.mjs +143 -0
  148. package/src/hooks/capability.mjs +7 -5
  149. package/src/hooks/dispatcher.mjs +209 -60
  150. package/src/hooks/gates.mjs +10 -43
  151. package/src/hooks/resolve.mjs +4 -14
  152. package/src/hooks/shim.mjs +5 -2
  153. package/src/hooks/where.mjs +2 -7
  154. package/src/identity.mjs +31 -12
  155. package/src/index/coverage.mjs +58 -0
  156. package/src/index/extract.mjs +6 -16
  157. package/src/index/gate.mjs +1 -1
  158. package/src/index/govern.mjs +26 -9
  159. package/src/index/impact.mjs +4 -8
  160. package/src/index/map.mjs +14 -15
  161. package/src/index/open.mjs +173 -0
  162. package/src/index/persist.mjs +224 -57
  163. package/src/index/store.mjs +82 -39
  164. package/src/index/tests.mjs +2 -6
  165. package/src/journal.mjs +94 -20
  166. package/src/kernel/card.mjs +37 -63
  167. package/src/kernel/checks.mjs +4 -10
  168. package/src/lease.mjs +102 -7
  169. package/src/ledger/index.mjs +150 -14
  170. package/src/local/client.mjs +4 -6
  171. package/src/locate.mjs +33 -9
  172. package/src/manifest/schema.mjs +213 -0
  173. package/src/mcp/paginate.mjs +33 -0
  174. package/src/mcp/resources.mjs +7 -10
  175. package/src/mcp/schemas.mjs +512 -0
  176. package/src/mcp/server.mjs +119 -25
  177. package/src/mcp/tools-facts.mjs +326 -0
  178. package/src/mcp/tools-read.mjs +221 -0
  179. package/src/mcp/tools.mjs +4 -967
  180. package/src/measure/corpus.mjs +150 -0
  181. package/src/measure/metrics.mjs +236 -0
  182. package/src/measure/records.mjs +211 -0
  183. package/src/measure/session.mjs +3 -2
  184. package/src/measure/stats.mjs +538 -0
  185. package/src/measure/task-schema.mjs +125 -0
  186. package/src/measure/tasks.mjs +69 -0
  187. package/src/memory/decide.mjs +6 -15
  188. package/src/memory/lesson-text.mjs +61 -0
  189. package/src/memory/lessons.mjs +29 -82
  190. package/src/name.mjs +7 -0
  191. package/src/node-version.mjs +37 -0
  192. package/src/output/index.mjs +209 -10
  193. package/src/packs/manage.mjs +32 -12
  194. package/src/packs.mjs +20 -2
  195. package/src/plan/index.mjs +1 -1
  196. package/src/plugins.mjs +22 -16
  197. package/src/prbody.mjs +7 -11
  198. package/src/projection/loaders.mjs +7 -692
  199. package/src/projection/lock.mjs +11 -1
  200. package/src/projection/manifest.mjs +29 -468
  201. package/src/projection/mdc.mjs +7 -8
  202. package/src/projection/project.mjs +126 -221
  203. package/src/projection/region.mjs +561 -0
  204. package/src/projection/rules.mjs +20 -550
  205. package/src/projection/surfaces.mjs +43 -210
  206. package/src/projection/targets.mjs +5 -5
  207. package/src/repo-root.mjs +31 -0
  208. package/src/resolve/eval.mjs +2 -1
  209. package/src/resolve/fingerprint.mjs +19 -22
  210. package/src/resolve/resolve.mjs +1 -41
  211. package/src/review/critic.mjs +10 -13
  212. package/src/run.mjs +98 -0
  213. package/src/secrets.mjs +14 -22
  214. package/src/state/events.mjs +129 -0
  215. package/src/status-snapshot.mjs +233 -0
  216. package/src/status.mjs +2 -6
  217. package/src/sys/git.mjs +82 -0
  218. package/src/sys/proc.mjs +151 -0
  219. package/src/testing/parsers.mjs +265 -0
  220. package/src/testing/patches.mjs +23 -0
  221. package/src/testing/paths.mjs +49 -0
  222. package/src/testing/runners.mjs +186 -0
  223. package/src/testing/vault.mjs +68 -0
  224. package/src/text/frontmatter.mjs +49 -0
  225. package/src/text/tokens.mjs +52 -0
  226. package/src/toolwords.mjs +3 -0
  227. package/src/util/fs.mjs +20 -0
  228. package/src/util/sort.mjs +12 -0
  229. package/src/workspace.mjs +58 -11
  230. package/src/write/plan.mjs +82 -0
  231. package/templates/plan/tracker.json +1 -0
  232. package/docs/decisions/ADR-033-three-plan-rows-closed-by-decision-not-by-authoring.md +0 -82
  233. package/docs/decisions/ADR-102-the-two-queued-review-rows-are-closed-by-ruling.md +0 -49
  234. package/docs/decisions/README.md +0 -600
  235. package/src/bench/tasks.mjs +0 -36
@@ -0,0 +1,561 @@
1
+ // The desired region, in one place, so `plan` and `check` cannot disagree.
2
+ //
3
+ // Moved out of rules.mjs when that module crossed the ceiling. The projection it
4
+ // computes is one answer with one caller contract: `sync` writes it, `check` compares
5
+ // it, and a second copy of it would report drift on a tree `sync` had just written.
6
+
7
+ import { readFile, readdir } from 'node:fs/promises';
8
+ import { createHash } from 'node:crypto';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { dirname, join, resolve } from 'node:path';
11
+
12
+ import { fingerprint, KNOWN_TAGS } from '../resolve/fingerprint.mjs';
13
+ import { loadMdcRules, renderMdc } from './mdc.mjs';
14
+ import { foldsRules, resolveSurfaces, rulePath, canScope } from './surfaces.mjs';
15
+ import { ruleTargets } from './targets.mjs';
16
+ import { compose } from './markers.mjs';
17
+ import { declaredBudget, declaredShared, readManifest } from './manifest.mjs';
18
+ import { loadManifest } from '../manifest/schema.mjs';
19
+ import { commandCard, CARD_LIMIT_BYTES } from '../kernel/card.mjs';
20
+ import { packToBudget } from '../kernel/budget.mjs';
21
+ import { filterInferable, inferableDefect, inferableProofs } from '../kernel/inferability.mjs';
22
+ import { checkDefect, foldChecks } from '../kernel/checks.mjs';
23
+ import { foldVariants, readLockedVariants, variantsDefect } from '../kernel/variants.mjs';
24
+ import { BASELINES } from './baselines.mjs';
25
+ import { CLI, MANIFEST_FILE } from '../name.mjs';
26
+ import { installedSkills } from './disclosure.mjs';
27
+ import { PACK_DIR, resolvePacks } from '../packs.mjs';
28
+ import { discoverPackages } from '../monorepo.mjs';
29
+ import { KERNEL_CLASSES, ORIENTATION_POINTER, byPriorityThenId, crossRefProblems, frameSource, inferableEvidence, loadRules, mdcTargets, projectionMode, provenanceDigest, render, ruleBodies, select, sourceTitle, stableOrder, stripFrontmatter, toolRule } from './rules.mjs';
30
+
31
+ export async function desiredRegion(root, flags) {
32
+ const { stack, facts, manifest } = await fingerprint(root);
33
+ const lockedVariants =
34
+ flags?.variants !== undefined ? flags.variants : await readLockedVariants(root);
35
+ const all = await loadRules(root);
36
+ const { selected, fallback, notes } = select(all, stack, facts);
37
+ const { resolved, bodies, problems, notes: ruleNotes } = await ruleBodies(
38
+ root,
39
+ manifest,
40
+ { ...(flags ?? {}), variants: lockedVariants },
41
+ );
42
+ notes.push(...ruleNotes);
43
+
44
+ // A profile that declares a scope leaves the region only when every selected surface
45
+ // can load it narrowly. The alternative is a profile written only as a scoped file for
46
+ // a reader whose surface cannot scope — a rule nobody loads, which is worse than one
47
+ // that loads eagerly (ADR-071). A surface that cannot scope it therefore keeps the
48
+ // profile in the region and says so, rather than letting the region quietly shrink.
49
+ const narrowing = resolved.surfaces.every((s) => canScope(s));
50
+ const scoped = [];
51
+ const inRegion = [];
52
+ for (const r of selected) {
53
+ const declares = Array.isArray(r.scope) && r.scope.length > 0 && r.error === null;
54
+ if (!declares) {
55
+ inRegion.push(r);
56
+ continue;
57
+ }
58
+ // A profile only leaves the region when a narrowed file can replace it. When any
59
+ // selected surface cannot narrow, the file would be the only home for a rule that
60
+ // reader cannot reach — so it stays, and says why.
61
+ if (narrowing) {
62
+ const vf = foldVariants(r.body, r.id ?? '', lockedVariants);
63
+ scoped.push(vf.changed ? { ...r, body: vf.body } : r);
64
+ continue;
65
+ }
66
+ inRegion.push(r);
67
+ notes.push(
68
+ `${r.id} declares simt-scope, but ${resolved.source} selects a surface that cannot narrow a rule, so it stays in the region`,
69
+ );
70
+ }
71
+
72
+ // The kernel. In `kernel` mode only the hard and command classes are packed into the
73
+ // region and every other rule is deferred to `rules show <id>`, which is what makes
74
+ // R08's accept criterion reachable at all: a budget cannot be met by a projection that
75
+ // never tries. `full` is the default and stays it until R02 has measured that a
76
+ // kernel does not lose compliance, because nobody has measured it yet.
77
+ //
78
+ // A rule with no stated class is deferred, not packed. The two mistakes are not
79
+ // symmetric: packing a line that should have been deferred spends the budget the mode
80
+ // exists to save, while deferring a line that should have been packed costs a reader
81
+ // one `rules show`. The mode is a promise about bytes, so it is the bytes that win.
82
+ // An explicit `mode` flag overrides the declared one. The caller is the MCP
83
+ // `simt://kernel` resource, which by name promises the kernel's bytes for any
84
+ // repository: the declared mode governs what `sync` writes to disk, not what a read
85
+ // path may look at, so the read renders in the mode the URI names instead of
86
+ // re-reading a manifest it must not obey (ADR-002).
87
+ const mode = typeof flags?.mode === 'string' ? flags.mode : await projectionMode(root);
88
+ const packed = [];
89
+ const deferred = [];
90
+ for (const r of inRegion) {
91
+ if (mode === 'kernel' && (r.error !== null || !KERNEL_CLASSES.has(r.priority))) deferred.push(r);
92
+ else packed.push(r);
93
+ }
94
+ // The command card leads the region. The exact commands for this repository are the
95
+ // bytes a reader cannot infer from rules that are identical everywhere (plan 0003 R10),
96
+ // so they go first — above even the core rules. It is derived from committed evidence
97
+ // only, in one place, so `plan` and `checkTarget` cannot disagree about it and two
98
+ // machines render it byte-identically.
99
+ const { card, proofs } = await inferableEvidence(root, { stack, facts, manifest });
100
+ if (card.dropped.length > 0) {
101
+ // Reported where every other projection note is reported. A card that lost a command
102
+ // in silence is a card a reader cannot tell is incomplete.
103
+ notes.push(
104
+ `command card: dropped ${card.dropped.join(', ')} to stay within ${CARD_LIMIT_BYTES} bytes`,
105
+ );
106
+ }
107
+ // Inferability (R09). A marked line leaves when the repository proves the evidence it
108
+ // names. `shipped` is a separate list from `packed` because they are separate decisions:
109
+ // the kernel is about which classes cost a reader nothing to skip, and this is about
110
+ // which lines the reader already knows.
111
+ const inferable = [];
112
+ const shipped = [];
113
+ const variantsSelected = [];
114
+ let enforced = 0;
115
+ for (const r of packed) {
116
+ const variantFolded = foldVariants(r.body, r.id ?? '', lockedVariants);
117
+ const filtered = filterInferable(variantFolded.body, proofs);
118
+ const folded = foldChecks(filtered.body);
119
+ enforced += folded.enforced.length;
120
+ variantsSelected.push(...variantFolded.selected);
121
+ if (!variantFolded.changed && !filtered.changed && !folded.changed) {
122
+ shipped.push(r);
123
+ continue;
124
+ }
125
+ for (const x of filtered.removed) inferable.push({ rule: r.id, text: x.text, expr: x.expr });
126
+ shipped.push({ ...r, body: folded.body });
127
+ }
128
+ // A body that points the reader at a profile they cannot reach is a rule-text defect:
129
+ // the region renders, but the reference dangles. Kept out of `problems` because that
130
+ // array is the mdc list `sync` already reports, and one fault must not print twice.
131
+ const crossRefs = [];
132
+ const selectedIds = new Set(selected.map((r) => r.id));
133
+ for (const r of shipped) {
134
+ for (const p of crossRefProblems(r.body, all, selectedIds)) {
135
+ crossRefs.push(`${r.id}: ${p}`);
136
+ }
137
+ }
138
+ const lockedNonDefault = variantsSelected.filter((v) => v.locked && v.winner !== v.baseline);
139
+ if (lockedNonDefault.length > 0) {
140
+ notes.push(
141
+ `variants: applied ${lockedNonDefault.length} locked variant(s) (${lockedNonDefault.map((v) => `${v.slotId}=${v.winner}`).join(', ')})`,
142
+ );
143
+ }
144
+ if (enforced > 0) {
145
+ notes.push(
146
+ `enforced: ${enforced} line(s) left the region because a checker runs them`,
147
+ );
148
+ }
149
+ if (inferable.length > 0) {
150
+ // Never silent, and never a heading. A line that left with no trace repeats the
151
+ // mistake ADR-073 rejected for deferred rules, and a `## Dropped` section spends region
152
+ // bytes on lines the reader is being told not to read. A count they can act on, plus —
153
+ // with `--explain` — the evidence behind each one, is the third option.
154
+ notes.push(
155
+ `inferability: dropped ${inferable.length} line(s) this repository already proves; ${CLI} sync --explain names each one and the evidence behind it`,
156
+ );
157
+ if (flags?.explain === true) {
158
+ for (const x of inferable) {
159
+ notes.push(`inferable: ${x.rule} dropped "${x.text}" — proved by ${x.expr}`);
160
+ }
161
+ }
162
+ }
163
+ const folded = foldsRules(resolved) ? bodies.map(({ rule }) => rule.id) : [];
164
+
165
+ // The workspace-shared rules this repository declared (ADR-084).
166
+ //
167
+ // Read from the manifest and never from the reader's home directory, because this
168
+ // function is what `sync` and `check` both call: a region that depended on what
169
+ // somebody had installed would render differently on a machine where they had not,
170
+ // and CI would report drift on a tree `sync` had just written. The ids travel in the
171
+ // manifest so the answer to "what leaves this region" is a fact about the repository.
172
+ const declared = declaredShared(manifest);
173
+ const carriedIds = new Set(declared.level === null ? [] : [...declared.rules]);
174
+
175
+ // Every rule the workspace carries, as the rule objects the index below names. Both
176
+ // lists, because a surface that folds its rules into the primary document carries the
177
+ // canonical process bodies in that document too — and a reader who cannot find
178
+ // `slice-commit` anywhere near their repository will look for it in AGENTS.md.
179
+ const carried = [
180
+ ...shipped.filter((r) => carriedIds.has(r.id)).map((rule) => ({ rule, kind: 'profile' })),
181
+ ...bodies.filter(({ rule }) => carriedIds.has(rule.id)).map(({ rule }) => ({ rule, kind: 'process' })),
182
+ ];
183
+
184
+ // The rules this root would carry in its region, with the bytes it would carry them
185
+ // in — the input ADR-084's workspace intersection compares.
186
+ //
187
+ // Computed from `shipped` rather than from what the region ends up carrying, and that
188
+ // is the whole reason it is computed at all: a rule already declared shared must still
189
+ // appear here, or a second `shared install` would intersect against a list that no
190
+ // longer contained it and shrink the shared file every time anybody ran the command.
191
+ // The declaration is an input to the region; it is not an input to what is shareable.
192
+ const shareable = [
193
+ // Only the rules this package ships. A repository's own profile, or a pack it
194
+ // installed, is policy somebody chose to write: carrying it into a shared home file
195
+ // would mean editing that file to change a repository's rules, and the copy would
196
+ // reach every other repository in the estate that declared the same id. A rule
197
+ // somebody can override must stay somewhere they own.
198
+ ...shipped
199
+ .filter((r) => r.error === null && toolRule(r) && typeof r.id === 'string' && r.id !== '')
200
+ .map((r) => ({
201
+ id: r.id,
202
+ source: r.source,
203
+ priority: r.priority ?? null,
204
+ rendered: frameSource(r, stripFrontmatter(r.body).trim(), 'profile'),
205
+ })),
206
+ // The folded process bodies, and only while they are folded. A surface that writes
207
+ // one file per rule expects that file at a path inside the repository, so a
208
+ // user-level copy cannot stand in for it — but when the surface folds the whole region
209
+ // into the primary document, those bytes are as repeated across a workspace as the
210
+ // profiles are, and `tokens --repos` named them as the last duplicate block in a
211
+ // two-repository measurement.
212
+ ...bodies
213
+ .filter(({ rule }) => folded.includes(rule.id) && toolRule(rule))
214
+ .map(({ rule, body }) => ({
215
+ id: rule.id,
216
+ source: rule.source,
217
+ priority: rule.priority ?? null,
218
+ rendered: frameSource(rule, body, 'process'),
219
+ })),
220
+ ].filter((r) => r.rendered !== '');
221
+
222
+ // The selected rules that are not shareable, with the reason. `shared plan` reporting
223
+ // only what it carries would imply every profile in the workspace had been accounted
224
+ // for, and a reader whose own house rule is missing from the list would conclude it
225
+ // moved — so the names it did not take, and why, are data rather than an omission.
226
+ const shareableIds = new Set(shareable.map((r) => r.id));
227
+ const excluded = selected
228
+ .filter((r) => typeof r.id === 'string' && r.id !== '' && !shareableIds.has(r.id))
229
+ .map((r) => ({
230
+ id: r.id,
231
+ why: r.error !== null ? 'error' : toolRule(r) ? 'empty' : 'policy',
232
+ }));
233
+
234
+ // The budget, and the bytes held back for what loads beside the region.
235
+ //
236
+ // Read from the manifest rather than from the plan's spelling of it. Plan 0003 R08
237
+ // wrote `projection.budget.bytes`, and ADR-072 moved the key to the top level because
238
+ // `projection` is a generated key `upgrade` replaces wholesale - a budget that reset
239
+ // itself on upgrade would reset the reader's context size without anyone asking. The
240
+ // plan is not edited: the key it names is wrong, and a ruling that supersedes it is
241
+ // the record of why.
242
+ const budget = declaredBudget(manifest);
243
+ // Names and triggers only. Read once, outside the packer, because a skill does not
244
+ // change as rules are cut and reading its body here would put the cost back into the
245
+ // region the index exists to keep it out of (ADR-085).
246
+ const skills = await installedSkills(root);
247
+
248
+ // The digest is needed before the region can be weighed rather than after, because the
249
+ // provenance header is part of what lands in the file. `provenanceDigest` is a pure
250
+ // function of the bytes this package ships, so computing it once and passing it down is
251
+ // the same value the tail of this function was getting on its own.
252
+ const sha = await provenanceDigest();
253
+
254
+ /**
255
+ * The region, assembled from whatever survived the budget (ADR-083).
256
+ *
257
+ * One function, called once for the whole projection and again for each attempt the
258
+ * packer makes, so a cut region and an uncut one are the same document by construction
259
+ * rather than by two functions agreeing. The card, the inferability notes, the folded
260
+ * process bodies and the disclosure index are not candidates for a cut: a budget is a
261
+ * decision about rules, and dropping the index would hide the rules the cut removed.
262
+ */
263
+ const assemble = (cut) => {
264
+ // A rule the workspace carries once leaves the region, and so does a rule the packer
265
+ // could not afford. Both are exclusions from the same list, so the section below can
266
+ // name all three reasons — which is the only reason the section exists: a reader who
267
+ // opens AGENTS.md and does not find a rule they know is there will look for it.
268
+ const kept = shipped.filter((r) => !cut.has(r.id) && !carriedIds.has(r.id));
269
+ // Stable bytes first (ADR-086). Core, then the profiles this package ships, then
270
+ // everything this repository added — the card, its own profiles, the process
271
+ // bodies. A line the repository edits then changes only the tail, and the prefix
272
+ // a reader has cached stays byte-identical. The card used to lead (ADR-077 ruling
273
+ // 1); it now leads the tail, because a command this repository owns is the thing
274
+ // an edit is most likely to move.
275
+ const stable = kept.filter((r) => toolRule(r)).sort(stableOrder);
276
+ const repoRules = kept.filter((r) => !toolRule(r)).sort((a, b) => String(a.id).localeCompare(String(b.id)));
277
+ let text = render(stable);
278
+ if (card.text) text += `${text === '' ? '' : '\n\n'}${card.text}`;
279
+ // The pointer follows the card: the card says what this repository runs, and the
280
+ // pointer says how the tool serves a task. Adjacent, they read as one block of
281
+ // repo-facing advice instead of two facts the reader has to connect.
282
+ text += `${text === '' ? '' : '\n\n'}${ORIENTATION_POINTER}`;
283
+ const repoText = render(repoRules);
284
+ if (repoText) text += `\n\n${repoText}`;
285
+ const sources = [...stable, ...repoRules].map((r) => r.source);
286
+
287
+ // Every reason a rule is missing lands in this one section, and each line says which
288
+ // it was. A rule deferred by its class, a rule cut to reach a byte count and a rule
289
+ // the workspace carries once are three different decisions, but they are the same fact
290
+ // to a reader — it is not in this file — and three headings would spend region bytes
291
+ // on structure nobody can act on. The line names the command that shows the rule,
292
+ // because for all three the remedy is the same single read.
293
+ //
294
+ // The label is the rule's own frame title, which is why each entry carries the kind it
295
+ // is rendered as: a canonical rule that the surface folds in is `Process: <id>` in the
296
+ // shared file, and an index that calls it `Stack:` sends the reader looking for the
297
+ // wrong thing.
298
+ const omitted = [
299
+ ...deferred.map((r) => ({ rule: r, kind: 'profile', why: `${r.priority ?? 'unclassified'}, deferred in kernel mode` })),
300
+ ...shipped
301
+ .filter((r) => cut.has(r.id))
302
+ .map((r) => ({
303
+ rule: r,
304
+ kind: 'profile',
305
+ why: `${r.priority ?? 'unclassified'}, cut to fit the declared budget of ${budget} bytes`,
306
+ })),
307
+ ...carried.map(({ rule, kind }) => ({
308
+ rule,
309
+ kind,
310
+ // No path here, deliberately. This text is rendered by `sync` in CI, where the
311
+ // reader's home directory is somebody else's, and a path is the one thing in a
312
+ // remedy that cannot be true on both. The remedy is a command that works on the
313
+ // machine the reader is on.
314
+ why: `${rule.priority ?? 'unclassified'}, carried once per workspace in your reader's user-level rules file instead; if your reader has no copy, run: ${CLI} shared install`,
315
+ })),
316
+ ];
317
+ if (omitted.length > 0) {
318
+ // The pointer is the same shape as the scoped one above, and for the same reason:
319
+ // a reader who opens AGENTS.md and does not find a rule they know is there will
320
+ // look for it. What it costs to find it has to be one command, named per rule.
321
+ const lines = omitted
322
+ .sort((a, b) => byPriorityThenId(a.rule, b.rule))
323
+ .map(
324
+ ({ rule, kind, why }) =>
325
+ `- ${sourceTitle(rule, kind)} — ${why}. Show it with: ${CLI} rules show ${rule.id}`,
326
+ );
327
+ // `## Rules not in this region`, not `## Deferred rules`. The heading was written
328
+ // when there was one reason to be here (ADR-073) and it is region text a reader
329
+ // reads, so a heading that names one of three reasons misdescribes the two others
330
+ // (ADR-084).
331
+ text += `\n\n## Rules not in this region\n\n${lines.join('\n')}`;
332
+ for (const { rule } of omitted) sources.push(rule.source);
333
+ }
334
+
335
+ if (folded.length > 0) {
336
+ for (const { rule, body: ruleBody } of bodies) {
337
+ // A body the workspace carries once is not folded in here either. The heading is
338
+ // about how the surface loads the region, so it stays; the rule under it does not,
339
+ // and a region that carried the same bytes twice is the redundancy ADR-084 exists
340
+ // to remove — reintroduced by the feature that removes it.
341
+ if (carriedIds.has(rule.id)) continue;
342
+ // `## Process:`, not `### id`. The body already uses `##`, and a third-level
343
+ // heading in front of a second-level one is the break a reader cannot repair.
344
+ text += `\n\n${frameSource(rule, ruleBody, 'process')}`;
345
+ sources.push(rule.source);
346
+ }
347
+ }
348
+
349
+ // Last, because this is the index of what the file deliberately does not contain
350
+ // (ADR-085). A scoped profile keeps the pointer ADR-071 requires — its patterns and
351
+ // the files it moved to — and a skill keeps its name and the description that says
352
+ // when to open it. The body of either is the thing that was moved out.
353
+ const disclosure = [];
354
+ if (scoped.length > 0 && narrowing) {
355
+ for (const r of scoped) {
356
+ disclosure.push(
357
+ `- ${sourceTitle(r, 'profile')} — loads only when a matching file is in play (${r.scope.join(', ')}): ${scopedPaths(r, resolved).join(', ')}`,
358
+ );
359
+ sources.push(r.source);
360
+ }
361
+ }
362
+ const skillNames = new Map();
363
+ for (const skill of skills) skillNames.set(skill.name, (skillNames.get(skill.name) ?? 0) + 1);
364
+ for (const skill of skills) {
365
+ const label = skillNames.get(skill.name) > 1 ? `${skill.name} (${skill.dir})` : skill.name;
366
+ disclosure.push(
367
+ skill.trigger === ''
368
+ ? `- ${label} — no description, so nothing says when to open it. Show it with: ${CLI} skills show ${skill.name}`
369
+ : `- ${label} — ${skill.trigger}`,
370
+ );
371
+ }
372
+ if (disclosure.length > 0) text += `\n\n## Disclosure\n\n${disclosure.join('\n')}`;
373
+
374
+ return { body: text, sources };
375
+ };
376
+
377
+ // What the region will weigh in the file it lands in, measured the way the meter
378
+ // measures it: the composed region text, markers and provenance header included. One
379
+ // byte conservative, because the file's own trailing newline falls outside the span —
380
+ // and conservative in that direction is the only direction a ceiling can afford.
381
+ const regionBytes = (assembled) =>
382
+ Buffer.byteLength(compose(assembled.body, { sha, sources: assembled.sources }));
383
+
384
+ let assembled = assemble(new Set());
385
+ let packing = null;
386
+ if (mode === 'kernel') {
387
+ const reserve = await budgetReserve(root, resolved, bodies, sha);
388
+ const result = packToBudget({
389
+ // Least valuable first: the comparator the deferred section already uses, reversed.
390
+ // Class decides and the id breaks the tie, so the cut order is a fact about the
391
+ // repository rather than about the order the filesystem listed files in.
392
+ //
393
+ // The workspace-shared rules are not candidates, and that is not a rounding: cutting
394
+ // one cannot make the region smaller by more than the index line it adds to the
395
+ // section below, because the rule is carried once per workspace whatever this region
396
+ // does. A packer that spent its budget on them would report a saving it did not make.
397
+ candidates: shipped
398
+ .filter((r) => !carriedIds.has(r.id))
399
+ .sort((a, b) => -byPriorityThenId(a, b)),
400
+ ceiling: budget - reserve,
401
+ costs: (cut) => regionBytes(assemble(cut)),
402
+ });
403
+ packing = { ...result, bytes: budget, ceiling: budget - reserve, reserve };
404
+ if (result.cut.length > 0) assembled = assemble(new Set(result.cut));
405
+ if (result.cut.length > 0) {
406
+ notes.push(
407
+ `budget: cut ${result.cut.length} kernel rule(s) — ${result.cut.join(', ')} — from ${result.before} to ${result.after} bytes against a declared budget of ${budget}, with ${reserve} reserved for the generated files that load beside the region`,
408
+ );
409
+ }
410
+ if (result.floorHeld) {
411
+ // The one case the packer cannot fix, said where the reader will see it. `hard` is
412
+ // the floor, so the bytes still over the line are this repository's own hard
413
+ // constraints and the only levers left are its own: a larger budget, or a rule that
414
+ // is not as hard as it is declared. ADR-072's kernel finding says both; this says
415
+ // they were tried first.
416
+ notes.push(
417
+ `budget: still ${result.after} bytes after every rule outside the hard class was cut, against a ceiling of ${budget - reserve}; a hard constraint is not cut to reach a byte count, so the kernel itself is over the line`,
418
+ );
419
+ }
420
+ if (result.floorHeld && reserve >= budget) {
421
+ // A ceiling of zero or less is arithmetically true and useless to read: it says the
422
+ // region is allowed no bytes, without saying that the files loading beside it have
423
+ // already spent the whole budget. One number in that manifest is the only lever, and
424
+ // a reader left to infer it from a subtraction is a reader who will demote a hard
425
+ // rule to fix a budget that was set below the files it covers.
426
+ notes.push(
427
+ `budget: the ${reserve} bytes reserved for the generated files that load beside the region already reach the ${budget} declared, so no cut order meets this budget and the region is cut as far as the hard class allows`,
428
+ );
429
+ }
430
+ }
431
+
432
+ const meta = {
433
+ sha,
434
+ sources: assembled.sources,
435
+ };
436
+ return {
437
+ stack,
438
+ facts,
439
+ manifest,
440
+ all,
441
+ profiles: selected.map((r) => r.id),
442
+ folded,
443
+ mode,
444
+ deferred: deferred.map((r) => r.id),
445
+ // What the workspace carries once per reader instead of here (ADR-084), as ids. The
446
+ // declaration is what `check` and `sync` both read to decide the region, so the ids
447
+ // that actually left are reported for the same reason the budget's cuts are: a rule
448
+ // that disappeared needs a name in the output, or a reader looks for it in vain.
449
+ carried: carried.map(({ rule }) => rule.id),
450
+ // What this root could contribute to a workspace's shared file, with the bytes it
451
+ // would contribute. Read by `simt shared`, never by the projection — which is why
452
+ // computing it costs a frame per rule and buys nothing on `sync`.
453
+ shareable,
454
+ // What it selected and cannot contribute, with the reason. Reported so that a rule
455
+ // staying in the region is always a decision somebody can see rather than an absence.
456
+ excluded,
457
+ // What the budget cost this projection (ADR-083), or null in `full` mode where no
458
+ // ceiling is applied because nothing is cut. The finding and `simt tokens` both read
459
+ // this rather than re-deriving it, so a cut cannot be reported one way and measured
460
+ // another.
461
+ budget: packing === null
462
+ ? null
463
+ : {
464
+ bytes: packing.bytes,
465
+ ceiling: packing.ceiling,
466
+ reserve: packing.reserve,
467
+ before: packing.before,
468
+ after: packing.after,
469
+ floorHeld: packing.floorHeld,
470
+ cuts: shipped
471
+ .filter((r) => packing.cut.includes(r.id))
472
+ .map((r) => ({ id: r.id, priority: r.priority ?? 'unclassified' })),
473
+ },
474
+ // The marked lines that left, each with the evidence that dropped it. The region is
475
+ // written without them; `--explain` is what reads this list, so a removal is reportable
476
+ // without spending region bytes and without a second computation to find it.
477
+ inferable,
478
+ // The profiles that left the region, and the surfaces that accepted them as files.
479
+ // `plan` writes them and `checkTarget` gates them through this list, so a projected
480
+ // file and a drifted one are decided by the same computation.
481
+ scoped,
482
+ narrowing,
483
+ surfaces: resolved.ids,
484
+ surfaceSource: resolved.source,
485
+ problems,
486
+ crossRefs,
487
+ fallback,
488
+ notes,
489
+ body: assembled.body,
490
+ meta,
491
+ };
492
+ }
493
+
494
+ /**
495
+ * The bytes held back from the region's own ceiling for the always-on files that load
496
+ * beside it.
497
+ *
498
+ * The budget is one number for a repository, not for one file, so packing the region
499
+ * against the whole number would ship a projection that fits on its own and pushes the
500
+ * total over the line the moment its rule files are written. Both terms below are lower
501
+ * bounds on what that costs, and the larger is taken because the failure each one covers
502
+ * is the one that must not happen: under-reserving reports compliance for a projection
503
+ * that is over budget.
504
+ *
505
+ * The region's own span is deliberately not in either. It is the one number that moves
506
+ * when this projection is packed, and a ceiling that depended on the thing it governs
507
+ * would rewrite the region on the next run and report drift on a tree `sync` had just
508
+ * written - the step-6 defect, rebuilt one layer up.
509
+ *
510
+ * @param {string} root
511
+ * @param {object} resolved the surfaces this projection writes for
512
+ * @param {{rule: object, body: string}[]} bodies the rule bodies being projected
513
+ * @param {string} sha the provenance digest those files will be stamped with
514
+ * @returns {Promise<number>}
515
+ */
516
+ async function budgetReserve(root, resolved, bodies, sha) {
517
+ // Imported here rather than at the top of the module: `measure/context.mjs` reaches back
518
+ // into `projection/project.mjs` for the read-limit findings, so a static import from
519
+ // `rules.mjs` closes a loop through three modules that all have to survive being loaded
520
+ // in any order. The loop between the other two already exists and is load-bearing in
521
+ // neither direction; this one is walked only when a kernel is being packed.
522
+ const { measureRoot } = await import('../measure/context.mjs');
523
+ const measured = await measureRoot(root);
524
+ const region = measured.documents.find((d) => d.channel === 'region');
525
+ const installed = Math.max(0, measured.generatedBytes - (region?.generatedBytes ?? 0));
526
+
527
+ // What this projection is about to write, for a repository that has not written it yet.
528
+ // `ruleTargets` is the one place a rule file is turned into bytes, so the number comes
529
+ // from there rather than from a second measurement of the same file — and its notes go
530
+ // nowhere, because `mdcTargets` reports the same ones for the same files in the same run.
531
+ let planned = 0;
532
+ for (const { rule, body } of bodies) {
533
+ for (const target of (await ruleTargets(root, rule, body, sha, resolved, [])).targets) {
534
+ planned += target.bytes;
535
+ }
536
+ }
537
+ return Math.max(installed, planned);
538
+ }
539
+
540
+ /**
541
+ * Every per-rule file a scoped profile is written to, as paths a reader can open.
542
+ *
543
+ * Only the surfaces that can scope get one: a Cursor `.mdc` with `globs` and
544
+ * `alwaysApply: false`, an Antigravity file with `trigger: glob`, a Copilot
545
+ * `.instructions.md` with `applyTo`. A surface that reads the region already (opencode)
546
+ * has no file channel at all, and Claude's scoping key is the documented-defect one,
547
+ * so neither appears here.
548
+ */
549
+ function scopedPaths(rule, resolved) {
550
+ const out = [];
551
+ for (const s of resolved.surfaces) {
552
+ if (!canScope(s) || !s.rule) continue;
553
+ // A folded surface already carries the whole region; it is the reason this profile
554
+ // is only a file when folding is off, which is the caller's question to answer.
555
+ if (s.foldRules === true && s.readsPrimary === true && foldsRules(resolved)) continue;
556
+ out.push(rulePath(s.id, rule.id));
557
+ }
558
+ return out;
559
+ }
560
+
561
+