@arcforge/platform 2.0.166

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 (207) hide show
  1. package/README.md +31 -0
  2. package/package.json +69 -0
  3. package/src/bin/supervisor.ts +102 -0
  4. package/src/bin/test-api.ts +30 -0
  5. package/src/bin/test-preload.ts +308 -0
  6. package/src/bin/update-helper.ts +32 -0
  7. package/src/build/bench/CLAUDE.md +106 -0
  8. package/src/build/bench/SPEC.md +209 -0
  9. package/src/build/bench/agents.ts +105 -0
  10. package/src/build/bench/axes.ts +84 -0
  11. package/src/build/bench/bench.ts +96 -0
  12. package/src/build/bench/discover.ts +147 -0
  13. package/src/build/bench/index.ts +7 -0
  14. package/src/build/bench/log.ts +47 -0
  15. package/src/build/bench/matrix.ts +23 -0
  16. package/src/build/bench/preload.ts +440 -0
  17. package/src/build/bench/prepare.ts +61 -0
  18. package/src/build/bench/projection.ts +112 -0
  19. package/src/build/bench/resolve.ts +54 -0
  20. package/src/build/bench/runner.ts +309 -0
  21. package/src/build/bench/schema/extract.ts +148 -0
  22. package/src/build/bench/schema/index.ts +2 -0
  23. package/src/build/bench/schema/schema.ts +95 -0
  24. package/src/build/bench/schema/worker.ts +30 -0
  25. package/src/build/bench/typegen.ts +119 -0
  26. package/src/build/bench/workspace/files.ts +139 -0
  27. package/src/build/bench/workspace/handle.ts +133 -0
  28. package/src/build/bench/workspace/index.ts +11 -0
  29. package/src/build/bench/workspace/workspace.ts +14 -0
  30. package/src/build/blueprint/blueprint.ts +398 -0
  31. package/src/build/blueprint/cognet/abi.ts +207 -0
  32. package/src/build/blueprint/cognet/bundle-worker.ts +93 -0
  33. package/src/build/blueprint/cognet/bundle.ts +664 -0
  34. package/src/build/blueprint/cognet/cognet.ts +249 -0
  35. package/src/build/blueprint/cognet/index.ts +10 -0
  36. package/src/build/blueprint/cognet/manifest.ts +38 -0
  37. package/src/build/blueprint/cognet/resolve.ts +113 -0
  38. package/src/build/blueprint/collisions.ts +51 -0
  39. package/src/build/blueprint/index.ts +29 -0
  40. package/src/build/blueprint/modules/entries.ts +117 -0
  41. package/src/build/blueprint/modules/index.ts +300 -0
  42. package/src/build/blueprint/modules/meta.ts +174 -0
  43. package/src/build/blueprint/scan/boot.ts +34 -0
  44. package/src/build/blueprint/scan/cognetImports.ts +56 -0
  45. package/src/build/blueprint/scan/components.ts +45 -0
  46. package/src/build/blueprint/scan/config.ts +234 -0
  47. package/src/build/blueprint/scan/configImports.ts +232 -0
  48. package/src/build/blueprint/scan/declare-worker.ts +61 -0
  49. package/src/build/blueprint/scan/declare.ts +393 -0
  50. package/src/build/blueprint/scan/h3-globals.ts +137 -0
  51. package/src/build/blueprint/scan/knowledge.ts +101 -0
  52. package/src/build/blueprint/scan/middleware.ts +110 -0
  53. package/src/build/blueprint/scan/moduleImports.ts +79 -0
  54. package/src/build/blueprint/scan/plugins.ts +93 -0
  55. package/src/build/blueprint/scan/promptPackages.ts +45 -0
  56. package/src/build/blueprint/scan/prompts.ts +164 -0
  57. package/src/build/blueprint/scan/published.ts +131 -0
  58. package/src/build/blueprint/scan/resolve.ts +398 -0
  59. package/src/build/blueprint/scan/routes.ts +109 -0
  60. package/src/build/blueprint/scan/scripts.ts +119 -0
  61. package/src/build/blueprint/scan/tool-bundle-worker.ts +69 -0
  62. package/src/build/blueprint/scan/tools.ts +610 -0
  63. package/src/build/blueprint/types.ts +28 -0
  64. package/src/build/extensions/config.ts +261 -0
  65. package/src/build/extensions/edit.ts +684 -0
  66. package/src/build/extensions/extensions.ts +731 -0
  67. package/src/build/extensions/index.ts +10 -0
  68. package/src/build/extensions/load.ts +350 -0
  69. package/src/build/extensions/registrations.ts +189 -0
  70. package/src/build/extensions/store.ts +200 -0
  71. package/src/build/frame/frame.ts +145 -0
  72. package/src/build/frame/index.ts +5 -0
  73. package/src/build/frame/migrate.ts +246 -0
  74. package/src/build/project/bundle/agent.ts +382 -0
  75. package/src/build/project/bundle/artifacts.ts +88 -0
  76. package/src/build/project/bundle/assets.ts +385 -0
  77. package/src/build/project/bundle/bundle.ts +160 -0
  78. package/src/build/project/bundle/imports.ts +102 -0
  79. package/src/build/project/bundle/index.ts +16 -0
  80. package/src/build/project/bundle/module.ts +130 -0
  81. package/src/build/project/bundle/source.ts +136 -0
  82. package/src/build/project/bundle/stage.ts +97 -0
  83. package/src/build/project/bundle/types.ts +111 -0
  84. package/src/build/project/cognet.ts +156 -0
  85. package/src/build/project/create/agent.ts +52 -0
  86. package/src/build/project/create/bench.ts +81 -0
  87. package/src/build/project/create/cognet.ts +102 -0
  88. package/src/build/project/create/extension.ts +63 -0
  89. package/src/build/project/create/module.ts +43 -0
  90. package/src/build/project/create/profile.ts +102 -0
  91. package/src/build/project/create/prompt.ts +68 -0
  92. package/src/build/project/create/templates.ts +88 -0
  93. package/src/build/project/deploy.ts +96 -0
  94. package/src/build/project/index.ts +40 -0
  95. package/src/build/project/installer.ts +616 -0
  96. package/src/build/project/kinds.ts +374 -0
  97. package/src/build/project/links.ts +33 -0
  98. package/src/build/project/manifest/bunfig.ts +139 -0
  99. package/src/build/project/manifest/config.ts +246 -0
  100. package/src/build/project/manifest/env.ts +184 -0
  101. package/src/build/project/manifest/index.ts +9 -0
  102. package/src/build/project/manifest/manifest.ts +49 -0
  103. package/src/build/project/manifest/model.ts +124 -0
  104. package/src/build/project/manifest/package.ts +386 -0
  105. package/src/build/project/manifest/text.ts +19 -0
  106. package/src/build/project/models/fetch.ts +123 -0
  107. package/src/build/project/models/index.ts +8 -0
  108. package/src/build/project/models/models.ts +111 -0
  109. package/src/build/project/models/specifier.ts +106 -0
  110. package/src/build/project/models/store.ts +202 -0
  111. package/src/build/project/modules/hash.ts +31 -0
  112. package/src/build/project/modules/index.ts +5 -0
  113. package/src/build/project/modules/lock.ts +78 -0
  114. package/src/build/project/modules/modules.ts +155 -0
  115. package/src/build/project/prepare.ts +709 -0
  116. package/src/build/project/project.ts +253 -0
  117. package/src/build/project/projects.ts +164 -0
  118. package/src/build/project/propagation.ts +120 -0
  119. package/src/build/project/publish/verify.ts +312 -0
  120. package/src/build/project/publish.ts +155 -0
  121. package/src/build/project/reconcile.ts +93 -0
  122. package/src/build/project/specifier.ts +42 -0
  123. package/src/build/project/tree.ts +615 -0
  124. package/src/build/project/treecache.ts +356 -0
  125. package/src/build/project/typegen/axon-dts.ts +362 -0
  126. package/src/build/project/typegen/cognet-dts.ts +91 -0
  127. package/src/build/project/typegen/components.ts +45 -0
  128. package/src/build/project/typegen/env.ts +59 -0
  129. package/src/build/project/typegen/generators.ts +108 -0
  130. package/src/build/project/typegen/hooks.ts +71 -0
  131. package/src/build/project/typegen/index.ts +137 -0
  132. package/src/build/project/typegen/prompt-dts.ts +40 -0
  133. package/src/build/project/typegen/prompts.ts +36 -0
  134. package/src/build/project/typegen/registry-dts.ts +109 -0
  135. package/src/build/project/typegen/scripts.ts +37 -0
  136. package/src/build/project/typegen/tools.ts +31 -0
  137. package/src/build/project/typegen/tsconfig.ts +243 -0
  138. package/src/build/project/typegen/tui-dts.ts +120 -0
  139. package/src/build/project/typegen/write.ts +40 -0
  140. package/src/build/project/verify.ts +268 -0
  141. package/src/build/project/watcher.ts +266 -0
  142. package/src/build/runtime/agent.ts +550 -0
  143. package/src/build/runtime/escalations.ts +159 -0
  144. package/src/build/runtime/index.ts +15 -0
  145. package/src/build/runtime/instances.ts +604 -0
  146. package/src/build/runtime/profile.ts +91 -0
  147. package/src/build/runtime/progress.ts +143 -0
  148. package/src/build/runtime/requests.ts +167 -0
  149. package/src/build/runtime/resolve.ts +159 -0
  150. package/src/build/runtime/runtime.ts +233 -0
  151. package/src/build/runtime/sessions/index.ts +5 -0
  152. package/src/build/runtime/sessions/record.ts +145 -0
  153. package/src/build/runtime/sessions/sessions.ts +240 -0
  154. package/src/build/runtime/zeno.ts +120 -0
  155. package/src/index.ts +11 -0
  156. package/src/link/agent-main.ts +395 -0
  157. package/src/link/index.ts +70 -0
  158. package/src/link/services.ts +120 -0
  159. package/src/platform.ts +293 -0
  160. package/src/procs/index.ts +15 -0
  161. package/src/procs/tree.ts +177 -0
  162. package/src/services/cloud.ts +419 -0
  163. package/src/services/control/client.ts +126 -0
  164. package/src/services/control/dispatch.ts +156 -0
  165. package/src/services/control/index.ts +17 -0
  166. package/src/services/control/protocol.ts +179 -0
  167. package/src/services/control/server.ts +241 -0
  168. package/src/services/deployments.ts +81 -0
  169. package/src/services/files.ts +329 -0
  170. package/src/services/index.ts +5 -0
  171. package/src/services/mic/capture.ts +248 -0
  172. package/src/services/mic/config.ts +109 -0
  173. package/src/services/mic/fft.ts +93 -0
  174. package/src/services/mic/index.ts +139 -0
  175. package/src/services/mic/visualizer.ts +46 -0
  176. package/src/services/ollama/catalog.ts +122 -0
  177. package/src/services/ollama/http.ts +124 -0
  178. package/src/services/ollama/index.ts +13 -0
  179. package/src/services/ollama/models.ts +153 -0
  180. package/src/services/ollama/ollama.ts +89 -0
  181. package/src/services/ollama/registry.ts +112 -0
  182. package/src/services/ollama/types.ts +72 -0
  183. package/src/services/prompts.ts +76 -0
  184. package/src/services/registry.ts +220 -0
  185. package/src/services/resources/hardware.ts +125 -0
  186. package/src/services/resources/index.ts +6 -0
  187. package/src/services/resources/reservations.ts +162 -0
  188. package/src/services/resources/resources.ts +156 -0
  189. package/src/services/running/index.ts +1 -0
  190. package/src/services/running/running.ts +200 -0
  191. package/src/services/store/disk.ts +97 -0
  192. package/src/services/store/index.ts +15 -0
  193. package/src/services/store/store.ts +729 -0
  194. package/src/services/store/types.ts +303 -0
  195. package/src/services/test/child.ts +150 -0
  196. package/src/services/test/events.ts +102 -0
  197. package/src/services/test/files.ts +26 -0
  198. package/src/services/test/frames.ts +39 -0
  199. package/src/services/test/index.ts +7 -0
  200. package/src/services/test/runner.ts +122 -0
  201. package/src/services/test/types.ts +26 -0
  202. package/src/services/update/contract.ts +77 -0
  203. package/src/services/update/index.ts +12 -0
  204. package/src/services/update/installer.ts +139 -0
  205. package/src/services/update/updates.ts +137 -0
  206. package/src/utils/fs.ts +148 -0
  207. package/src/utils/tsast.ts +102 -0
@@ -0,0 +1,356 @@
1
+ import { join } from "node:path"
2
+ import { homedir } from "node:os"
3
+ import { cp, mkdir, mkdtemp, readdir, readlink, rename, rm } from "node:fs/promises"
4
+ import { existsSync } from "node:fs"
5
+ import { resolveAbsoluteLinks } from "./links"
6
+
7
+ /**
8
+ * TreeCache — resolved dependency trees, shared machine-wide.
9
+ *
10
+ * Extracted from Tree so it can be TESTED. It was ~200 lines of the
11
+ * highest-risk code in the install path — shared mutable state, LRU eviction,
12
+ * symlink grafting, content hashing — reachable only through a full `bun
13
+ * install` against a hardcoded `~/.axon` path, and it had zero tests. It also
14
+ * caused half the dependency incidents this system has had: eviction deleted a
15
+ * tree a live project was grafted onto, and every package in that project went
16
+ * dangling at once.
17
+ *
18
+ * `root` is injectable for exactly that reason. A test must never be able to
19
+ * evict a developer's real cache, and a cache that can only be exercised
20
+ * through the real one will not be exercised at all.
21
+ *
22
+ * Safe to delete at any time: a miss just does the install.
23
+ */
24
+
25
+ export type TreeCacheOpts = {
26
+ /** Where entries live. Defaults to ~/.axon/cache/trees. Tests inject a temp dir. */
27
+ root?: string
28
+ /** How many entries to keep. Tests shrink it to make eviction observable. */
29
+ max?: number
30
+ }
31
+
32
+ export const DEFAULT_TREE_CACHE = join(homedir(), ".axon", "cache", "trees")
33
+ export const DEFAULT_MAX_TREES = 24
34
+
35
+ export function TreeCache(opts: TreeCacheOpts = {}) {
36
+ const cacheRoot = opts.root ?? DEFAULT_TREE_CACHE
37
+ const maxTrees = opts.max ?? DEFAULT_MAX_TREES
38
+
39
+
40
+ /**
41
+ * Where resolved dependency trees are kept, machine-wide.
42
+ *
43
+ * Beside bun's own install cache rather than in the project, because the
44
+ * whole point is that unrelated projects with the same dependencies share
45
+ * one resolution. Safe to delete at any time — a miss just does the install.
46
+ */
47
+
48
+
49
+ /**
50
+ * Newline-delimited project roots whose node_modules symlink into this tree.
51
+ *
52
+ * Dot-prefixed so it is filtered out of the cache listing alongside `.used`.
53
+ */
54
+ const REFERRERS_FILE = ".referrers"
55
+
56
+ /**
57
+ * The cache key: a hash of everything the install reads.
58
+ *
59
+ * package.json carries the rebased dependency set, bunfig.toml the registry
60
+ * mapping, and bun.lock the pin deciding which versions those ranges collapse
61
+ * to. Together they are everything the install reads, so equal keys mean equal
62
+ * trees.
63
+ *
64
+ * Each is stripped of the project's own IDENTITY before hashing. A package's
65
+ * name and version sit in its manifest and are echoed into its lockfile, but
66
+ * they do not change what it depends on — and including them made every
67
+ * project a unique key, so two agents with byte-identical dependencies missed
68
+ * each other's entries and the cache never hit at all.
69
+ *
70
+ * `file:` dependencies are the one input whose CONTENT can change without the
71
+ * manifest moving — a local checkout is edited in place. They are hashed by
72
+ * path only, deliberately: they are symlinked or copied in from that live
73
+ * checkout on every install anyway, so a stale cache entry cannot hide an
74
+ * edit to one.
75
+ */
76
+ async function treeKey(staging: string): Promise<string | null> {
77
+ const manifest = Bun.file(join(staging, "package.json"))
78
+ if (!(await manifest.exists())) return null
79
+
80
+ const declared = JSON.parse(await manifest.text()) as {
81
+ dependencies?: Record<string, string>
82
+ overrides?: Record<string, string>
83
+ }
84
+
85
+ const hash = new Bun.CryptoHasher("sha256")
86
+ hash.update(JSON.stringify(sortedEntries(declared.dependencies)))
87
+ hash.update(JSON.stringify(sortedEntries(declared.overrides)))
88
+
89
+ // The registry mapping decides WHERE those ranges resolve from — the same
90
+ // range against a different registry is a different tree.
91
+ const bunfig = Bun.file(join(staging, "bunfig.toml"))
92
+ if (await bunfig.exists()) hash.update(await bunfig.arrayBuffer())
93
+
94
+ // The pin. Its `workspaces[""]` block is the project restating its own
95
+ // name/version/dependencies, which is identity rather than resolution —
96
+ // dropped so two projects that resolved to the same versions share an
97
+ // entry. What remains ("packages", and any overrides) is the resolution
98
+ // itself.
99
+ const lock = Bun.file(join(staging, "bun.lock"))
100
+ if (await lock.exists()) {
101
+ const text = await lock.text()
102
+ try {
103
+ const { workspaces: _identity, ...resolution } = JSON.parse(text) as Record<string, unknown>
104
+ hash.update(JSON.stringify(resolution))
105
+ } catch {
106
+ // bun.lock is JSONC (trailing commas) and may not parse as strict
107
+ // JSON. Hashing it whole is the conservative fallback: it can only
108
+ // cost a miss, never a wrong hit.
109
+ hash.update(text)
110
+ }
111
+ }
112
+
113
+ return hash.digest("hex").slice(0, 32)
114
+ }
115
+
116
+ /** Key-stable form of a dependency map — object order must not change the hash. */
117
+ function sortedEntries(record: Record<string, string> | undefined): Array<[string, string]> {
118
+ return Object.entries(record ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
119
+ }
120
+
121
+ /**
122
+ * How many resolved trees the cache keeps.
123
+ *
124
+ * Bounded by COUNT rather than bytes, because a tree's size is not knowable
125
+ * without walking it — ~1400 files each, and stat'ing every one of them on
126
+ * every publish would cost more than the copy the cache exists to avoid.
127
+ * Count is a proxy the filesystem answers in one readdir.
128
+ *
129
+ * 24 entries is roughly 1–2GB at observed sizes (18MB median, 69MB worst),
130
+ * and comfortably more distinct dependency sets than one machine works on
131
+ * at once — the resident set is a handful of agents plus whatever the test
132
+ * suite builds. Overshooting the budget costs disk; undershooting costs a
133
+ * reinstall, which is slow but always correct.
134
+ */
135
+
136
+
137
+ /**
138
+ * Mark an entry as used, so eviction can tell hot from cold.
139
+ *
140
+ * A `.used` file rather than the directory's own mtime: reading a tree
141
+ * (which is all a cache hit does) does not touch mtime on any platform, so
142
+ * mtime records when an entry was WRITTEN and would evict by age rather
143
+ * than by use — throwing away the tree every project on the machine shares
144
+ * because it happened to be resolved first.
145
+ *
146
+ * Best-effort by the same rule as everything else here: a cache that cannot
147
+ * record a touch still serves the tree.
148
+ */
149
+ async function touchTree(dir: string): Promise<void> {
150
+ await Bun.write(join(dir, ".used"), "").catch(() => {})
151
+ }
152
+
153
+ /**
154
+ * Evict the coldest entries until the cache is within maxTrees.
155
+ *
156
+ * Called after a publish, never before: the entry just written is the one
157
+ * most likely to be read next, so it must be present and touched before
158
+ * anything is chosen for removal.
159
+ *
160
+ * Entries whose `.used` cannot be read sort oldest — an entry from before
161
+ * this bookkeeping existed (every entry on an upgraded machine) has no
162
+ * marker, and treating it as cold is right: it is genuinely unknown
163
+ * whether anything still wants it, and a wrong guess costs one reinstall.
164
+ *
165
+ * Swallows failures for the same reason publishTree does: the cache is an
166
+ * optimization with an authoritative fallback, and a full or read-only home
167
+ * must never break a build.
168
+ */
169
+ async function evictTrees(): Promise<void> {
170
+ try {
171
+ const names = (await readdir(cacheRoot)).filter(name => !name.startsWith("."))
172
+ if (names.length <= maxTrees) return
173
+
174
+ const entries = await Promise.all(names.map(async name => ({
175
+ name,
176
+ usedAt: await Bun.file(join(cacheRoot, name, ".used")).stat()
177
+ .then(info => info.mtimeMs)
178
+ .catch(() => 0),
179
+ })))
180
+
181
+ entries.sort((a, b) => a.usedAt - b.usedAt)
182
+
183
+ // Coldest first, but never a tree a project is still pointing at.
184
+ // Deleting one of those does not cost a reinstall — it leaves that
185
+ // project's node_modules full of dangling symlinks, which every
186
+ // resolver reports as "package not installed" and no amount of
187
+ // re-running fixes without a full reinstall.
188
+ //
189
+ // The budget can therefore be exceeded, deliberately: maxTrees bounds
190
+ // disk, and disk is recoverable where a silently broken agent is not.
191
+ // In practice referenced trees ARE the working set, so the overshoot is
192
+ // bounded by how many projects exist on the machine.
193
+ let over = entries.length - maxTrees
194
+ for (const entry of entries) {
195
+ if (over <= 0) break
196
+ const dir = join(cacheRoot, entry.name)
197
+ if (await isReferenced(dir)) continue
198
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
199
+ over -= 1
200
+ }
201
+ } catch {
202
+ // An unreadable cache directory is not a build failure.
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Store a resolved tree under its key, atomically.
208
+ *
209
+ * Built beside the cache and then renamed in, so a reader either sees no
210
+ * entry or a complete one — never a directory still being copied into. Two
211
+ * workers resolving the same manifest at once both publish; the rename makes
212
+ * the loser's write a no-op rather than a corruption, which is why the EEXIST
213
+ * path is ignored rather than retried.
214
+ *
215
+ * Every failure here is swallowed on purpose, and it is the one place in this
216
+ * file where that is right: the cache is an optimization with an authoritative
217
+ * fallback one line below (the real install already ran). A full disk or a
218
+ * read-only home must slow the build down, not break it.
219
+ */
220
+ async function publishTree(key: string, staging: string): Promise<void> {
221
+ const final = join(cacheRoot, key)
222
+ // Already published by an earlier build or a concurrent worker. Still a
223
+ // use — without this the entry keeps its original write time forever and
224
+ // eventually sorts oldest despite being the most reused tree on the box.
225
+ if (existsSync(final)) return touchTree(final)
226
+
227
+ let pending: string | null = null
228
+ try {
229
+ await mkdir(cacheRoot, { recursive: true })
230
+ pending = await mkdtemp(join(cacheRoot, `.pending-${key}-`))
231
+ // verbatimSymlinks, NOT dereference: bun's isolated linker keeps one
232
+ // real copy of each package under `node_modules/.bun/` and makes every
233
+ // other appearance a symlink into it. Dereferencing flattens the
234
+ // top-level links but silently drops packages that are only reachable
235
+ // through a nested one (`hookable`, reached via .bun/h3@…/node_modules),
236
+ // producing a tree that resolves until something imports them.
237
+ // Preserving the links keeps the layout bun actually built.
238
+ // Same split as materialize(): keep the relative links bun's isolated
239
+ // linker built (they stay valid inside the tree and are most of its
240
+ // size), resolve the absolute ones. Here it is load-bearing rather
241
+ // than merely faster — an absolute link points into the staging
242
+ // directory this function is about to delete, and a cached entry
243
+ // holding one would hand every future project a dangling path.
244
+ await cp(join(staging, "node_modules"), join(pending, "node_modules"), { recursive: true, verbatimSymlinks: true })
245
+ await resolveAbsoluteLinks(join(pending, "node_modules"))
246
+ const lock = join(staging, "bun.lock")
247
+ if (existsSync(lock)) await cp(lock, join(pending, "bun.lock"))
248
+ await rename(pending, final)
249
+ pending = null
250
+ // Touch before evicting: the entry just published is the one most
251
+ // likely to be read next, and must never be the one chosen.
252
+ await touchTree(final)
253
+ await evictTrees()
254
+ } catch {
255
+ // Lost the rename race, or the cache is unwritable. Either way the
256
+ // caller has a valid tree in staging and proceeds unaffected.
257
+ } finally {
258
+ if (pending) await rm(pending, { recursive: true, force: true }).catch(() => {})
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Symlink the dependencies declared with a local protocol.
264
+ *
265
+ * They were withheld from the isolated install (see above), so the
266
+ * materialized tree has no copy of them. A symlink is deliberate rather than
267
+ * a copy: the point of pointing an agent at a local checkout is that edits to
268
+ * that checkout are live, which a copy would defeat.
269
+ *
270
+ * `workspace:*` resolves by walking up for the workspace root and finding the
271
+ * package by name; `file:` carries its own path.
272
+ */
273
+
274
+ /**
275
+ * Record that a project's node_modules now points into a cached tree.
276
+ *
277
+ * Eviction reads these to avoid deleting a tree something still depends on.
278
+ * A grafted project holds NOTHING but symlinks into the cache, so removing
279
+ * its tree does not slow it down — it breaks it outright, leaving a
280
+ * node_modules full of dangling links that every resolver reports as "package
281
+ * not installed". That is the failure this exists to prevent: an unrelated
282
+ * project's install pushed the cache past maxTrees and silently unmade a
283
+ * working agent, which then reported a missing cognet and sent the user
284
+ * looking for a typo in their config.
285
+ *
286
+ * Best-effort, like everything else about the cache: a referrer that cannot be
287
+ * recorded costs a wrongly-evicted tree (one reinstall), never a broken write.
288
+ */
289
+ async function addReferrer(treeDir: string, projectRoot: string): Promise<void> {
290
+ try {
291
+ const path = join(treeDir, REFERRERS_FILE)
292
+ const existing = await Bun.file(path).text().then(
293
+ text => text.split("\n").filter(Boolean),
294
+ () => [] as string[],
295
+ )
296
+ if (existing.includes(projectRoot)) return
297
+ await Bun.write(path, [...existing, projectRoot].join("\n"))
298
+ } catch {
299
+ // A cache that cannot record a referrer still serves the tree.
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Is any project still pointing its node_modules into this tree?
305
+ *
306
+ * Referrers are verified rather than trusted: a project can be deleted, moved,
307
+ * or reinstalled onto a different tree, and a stale entry would pin an entry
308
+ * in the cache forever. The check is what makes the list self-cleaning — a
309
+ * referrer whose node_modules no longer resolves into THIS tree does not count.
310
+ */
311
+ async function isReferenced(treeDir: string): Promise<boolean> {
312
+ try {
313
+ const listed = await Bun.file(join(treeDir, REFERRERS_FILE)).text()
314
+ for (const projectRoot of listed.split("\n").filter(Boolean)) {
315
+ const modules = join(projectRoot, "node_modules")
316
+ let entries: string[]
317
+ try {
318
+ entries = await readdir(modules)
319
+ } catch {
320
+ continue // project gone, or has no node_modules any more
321
+ }
322
+ for (const entry of entries) {
323
+ const link = await readlink(join(modules, entry)).catch(() => null)
324
+ if (link?.startsWith(`${treeDir}/`)) return true
325
+ }
326
+ }
327
+ } catch {
328
+ // No referrer file — an entry from before this bookkeeping existed.
329
+ // Treated as unreferenced, which is the pre-existing behaviour.
330
+ }
331
+ return false
332
+ }
333
+
334
+
335
+ return {
336
+ root: cacheRoot,
337
+ key: treeKey,
338
+ publish: publishTree,
339
+ touch: touchTree,
340
+ evict: evictTrees,
341
+ addReferrer: addReferrer,
342
+ isReferenced: isReferenced,
343
+ /** Entry directory for a key, whether or not it exists. */
344
+ entry: (key: string) => join(cacheRoot, key),
345
+ /** Every entry currently cached, newest-agnostic. */
346
+ async list(): Promise<string[]> {
347
+ try {
348
+ return (await readdir(cacheRoot)).filter(name => !name.startsWith("."))
349
+ } catch {
350
+ return []
351
+ }
352
+ },
353
+ }
354
+ }
355
+
356
+ export type TreeCacheT = ReturnType<typeof TreeCache>