@vibe-agent-toolkit/cli 0.2.0-rc.2 → 0.2.0-rc.4

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 (211) hide show
  1. package/dist/bin/vat +68 -16
  2. package/dist/bin/vat.js +68 -16
  3. package/dist/bin/vat.js.map +1 -1
  4. package/dist/bin.js +157 -37
  5. package/dist/bin.js.map +1 -1
  6. package/dist/command-loaders.d.ts +44 -0
  7. package/dist/command-loaders.d.ts.map +1 -0
  8. package/dist/command-loaders.js +58 -0
  9. package/dist/command-loaders.js.map +1 -0
  10. package/dist/commands/agent/index.js +1 -1
  11. package/dist/commands/agent/install.d.ts.map +1 -1
  12. package/dist/commands/agent/install.js +46 -5
  13. package/dist/commands/agent/install.js.map +1 -1
  14. package/dist/commands/audit/distributed-tree.d.ts +2 -2
  15. package/dist/commands/audit/distributed-tree.d.ts.map +1 -1
  16. package/dist/commands/audit/distributed-tree.js +2 -1
  17. package/dist/commands/audit/distributed-tree.js.map +1 -1
  18. package/dist/commands/audit/git-url-clone.d.ts +1 -1
  19. package/dist/commands/audit/git-url-clone.d.ts.map +1 -1
  20. package/dist/commands/audit/git-url-clone.js.map +1 -1
  21. package/dist/commands/audit/hierarchical-output.d.ts +1 -1
  22. package/dist/commands/audit/hierarchical-output.d.ts.map +1 -1
  23. package/dist/commands/audit/hierarchical-output.js +1 -1
  24. package/dist/commands/audit/hierarchical-output.js.map +1 -1
  25. package/dist/commands/audit.d.ts +22 -1
  26. package/dist/commands/audit.d.ts.map +1 -1
  27. package/dist/commands/audit.js +224 -24
  28. package/dist/commands/audit.js.map +1 -1
  29. package/dist/commands/build.d.ts +1 -1
  30. package/dist/commands/build.d.ts.map +1 -1
  31. package/dist/commands/build.js +15 -12
  32. package/dist/commands/build.js.map +1 -1
  33. package/dist/commands/cache/cache-control.d.ts +82 -0
  34. package/dist/commands/cache/cache-control.d.ts.map +1 -0
  35. package/dist/commands/cache/cache-control.js +86 -0
  36. package/dist/commands/cache/cache-control.js.map +1 -0
  37. package/dist/commands/cache/clear.d.ts +17 -3
  38. package/dist/commands/cache/clear.d.ts.map +1 -1
  39. package/dist/commands/cache/clear.js +68 -3
  40. package/dist/commands/cache/clear.js.map +1 -1
  41. package/dist/commands/cache/index.d.ts +13 -63
  42. package/dist/commands/cache/index.d.ts.map +1 -1
  43. package/dist/commands/cache/index.js +38 -79
  44. package/dist/commands/cache/index.js.map +1 -1
  45. package/dist/commands/claude/budget.d.ts +157 -0
  46. package/dist/commands/claude/budget.d.ts.map +1 -0
  47. package/dist/commands/claude/budget.js +412 -0
  48. package/dist/commands/claude/budget.js.map +1 -0
  49. package/dist/commands/claude/context.d.ts +340 -0
  50. package/dist/commands/claude/context.d.ts.map +1 -0
  51. package/dist/commands/claude/context.js +1079 -0
  52. package/dist/commands/claude/context.js.map +1 -0
  53. package/dist/commands/claude/index.d.ts +13 -0
  54. package/dist/commands/claude/index.d.ts.map +1 -1
  55. package/dist/commands/claude/index.js +24 -2
  56. package/dist/commands/claude/index.js.map +1 -1
  57. package/dist/commands/claude/marketplace/git-publish.d.ts.map +1 -1
  58. package/dist/commands/claude/marketplace/git-publish.js +18 -19
  59. package/dist/commands/claude/marketplace/git-publish.js.map +1 -1
  60. package/dist/commands/claude/marketplace/validate.d.ts +19 -1
  61. package/dist/commands/claude/marketplace/validate.d.ts.map +1 -1
  62. package/dist/commands/claude/marketplace/validate.js +41 -21
  63. package/dist/commands/claude/marketplace/validate.js.map +1 -1
  64. package/dist/commands/claude/plugin/build.d.ts +18 -2
  65. package/dist/commands/claude/plugin/build.d.ts.map +1 -1
  66. package/dist/commands/claude/plugin/build.js +55 -18
  67. package/dist/commands/claude/plugin/build.js.map +1 -1
  68. package/dist/commands/claude/plugin/helpers.d.ts.map +1 -1
  69. package/dist/commands/claude/plugin/helpers.js +2 -1
  70. package/dist/commands/claude/plugin/helpers.js.map +1 -1
  71. package/dist/commands/claude/plugin/install.d.ts.map +1 -1
  72. package/dist/commands/claude/plugin/install.js +24 -3
  73. package/dist/commands/claude/plugin/install.js.map +1 -1
  74. package/dist/commands/claude/plugin/tree-copy.d.ts.map +1 -1
  75. package/dist/commands/claude/plugin/tree-copy.js +2 -1
  76. package/dist/commands/claude/plugin/tree-copy.js.map +1 -1
  77. package/dist/commands/consistency-check.d.ts.map +1 -1
  78. package/dist/commands/consistency-check.js +4 -3
  79. package/dist/commands/consistency-check.js.map +1 -1
  80. package/dist/commands/corpus/report.d.ts +1 -1
  81. package/dist/commands/corpus/report.d.ts.map +1 -1
  82. package/dist/commands/corpus/runner.d.ts.map +1 -1
  83. package/dist/commands/corpus/runner.js +3 -2
  84. package/dist/commands/corpus/runner.js.map +1 -1
  85. package/dist/commands/corpus/scan.d.ts.map +1 -1
  86. package/dist/commands/corpus/scan.js +18 -8
  87. package/dist/commands/corpus/scan.js.map +1 -1
  88. package/dist/commands/doctor.d.ts +36 -0
  89. package/dist/commands/doctor.d.ts.map +1 -1
  90. package/dist/commands/doctor.js +99 -2
  91. package/dist/commands/doctor.js.map +1 -1
  92. package/dist/commands/inventory.d.ts +13 -1
  93. package/dist/commands/inventory.d.ts.map +1 -1
  94. package/dist/commands/inventory.js +118 -13
  95. package/dist/commands/inventory.js.map +1 -1
  96. package/dist/commands/mcp/collections.d.ts +1 -1
  97. package/dist/commands/mcp/collections.d.ts.map +1 -1
  98. package/dist/commands/phase-utils.d.ts +155 -104
  99. package/dist/commands/phase-utils.d.ts.map +1 -1
  100. package/dist/commands/phase-utils.js +109 -155
  101. package/dist/commands/phase-utils.js.map +1 -1
  102. package/dist/commands/rag/index-command.d.ts +39 -0
  103. package/dist/commands/rag/index-command.d.ts.map +1 -1
  104. package/dist/commands/rag/index-command.js +28 -2
  105. package/dist/commands/rag/index-command.js.map +1 -1
  106. package/dist/commands/rag/index.d.ts.map +1 -1
  107. package/dist/commands/rag/index.js +21 -10
  108. package/dist/commands/rag/index.js.map +1 -1
  109. package/dist/commands/resources/index.d.ts.map +1 -1
  110. package/dist/commands/resources/index.js +10 -2
  111. package/dist/commands/resources/index.js.map +1 -1
  112. package/dist/commands/resources/scan.d.ts +24 -0
  113. package/dist/commands/resources/scan.d.ts.map +1 -1
  114. package/dist/commands/resources/scan.js +19 -6
  115. package/dist/commands/resources/scan.js.map +1 -1
  116. package/dist/commands/resources/validate.d.ts +12 -1
  117. package/dist/commands/resources/validate.d.ts.map +1 -1
  118. package/dist/commands/resources/validate.js +102 -51
  119. package/dist/commands/resources/validate.js.map +1 -1
  120. package/dist/commands/skill/review-checklist.d.ts.map +1 -1
  121. package/dist/commands/skill/review-checklist.js +1 -0
  122. package/dist/commands/skill/review-checklist.js.map +1 -1
  123. package/dist/commands/skill/review.js +2 -2
  124. package/dist/commands/skill/review.js.map +1 -1
  125. package/dist/commands/skill/test/configure.d.ts +19 -0
  126. package/dist/commands/skill/test/configure.d.ts.map +1 -1
  127. package/dist/commands/skill/test/configure.js +18 -3
  128. package/dist/commands/skill/test/configure.js.map +1 -1
  129. package/dist/commands/skill/test/run.d.ts +51 -4
  130. package/dist/commands/skill/test/run.d.ts.map +1 -1
  131. package/dist/commands/skill/test/run.js +123 -12
  132. package/dist/commands/skill/test/run.js.map +1 -1
  133. package/dist/commands/skills/build.d.ts +11 -1
  134. package/dist/commands/skills/build.d.ts.map +1 -1
  135. package/dist/commands/skills/build.js +154 -61
  136. package/dist/commands/skills/build.js.map +1 -1
  137. package/dist/commands/skills/package.d.ts +1 -1
  138. package/dist/commands/skills/package.d.ts.map +1 -1
  139. package/dist/commands/skills/package.js.map +1 -1
  140. package/dist/commands/skills/skill-discovery.d.ts.map +1 -1
  141. package/dist/commands/skills/skill-discovery.js +2 -1
  142. package/dist/commands/skills/skill-discovery.js.map +1 -1
  143. package/dist/commands/skills/validate.d.ts +79 -2
  144. package/dist/commands/skills/validate.d.ts.map +1 -1
  145. package/dist/commands/skills/validate.js +101 -48
  146. package/dist/commands/skills/validate.js.map +1 -1
  147. package/dist/commands/validate.d.ts.map +1 -1
  148. package/dist/commands/validate.js +26 -16
  149. package/dist/commands/validate.js.map +1 -1
  150. package/dist/commands/verify.d.ts +11 -10
  151. package/dist/commands/verify.d.ts.map +1 -1
  152. package/dist/commands/verify.js +49 -38
  153. package/dist/commands/verify.js.map +1 -1
  154. package/dist/utils/command-error.d.ts +33 -2
  155. package/dist/utils/command-error.d.ts.map +1 -1
  156. package/dist/utils/command-error.js +34 -10
  157. package/dist/utils/command-error.js.map +1 -1
  158. package/dist/utils/config-loader.d.ts.map +1 -1
  159. package/dist/utils/config-loader.js +7 -1
  160. package/dist/utils/config-loader.js.map +1 -1
  161. package/dist/utils/context-budget-issues.d.ts +108 -0
  162. package/dist/utils/context-budget-issues.d.ts.map +1 -0
  163. package/dist/utils/context-budget-issues.js +280 -0
  164. package/dist/utils/context-budget-issues.js.map +1 -0
  165. package/dist/utils/corpus-target.d.ts +48 -0
  166. package/dist/utils/corpus-target.d.ts.map +1 -0
  167. package/dist/utils/corpus-target.js +61 -0
  168. package/dist/utils/corpus-target.js.map +1 -0
  169. package/dist/utils/issue-anchor.d.ts +2 -2
  170. package/dist/utils/issue-anchor.d.ts.map +1 -1
  171. package/dist/utils/issue-anchor.js +1 -1
  172. package/dist/utils/issue-rendering.d.ts +1 -1
  173. package/dist/utils/issue-rendering.d.ts.map +1 -1
  174. package/dist/utils/issue-rendering.js +1 -1
  175. package/dist/utils/issue-rendering.js.map +1 -1
  176. package/dist/utils/issue-severity.d.ts +1 -1
  177. package/dist/utils/issue-severity.d.ts.map +1 -1
  178. package/dist/utils/issue-severity.js +1 -1
  179. package/dist/utils/issue-severity.js.map +1 -1
  180. package/dist/utils/optional-backend.d.ts +77 -0
  181. package/dist/utils/optional-backend.d.ts.map +1 -0
  182. package/dist/utils/optional-backend.js +115 -0
  183. package/dist/utils/optional-backend.js.map +1 -0
  184. package/dist/utils/output.d.ts +17 -0
  185. package/dist/utils/output.d.ts.map +1 -1
  186. package/dist/utils/output.js +19 -0
  187. package/dist/utils/output.js.map +1 -1
  188. package/dist/utils/population-wiring.d.ts +100 -0
  189. package/dist/utils/population-wiring.d.ts.map +1 -0
  190. package/dist/utils/population-wiring.js +98 -0
  191. package/dist/utils/population-wiring.js.map +1 -0
  192. package/dist/utils/projection-store.d.ts +188 -0
  193. package/dist/utils/projection-store.d.ts.map +1 -0
  194. package/dist/utils/projection-store.js +257 -0
  195. package/dist/utils/projection-store.js.map +1 -0
  196. package/dist/utils/resource-loader.d.ts +128 -2
  197. package/dist/utils/resource-loader.d.ts.map +1 -1
  198. package/dist/utils/resource-loader.js +234 -7
  199. package/dist/utils/resource-loader.js.map +1 -1
  200. package/dist/utils/verdict-helpers.d.ts +1 -1
  201. package/dist/utils/verdict-helpers.d.ts.map +1 -1
  202. package/dist/utils/verdict-helpers.js +1 -1
  203. package/dist/utils/verdict-helpers.js.map +1 -1
  204. package/docs/agent.md +2 -2
  205. package/docs/mcp.md +2 -2
  206. package/docs/resources.md +8 -1
  207. package/package.json +15 -12
  208. package/dist/commands/resources/command-helpers.d.ts +0 -5
  209. package/dist/commands/resources/command-helpers.d.ts.map +0 -1
  210. package/dist/commands/resources/command-helpers.js +0 -6
  211. package/dist/commands/resources/command-helpers.js.map +0 -1
@@ -0,0 +1,1079 @@
1
+ /**
2
+ * `vat claude context [path]` — what loads into an agent's context here, and
3
+ * what it costs.
4
+ *
5
+ * The first ANALYSIS verb under `vat claude`, which until now held only
6
+ * management verbs (plugins, marketplaces, org administration). It answers a
7
+ * question, changes nothing, and never gates: there is no threshold anywhere in
8
+ * this file, and the only non-zero exit is {@link handleCommandError}'s 2 for a
9
+ * system failure. A number that fails a build teaches people to stop reading it.
10
+ *
11
+ * ## Everything below is orchestration and formatting — deliberately
12
+ *
13
+ * Which files load, why, and what they cost are all decided in
14
+ * `@vibe-agent-toolkit/resources` (`whatLoadsAt` and `account`). This module
15
+ * populates, calls them, and renders. It computes nothing about context loading
16
+ * of its own, which is the CLI-stays-dumb rule applied to a lane where the
17
+ * temptation is strong: the totals are right there and a "just one more derived
18
+ * field" would put a second, unowned model of the vendor's behaviour in the
19
+ * package no other package can depend on.
20
+ *
21
+ * ## The limits ride WITH the run — ONCE — in every format
22
+ *
23
+ * Spec §11 puts the stated limits in the command's own output rather than in a
24
+ * doc, because a limit a reader has to go and find is a limit that never reaches
25
+ * the person acting on the number. So {@link CLAUDE_CONTEXT_LIMITS} and
26
+ * {@link CLAUDE_CONTEXT_MODELLED_BEHAVIOURS} are fields of the yaml/json
27
+ * ENVELOPE and a printed section of the text rendering, and
28
+ * {@link CLAUDE_CONTEXT_BOUNDS_STATEMENT} — *neither a floor nor a ceiling* —
29
+ * appears in all three. All three are imported, never restated: the sentence is
30
+ * domain content owned beside the list it frames, so every other consumer of the
31
+ * list reaches it too.
32
+ *
33
+ * ⛔ They belong to the ENVELOPE, never to an answer or a region, and every
34
+ * rendering obeys that identically — see {@link ContextEnvelope} for why.
35
+ * Attaching them per answer was not a formatting preference: on the whole-tree
36
+ * sweep `--all` used to be (6,224 answers on this repository) `--format json`
37
+ * measured 76,877,016 bytes and measures 6,581,468 with the block hoisted — 70.3
38
+ * MB of ONE byte-identical paragraph, repeated. That is the JSON spelling of the
39
+ * very burial {@link renderEnvelopeText} refuses to do in text, and it is why
40
+ * {@link ContextCostMapEnvelope} hoists the same block rather than growing one
41
+ * per region.
42
+ *
43
+ * ## `--all` is a MAP, not a sweep
44
+ *
45
+ * ⛔ `--all` emits no per-path documents in any format. It used to answer for
46
+ * every realized path — 10,438 documents and 205,918 lines on a large adopter
47
+ * monorepo, ~491 s — which is not a report anyone reads. It now emits the
48
+ * whole-tree cost map {@link buildContextCostMap} builds, which answers the
49
+ * question the flag exists for: where in this tree is it expensive to work.
50
+ * Naming paths is the drill-down, and is the only way to get a per-path answer.
51
+ *
52
+ * ⛔ Nothing here may read as "complete". Many of the stated limits are signed
53
+ * `over-report`/`under-report` and apply whether or not `unknownTokenRows`,
54
+ * `skippedOversizeRows` and `prunedRows` are all zero, so zeroed counters are not
55
+ * a licence for the words "total cost", "full" or "all context".
56
+ *
57
+ * ⛔ A `null` token or byte count is an UNKNOWN SIZE and is never rendered as 0 —
58
+ * see {@link chargeText}. A confident zero is indistinguishable from a measured
59
+ * one, and the same reasoning is why an unrealized path answers `unknown` rather
60
+ * than an empty table.
61
+ */
62
+ import { account, buildClaudeContextPopulation, buildContextCostMap, CLAUDE_CONTEXT_BOUNDS_STATEMENT, CLAUDE_CONTEXT_LIMITS, CLAUDE_CONTEXT_MODELLED_BEHAVIOURS, CLAUDE_MD_TAG, discoverableFrom, whatLoadsAt, } from '@vibe-agent-toolkit/resources';
63
+ import { findProjectRoot } from '@vibe-agent-toolkit/utils';
64
+ import { Command, Option } from 'commander';
65
+ import { handleCommandError } from '../../utils/command-error.js';
66
+ import { targetPathWithin } from '../../utils/corpus-target.js';
67
+ import { createLogger } from '../../utils/logger.js';
68
+ import { writeJsonOutput, writeStdoutSync, writeYamlOutput } from '../../utils/output.js';
69
+ import { populationWiring } from '../../utils/population-wiring.js';
70
+ import { withPopulationCache } from '../../utils/projection-store.js';
71
+ import { gitTrackerForProjectRoot } from '../audit/distributed-tree.js';
72
+ /** Soft wrap width for the printed limit statements. */
73
+ const WRAP_COLUMNS = 96;
74
+ /** How this command names itself in a refusal. */
75
+ const COMMAND_NAME = 'vat claude context';
76
+ /**
77
+ * How many rows each RANKED section of the `--all` cost map prints.
78
+ *
79
+ * ⛔ A cap exists because the previous shape of `--all` had none: it answered for
80
+ * every realized path, which on a large adopter monorepo was 10,438 documents and
81
+ * 205,918 lines — an output nobody, human or agent, can act on. The map collapses
82
+ * that to two ranked lists, and a ranked list is only useful if its head is
83
+ * readable in one screen. 20 is that head: enough that a real hot spot is
84
+ * somewhere in it, few enough that the whole report stays scannable.
85
+ *
86
+ * ⛔ It bounds the TEXT rendering ONLY. `--format json` carries the map whole —
87
+ * see {@link ContextCostMapEnvelope} — because a program asked for the map, not
88
+ * for a summary of it, and a silently-truncated array is a defect a consumer
89
+ * cannot see.
90
+ *
91
+ * ⛔ Whenever it fires, {@link omittedNotice} says how many rows were left out. A
92
+ * silent cap reads as "this is everything", which is the one thing this report
93
+ * must never say. Exported so a test pins the notice's arithmetic against the
94
+ * same number the renderer slices at, rather than against a literal that is free
95
+ * to disagree with it.
96
+ */
97
+ export const COST_MAP_ROW_LIMIT = 20;
98
+ /**
99
+ * What the two halves of the cost map mean, and which one is exact.
100
+ *
101
+ * Printed under the heading because the numbers are unreadable without it: a
102
+ * reader who takes the per-region figure for an average, or borrows a
103
+ * region-mate's on-demand figure, has read the report backwards. This paraphrases
104
+ * the contracts `RegionCost.alwaysTokens` and `DirectoryCost.onDemandTokens`
105
+ * state in `@vibe-agent-toolkit/resources` — it asserts nothing this module
106
+ * decided, and computes nothing.
107
+ */
108
+ const COST_MAP_METHOD_STATEMENT = 'Directories are ranked by what it costs to work in them: the at-launch floor PLUS what fires'
109
+ + ' on demand there, because a cheap rule under a heavy instruction chain is still an expensive'
110
+ + ' place to work.'
111
+ + ' Every working location in a region loads the same files at launch, so the at-launch figure is'
112
+ + ' EXACT for the whole region rather than an average over it. On-demand cost is reported per'
113
+ + ' DIRECTORY instead, because a path-scoped rule is admitted where some file under that'
114
+ + " directory matches its globs and nowhere else — a region-mate's on-demand figure is never a"
115
+ + " substitute for a directory's own. Only a FILE query is exact for path-scoped rules: name a"
116
+ + ' path (vat claude context src/index.ts) to get one.';
117
+ /**
118
+ * Create the `vat claude context [path]` command.
119
+ *
120
+ * @returns The configured Commander command
121
+ */
122
+ export function createContextCommand() {
123
+ const command = new Command('context');
124
+ command
125
+ .description('Report what Claude Code loads into context at a path, why, and what it costs')
126
+ .argument('[paths...]', 'Files or directories to answer for (default: the current directory)')
127
+ .addOption(new Option('--format <format>', 'Output format: text (default), yaml, or json').choices([
128
+ 'text',
129
+ 'yaml',
130
+ 'json',
131
+ ]).default('text'))
132
+ .option('--all', 'Report the whole-tree cost map — launch cost per region, total cost per directory —'
133
+ + ' instead of answering for named paths')
134
+ .option('--discoverable', 'Also report what the loaded files LINK TO in one hop and the harness does not load')
135
+ .option('--debug', 'Verbose logging to stderr')
136
+ .action(claudeContextCommand)
137
+ .addHelpText('after', `
138
+ Description:
139
+ Report which CLAUDE.md files, .claude/rules files and @-imported files load
140
+ into an agent's context at a path, why each one is there, and what it costs.
141
+ A FILE argument is exact. A directory argument classifies each path-scoped
142
+ rule as ∀ (its glob covers every file there, so it is a second CLAUDE.md for
143
+ that directory) or ∃ (some file there matches, and the answer names it); a
144
+ rule no file there can match is left out rather than charged.
145
+
146
+ Several paths may be named at once. The tree is enumerated ONCE and every
147
+ path answered from that one population, so asking about ten paths together
148
+ costs what asking about one costs — not ten times it. No paths means the
149
+ current directory.
150
+
151
+ --all answers a different question: where in this tree is it expensive to
152
+ work. It reports launch cost once per REGION (every directory inheriting one
153
+ CLAUDE.md chain — exact for all of them, not an average) and, per DIRECTORY,
154
+ the TOTAL of that launch floor and what fires on demand there (a path-scoped
155
+ rule fires for some directories and not others, so the on-demand half is
156
+ never borrowed from a region-mate). Directories are ranked by that total. It
157
+ emits no per-path documents; name paths for those. --discoverable applies to
158
+ named paths only.
159
+
160
+ Output:
161
+ - kind: context-answers for named paths, context-cost-map for --all —
162
+ the two are different documents, so never guess which you hold
163
+ - root: the corpus root that was enumerated
164
+ - answers: (context-answers) one document per requested path, in the order
165
+ requested — always a list, even for one path, so consumers never
166
+ branch on count; with totals, rows, and every admitting predicate
167
+ - costMap: (context-cost-map) regions worst-first by launch cost, directories
168
+ worst-first by total cost (launch + on demand), the tree-level
169
+ roll-up of rows nothing could be measured for, plus the counts of
170
+ locations evaluated, queried, and left out for want of an answer
171
+ - limits: what this run deliberately does not settle, in both directions.
172
+ On the ENVELOPE beside root, never on an answer or a region — they
173
+ bound the method rather than any one path, so they are stated
174
+ exactly once however much was measured
175
+
176
+ Counts of rows whose size is unknown, skipped by the 4 MiB cliff, or pruned
177
+ behind one are reported beside every estimate and NEVER summed into it. The
178
+ text rendering prints the top ${COST_MAP_ROW_LIMIT} of each ranked list and says how many it
179
+ left out; --format json carries the map whole.
180
+
181
+ A path the projection never realized answers kind: unknown — never zero.
182
+ Diagnostics and blob-stage refusals go to stderr; stdout is the document.
183
+
184
+ Exit Codes:
185
+ 0 - An answer was produced (there is no threshold and no gate)
186
+ 1 - Invalid usage (unknown option, or an unsupported --format value)
187
+ 2 - System error (a path outside the corpus root, unreadable tree)
188
+
189
+ Example:
190
+ $ vat claude context src/index.ts docs/ README.md # one scan, three answers
191
+ `);
192
+ return command;
193
+ }
194
+ /**
195
+ * Action handler for `vat claude context [path]`.
196
+ *
197
+ * ⛔ The two branches produce DIFFERENT documents and there is no third mode: a
198
+ * `--per-path` escape hatch back to the old sweep is exactly the backward
199
+ * compatibility shim this project forbids pre-1.0, and naming paths explicitly
200
+ * already gives the per-path answer — now from a population the caller pays for
201
+ * once instead of ten thousand times.
202
+ *
203
+ * @param pathArgs - The paths to answer for; empty means the current directory
204
+ * @param options - The command's flags
205
+ */
206
+ export async function claudeContextCommand(pathArgs, options) {
207
+ const logger = createLogger(options.debug === true ? { debug: true } : {});
208
+ const startTime = Date.now();
209
+ const sweep = options.all === true;
210
+ try {
211
+ const root = findProjectRoot(process.cwd()) ?? process.cwd();
212
+ // 🔑 Every argument is resolved BEFORE the population, not inside the map.
213
+ // A path outside the corpus is a usage error, and finding it afterwards
214
+ // would charge the caller a full population — minutes on a cold cache — to
215
+ // be told they mistyped. `--all` has no arguments to check.
216
+ const requested = sweep ? [] : targetsWithin(root, pathArgs);
217
+ const projection = await populateContext(root, logger);
218
+ const format = options.format ?? 'text';
219
+ if (sweep) {
220
+ // Every number in the map is decided in `@vibe-agent-toolkit/resources`.
221
+ // This branch calls one function and formats what it returns.
222
+ const map = buildContextCostMap(projection);
223
+ emit(costMapEnvelope(root, map), renderCostMapText(map), format);
224
+ }
225
+ else {
226
+ // ONE population, N queries. `whatLoadsAt` is a pure read of materialised
227
+ // tables, so the marginal cost of another path is a map lookup — which is
228
+ // the whole reason this command takes a list rather than being run twice.
229
+ const answers = requested.map((target) => documentFor(target, projection, root, options.discoverable === true));
230
+ emit(contextEnvelope(root, answers), renderEnvelopeText(answers), format);
231
+ }
232
+ // ⛔ Always 0. There is no threshold in this command and there is not going
233
+ // to be one — a number that fails a build is a number people learn to stop
234
+ // reading. The explicit exit matches every other leaf here and guarantees the
235
+ // process ends rather than waiting on whatever the population left behind.
236
+ process.exit(0);
237
+ }
238
+ catch (error) {
239
+ handleCommandError(error, logger, startTime, 'claude context');
240
+ }
241
+ }
242
+ /**
243
+ * The answer document for one query.
244
+ *
245
+ * Split from the handler so the handler stays a straight line: the accounting
246
+ * call needs the `claude-md` identity set, and threading that through the
247
+ * handler body put three statements between the query and its document.
248
+ *
249
+ * Returns the document alone — rendering moved to {@link renderEnvelopeText},
250
+ * which needs every document at once to print the limits exactly once, and the
251
+ * limits themselves are attached by {@link contextEnvelope}, never here.
252
+ *
253
+ * ⛔ Exported so it can be TESTED. What has to be pinned is an ABSENCE — that no
254
+ * limit field is on the returned document — and an absence is only observable by
255
+ * calling the function that would have added it.
256
+ *
257
+ * @param answer - The query's answer
258
+ * @param projection - The populated projection, for the `claude-md` tag rows
259
+ * @param discoverable - Whether to compute the one-hop reachable set
260
+ * @returns The answer document
261
+ */
262
+ export function answerDocument(answer, projection, discoverable) {
263
+ // The cliff and root discovery read ONE vocabulary: these are the ids the
264
+ // shipped `classifyPath` tagged, not a second basename rule invented here.
265
+ const claudeMdIds = new Set(projection.resourceTags
266
+ .filter((tag) => tag.tag === CLAUDE_MD_TAG)
267
+ .map((tag) => tag.resourceId));
268
+ const accounted = account(answer, claudeMdIds);
269
+ // 🔑 `conditions`, `overBudgetRules` and `unattributedImports` live on the
270
+ // ORIGINAL answer — `AccountedContext` is `{rows, totals}` and nothing else.
271
+ // Reading them off the accounting result silently drops every warning.
272
+ const document = {
273
+ kind: 'answer',
274
+ input: answer.input,
275
+ directory: answer.directory,
276
+ file: answer.file,
277
+ totals: accounted.totals,
278
+ rows: accounted.rows,
279
+ conditions: answer.conditions,
280
+ overBudgetRules: answer.overBudgetRules,
281
+ unattributedImports: answer.unattributedImports,
282
+ // The ANSWER is passed, not recomputed: it is the authority for what is
283
+ // already loaded, and the two lenses partitioning depends on both reading
284
+ // one loaded set.
285
+ discoverable: discoverable ? discoverableFrom(projection, answer) : null,
286
+ };
287
+ return document;
288
+ }
289
+ /**
290
+ * Wrap the run's documents in the envelope, with the limits attached ONCE.
291
+ *
292
+ * The one place {@link CLAUDE_CONTEXT_LIMITS} and its two companions enter the
293
+ * machine-readable output. Keeping that a single assignment is what makes the
294
+ * "stated once" property structural rather than a habit: there is no per-answer
295
+ * site left where a copy could be reintroduced.
296
+ *
297
+ * ⛔ Exported so it can be TESTED alongside {@link answerDocument} — the
298
+ * regression this guards (an answer growing its own copy of the block) is a
299
+ * property of the two functions TOGETHER, and a test that can reach only one of
300
+ * them cannot see it.
301
+ *
302
+ * @param root - The corpus root that was enumerated
303
+ * @param answers - One document per requested path, in the order requested
304
+ * @returns The envelope, ready to serialize
305
+ */
306
+ export function contextEnvelope(root, answers) {
307
+ return {
308
+ kind: 'context-answers',
309
+ root,
310
+ answers,
311
+ boundsStatement: CLAUDE_CONTEXT_BOUNDS_STATEMENT,
312
+ limits: CLAUDE_CONTEXT_LIMITS,
313
+ modelledBehaviours: CLAUDE_CONTEXT_MODELLED_BEHAVIOURS,
314
+ };
315
+ }
316
+ /**
317
+ * Wrap the `--all` cost map in its envelope, with the limits attached ONCE.
318
+ *
319
+ * The mirror of {@link contextEnvelope}, and deliberately its own function rather
320
+ * than a generic over both: the two envelopes differ in more than one field, and
321
+ * a shared builder taking a payload would make `kind` a parameter — which is how
322
+ * a discriminator stops discriminating.
323
+ *
324
+ * ⛔ Exported so a test can pin, over a many-region map, that the limit block
325
+ * appears exactly ONCE in the serialized document. Presence passes on a copy per
326
+ * region, which is the 70.3 MB defect this command already shipped once.
327
+ *
328
+ * @param root - The corpus root that was enumerated
329
+ * @param costMap - The whole-tree cost map, carried entire
330
+ * @returns The envelope, ready to serialize
331
+ */
332
+ export function costMapEnvelope(root, costMap) {
333
+ return {
334
+ kind: 'context-cost-map',
335
+ root,
336
+ costMap,
337
+ boundsStatement: CLAUDE_CONTEXT_BOUNDS_STATEMENT,
338
+ limits: CLAUDE_CONTEXT_LIMITS,
339
+ modelledBehaviours: CLAUDE_CONTEXT_MODELLED_BEHAVIOURS,
340
+ };
341
+ }
342
+ /**
343
+ * Resolve every requested path, defaulting to the current directory.
344
+ *
345
+ * No arguments means the current directory — NOT the whole corpus. `--all` is
346
+ * the sweep, spelled explicitly, because a bare `vat claude context` answering
347
+ * for thousands of paths would turn the friendliest invocation into the most
348
+ * expensive one.
349
+ *
350
+ * @param root - The discovered project root
351
+ * @param pathArgs - The path arguments, possibly empty
352
+ * @returns One root-relative target per argument, in argument order
353
+ */
354
+ function targetsWithin(root, pathArgs) {
355
+ if (pathArgs.length === 0)
356
+ return [targetPathWithin(root, undefined, COMMAND_NAME)];
357
+ return pathArgs.map((pathArg) => targetPathWithin(root, pathArg, COMMAND_NAME));
358
+ }
359
+ /**
360
+ * The document for one target, answer or non-answer.
361
+ *
362
+ * @param target - The root-relative path to answer for
363
+ * @param projection - The populated projection
364
+ * @param root - The corpus root, for the non-answer's explanation
365
+ * @param discoverable - Whether to compute the one-hop reachable set
366
+ * @returns The answer document, or the structurally-different unknown document
367
+ */
368
+ function documentFor(target, projection, root, discoverable) {
369
+ const answer = whatLoadsAt(projection, target);
370
+ if (answer.kind === 'unknown')
371
+ return unknownDocumentFor(answer.input, root);
372
+ return answerDocument(answer, projection, discoverable);
373
+ }
374
+ /**
375
+ * Render every answer for a person, with the limits stated exactly once.
376
+ *
377
+ * ⛔ The limits are printed ONCE, after the last answer, rather than per answer.
378
+ * They are properties of the MEASUREMENT METHOD, not of any one path, so
379
+ * repeating them per path would read as though each answer carried its own
380
+ * caveats — and across a many-path run would bury the answers under identical
381
+ * paragraphs. A run with no answered path prints no limits at all, for the same
382
+ * reason {@link unknownDocumentFor} omits them: nothing was measured, so there is
383
+ * no measurement to bound.
384
+ *
385
+ * @param documents - The answers, in requested order
386
+ * @returns The text rendering, newline-terminated
387
+ */
388
+ function renderEnvelopeText(documents) {
389
+ const bodies = documents.map((document) => document.kind === 'unknown' ? renderUnknownText(document) : renderAnswerText(document));
390
+ const measured = documents.some((document) => document.kind === 'answer');
391
+ if (!measured)
392
+ return bodies.join('\n');
393
+ return `${bodies.join('\n')}${limitSection().join('\n')}\n`;
394
+ }
395
+ /**
396
+ * Render the `--all` cost map for a person: where in this tree it is expensive
397
+ * to work.
398
+ *
399
+ * Four sections, in the order a reader needs them — the region table (what each
400
+ * part of the tree costs at launch), the regions' own files (what they are paying
401
+ * for), the directories that cost the most to work in overall, and what the map
402
+ * looked at — then the limits, ONCE.
403
+ *
404
+ * ⛔ Every ranked section is capped at {@link COST_MAP_ROW_LIMIT} and every cap
405
+ * that fires announces itself. ⛔ Nothing here sums an unknown into a total or
406
+ * calls any figure complete: the counted-not-summed rows are printed beside each
407
+ * estimate, and the stated limits apply whether or not those counters are zero.
408
+ *
409
+ * ⛔ Exported so the properties above can be TESTED with inputs a real tree never
410
+ * produces — a null token count, more directories than the cap. On this repository
411
+ * every file has a measured blob, so an assertion driven by a real run compares
412
+ * `false === false` and would keep passing against a `?? 0`.
413
+ *
414
+ * @param map - The whole-tree cost map from `buildContextCostMap`
415
+ * @returns The text rendering, newline-terminated
416
+ */
417
+ export function renderCostMapText(map) {
418
+ const lines = [
419
+ 'Context cost by region — what it costs to work in each part of this tree',
420
+ '',
421
+ ...wrapStatement(COST_MAP_METHOD_STATEMENT, ' '),
422
+ '',
423
+ ...regionTable(map.regions),
424
+ ...map.regions.slice(0, COST_MAP_ROW_LIMIT).flatMap(regionDetail),
425
+ ...directoryTable(map.directories),
426
+ ...coverageLines(map),
427
+ ];
428
+ return `${lines.join('\n')}\n${limitSection().join('\n')}\n`;
429
+ }
430
+ /**
431
+ * The ranked region table: what a session pays at launch in each part of the tree.
432
+ *
433
+ * @param regions - The regions, already worst-first by launch cost
434
+ * @returns The section's lines, blank-terminated
435
+ */
436
+ function regionTable(regions) {
437
+ const shown = regions.slice(0, COST_MAP_ROW_LIMIT);
438
+ const lines = [' at launch locations region'];
439
+ for (const region of shown) {
440
+ lines.push(` ${padCount(region.alwaysTokens, 9)} ${padCount(region.locationCount, 9)}`
441
+ + ` ${displayPath(region.representative)}`);
442
+ }
443
+ lines.push(...omittedNotice(shown.length, regions.length, 'region', 'regions'), '');
444
+ return lines;
445
+ }
446
+ /**
447
+ * One region's launch-time bill, itemised.
448
+ *
449
+ * 🔑 The rows are rendered by {@link rowSection}, the same function the per-path
450
+ * answer uses, so a file reads identically in both reports and there is exactly
451
+ * one admission-describer. Its `loadClass` filter is a no-op here — `alwaysRows`
452
+ * is already that class — and passing it anyway keeps the call honest rather than
453
+ * relying on the caller's guarantee.
454
+ *
455
+ * @param region - The region to itemise
456
+ * @returns The section's lines, blank-terminated
457
+ */
458
+ function regionDetail(region) {
459
+ return [
460
+ `Region ${displayPath(region.representative)} — ${groupDigits(region.alwaysTokens)} tokens`
461
+ + ` at launch, ${countOf(region.locationCount, 'location', 'locations')}`,
462
+ ...quietCounterLines(region),
463
+ ...nestBlock(rowSection('Loaded at launch', region.alwaysRows, 'always')),
464
+ '',
465
+ ];
466
+ }
467
+ /**
468
+ * A region's three counters, printed only when one of them has something to say.
469
+ *
470
+ * ⛔ **This suppression is safe ONLY because the tree-level roll-up in
471
+ * {@link coverageLines} prints UNCONDITIONALLY, zeros included.** The honesty
472
+ * rule in this lane is that a reader must never be able to mistake "nothing here
473
+ * was unmeasurable" for "nobody counted", and after this suppression the roll-up
474
+ * is the single thing in the report carrying that. Silence a region's zeros only
475
+ * while a tree-level zero is still printed somewhere; drop the roll-up and this
476
+ * function has to go back to unconditional.
477
+ *
478
+ * ⛔ Deliberately NOT applied to {@link estimateLines}. A single-path answer has
479
+ * no roll-up to fall back on, so its counters are the only statement that the
480
+ * rows were counted at all and must keep printing whatever their values.
481
+ *
482
+ * The measured motivation: nine regions on this repository printed 27 lines of
483
+ * pure zeros, burying the launch bills the section exists to show.
484
+ *
485
+ * @param region - The region whose counters to print
486
+ * @returns The three lines, or none when all three are zero
487
+ */
488
+ function quietCounterLines(region) {
489
+ const anything = region.unknownTokenRows + region.skippedOversizeRows + region.prunedRows;
490
+ if (anything === 0)
491
+ return [];
492
+ // Whole block or nothing: a reader comparing two regions must be comparing the
493
+ // same three lines, not one region's selected non-zeros.
494
+ return counterLines(region);
495
+ }
496
+ /**
497
+ * Indent a borrowed section one level, and drop the blank line it terminates with.
498
+ *
499
+ * {@link rowSection} is written for the per-path answer, where it sits at the top
500
+ * level and separates itself from what follows. Nested under a region heading it
501
+ * needs a level of indent, and its terminator would double the region's own — so
502
+ * this drops every blank rather than the last one specifically, which is exact
503
+ * because that section emits no interior blanks.
504
+ *
505
+ * @param lines - The borrowed section's lines
506
+ * @returns The same lines, indented, with blanks removed
507
+ */
508
+ function nestBlock(lines) {
509
+ return lines.filter((line) => line !== '').map((line) => ` ${line}`);
510
+ }
511
+ /**
512
+ * The ranked directory table: where in this tree it is most expensive to work.
513
+ *
514
+ * ⛔ Ordered and headed by TOTAL cost — the launch floor plus the on-demand
515
+ * burden — which is the key `buildContextCostMap` sorts by. Ranking on a key the
516
+ * producer did not sort on would make the column descend non-monotonically and
517
+ * read as a bug; ranking on the on-demand half alone would answer "where does a
518
+ * rule fire", which is not the question the map is for.
519
+ *
520
+ * ⛔ Every one of the three figures is READ. The CLI does not add
521
+ * `alwaysTokens` to `onDemandTokens` here — that sum is `DirectoryCost.
522
+ * totalTokens`, computed where both halves are known to be charged-only totals.
523
+ * A second sum in this module would be a second, unowned model of what "cost"
524
+ * means, free to disagree with the ranking beside it. Both halves stay in the
525
+ * table because they are acted on differently: the floor by moving instructions,
526
+ * the burden by scoping rules.
527
+ *
528
+ * @param directories - The directories, already worst-first by total cost
529
+ * @returns The section's lines, blank-terminated, or none when there are none
530
+ */
531
+ function directoryTable(directories) {
532
+ if (directories.length === 0)
533
+ return [];
534
+ const shown = directories.slice(0, COST_MAP_ROW_LIMIT);
535
+ const lines = [
536
+ 'Most expensive directories to work in — at launch PLUS what fires on demand there',
537
+ ' total at launch on demand directory',
538
+ ];
539
+ for (const directory of shown) {
540
+ lines.push(` ${padCount(directory.totalTokens, 9)} ${padCount(directory.alwaysTokens, 9)}`
541
+ + ` ${padCount(directory.onDemandTokens, 9)} ${displayPath(directory.directory)}`
542
+ // ⛔ The unknown-row suffix appears only when there is one, for the same
543
+ // reason and under the same condition as {@link quietCounterLines}: the
544
+ // tree-level roll-up in {@link coverageLines} states unconditionally that
545
+ // these rows were counted, so twenty repetitions of "0 rows of unknown
546
+ // size" buy nothing and crowd out the paths the table is ranking. Remove
547
+ // the roll-up and this suffix has to become unconditional again.
548
+ + unknownRowSuffix(directory.unknownTokenRows));
549
+ }
550
+ lines.push(...omittedNotice(shown.length, directories.length, 'directory', 'directories'), '');
551
+ return lines;
552
+ }
553
+ /**
554
+ * The note that a directory's on-demand cost is an under-report, when it is.
555
+ *
556
+ * @param unknownTokenRows - On-demand rows at that directory whose size is unknown
557
+ * @returns The suffix, or nothing at all when every row was measured
558
+ */
559
+ function unknownRowSuffix(unknownTokenRows) {
560
+ if (unknownTokenRows === 0)
561
+ return '';
562
+ return ` · ${countOf(unknownTokenRows, 'row', 'rows')} of unknown size, counted not summed`;
563
+ }
564
+ /**
565
+ * What the map looked at, including the locations it could not answer for.
566
+ *
567
+ * ⛔ `skippedUnknownLocations` is PRINTED, not folded away. A location left out
568
+ * because a query it needed answered `unknown` is a hole in the map, and a report
569
+ * that quietly dropped it would be indistinguishable from one where every
570
+ * location answered.
571
+ *
572
+ * ⛔ The tree-level roll-up prints UNCONDITIONALLY, all-zero included, and that
573
+ * is load-bearing: {@link quietCounterLines} suppresses the per-region zeros, so
574
+ * this is the only place left saying the rows were counted at all. A zero here is
575
+ * a measurement; an absent line would be indistinguishable from nobody looking.
576
+ *
577
+ * @param map - The cost map
578
+ * @returns The section's lines, blank-terminated
579
+ */
580
+ function coverageLines(map) {
581
+ return [
582
+ 'What this map looked at',
583
+ ` working locations evaluated ${groupDigits(map.evaluatedDirectories)}`,
584
+ ` queries issued ${groupDigits(map.queriedDirectories)}`,
585
+ ` no answer of their own ${countOf(map.skippedUnknownLocations, 'location', 'locations')}`
586
+ + ' (left out of the table above, never counted as zero)',
587
+ ' rows this map could not measure, over every region and directory above:',
588
+ ...counterLines(map.unmeasuredRows),
589
+ '',
590
+ ];
591
+ }
592
+ /**
593
+ * Say how many ranked rows were left unprinted, or say nothing when none were.
594
+ *
595
+ * ⛔ The COUNT is the point. "Some rows were omitted" leaves a reader unable to
596
+ * tell a table that dropped three rows from one that dropped three thousand, and
597
+ * a cap with no notice at all reads as "this is everything" — which is the claim
598
+ * this whole report is built not to make.
599
+ *
600
+ * @param shown - How many rows were printed
601
+ * @param total - How many there were
602
+ * @param singular - What one omitted row is, for the `total - shown === 1` case
603
+ * @param plural - What several of them are
604
+ * @returns The notice line, or none when nothing was truncated
605
+ */
606
+ function omittedNotice(shown, total, singular, plural) {
607
+ if (total <= shown)
608
+ return [];
609
+ const omitted = total - shown;
610
+ const noun = omitted === 1 ? singular : plural;
611
+ return [
612
+ ` ... and ${groupDigits(omitted)} more ${noun} not shown —`
613
+ + ` this is the ${groupDigits(shown)} most expensive, not the whole tree`,
614
+ ];
615
+ }
616
+ /**
617
+ * The three row counters that keep an estimate from reading as settled.
618
+ *
619
+ * Shared by the per-path answer and by every region of the cost map, because it
620
+ * is one rule stated in one place: a row whose size is unknown, whose file the
621
+ * 4 MiB cliff skipped, or which sits behind such a file is COUNTED here and
622
+ * summed into nothing. Two copies of these three lines would be two places for a
623
+ * `?? 0` to appear in.
624
+ *
625
+ * @param counters - Anything carrying the three counts — `ContextTotals`, or a
626
+ * region's own always-row counts
627
+ * @returns The three lines, unterminated
628
+ */
629
+ function counterLines(counters) {
630
+ return [
631
+ ` size unknown ${countOf(counters.unknownTokenRows, 'row', 'rows')}`
632
+ + ' (counted, never summed as zero)',
633
+ ` skipped over 4 MiB ${countOf(counters.skippedOversizeRows, 'row', 'rows')}`,
634
+ ` pruned behind a skip ${countOf(counters.prunedRows, 'row', 'rows')}`,
635
+ ];
636
+ }
637
+ /**
638
+ * A count with its noun, digit-grouped and agreeing in number.
639
+ *
640
+ * The alternative — a bare `${n} ${plural}` — prints "1 locations" whenever a
641
+ * region has exactly one, which is the common case on a tree with many small
642
+ * packages and reads as a rendering bug the moment anyone sees it. Both forms are
643
+ * PARAMETERS rather than a suffixed `s`, because the nouns this report uses are
644
+ * not all regular ("directory" is the counter-example living two functions away).
645
+ *
646
+ * @param value - The count
647
+ * @param singular - The noun for exactly one
648
+ * @param plural - The noun for any other count, zero included
649
+ * @returns The count and its noun
650
+ */
651
+ function countOf(value, singular, plural) {
652
+ return `${groupDigits(value)} ${value === 1 ? singular : plural}`;
653
+ }
654
+ /**
655
+ * A count, digit-grouped and right-aligned to a column width.
656
+ *
657
+ * @param value - The count
658
+ * @param width - The column width; a longer number overflows rather than truncates
659
+ * @returns The padded text
660
+ */
661
+ function padCount(value, width) {
662
+ return groupDigits(value).padStart(width);
663
+ }
664
+ /**
665
+ * A non-negative integer with thousands separators.
666
+ *
667
+ * ⚠️ Written out by hand rather than through `toLocaleString` or `Intl`: those
668
+ * are ICU- and locale-dependent, so the same tree would render `38,412` on one
669
+ * machine and `38 412` on another, and this report is exactly the kind of output
670
+ * people diff between machines. Every number reaching it is a token estimate or a
671
+ * row count, so the negative case cannot arise and is not invented for.
672
+ *
673
+ * @param value - The count
674
+ * @returns The grouped digits
675
+ */
676
+ function groupDigits(value) {
677
+ const digits = String(value);
678
+ let grouped = '';
679
+ for (const [index, digit] of [...digits].entries()) {
680
+ if (index > 0 && (digits.length - index) % 3 === 0)
681
+ grouped += ',';
682
+ grouped += digit;
683
+ }
684
+ return grouped;
685
+ }
686
+ /**
687
+ * Populate the Claude-context lane for one tree.
688
+ *
689
+ * @param root - The absolute corpus root
690
+ * @param logger - Where blob-stage refusals go. **stderr**, never stdout: this
691
+ * command's stdout is the document a caller parses, and a diagnostic in the
692
+ * middle of it breaks every consumer
693
+ * @returns The populated projection
694
+ */
695
+ async function populateContext(root, logger) {
696
+ return withPopulationCache({ root }, async (cache) => {
697
+ const gitTracker = await gitTrackerForProjectRoot(root);
698
+ return buildClaudeContextPopulation({ root, ...populationWiring(logger, gitTracker, cache, root) });
699
+ });
700
+ }
701
+ /**
702
+ * Write the document in the requested format.
703
+ *
704
+ * @param document - The yaml/json payload
705
+ * @param text - The text rendering of the same answer
706
+ * @param format - The selected format
707
+ */
708
+ function emit(document, text, format) {
709
+ if (format === 'json') {
710
+ writeJsonOutput(document);
711
+ return;
712
+ }
713
+ if (format === 'yaml') {
714
+ writeYamlOutput(document);
715
+ return;
716
+ }
717
+ writeStdoutSync(text);
718
+ }
719
+ /**
720
+ * The non-answer, spelled so it cannot be mistaken for an empty answer.
721
+ *
722
+ * ⛔ **A non-answer publishes no measurement, in every format.** No `totals`, no
723
+ * `rows`: nothing was measured here, so anything readable as a figure would
724
+ * assert that a measurement happened, which is the exact confusion `kind:
725
+ * 'unknown'` exists to prevent. The limits are one level up on the ENVELOPE and
726
+ * bound the run's method, not this path — a sweep whose every path was
727
+ * unrealized still measured nothing, and the `explanation` carries the only
728
+ * caveat that applies to a non-answer, which is that there is no answer.
729
+ *
730
+ * @param input - The path that was asked about
731
+ * @param root - The corpus root that was enumerated
732
+ * @returns The unknown document
733
+ */
734
+ function unknownDocumentFor(input, root) {
735
+ return {
736
+ kind: 'unknown',
737
+ input,
738
+ reason: 'path-not-realized',
739
+ explanation: `${displayPath(input)} is not a path this projection realized under ${root}, so VAT did not`
740
+ + ' look at it. This is NOT an answer of "nothing loads here" — no context was measured at'
741
+ + ' all. Check the path exists and is not excluded from enumeration.',
742
+ };
743
+ }
744
+ /**
745
+ * Render the non-answer for a person.
746
+ *
747
+ * @param document - The unknown document
748
+ * @returns The text rendering, newline-terminated
749
+ */
750
+ function renderUnknownText(document) {
751
+ return [
752
+ `NO ANSWER for ${displayPath(document.input)} — reason: ${document.reason}`,
753
+ '',
754
+ ...wrapStatement(document.explanation, ' '),
755
+ '',
756
+ ].join('\n');
757
+ }
758
+ /**
759
+ * Render the answer for a person.
760
+ *
761
+ * @param document - The answer document
762
+ * @returns The text rendering, newline-terminated
763
+ */
764
+ function renderAnswerText(document) {
765
+ const lines = [
766
+ ...headingLines(document),
767
+ ...estimateLines(document.totals),
768
+ ...rowSection('Loaded at launch (always)', document.rows, 'always'),
769
+ ...rowSection('Loaded on demand', document.rows, 'on-demand'),
770
+ ...listSection('Conditions', document.conditions.map(conditionLine)),
771
+ ...listSection('Rules whose paths: list exceeded the vendor pattern budget', document.overBudgetRules),
772
+ ...listSection('Imported files no importer could be attributed to', document.unattributedImports),
773
+ ...discoverySection(document.discoverable),
774
+ ];
775
+ return `${lines.join('\n')}\n`;
776
+ }
777
+ /**
778
+ * What the loaded files point at and the harness does not load.
779
+ *
780
+ * ⛔ Printed under its own heading with its own total, never merged into the
781
+ * token estimate. Nothing loads a markdown link, so this is an upper bound on a
782
+ * VOLUNTARY cost — what following every link once would add — and adding it to a
783
+ * context-budget figure would charge a session for documents it may never open.
784
+ * The heading says "not loaded" for a reader who sees only this section.
785
+ *
786
+ * A `null` argument means the lens was not asked for and prints NOTHING. An
787
+ * empty `rows` prints the heading with a zero, because "this file links nowhere"
788
+ * is a real and useful answer that must not be confused with "nobody looked".
789
+ *
790
+ * @param discoverable - The lens's answer, or null when `--discoverable` was off
791
+ * @returns The section's lines, or none when the lens did not run
792
+ */
793
+ function discoverySection(discoverable) {
794
+ if (discoverable === null)
795
+ return [];
796
+ const { rows, totals } = discoverable;
797
+ const lines = [
798
+ 'Discoverable in one hop — LINKED from the loaded files, NOT loaded',
799
+ ` ${groupDigits(totals.discoverableTokens)} tokens if every link were followed once`
800
+ + ' (a ceiling, never a charge)',
801
+ ` ${groupDigits(totals.unknownTokenRows)} size unknown`
802
+ + ` · ${groupDigits(totals.unrealizedRows)} not in this tree`
803
+ + ` · ${groupDigits(totals.outsideRootRows)} outside the root`,
804
+ ];
805
+ for (const row of rows) {
806
+ lines.push(` ${displayPath(row.path)} — ${discoverableCost(row)}`);
807
+ for (const citation of row.citedBy) {
808
+ const text = citation.text === null ? '' : ` as "${citation.text}"`;
809
+ lines.push(` linked from ${displayPath(citation.fromPath)}:${citation.line}${text}`);
810
+ }
811
+ }
812
+ lines.push('');
813
+ return lines;
814
+ }
815
+ /**
816
+ * What one discoverable row would cost, or why VAT cannot say.
817
+ *
818
+ * ⛔ Never `0` for an unmeasured row, the same rule {@link chargeText} enforces
819
+ * one section up. `unrealized` says what it is — an absence in THIS projection —
820
+ * rather than "broken": adjudicating a link is `vat resources validate`'s lane.
821
+ *
822
+ * @param row - The discoverable row
823
+ * @returns The cost phrase
824
+ */
825
+ function discoverableCost(row) {
826
+ if (row.reach === 'outside-root')
827
+ return 'outside the corpus root, so its size is unknowable here';
828
+ if (row.reach === 'unrealized')
829
+ return 'not realized in this projection, so nothing is known of it';
830
+ if (row.tokens === null)
831
+ return 'size unknown: no measured blob, so it is counted, not summed';
832
+ return `${groupDigits(row.tokens)} tokens if opened`;
833
+ }
834
+ /**
835
+ * The heading, which states up front whether the query was exact.
836
+ *
837
+ * @param document - The answer document
838
+ * @returns The heading lines, blank-terminated
839
+ */
840
+ function headingLines(document) {
841
+ const exactness = document.file === null
842
+ ? 'DIRECTORY query — a path-scoped rule is reported as ∀ (covers every file here)'
843
+ + ' or ∃ (some file here matches); only a FILE query is exact'
844
+ : 'FILE query — path-scoped rules are matched exactly';
845
+ return [`Claude Code context at ${displayPath(document.input)}`, ` ${exactness}`, ''];
846
+ }
847
+ /**
848
+ * The token estimate and the three counters that keep it from reading as settled.
849
+ *
850
+ * @param totals - The accounting totals
851
+ * @returns The section's lines, blank-terminated
852
+ */
853
+ function estimateLines(totals) {
854
+ return [
855
+ 'Token estimate',
856
+ ` always-loaded ${groupDigits(totals.alwaysTokens)} tokens`,
857
+ ` on-demand ${groupDigits(totals.onDemandTokens)} tokens`,
858
+ // ⛔ UNCONDITIONAL here, unlike a region's — see {@link quietCounterLines}.
859
+ // A single-path answer has no tree-level roll-up to fall back on, so these
860
+ // three lines are its only statement that the rows were counted at all.
861
+ ...counterLines(totals),
862
+ '',
863
+ ];
864
+ }
865
+ /**
866
+ * One load class's rows, each with every predicate that admitted it.
867
+ *
868
+ * @param title - The section heading
869
+ * @param rows - Every accounted row
870
+ * @param loadClass - The class this section reports
871
+ * @returns The section's lines, or none when the class is empty
872
+ */
873
+ function rowSection(title, rows, loadClass) {
874
+ const selected = rows.filter((row) => row.loadClass === loadClass);
875
+ if (selected.length === 0)
876
+ return [];
877
+ const lines = [title];
878
+ for (const row of selected) {
879
+ lines.push(` ${row.path} — ${chargeText(row)}`);
880
+ for (const admission of row.admissions) {
881
+ lines.push(` ${describeAdmission(admission)}`);
882
+ }
883
+ }
884
+ lines.push('');
885
+ return lines;
886
+ }
887
+ /**
888
+ * What one row costs, or why it costs nothing.
889
+ *
890
+ * ⛔ A null token count renders as "size unknown", never as `0`. The `charged`
891
+ * branch cannot be reached with a null — `chargeOf` classifies those
892
+ * `unknown-size` first — but the check is written as a value test rather than a
893
+ * `?? 0`, so if that ever changed the output would say what it knows instead of
894
+ * asserting a measurement it does not have.
895
+ *
896
+ * **Exported solely so that rule can be pinned by a test that would FAIL if a
897
+ * `?? 0` were introduced.** The property lives in the RENDERER and nowhere else:
898
+ * an assertion over the json rows only re-states what `account` already
899
+ * guarantees, and on any real tree every row carries a blob, so such an
900
+ * assertion compares `false === false` and passes without ever reaching the code
901
+ * that could print a zero. It is not part of this module's command surface and
902
+ * nothing outside its own test may call it.
903
+ *
904
+ * @param row - The accounted row
905
+ * @returns The cost phrase
906
+ */
907
+ export function chargeText(row) {
908
+ if (row.charge === 'oversize-skipped') {
909
+ return 'skipped: past the 4 MiB CLAUDE.md cliff, so none of it loads';
910
+ }
911
+ if (row.charge === 'pruned-by-oversize') {
912
+ return 'not reached: every import route into it passes through a skipped file';
913
+ }
914
+ if (row.tokens === null)
915
+ return 'size unknown: no measured blob, so it is counted, not summed';
916
+ // ⚠️ Grouped through the SAME helper the tables use. Two spellings of one
917
+ // quantity — `14,396` in a column and `8385` on the row ten lines below it —
918
+ // read as a bug in the measurement rather than as a formatting choice. This
919
+ // changes only how the number is written, never whether one is written: the
920
+ // null branch above is what keeps an unknown size out of the digits entirely.
921
+ return `${groupDigits(row.tokens)} tokens`;
922
+ }
923
+ /**
924
+ * One admission, in prose.
925
+ *
926
+ * @param admission - Why the row is in the answer
927
+ * @returns The prose form
928
+ */
929
+ function describeAdmission(admission) {
930
+ switch (admission.kind) {
931
+ case 'ancestry':
932
+ return `CLAUDE.md chain, from ${displayPath(admission.dir)}`;
933
+ case 'root-rule':
934
+ return 'root-scope rules file';
935
+ case 'nested-rule':
936
+ return `nested rules file, under ${displayPath(admission.under)}`;
937
+ case 'glob-rule':
938
+ return `rule matched ${admission.pattern}`;
939
+ case 'glob-rule-covers-dir':
940
+ return `∀ rule covers EVERY file here via ${admission.pattern}`
941
+ + ' — a second CLAUDE.md for this directory in all but name';
942
+ case 'glob-rule-may-fire':
943
+ return `∃ rule may fire here — ${admission.pattern} matches ${displayPath(admission.examplePath)}`
944
+ + ', among possibly others; ask about a FILE for an exact answer';
945
+ // Spelled out rather than left to a `default`, so that adding a seventh
946
+ // admission kind upstream is a lint error here instead of an import
947
+ // description silently applied to something that is not an import.
948
+ case 'import':
949
+ return describeImport(admission);
950
+ }
951
+ }
952
+ /**
953
+ * One import admission, in prose.
954
+ *
955
+ * An unattributed member says so rather than naming a plausible importer: the
956
+ * query reports `viaPath: null` precisely when it could not attribute a parent,
957
+ * and inventing one here would launder that into a fact.
958
+ *
959
+ * @param admission - The import admission
960
+ * @returns The prose form
961
+ */
962
+ function describeImport(admission) {
963
+ if (admission.viaPath === null || admission.depth === null) {
964
+ return `@-imported into the closure rooted at ${admission.rootPath}, importer unattributed`;
965
+ }
966
+ return `imported by ${admission.viaPath} at depth ${admission.depth}`
967
+ + ` (closure rooted at ${admission.rootPath})`;
968
+ }
969
+ /**
970
+ * One condition, in the compact `severity code at location: message` shape.
971
+ *
972
+ * @param condition - The graded condition
973
+ * @returns The line
974
+ */
975
+ function conditionLine(condition) {
976
+ const reference = condition.sourceRef === null ? '' : ` [${condition.sourceRef}]`;
977
+ return ` ${condition.severity.padEnd(5)} ${condition.code}`
978
+ + ` at ${conditionLocation(condition)}${reference}: ${condition.message}`;
979
+ }
980
+ /**
981
+ * Where a condition points, using the most specific provenance it carries.
982
+ *
983
+ * @param condition - The graded condition
984
+ * @returns A path, or a `path:line`
985
+ */
986
+ function conditionLocation(condition) {
987
+ if (condition.sourcePath === null)
988
+ return condition.path;
989
+ if (condition.sourceLine === null)
990
+ return condition.sourcePath;
991
+ return `${condition.sourcePath}:${condition.sourceLine}`;
992
+ }
993
+ /**
994
+ * A heading plus its lines, or nothing at all when there are none.
995
+ *
996
+ * @param title - The section heading
997
+ * @param entries - The already-formatted lines, or bare strings to indent
998
+ * @returns The section's lines, blank-terminated, or none
999
+ */
1000
+ function listSection(title, entries) {
1001
+ if (entries.length === 0)
1002
+ return [];
1003
+ return [title, ...entries.map((entry) => (entry.startsWith(' ') ? entry : ` ${entry}`)), ''];
1004
+ }
1005
+ /**
1006
+ * The limits section — the one part of this rendering that is never omitted.
1007
+ *
1008
+ * Printed even when there is nothing else to say, because the limits are a
1009
+ * property of the METHOD rather than of this particular tree: an answer with no
1010
+ * conditions and no unknown rows is subject to exactly the same signed
1011
+ * over/under-report bounds as a messy one.
1012
+ *
1013
+ * ⛔ Reads the imported constants, NOT an answer document — the same source
1014
+ * {@link contextEnvelope} reads. It took no argument's worth of per-answer data
1015
+ * even when the fields were on the answer, and threading one through was what
1016
+ * made "the limits belong to an answer" look true.
1017
+ *
1018
+ * @returns The section's lines
1019
+ */
1020
+ function limitSection() {
1021
+ const lines = [
1022
+ 'What this answer does not settle',
1023
+ ...wrapStatement(CLAUDE_CONTEXT_BOUNDS_STATEMENT, ' '),
1024
+ '',
1025
+ ];
1026
+ for (const limit of CLAUDE_CONTEXT_LIMITS) {
1027
+ lines.push(` ${limit.direction}: ${limit.id}`);
1028
+ lines.push(...wrapStatement(limit.statement, ' '));
1029
+ }
1030
+ lines.push('', 'Modelled Claude Code behaviours (vendor versions, each cited)');
1031
+ for (const behaviour of CLAUDE_CONTEXT_MODELLED_BEHAVIOURS) {
1032
+ lines.push(` ${behaviour.behaviour}`);
1033
+ lines.push(` ${behaviour.introducedIn} — ${behaviour.citedFrom}`);
1034
+ }
1035
+ return lines;
1036
+ }
1037
+ /**
1038
+ * Soft-wrap a statement to {@link WRAP_COLUMNS}, under a fixed indent.
1039
+ *
1040
+ * The limit statements are two and three sentences long and are the part of this
1041
+ * output people actually have to read; unwrapped they arrive as one 400-column
1042
+ * line that a terminal breaks mid-word.
1043
+ *
1044
+ * @param text - The statement
1045
+ * @param indent - Leading whitespace for every produced line
1046
+ * @returns One or more indented lines
1047
+ */
1048
+ function wrapStatement(text, indent) {
1049
+ const width = Math.max(WRAP_COLUMNS - indent.length, 20);
1050
+ const lines = [];
1051
+ let pending = [];
1052
+ let used = 0;
1053
+ for (const word of text.split(' ')) {
1054
+ if (pending.length > 0 && used + pending.length + word.length > width) {
1055
+ lines.push(indent + pending.join(' '));
1056
+ pending = [];
1057
+ used = 0;
1058
+ }
1059
+ pending.push(word);
1060
+ used += word.length;
1061
+ }
1062
+ if (pending.length > 0)
1063
+ lines.push(indent + pending.join(' '));
1064
+ return lines;
1065
+ }
1066
+ /**
1067
+ * A root-relative path as a reader should see it.
1068
+ *
1069
+ * The corpus root itself is `''`, which renders as nothing at all and reads like
1070
+ * a bug. Only the empty case is special-cased — every other path is printed
1071
+ * exactly as the projection holds it, so a reader can paste it straight back in.
1072
+ *
1073
+ * @param path - The root-relative path
1074
+ * @returns The display form
1075
+ */
1076
+ function displayPath(path) {
1077
+ return path === '' ? '<corpus root>' : path;
1078
+ }
1079
+ //# sourceMappingURL=context.js.map