simt-dev 0.7.1 → 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 (186) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +169 -80
  3. package/docs/decisions/ADR-014-workspace-is-configuration.md +1 -1
  4. package/docs/decisions/ADR-025-a-baseline-is-a-region-in-a-file-the-repo-owns.md +1 -1
  5. package/docs/decisions/ADR-026-a-config-without-a-region-is-a-file-the-repo-owns.md +1 -1
  6. package/docs/decisions/ADR-027-the-one-gitattributes-line-that-is-neither-dangerous-nor-empty.md +1 -1
  7. package/docs/decisions/ADR-028-a-base-file-is-a-floor-so-the-disagreement-it-cannot-repair-becomes-a-check.md +1 -1
  8. package/docs/decisions/ADR-029-the-pins-a-repository-declares-are-its-own.md +1 -1
  9. package/docs/decisions/ADR-030-what-a-plan-does-not-ship-is-a-decision-with-a-record.md +1 -1
  10. package/docs/decisions/ADR-048-a-baseline-carries-only-keys-a-reader-honours.md +1 -1
  11. package/docs/decisions/ADR-082-the-tracker-override-is-a-manifest-key.md +1 -1
  12. package/docs/decisions/ADR-126-the-mcp-surface-stays-a-reader-so-there-is-no-write-path-to-build.md +68 -0
  13. package/docs/decisions/ADR-127-the-mcp-tool-list-is-written-by-hand-and-roots-is-not-asked-for.md +65 -0
  14. package/docs/decisions/ADR-128-a-research-plan-is-a-plan-and-the-tracker-reads-it.md +42 -0
  15. package/ecosystems/bun.json +6 -0
  16. package/ecosystems/cargo.json +25 -0
  17. package/ecosystems/composer.json +6 -0
  18. package/ecosystems/dart.json +24 -0
  19. package/ecosystems/deno.json +21 -0
  20. package/ecosystems/devcontainers.json +6 -0
  21. package/ecosystems/docker-compose.json +6 -0
  22. package/ecosystems/docker.json +6 -0
  23. package/ecosystems/dotnet.json +25 -0
  24. package/ecosystems/elixir.json +23 -0
  25. package/ecosystems/gitsubmodule.json +6 -0
  26. package/ecosystems/go.json +25 -0
  27. package/ecosystems/gradle.json +13 -0
  28. package/ecosystems/maven.json +23 -0
  29. package/ecosystems/node.json +25 -0
  30. package/ecosystems/python.json +20 -0
  31. package/ecosystems/ruby.json +23 -0
  32. package/ecosystems/swift.json +25 -0
  33. package/ecosystems/terraform.json +6 -0
  34. package/ecosystems/uv.json +6 -0
  35. package/harnesses/antigravity.json +162 -0
  36. package/harnesses/claude.json +206 -0
  37. package/harnesses/codex.json +136 -0
  38. package/harnesses/copilot.json +88 -0
  39. package/harnesses/cursor.json +140 -0
  40. package/harnesses/deepseek.json +99 -0
  41. package/harnesses/gemini.json +122 -0
  42. package/harnesses/opencode.json +173 -0
  43. package/package.json +3 -1
  44. package/rules/mdc/intake-questions.mdc +8 -0
  45. package/src/advice/advice.mjs +3 -2
  46. package/src/agenthooks/render.mjs +86 -180
  47. package/src/agents/render.mjs +15 -18
  48. package/src/api.mjs +7 -5
  49. package/src/argv.mjs +19 -0
  50. package/src/bench/ablate.mjs +3 -4
  51. package/src/bench/adapters.json +155 -113
  52. package/src/bench/adapters.mjs +466 -0
  53. package/src/bench/arms.mjs +333 -0
  54. package/src/bench/grade.mjs +12 -26
  55. package/src/bench/graders.mjs +42 -0
  56. package/src/bench/mine.mjs +17 -535
  57. package/src/bench/probe-ledger.mjs +149 -0
  58. package/src/bench/probes.catalog.mjs +918 -0
  59. package/src/bench/probes.mjs +15 -1037
  60. package/src/bench/render.mjs +111 -0
  61. package/src/bench/report.mjs +116 -971
  62. package/src/bench/run.mjs +164 -881
  63. package/src/bench/variants.mjs +4 -5
  64. package/src/bench/workspace.mjs +160 -0
  65. package/src/brief/assemble.mjs +11 -13
  66. package/src/ci/dependabot.mjs +25 -55
  67. package/src/commands/agent.mjs +1 -9
  68. package/src/commands/agenthook.mjs +66 -35
  69. package/src/commands/bench.mjs +2 -2
  70. package/src/commands/ci.mjs +11 -13
  71. package/src/commands/docs.mjs +88 -0
  72. package/src/commands/gate.mjs +10 -13
  73. package/src/commands/harness.mjs +3 -3
  74. package/src/commands/help.mjs +44 -3
  75. package/src/commands/hooks.mjs +20 -20
  76. package/src/commands/ignore.mjs +11 -7
  77. package/src/commands/impact.mjs +4 -8
  78. package/src/commands/index.mjs +49 -9
  79. package/src/commands/init-scan.mjs +90 -0
  80. package/src/commands/init.mjs +122 -104
  81. package/src/commands/lease.mjs +67 -18
  82. package/src/commands/map.mjs +10 -5
  83. package/src/commands/mcp.mjs +2 -17
  84. package/src/commands/repoindex.mjs +8 -8
  85. package/src/commands/rules.mjs +8 -4
  86. package/src/commands/shared.mjs +12 -16
  87. package/src/commands/skills.mjs +5 -6
  88. package/src/commands/skillscompile.mjs +3 -3
  89. package/src/commands/skillsinstall.mjs +5 -4
  90. package/src/commands/slice.mjs +199 -64
  91. package/src/commands/spec.mjs +78 -62
  92. package/src/commands/status.mjs +24 -12
  93. package/src/commands/sync.mjs +14 -14
  94. package/src/commands/tests.mjs +12 -12
  95. package/src/commands/tokens.mjs +19 -24
  96. package/src/commands/upgrade.mjs +8 -4
  97. package/src/commands/why.mjs +6 -13
  98. package/src/compare/hooksstate.mjs +2 -6
  99. package/src/compare/learn.mjs +3 -1
  100. package/src/decisions/index.mjs +3 -2
  101. package/src/docs/commands.mjs +65 -0
  102. package/src/ecosystem/records.mjs +219 -0
  103. package/src/explain.mjs +31 -0
  104. package/src/gates/index.mjs +385 -0
  105. package/src/graph/compile.mjs +8 -4
  106. package/src/graph/load.mjs +2 -1
  107. package/src/graph/spec.mjs +10 -8
  108. package/src/harness/records.mjs +143 -0
  109. package/src/hooks/capability.mjs +5 -3
  110. package/src/hooks/dispatcher.mjs +26 -32
  111. package/src/hooks/gates.mjs +12 -2
  112. package/src/hooks/resolve.mjs +2 -7
  113. package/src/hooks/where.mjs +2 -7
  114. package/src/identity.mjs +2 -11
  115. package/src/index/coverage.mjs +58 -0
  116. package/src/index/extract.mjs +6 -16
  117. package/src/index/gate.mjs +1 -1
  118. package/src/index/govern.mjs +26 -9
  119. package/src/index/impact.mjs +4 -8
  120. package/src/index/map.mjs +14 -15
  121. package/src/index/open.mjs +173 -0
  122. package/src/index/persist.mjs +224 -57
  123. package/src/index/store.mjs +82 -39
  124. package/src/index/tests.mjs +2 -6
  125. package/src/journal.mjs +16 -11
  126. package/src/kernel/card.mjs +37 -63
  127. package/src/kernel/checks.mjs +4 -10
  128. package/src/lease.mjs +102 -7
  129. package/src/ledger/index.mjs +124 -17
  130. package/src/mcp/paginate.mjs +33 -0
  131. package/src/mcp/schemas.mjs +512 -0
  132. package/src/mcp/server.mjs +49 -9
  133. package/src/mcp/tools-facts.mjs +326 -0
  134. package/src/mcp/tools-read.mjs +221 -0
  135. package/src/mcp/tools.mjs +4 -1005
  136. package/src/{bench → measure}/corpus.mjs +1 -1
  137. package/src/measure/metrics.mjs +236 -0
  138. package/src/measure/records.mjs +211 -0
  139. package/src/measure/stats.mjs +538 -0
  140. package/src/measure/task-schema.mjs +125 -0
  141. package/src/measure/tasks.mjs +69 -0
  142. package/src/memory/decide.mjs +6 -15
  143. package/src/memory/lesson-text.mjs +61 -0
  144. package/src/memory/lessons.mjs +29 -82
  145. package/src/name.mjs +7 -0
  146. package/src/output/index.mjs +122 -31
  147. package/src/packs/manage.mjs +15 -9
  148. package/src/plan/index.mjs +1 -1
  149. package/src/plugins.mjs +22 -16
  150. package/src/prbody.mjs +7 -11
  151. package/src/projection/loaders.mjs +7 -692
  152. package/src/projection/manifest.mjs +10 -435
  153. package/src/projection/mdc.mjs +7 -8
  154. package/src/projection/project.mjs +126 -221
  155. package/src/projection/region.mjs +561 -0
  156. package/src/projection/rules.mjs +16 -547
  157. package/src/projection/surfaces.mjs +43 -210
  158. package/src/projection/targets.mjs +5 -5
  159. package/src/repo-root.mjs +13 -1
  160. package/src/resolve/eval.mjs +2 -1
  161. package/src/resolve/fingerprint.mjs +0 -7
  162. package/src/resolve/resolve.mjs +1 -41
  163. package/src/review/critic.mjs +8 -12
  164. package/src/run.mjs +98 -0
  165. package/src/secrets.mjs +14 -22
  166. package/src/state/events.mjs +129 -0
  167. package/src/status-snapshot.mjs +233 -0
  168. package/src/status.mjs +2 -6
  169. package/src/sys/git.mjs +82 -0
  170. package/src/{bench/process.mjs → sys/proc.mjs} +28 -5
  171. package/src/testing/parsers.mjs +265 -0
  172. package/src/testing/patches.mjs +23 -0
  173. package/src/testing/paths.mjs +49 -0
  174. package/src/testing/runners.mjs +186 -0
  175. package/src/testing/vault.mjs +68 -0
  176. package/src/text/frontmatter.mjs +49 -0
  177. package/src/text/tokens.mjs +52 -0
  178. package/src/toolwords.mjs +1 -1
  179. package/src/util/fs.mjs +20 -0
  180. package/src/util/sort.mjs +12 -0
  181. package/src/workspace.mjs +3 -1
  182. package/src/write/plan.mjs +82 -0
  183. package/templates/plan/tracker.json +1 -0
  184. package/docs/decisions/ADR-033-three-plan-rows-closed-by-decision-not-by-authoring.md +0 -82
  185. package/docs/decisions/ADR-102-the-two-queued-review-rows-are-closed-by-ruling.md +0 -49
  186. package/src/bench/tasks.mjs +0 -36
@@ -30,6 +30,8 @@ import { loadMdcRules, renderMdc } from './mdc.mjs';
30
30
  import { foldsRules, resolveSurfaces, rulePath, canScope } from './surfaces.mjs';
31
31
  import { ruleTargets } from './targets.mjs';
32
32
  import { compose } from './markers.mjs';
33
+ import { desiredRegion } from './region.mjs';
34
+ export { desiredRegion } from './region.mjs';
33
35
  import { declaredBudget, declaredShared, readManifest } from './manifest.mjs';
34
36
  import { loadManifest } from '../manifest/schema.mjs';
35
37
  import { commandCard, CARD_LIMIT_BYTES } from '../kernel/card.mjs';
@@ -42,6 +44,7 @@ import { CLI, MANIFEST_FILE } from '../name.mjs';
42
44
  import { installedSkills } from './disclosure.mjs';
43
45
  import { PACK_DIR, resolvePacks } from '../packs.mjs';
44
46
  import { discoverPackages } from '../monorepo.mjs';
47
+ import { parseFrontmatter as splitBlock, stripFrontmatter as stripBlock } from '../text/frontmatter.mjs';
45
48
 
46
49
  const HERE = dirname(fileURLToPath(import.meta.url));
47
50
  export const ROOT = resolve(HERE, '..', '..');
@@ -268,8 +271,6 @@ export async function readDeclared(root) {
268
271
  };
269
272
  }
270
273
 
271
-
272
-
273
274
  /**
274
275
  * Render every canonical `.mdc` rule into its own generated region.
275
276
  *
@@ -351,7 +352,7 @@ export function ruleValues(rule, declared, surfaces) {
351
352
  return values;
352
353
  }
353
354
 
354
- async function ruleBodies(root, manifest, flags) {
355
+ export async function ruleBodies(root, manifest, flags) {
355
356
  const problems = [];
356
357
  const notes = [];
357
358
  const skipped = [];
@@ -445,7 +446,7 @@ async function ruleBodies(root, manifest, flags) {
445
446
  * card comes back alongside because the caller that needs the proofs also needs the card's
446
447
  * bytes, and building it twice would read the manifest twice for no second answer.
447
448
  */
448
- async function inferableEvidence(root, { stack, facts, manifest }) {
449
+ export async function inferableEvidence(root, { stack, facts, manifest }) {
449
450
  const card = await commandCard({ root, manifest, stack, facts });
450
451
  return { card, proofs: inferableProofs({ facts, stack, card, manifest }) };
451
452
  }
@@ -466,540 +467,10 @@ async function inferableEvidence(root, { stack, facts, manifest }) {
466
467
  * shared file, which is how the first version of this predicate lost three of five rules
467
468
  * in a two-repository measurement without failing anything.
468
469
  */
469
- function toolRule(rule) {
470
+ export function toolRule(rule) {
470
471
  return rule.origin !== undefined ? rule.origin === 'central' : rule.source.startsWith('rules/');
471
472
  }
472
473
 
473
- export async function desiredRegion(root, flags) {
474
- const { stack, facts, manifest } = await fingerprint(root);
475
- const lockedVariants =
476
- flags?.variants !== undefined ? flags.variants : await readLockedVariants(root);
477
- const all = await loadRules(root);
478
- const { selected, fallback, notes } = select(all, stack, facts);
479
- const { resolved, bodies, problems, notes: ruleNotes } = await ruleBodies(
480
- root,
481
- manifest,
482
- { ...(flags ?? {}), variants: lockedVariants },
483
- );
484
- notes.push(...ruleNotes);
485
-
486
- // A profile that declares a scope leaves the region only when every selected surface
487
- // can load it narrowly. The alternative is a profile written only as a scoped file for
488
- // a reader whose surface cannot scope — a rule nobody loads, which is worse than one
489
- // that loads eagerly (ADR-071). A surface that cannot scope it therefore keeps the
490
- // profile in the region and says so, rather than letting the region quietly shrink.
491
- const narrowing = resolved.surfaces.every((s) => canScope(s));
492
- const scoped = [];
493
- const inRegion = [];
494
- for (const r of selected) {
495
- const declares = Array.isArray(r.scope) && r.scope.length > 0 && r.error === null;
496
- if (!declares) {
497
- inRegion.push(r);
498
- continue;
499
- }
500
- // A profile only leaves the region when a narrowed file can replace it. When any
501
- // selected surface cannot narrow, the file would be the only home for a rule that
502
- // reader cannot reach — so it stays, and says why.
503
- if (narrowing) {
504
- const vf = foldVariants(r.body, r.id ?? '', lockedVariants);
505
- scoped.push(vf.changed ? { ...r, body: vf.body } : r);
506
- continue;
507
- }
508
- inRegion.push(r);
509
- notes.push(
510
- `${r.id} declares simt-scope, but ${resolved.source} selects a surface that cannot narrow a rule, so it stays in the region`,
511
- );
512
- }
513
-
514
- // The kernel. In `kernel` mode only the hard and command classes are packed into the
515
- // region and every other rule is deferred to `rules show <id>`, which is what makes
516
- // R08's accept criterion reachable at all: a budget cannot be met by a projection that
517
- // never tries. `full` is the default and stays it until R02 has measured that a
518
- // kernel does not lose compliance, because nobody has measured it yet.
519
- //
520
- // A rule with no stated class is deferred, not packed. The two mistakes are not
521
- // symmetric: packing a line that should have been deferred spends the budget the mode
522
- // exists to save, while deferring a line that should have been packed costs a reader
523
- // one `rules show`. The mode is a promise about bytes, so it is the bytes that win.
524
- // An explicit `mode` flag overrides the declared one. The caller is the MCP
525
- // `simt://kernel` resource, which by name promises the kernel's bytes for any
526
- // repository: the declared mode governs what `sync` writes to disk, not what a read
527
- // path may look at, so the read renders in the mode the URI names instead of
528
- // re-reading a manifest it must not obey (ADR-002).
529
- const mode = typeof flags?.mode === 'string' ? flags.mode : await projectionMode(root);
530
- const packed = [];
531
- const deferred = [];
532
- for (const r of inRegion) {
533
- if (mode === 'kernel' && (r.error !== null || !KERNEL_CLASSES.has(r.priority))) deferred.push(r);
534
- else packed.push(r);
535
- }
536
- // The command card leads the region. The exact commands for this repository are the
537
- // bytes a reader cannot infer from rules that are identical everywhere (plan 0003 R10),
538
- // so they go first — above even the core rules. It is derived from committed evidence
539
- // only, in one place, so `plan` and `checkTarget` cannot disagree about it and two
540
- // machines render it byte-identically.
541
- const { card, proofs } = await inferableEvidence(root, { stack, facts, manifest });
542
- if (card.dropped.length > 0) {
543
- // Reported where every other projection note is reported. A card that lost a command
544
- // in silence is a card a reader cannot tell is incomplete.
545
- notes.push(
546
- `command card: dropped ${card.dropped.join(', ')} to stay within ${CARD_LIMIT_BYTES} bytes`,
547
- );
548
- }
549
- // Inferability (R09). A marked line leaves when the repository proves the evidence it
550
- // names. `shipped` is a separate list from `packed` because they are separate decisions:
551
- // the kernel is about which classes cost a reader nothing to skip, and this is about
552
- // which lines the reader already knows.
553
- const inferable = [];
554
- const shipped = [];
555
- const variantsSelected = [];
556
- let enforced = 0;
557
- for (const r of packed) {
558
- const variantFolded = foldVariants(r.body, r.id ?? '', lockedVariants);
559
- const filtered = filterInferable(variantFolded.body, proofs);
560
- const folded = foldChecks(filtered.body);
561
- enforced += folded.enforced.length;
562
- variantsSelected.push(...variantFolded.selected);
563
- if (!variantFolded.changed && !filtered.changed && !folded.changed) {
564
- shipped.push(r);
565
- continue;
566
- }
567
- for (const x of filtered.removed) inferable.push({ rule: r.id, text: x.text, expr: x.expr });
568
- shipped.push({ ...r, body: folded.body });
569
- }
570
- // A body that points the reader at a profile they cannot reach is a rule-text defect:
571
- // the region renders, but the reference dangles. Kept out of `problems` because that
572
- // array is the mdc list `sync` already reports, and one fault must not print twice.
573
- const crossRefs = [];
574
- const selectedIds = new Set(selected.map((r) => r.id));
575
- for (const r of shipped) {
576
- for (const p of crossRefProblems(r.body, all, selectedIds)) {
577
- crossRefs.push(`${r.id}: ${p}`);
578
- }
579
- }
580
- const lockedNonDefault = variantsSelected.filter((v) => v.locked && v.winner !== v.baseline);
581
- if (lockedNonDefault.length > 0) {
582
- notes.push(
583
- `variants: applied ${lockedNonDefault.length} locked variant(s) (${lockedNonDefault.map((v) => `${v.slotId}=${v.winner}`).join(', ')})`,
584
- );
585
- }
586
- if (enforced > 0) {
587
- notes.push(
588
- `enforced: ${enforced} line(s) left the region because a checker runs them`,
589
- );
590
- }
591
- if (inferable.length > 0) {
592
- // Never silent, and never a heading. A line that left with no trace repeats the
593
- // mistake ADR-073 rejected for deferred rules, and a `## Dropped` section spends region
594
- // bytes on lines the reader is being told not to read. A count they can act on, plus —
595
- // with `--explain` — the evidence behind each one, is the third option.
596
- notes.push(
597
- `inferability: dropped ${inferable.length} line(s) this repository already proves; ${CLI} sync --explain names each one and the evidence behind it`,
598
- );
599
- if (flags?.explain === true) {
600
- for (const x of inferable) {
601
- notes.push(`inferable: ${x.rule} dropped "${x.text}" — proved by ${x.expr}`);
602
- }
603
- }
604
- }
605
- const folded = foldsRules(resolved) ? bodies.map(({ rule }) => rule.id) : [];
606
-
607
- // The workspace-shared rules this repository declared (ADR-084).
608
- //
609
- // Read from the manifest and never from the reader's home directory, because this
610
- // function is what `sync` and `check` both call: a region that depended on what
611
- // somebody had installed would render differently on a machine where they had not,
612
- // and CI would report drift on a tree `sync` had just written. The ids travel in the
613
- // manifest so the answer to "what leaves this region" is a fact about the repository.
614
- const declared = declaredShared(manifest);
615
- const carriedIds = new Set(declared.level === null ? [] : [...declared.rules]);
616
-
617
- // Every rule the workspace carries, as the rule objects the index below names. Both
618
- // lists, because a surface that folds its rules into the primary document carries the
619
- // canonical process bodies in that document too — and a reader who cannot find
620
- // `slice-commit` anywhere near their repository will look for it in AGENTS.md.
621
- const carried = [
622
- ...shipped.filter((r) => carriedIds.has(r.id)).map((rule) => ({ rule, kind: 'profile' })),
623
- ...bodies.filter(({ rule }) => carriedIds.has(rule.id)).map(({ rule }) => ({ rule, kind: 'process' })),
624
- ];
625
-
626
- // The rules this root would carry in its region, with the bytes it would carry them
627
- // in — the input ADR-084's workspace intersection compares.
628
- //
629
- // Computed from `shipped` rather than from what the region ends up carrying, and that
630
- // is the whole reason it is computed at all: a rule already declared shared must still
631
- // appear here, or a second `shared install` would intersect against a list that no
632
- // longer contained it and shrink the shared file every time anybody ran the command.
633
- // The declaration is an input to the region; it is not an input to what is shareable.
634
- const shareable = [
635
- // Only the rules this package ships. A repository's own profile, or a pack it
636
- // installed, is policy somebody chose to write: carrying it into a shared home file
637
- // would mean editing that file to change a repository's rules, and the copy would
638
- // reach every other repository in the estate that declared the same id. A rule
639
- // somebody can override must stay somewhere they own.
640
- ...shipped
641
- .filter((r) => r.error === null && toolRule(r) && typeof r.id === 'string' && r.id !== '')
642
- .map((r) => ({
643
- id: r.id,
644
- source: r.source,
645
- priority: r.priority ?? null,
646
- rendered: frameSource(r, stripFrontmatter(r.body).trim(), 'profile'),
647
- })),
648
- // The folded process bodies, and only while they are folded. A surface that writes
649
- // one file per rule expects that file at a path inside the repository, so a
650
- // user-level copy cannot stand in for it — but when the surface folds the whole region
651
- // into the primary document, those bytes are as repeated across a workspace as the
652
- // profiles are, and `tokens --repos` named them as the last duplicate block in a
653
- // two-repository measurement.
654
- ...bodies
655
- .filter(({ rule }) => folded.includes(rule.id) && toolRule(rule))
656
- .map(({ rule, body }) => ({
657
- id: rule.id,
658
- source: rule.source,
659
- priority: rule.priority ?? null,
660
- rendered: frameSource(rule, body, 'process'),
661
- })),
662
- ].filter((r) => r.rendered !== '');
663
-
664
- // The selected rules that are not shareable, with the reason. `shared plan` reporting
665
- // only what it carries would imply every profile in the workspace had been accounted
666
- // for, and a reader whose own house rule is missing from the list would conclude it
667
- // moved — so the names it did not take, and why, are data rather than an omission.
668
- const shareableIds = new Set(shareable.map((r) => r.id));
669
- const excluded = selected
670
- .filter((r) => typeof r.id === 'string' && r.id !== '' && !shareableIds.has(r.id))
671
- .map((r) => ({
672
- id: r.id,
673
- why: r.error !== null ? 'error' : toolRule(r) ? 'empty' : 'policy',
674
- }));
675
-
676
- // The budget, and the bytes held back for what loads beside the region.
677
- //
678
- // Read from the manifest rather than from the plan's spelling of it. Plan 0003 R08
679
- // wrote `projection.budget.bytes`, and ADR-072 moved the key to the top level because
680
- // `projection` is a generated key `upgrade` replaces wholesale - a budget that reset
681
- // itself on upgrade would reset the reader's context size without anyone asking. The
682
- // plan is not edited: the key it names is wrong, and a ruling that supersedes it is
683
- // the record of why.
684
- const budget = declaredBudget(manifest);
685
- // Names and triggers only. Read once, outside the packer, because a skill does not
686
- // change as rules are cut and reading its body here would put the cost back into the
687
- // region the index exists to keep it out of (ADR-085).
688
- const skills = await installedSkills(root);
689
-
690
- // The digest is needed before the region can be weighed rather than after, because the
691
- // provenance header is part of what lands in the file. `provenanceDigest` is a pure
692
- // function of the bytes this package ships, so computing it once and passing it down is
693
- // the same value the tail of this function was getting on its own.
694
- const sha = await provenanceDigest();
695
-
696
- /**
697
- * The region, assembled from whatever survived the budget (ADR-083).
698
- *
699
- * One function, called once for the whole projection and again for each attempt the
700
- * packer makes, so a cut region and an uncut one are the same document by construction
701
- * rather than by two functions agreeing. The card, the inferability notes, the folded
702
- * process bodies and the disclosure index are not candidates for a cut: a budget is a
703
- * decision about rules, and dropping the index would hide the rules the cut removed.
704
- */
705
- const assemble = (cut) => {
706
- // A rule the workspace carries once leaves the region, and so does a rule the packer
707
- // could not afford. Both are exclusions from the same list, so the section below can
708
- // name all three reasons — which is the only reason the section exists: a reader who
709
- // opens AGENTS.md and does not find a rule they know is there will look for it.
710
- const kept = shipped.filter((r) => !cut.has(r.id) && !carriedIds.has(r.id));
711
- // Stable bytes first (ADR-086). Core, then the profiles this package ships, then
712
- // everything this repository added — the card, its own profiles, the process
713
- // bodies. A line the repository edits then changes only the tail, and the prefix
714
- // a reader has cached stays byte-identical. The card used to lead (ADR-077 ruling
715
- // 1); it now leads the tail, because a command this repository owns is the thing
716
- // an edit is most likely to move.
717
- const stable = kept.filter((r) => toolRule(r)).sort(stableOrder);
718
- const repoRules = kept.filter((r) => !toolRule(r)).sort((a, b) => String(a.id).localeCompare(String(b.id)));
719
- let text = render(stable);
720
- if (card.text) text += `${text === '' ? '' : '\n\n'}${card.text}`;
721
- // The pointer follows the card: the card says what this repository runs, and the
722
- // pointer says how the tool serves a task. Adjacent, they read as one block of
723
- // repo-facing advice instead of two facts the reader has to connect.
724
- text += `${text === '' ? '' : '\n\n'}${ORIENTATION_POINTER}`;
725
- const repoText = render(repoRules);
726
- if (repoText) text += `\n\n${repoText}`;
727
- const sources = [...stable, ...repoRules].map((r) => r.source);
728
-
729
- // Every reason a rule is missing lands in this one section, and each line says which
730
- // it was. A rule deferred by its class, a rule cut to reach a byte count and a rule
731
- // the workspace carries once are three different decisions, but they are the same fact
732
- // to a reader — it is not in this file — and three headings would spend region bytes
733
- // on structure nobody can act on. The line names the command that shows the rule,
734
- // because for all three the remedy is the same single read.
735
- //
736
- // The label is the rule's own frame title, which is why each entry carries the kind it
737
- // is rendered as: a canonical rule that the surface folds in is `Process: <id>` in the
738
- // shared file, and an index that calls it `Stack:` sends the reader looking for the
739
- // wrong thing.
740
- const omitted = [
741
- ...deferred.map((r) => ({ rule: r, kind: 'profile', why: `${r.priority ?? 'unclassified'}, deferred in kernel mode` })),
742
- ...shipped
743
- .filter((r) => cut.has(r.id))
744
- .map((r) => ({
745
- rule: r,
746
- kind: 'profile',
747
- why: `${r.priority ?? 'unclassified'}, cut to fit the declared budget of ${budget} bytes`,
748
- })),
749
- ...carried.map(({ rule, kind }) => ({
750
- rule,
751
- kind,
752
- // No path here, deliberately. This text is rendered by `sync` in CI, where the
753
- // reader's home directory is somebody else's, and a path is the one thing in a
754
- // remedy that cannot be true on both. The remedy is a command that works on the
755
- // machine the reader is on.
756
- 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`,
757
- })),
758
- ];
759
- if (omitted.length > 0) {
760
- // The pointer is the same shape as the scoped one above, and for the same reason:
761
- // a reader who opens AGENTS.md and does not find a rule they know is there will
762
- // look for it. What it costs to find it has to be one command, named per rule.
763
- const lines = omitted
764
- .sort((a, b) => byPriorityThenId(a.rule, b.rule))
765
- .map(
766
- ({ rule, kind, why }) =>
767
- `- ${sourceTitle(rule, kind)} — ${why}. Show it with: ${CLI} rules show ${rule.id}`,
768
- );
769
- // `## Rules not in this region`, not `## Deferred rules`. The heading was written
770
- // when there was one reason to be here (ADR-073) and it is region text a reader
771
- // reads, so a heading that names one of three reasons misdescribes the two others
772
- // (ADR-084).
773
- text += `\n\n## Rules not in this region\n\n${lines.join('\n')}`;
774
- for (const { rule } of omitted) sources.push(rule.source);
775
- }
776
-
777
- if (folded.length > 0) {
778
- for (const { rule, body: ruleBody } of bodies) {
779
- // A body the workspace carries once is not folded in here either. The heading is
780
- // about how the surface loads the region, so it stays; the rule under it does not,
781
- // and a region that carried the same bytes twice is the redundancy ADR-084 exists
782
- // to remove — reintroduced by the feature that removes it.
783
- if (carriedIds.has(rule.id)) continue;
784
- // `## Process:`, not `### id`. The body already uses `##`, and a third-level
785
- // heading in front of a second-level one is the break a reader cannot repair.
786
- text += `\n\n${frameSource(rule, ruleBody, 'process')}`;
787
- sources.push(rule.source);
788
- }
789
- }
790
-
791
- // Last, because this is the index of what the file deliberately does not contain
792
- // (ADR-085). A scoped profile keeps the pointer ADR-071 requires — its patterns and
793
- // the files it moved to — and a skill keeps its name and the description that says
794
- // when to open it. The body of either is the thing that was moved out.
795
- const disclosure = [];
796
- if (scoped.length > 0 && narrowing) {
797
- for (const r of scoped) {
798
- disclosure.push(
799
- `- ${sourceTitle(r, 'profile')} — loads only when a matching file is in play (${r.scope.join(', ')}): ${scopedPaths(r, resolved).join(', ')}`,
800
- );
801
- sources.push(r.source);
802
- }
803
- }
804
- const skillNames = new Map();
805
- for (const skill of skills) skillNames.set(skill.name, (skillNames.get(skill.name) ?? 0) + 1);
806
- for (const skill of skills) {
807
- const label = skillNames.get(skill.name) > 1 ? `${skill.name} (${skill.dir})` : skill.name;
808
- disclosure.push(
809
- skill.trigger === ''
810
- ? `- ${label} — no description, so nothing says when to open it. Show it with: ${CLI} skills show ${skill.name}`
811
- : `- ${label} — ${skill.trigger}`,
812
- );
813
- }
814
- if (disclosure.length > 0) text += `\n\n## Disclosure\n\n${disclosure.join('\n')}`;
815
-
816
- return { body: text, sources };
817
- };
818
-
819
- // What the region will weigh in the file it lands in, measured the way the meter
820
- // measures it: the composed region text, markers and provenance header included. One
821
- // byte conservative, because the file's own trailing newline falls outside the span —
822
- // and conservative in that direction is the only direction a ceiling can afford.
823
- const regionBytes = (assembled) =>
824
- Buffer.byteLength(compose(assembled.body, { sha, sources: assembled.sources }));
825
-
826
- let assembled = assemble(new Set());
827
- let packing = null;
828
- if (mode === 'kernel') {
829
- const reserve = await budgetReserve(root, resolved, bodies, sha);
830
- const result = packToBudget({
831
- // Least valuable first: the comparator the deferred section already uses, reversed.
832
- // Class decides and the id breaks the tie, so the cut order is a fact about the
833
- // repository rather than about the order the filesystem listed files in.
834
- //
835
- // The workspace-shared rules are not candidates, and that is not a rounding: cutting
836
- // one cannot make the region smaller by more than the index line it adds to the
837
- // section below, because the rule is carried once per workspace whatever this region
838
- // does. A packer that spent its budget on them would report a saving it did not make.
839
- candidates: shipped
840
- .filter((r) => !carriedIds.has(r.id))
841
- .sort((a, b) => -byPriorityThenId(a, b)),
842
- ceiling: budget - reserve,
843
- costs: (cut) => regionBytes(assemble(cut)),
844
- });
845
- packing = { ...result, bytes: budget, ceiling: budget - reserve, reserve };
846
- if (result.cut.length > 0) assembled = assemble(new Set(result.cut));
847
- if (result.cut.length > 0) {
848
- notes.push(
849
- `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`,
850
- );
851
- }
852
- if (result.floorHeld) {
853
- // The one case the packer cannot fix, said where the reader will see it. `hard` is
854
- // the floor, so the bytes still over the line are this repository's own hard
855
- // constraints and the only levers left are its own: a larger budget, or a rule that
856
- // is not as hard as it is declared. ADR-072's kernel finding says both; this says
857
- // they were tried first.
858
- notes.push(
859
- `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`,
860
- );
861
- }
862
- if (result.floorHeld && reserve >= budget) {
863
- // A ceiling of zero or less is arithmetically true and useless to read: it says the
864
- // region is allowed no bytes, without saying that the files loading beside it have
865
- // already spent the whole budget. One number in that manifest is the only lever, and
866
- // a reader left to infer it from a subtraction is a reader who will demote a hard
867
- // rule to fix a budget that was set below the files it covers.
868
- notes.push(
869
- `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`,
870
- );
871
- }
872
- }
873
-
874
- const meta = {
875
- sha,
876
- sources: assembled.sources,
877
- };
878
- return {
879
- stack,
880
- facts,
881
- manifest,
882
- all,
883
- profiles: selected.map((r) => r.id),
884
- folded,
885
- mode,
886
- deferred: deferred.map((r) => r.id),
887
- // What the workspace carries once per reader instead of here (ADR-084), as ids. The
888
- // declaration is what `check` and `sync` both read to decide the region, so the ids
889
- // that actually left are reported for the same reason the budget's cuts are: a rule
890
- // that disappeared needs a name in the output, or a reader looks for it in vain.
891
- carried: carried.map(({ rule }) => rule.id),
892
- // What this root could contribute to a workspace's shared file, with the bytes it
893
- // would contribute. Read by `simt shared`, never by the projection — which is why
894
- // computing it costs a frame per rule and buys nothing on `sync`.
895
- shareable,
896
- // What it selected and cannot contribute, with the reason. Reported so that a rule
897
- // staying in the region is always a decision somebody can see rather than an absence.
898
- excluded,
899
- // What the budget cost this projection (ADR-083), or null in `full` mode where no
900
- // ceiling is applied because nothing is cut. The finding and `simt tokens` both read
901
- // this rather than re-deriving it, so a cut cannot be reported one way and measured
902
- // another.
903
- budget: packing === null
904
- ? null
905
- : {
906
- bytes: packing.bytes,
907
- ceiling: packing.ceiling,
908
- reserve: packing.reserve,
909
- before: packing.before,
910
- after: packing.after,
911
- floorHeld: packing.floorHeld,
912
- cuts: shipped
913
- .filter((r) => packing.cut.includes(r.id))
914
- .map((r) => ({ id: r.id, priority: r.priority ?? 'unclassified' })),
915
- },
916
- // The marked lines that left, each with the evidence that dropped it. The region is
917
- // written without them; `--explain` is what reads this list, so a removal is reportable
918
- // without spending region bytes and without a second computation to find it.
919
- inferable,
920
- // The profiles that left the region, and the surfaces that accepted them as files.
921
- // `plan` writes them and `checkTarget` gates them through this list, so a projected
922
- // file and a drifted one are decided by the same computation.
923
- scoped,
924
- narrowing,
925
- surfaces: resolved.ids,
926
- surfaceSource: resolved.source,
927
- problems,
928
- crossRefs,
929
- fallback,
930
- notes,
931
- body: assembled.body,
932
- meta,
933
- };
934
- }
935
-
936
- /**
937
- * The bytes held back from the region's own ceiling for the always-on files that load
938
- * beside it.
939
- *
940
- * The budget is one number for a repository, not for one file, so packing the region
941
- * against the whole number would ship a projection that fits on its own and pushes the
942
- * total over the line the moment its rule files are written. Both terms below are lower
943
- * bounds on what that costs, and the larger is taken because the failure each one covers
944
- * is the one that must not happen: under-reserving reports compliance for a projection
945
- * that is over budget.
946
- *
947
- * The region's own span is deliberately not in either. It is the one number that moves
948
- * when this projection is packed, and a ceiling that depended on the thing it governs
949
- * would rewrite the region on the next run and report drift on a tree `sync` had just
950
- * written - the step-6 defect, rebuilt one layer up.
951
- *
952
- * @param {string} root
953
- * @param {object} resolved the surfaces this projection writes for
954
- * @param {{rule: object, body: string}[]} bodies the rule bodies being projected
955
- * @param {string} sha the provenance digest those files will be stamped with
956
- * @returns {Promise<number>}
957
- */
958
- async function budgetReserve(root, resolved, bodies, sha) {
959
- // Imported here rather than at the top of the module: `measure/context.mjs` reaches back
960
- // into `projection/project.mjs` for the read-limit findings, so a static import from
961
- // `rules.mjs` closes a loop through three modules that all have to survive being loaded
962
- // in any order. The loop between the other two already exists and is load-bearing in
963
- // neither direction; this one is walked only when a kernel is being packed.
964
- const { measureRoot } = await import('../measure/context.mjs');
965
- const measured = await measureRoot(root);
966
- const region = measured.documents.find((d) => d.channel === 'region');
967
- const installed = Math.max(0, measured.generatedBytes - (region?.generatedBytes ?? 0));
968
-
969
- // What this projection is about to write, for a repository that has not written it yet.
970
- // `ruleTargets` is the one place a rule file is turned into bytes, so the number comes
971
- // from there rather than from a second measurement of the same file — and its notes go
972
- // nowhere, because `mdcTargets` reports the same ones for the same files in the same run.
973
- let planned = 0;
974
- for (const { rule, body } of bodies) {
975
- for (const target of (await ruleTargets(root, rule, body, sha, resolved, [])).targets) {
976
- planned += target.bytes;
977
- }
978
- }
979
- return Math.max(installed, planned);
980
- }
981
-
982
- /**
983
- * Every per-rule file a scoped profile is written to, as paths a reader can open.
984
- *
985
- * Only the surfaces that can scope get one: a Cursor `.mdc` with `globs` and
986
- * `alwaysApply: false`, an Antigravity file with `trigger: glob`, a Copilot
987
- * `.instructions.md` with `applyTo`. A surface that reads the region already (opencode)
988
- * has no file channel at all, and Claude's scoping key is the documented-defect one,
989
- * so neither appears here.
990
- */
991
- function scopedPaths(rule, resolved) {
992
- const out = [];
993
- for (const s of resolved.surfaces) {
994
- if (!canScope(s) || !s.rule) continue;
995
- // A folded surface already carries the whole region; it is the reason this profile
996
- // is only a file when folding is off, which is the caller's question to answer.
997
- if (s.foldRules === true && s.readsPrimary === true && foldsRules(resolved)) continue;
998
- out.push(rulePath(s.id, rule.id));
999
- }
1000
- return out;
1001
- }
1002
-
1003
474
  /**
1004
475
  * Read every rule file once, with its frontmatter parsed, plus any repo-local
1005
476
  * profile under `.simt/profiles/`.
@@ -1288,7 +759,7 @@ export function render(selected) {
1288
759
  * yet says a kernel does not lose compliance (plan 0003 R02), so the mode that changes
1289
760
  * what a reader gets cannot be the one nobody chose.
1290
761
  */
1291
- async function projectionMode(root) {
762
+ export async function projectionMode(root) {
1292
763
  const { manifest } = await readManifest(root);
1293
764
  return manifest?.mode === 'kernel' ? 'kernel' : 'full';
1294
765
  }
@@ -1302,7 +773,7 @@ async function projectionMode(root) {
1302
773
  */
1303
774
  /** Core, then the remaining shipped profiles by id. Id, not load order: a directory
1304
775
  * listing is not a fact about the rules, and two machines must not disagree about it. */
1305
- function stableOrder(a, b) {
776
+ export function stableOrder(a, b) {
1306
777
  if (a.id === 'core') return b.id === 'core' ? 0 : -1;
1307
778
  if (b.id === 'core') return 1;
1308
779
  return String(a.id).localeCompare(String(b.id));
@@ -1326,7 +797,7 @@ export function byPriorityThenId(a, b) {
1326
797
  * substitutes it, so a rename of the file is a change in one place (MANIFEST_FILE),
1327
798
  * not a search across every rule body.
1328
799
  */
1329
- function frameSource(rule, body, kind) {
800
+ export function frameSource(rule, body, kind) {
1330
801
  const text = demoteHeadings(body.replaceAll('{manifest}', MANIFEST_FILE)).trim();
1331
802
  if (!text) return '';
1332
803
  const title = sourceTitle(rule, kind);
@@ -1334,7 +805,7 @@ function frameSource(rule, body, kind) {
1334
805
  return `## ${title}\n\n${text}`;
1335
806
  }
1336
807
 
1337
- function sourceTitle(rule, kind) {
808
+ export function sourceTitle(rule, kind) {
1338
809
  if (!rule?.id) return null;
1339
810
  if (kind === 'process') return `Process: ${rule.id}`;
1340
811
  if (rule.id === 'core') return 'Core';
@@ -1349,7 +820,7 @@ function sourceTitle(rule, kind) {
1349
820
  * backtick-quoted `<id> profile` in prose, and the `simt rules show <id>`
1350
821
  * command itself - an id that form names must exist, or the command 404s.
1351
822
  */
1352
- function crossRefProblems(body, all, selectedIds) {
823
+ export function crossRefProblems(body, all, selectedIds) {
1353
824
  const problems = [];
1354
825
  const seen = new Set();
1355
826
  for (const m of String(body).matchAll(/`([a-z0-9][a-z0-9-]*)`\s+profile|rules show ([a-z0-9][a-z0-9-]*)/g)) {
@@ -1386,10 +857,10 @@ function demoteHeadings(text) {
1386
857
  }
1387
858
 
1388
859
  function parseFrontmatter(text) {
1389
- const m = /^---\n([\s\S]*?)\n---\n?/.exec(text);
1390
- if (!m) return {};
860
+ const { front } = splitBlock(text);
861
+ if (front === null) return {};
1391
862
  const out = {};
1392
- for (const line of m[1].split('\n')) {
863
+ for (const line of front.split('\n')) {
1393
864
  const kv = /^([a-zA-Z-]+):\s*(.*)$/.exec(line);
1394
865
  if (!kv) continue;
1395
866
  const [, key, raw] = kv;
@@ -1415,12 +886,10 @@ function parseFrontmatter(text) {
1415
886
 
1416
887
  /** Frontmatter and the duplicated H1 are dropped: the region is embedded in a
1417
888
  * host document that already has a title, so repeating it wastes context. */
1418
- function stripFrontmatter(text) {
889
+ export function stripFrontmatter(text) {
1419
890
  // The frontmatter strip must also swallow the blank lines that follow it, or
1420
891
  // the H1 strip's `^` anchor lands on a newline and silently matches nothing.
1421
- return text
1422
- .replace(/^---\n[\s\S]*?\n---\n*/, '')
892
+ return stripBlock(text)
1423
893
  .replace(/^#\s+.*\n+/, '')
1424
894
  .trim();
1425
895
  }
1426
-