@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,664 @@
1
+ import { createHash } from "node:crypto"
2
+ import { readdir, rename, rm } from "node:fs/promises"
3
+ import { existsSync, lstatSync, realpathSync } from "node:fs"
4
+ import { homedir } from "node:os"
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
6
+ import { pathToFileURL } from "node:url"
7
+ import { err } from "@arcforge/err"
8
+ import { KERNEL_ABI_VERSION } from "@arcforge/types"
9
+ import type { CognetBlueprint, CognetDefinition } from "@arcforge/types"
10
+ import { fsx } from "../../../utils/fs"
11
+ import { Frame } from "../../frame"
12
+ import { readCognetAbi } from "./abi"
13
+
14
+ // The subprocess entry that actually runs Bun.build() — see runBundleWorker()
15
+ // for why this isn't inline.
16
+ //
17
+ // Packaged builds ship the worker as a sibling .js (see vterm.config.ts's
18
+ // onBundle + packageFiles); source checkouts run the .ts directly. Same
19
+ // resolution pattern as declare-worker/tool-bundle-worker — without it the
20
+ // installed CLI looks for a .ts that was never published and every agent
21
+ // fails to compile its brain.
22
+ const packagedWorker = resolve(import.meta.dir, "bundle-worker.js")
23
+ const BUNDLE_WORKER_PATH = existsSync(packagedWorker)
24
+ ? packagedWorker
25
+ : resolve(import.meta.dir, "bundle-worker.ts")
26
+
27
+ type BundleWorkerResult =
28
+ | { ok: true; code: string; mapCode?: string }
29
+ | { ok: false; message: string }
30
+
31
+ /**
32
+ * Runs bundle-worker.ts as a subprocess and reads its one JSON stdout line.
33
+ * Bun.build() is a native, single-threaded compute burst with no
34
+ * cooperative yield points — inline, it freezes VTerm's render/input loop
35
+ * for the whole compile (the bundle inlines @arcforge/core's entire source
36
+ * tree, so this is not a trivial burst). A subprocess moves that freeze
37
+ * off the process that owns the terminal.
38
+ */
39
+ async function runBundleWorker(entryPath: string, external: string[]): Promise<BundleWorkerResult> {
40
+ const proc = Bun.spawn(["bun", "run", BUNDLE_WORKER_PATH, entryPath, external.join(",")], {
41
+ stdout: "pipe",
42
+ stderr: "pipe",
43
+ })
44
+ const [stdout, stderr, exitCode] = await Promise.all([
45
+ new Response(proc.stdout).text(),
46
+ new Response(proc.stderr).text(),
47
+ proc.exited,
48
+ ])
49
+
50
+ const line = stdout.trim().split("\n").at(-1)
51
+ if (!line) {
52
+ return { ok: false, message: `bundle-worker produced no output (exit ${exitCode})${stderr ? `\n${stderr}` : ""}` }
53
+ }
54
+ return JSON.parse(line) as BundleWorkerResult
55
+ }
56
+
57
+ export type CognetArtifact = {
58
+ /** what the blueprint carries — pure data, path+hash form */
59
+ blueprint: CognetBlueprint & { path: string; hash: string }
60
+ }
61
+
62
+ /**
63
+ * The host module the generated entry composes with — a BARE SPECIFIER,
64
+ * resolved by the bundler from the agent's own node_modules.
65
+ *
66
+ * This used to be an absolute path into @arcforge/core's source tree, which
67
+ * resolved only inside this workspace: a published CLI ships no source, so
68
+ * cognet compilation could never have worked from an npm install. The host
69
+ * is a published package now (@arcforge/cognet), installed into every agent
70
+ * alongside @arcforge/types, so the same import works identically in a
71
+ * source checkout and a real install.
72
+ */
73
+ const HOST_SPECIFIER = "@arcforge/cognet"
74
+
75
+ /**
76
+ * The runtime a compiled bundle fuses to is @arcforge/cognet, and its VERSION
77
+ * is what the cache key needs — not a directory hash.
78
+ *
79
+ * This was previously a recursive hash of @arcforge/core's entire source tree, on
80
+ * the belief that the host pulled all of core in transitively. It never did:
81
+ * the host's real graph is itself plus the clock/ecs, and nothing from the
82
+ * kernel. So every unrelated core change rebuilt every agent's brain for no
83
+ * reason, and the one thing that genuinely matters — which runtime version got
84
+ * inlined — wasn't tracked at all. Reading the installed package's version
85
+ * fixes both directions.
86
+ */
87
+ async function hostVersion(agentRoot: string): Promise<string> {
88
+ let dir = resolve(agentRoot)
89
+ while (true) {
90
+ const hostDir = join(dir, "node_modules", "@arcforge", "cognet")
91
+ const manifest = join(hostDir, "package.json")
92
+ if (existsSync(manifest)) {
93
+ // A LINKED host is a source checkout, and its version is frozen
94
+ // at whatever was last published while its bytes change on every
95
+ // edit. Versioning it alone is the assumption above holding for
96
+ // exactly the case it was written for and failing silently for
97
+ // the other: a fixed host would be inlined into a bundle the
98
+ // cache already believed current, so the brain keeps running the
99
+ // old runtime and the fix looks like it did nothing.
100
+ //
101
+ // Only reached when a developer has linked the framework, so a
102
+ // published install pays nothing for it.
103
+ const linked = await linkedHostIdentity(hostDir)
104
+ if (linked) return linked
105
+
106
+ const pkg = await Bun.file(manifest).json() as { version?: string }
107
+ if (pkg.version) return pkg.version
108
+ }
109
+ const parent = dirname(dir)
110
+ if (parent === dir) break
111
+ dir = parent
112
+ }
113
+ // Declared but absent means the tree is mid-write, not that the agent is
114
+ // broken: `bun install` tears node_modules down and rebuilds it, so a scan
115
+ // landing inside that window sees a runtime that genuinely is not there
116
+ // for the instant it looks. Distinguishing the two lets a reload treat the
117
+ // transient case as "look again" instead of tearing down a working agent
118
+ // and printing a compile failure for an install that succeeded.
119
+ //
120
+ // Not declared at all is a real misconfiguration and still fails loudly.
121
+ const declared = await isDeclared(agentRoot)
122
+ throw err(declared ? "COGNET_RUNTIME_UNAVAILABLE" : "COGNET_BUILD_FAILED", {
123
+ detail: declared
124
+ ? `${HOST_SPECIFIER} is declared but not present under ${agentRoot} — the dependency tree is being rewritten, or the project needs \`axon prepare\``
125
+ : `${HOST_SPECIFIER} is not installed under ${agentRoot} — run \`axon prepare\` to install the cognet runtime`,
126
+ context: { agentRoot, specifier: HOST_SPECIFIER },
127
+ })
128
+ }
129
+
130
+ /**
131
+ * A content identity for a host that is a symlink into a source checkout.
132
+ *
133
+ * Null when the host is an ordinary installed directory — the version is the
134
+ * right key there, and hashing a published package's bytes on every compile
135
+ * would spend real time re-deriving a constant.
136
+ *
137
+ * Hashes only what the bundle actually inlines (`src/`), so an edit to the
138
+ * host's tests or README does not invalidate every agent's brain.
139
+ */
140
+ async function linkedHostIdentity(hostDir: string): Promise<string | null> {
141
+ let real: string
142
+ try {
143
+ if (!lstatSync(hostDir).isSymbolicLink()) return null
144
+ real = realpathSync(hostDir)
145
+ } catch {
146
+ return null
147
+ }
148
+
149
+ const hash = createHash("sha256")
150
+ const walked = await fsx.walk(join(real, "src"), { skipDirs: ["node_modules"] })
151
+ const files = walked
152
+ .filter(({ relPath }) => /\.(ts|tsx|js|mjs|json)$/.test(relPath))
153
+ .sort((a, b) => a.relPath.localeCompare(b.relPath))
154
+
155
+ for (const { absPath, relPath } of files) {
156
+ const text = await Bun.file(absPath).text().catch(() => null)
157
+ if (text !== null) hash.update(`${relPath}\0${text}`)
158
+ }
159
+
160
+ return `link:${hash.digest("hex")}`
161
+ }
162
+
163
+ /** Whether the project's own package.json declares the cognet runtime. */
164
+ async function isDeclared(agentRoot: string): Promise<boolean> {
165
+ const manifest = join(agentRoot, "package.json")
166
+ if (!existsSync(manifest)) return false
167
+ try {
168
+ const pkg = await Bun.file(manifest).json() as { dependencies?: Record<string, string> }
169
+ return Boolean(pkg.dependencies?.[HOST_SPECIFIER])
170
+ } catch {
171
+ // A package.json being rewritten right now is itself the transient
172
+ // case — an unreadable manifest is not evidence of a missing pin.
173
+ return true
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Compile one cognet source project into the agent's brain slot:
179
+ *
180
+ * <agent>/.agent/cognet/cognet.mjs — single self-contained ESM file
181
+ * <agent>/.agent/cognet/cognet.mjs.map — sourcemap (debuggability)
182
+ * <agent>/.agent/cognet/manifest.json — { name, version, abi, hash, wakeOn }
183
+ *
184
+ * The authoring surface is two clutter-free files — cognet.config.ts
185
+ * (declaration via defineCognet) and src/main.ts (a raw script declaring
186
+ * loop() against ambient globals). This step is the desugar:
187
+ *
188
+ * 1. WRAP main.ts — hoist its import statements out, defer its body into
189
+ * an exported async function. The script becomes callable; the host
190
+ * runs it once at load(), after the kernel global is bound.
191
+ * 2. GENERATE an entry that imports the host FIRST (module evaluation
192
+ * order — installing the globals before config/main evaluate), then
193
+ * composes: `export default CognetHost({ ...config, ...identity }, main)`,
194
+ * with identity resolved here from package.json + the kernel's ABI.
195
+ * 3. BUNDLE the entry (Bun.build) — host, config, main, and their whole
196
+ * import graph inlined into one file the runtime imports and verifies.
197
+ *
198
+ * The blueprint's identity is then read back off the ARTIFACT: we import the
199
+ * fresh bundle once here and read the composed definition's own fields, so
200
+ * what the blueprint claims and what the kernel will load cannot disagree.
201
+ *
202
+ * The Bun.build() + dynamic import() cycle below is real, non-trivial work
203
+ * (and — separately — importing a fresh built module repeatedly in the same
204
+ * process has shown module-resolution instability under bun test). Neither
205
+ * is free, so a source-input hash gates it: unchanged inputs since the last
206
+ * compile skip straight to the existing manifest instead of rebuilding.
207
+ */
208
+ /**
209
+ * The brain's entry file — `src/main.ts`, or `main.ts` at the cognet root.
210
+ *
211
+ * Both, because both are natural at their own scale. A published cognet with
212
+ * plugins, state and several modules wants `src/`; a brain inlined in an agent
213
+ * is often one file, and making it sit alone inside a `src/` directory is
214
+ * ceremony with nothing to organize. The layout is the author's call.
215
+ *
216
+ * `src/` wins when both exist rather than erroring: it is the conventional
217
+ * layout, so a stray top-level `main.ts` beside a real `src/main.ts` is far
218
+ * more likely to be a leftover than an intentional second entry.
219
+ *
220
+ * Throws with both candidates named — a cognet with no entry compiles to
221
+ * nothing, and the ENOENT this used to raise pointed only at `src/main.ts`,
222
+ * which was actively misleading for a flat layout.
223
+ */
224
+ function resolveCognetMain(sourceDir: string): string {
225
+ const nested = join(sourceDir, "src", "main.ts")
226
+ if (fsx.isFile(nested)) return nested
227
+
228
+ const flat = join(sourceDir, "main.ts")
229
+ if (fsx.isFile(flat)) return flat
230
+
231
+ throw err("COGNET_INVALID", {
232
+ detail: `no brain entry in ${sourceDir} — expected src/main.ts or main.ts`,
233
+ context: { sourceDir, candidates: [nested, flat] },
234
+ })
235
+ }
236
+
237
+ /**
238
+ * Who a cognet IS — read from its package.json, never from its config.
239
+ *
240
+ * One source of truth, and it is the one everything else already uses: the
241
+ * registry publishes under it, the installer resolves it, `package.json` in
242
+ * the agent depends on it. A `name`/`version` in cognet.config.ts was a second
243
+ * writable copy of the same fact and drifted exactly as duplicated facts do —
244
+ * @axon/zero published as 1.0.44 while identifying itself to the kernel as
245
+ * 0.1.2, undetected because publish read one file and the runtime read the
246
+ * other.
247
+ *
248
+ * An INLINE brain has no package.json of its own — it ships inside the agent's
249
+ * bundle and is asked for by nobody — so it borrows the agent's identity.
250
+ * `-brain` distinguishes the two in a flame graph and in the manifest, where
251
+ * seeing the agent's bare name would be confusing.
252
+ */
253
+ async function cognetIdentity(opts: { sourceDir: string; agentRoot: string; inline?: boolean }): Promise<{ name: string; version: string }> {
254
+ if (opts.inline) {
255
+ const agent = await fsx.readJson<{ name?: string; version?: string }>(join(opts.agentRoot, "package.json"))
256
+ const bare = (agent?.name ?? "agent").split("/").at(-1) ?? "agent"
257
+ return { name: `${bare}-brain`, version: agent?.version ?? "0.0.0" }
258
+ }
259
+
260
+ const pkg = await fsx.readJson<{ name?: string; version?: string }>(join(opts.sourceDir, "package.json"))
261
+ if (!pkg?.name || !pkg.version) {
262
+ throw err("COGNET_INVALID", {
263
+ detail: `${opts.sourceDir} — a published cognet must have a package.json with name and version; that IS its identity`,
264
+ context: { sourceDir: opts.sourceDir },
265
+ })
266
+ }
267
+ return { name: pkg.name, version: pkg.version }
268
+ }
269
+
270
+ /**
271
+ * The config module a brain gets when it declares no cognet.config.ts.
272
+ *
273
+ * Only `mode` — identity is resolved separately and injected, so this carries
274
+ * nothing an author could have written differently. It defaults to invocation,
275
+ * the shape of an agent that answers when spoken to, which is what an author
276
+ * writing their first `loop()` almost always means. A continuous brain is a
277
+ * deliberate choice about scheduling, and deliberate choices go in a file.
278
+ */
279
+ function synthesizedConfig(): string {
280
+ return [
281
+ "// generated by axon — this inline cognet declares no cognet.config.ts.",
282
+ "// Add one to set the schedule, wake mask, or model weights yourself;",
283
+ "// identity comes from package.json either way and is never authored.",
284
+ "export default {",
285
+ ` mode: { kind: "invocation" as const },`,
286
+ "}",
287
+ ].join("\n")
288
+ }
289
+
290
+ export async function bundleCognet(opts: {
291
+ sourceDir: string
292
+ agentRoot: string
293
+ /**
294
+ * Whether this brain lives inside the agent (`<agent>/cognet/`).
295
+ *
296
+ * Only relaxes the cognet.config.ts requirement — everything downstream
297
+ * treats the two identically, because by compile time they are.
298
+ */
299
+ inline?: boolean
300
+ /**
301
+ * Where the compiled artifact lands. Defaults to the agent's own
302
+ * `.agent/cognet/`, which is what every real compile wants.
303
+ *
304
+ * Publish verification overrides it: it compiles a candidate tarball to
305
+ * prove a consumer could, and must not overwrite the agent's live brain
306
+ * (or its manifest cache) to do so.
307
+ */
308
+ outDir?: string
309
+ }): Promise<CognetArtifact> {
310
+ const mainPath = resolveCognetMain(opts.sourceDir)
311
+ const configPath = join(opts.sourceDir, "cognet.config.ts")
312
+ const outDir = opts.outDir ?? Frame({ root: opts.agentRoot, kind: "agent" }).path("cognet")
313
+ const buildDir = join(outDir, ".build")
314
+ const outFile = join(outDir, "cognet.mjs")
315
+ const manifestFile = join(outDir, "manifest.json")
316
+
317
+ const mainSource = await Bun.file(mainPath).text()
318
+
319
+ // A cognet.config.ts is OPTIONAL for every brain, published or inline.
320
+ //
321
+ // It was once required of a published cognet, on the grounds that its
322
+ // name, version and ABI could come from nowhere else. All three now do:
323
+ // identity from package.json (the one copy the registry and installer
324
+ // already use), and the ABI from the kernel the compile ran against unless
325
+ // the author pinned one. What is left in the file is `mode`, which has a
326
+ // default — so requiring it meant a config file's worth of ceremony to
327
+ // restate three known facts.
328
+ //
329
+ // Absent, a config declaring only the default mode is synthesized. An
330
+ // author who wants a non-default schedule, a wake mask or engine
331
+ // requirements writes the file and gets the full surface.
332
+ const hasConfig = await Bun.file(configPath).exists()
333
+
334
+ const inputHash = await hashCognetInputs(opts.sourceDir, opts.agentRoot)
335
+ const cached = await readCachedArtifact(manifestFile, outFile, inputHash)
336
+ if (cached) return cached
337
+
338
+ // Nothing in this project's frame, but the SAME brain may already have
339
+ // been compiled for another project on this machine — the input hash is
340
+ // portable, so identical sources share an entry. Copy the artifact in and
341
+ // write this project's own manifest around it (path/sourceDir are
342
+ // project-specific, so only the .mjs travels).
343
+ const shared = await readSharedArtifact(inputHash)
344
+ if (shared) {
345
+ await Bun.write(outFile, shared.code)
346
+ await Bun.write(
347
+ manifestFile,
348
+ JSON.stringify({ ...shared.blueprint, path: outFile, inputHash, sourceDir: opts.sourceDir }, null, 4),
349
+ )
350
+ return { blueprint: { ...shared.blueprint, path: outFile } }
351
+ }
352
+
353
+ // 1. wrap the raw script — imports hoisted, body deferred
354
+ const { imports, body } = splitImports(mainSource, dirname(mainPath))
355
+ const wrapped = [
356
+ `// generated by axon — the raw script ${relative(opts.sourceDir, mainPath)}, made callable.`,
357
+ "// imports hoisted; body runs once at load(), after kernel binds.",
358
+ imports,
359
+ "export default async function __cognet_main(): Promise<void> {",
360
+ body,
361
+ "}",
362
+ ].join("\n")
363
+ await Bun.write(join(buildDir, "main.ts"), wrapped)
364
+
365
+ // 2. the composed entry — import order IS the wiring:
366
+ // host first (installs the ambient globals, incl. definePlugin),
367
+ // then plugins (their definePlugin(...) calls register hooks at import
368
+ // time — before load() fires "boot"), then config, then main.
369
+ const plugins = await discoverPlugins(opts.sourceDir)
370
+
371
+ // An inline brain with no config file gets one written into the build
372
+ // scratch, so the composition below stays identical for every cognet —
373
+ // CognetHost always receives a real config module, and only its origin
374
+ // differs.
375
+ let configImport = specifier(configPath)
376
+ if (!hasConfig) {
377
+ const synthesized = join(buildDir, "config.ts")
378
+ await Bun.write(synthesized, synthesizedConfig())
379
+ configImport = `"./config.ts"`
380
+ }
381
+
382
+ // Identity is resolved HERE and baked into the entry, never read off the
383
+ // config. The ABI a config may pin is honoured; absent, this compile's own
384
+ // kernel is stamped in, which is the truthful answer — the bundle really
385
+ // was built against it.
386
+ const identity = {
387
+ ...(await cognetIdentity({ sourceDir: opts.sourceDir, agentRoot: opts.agentRoot, inline: opts.inline })),
388
+ abi: (hasConfig ? await readCognetAbi(opts.sourceDir) : null) ?? KERNEL_ABI_VERSION,
389
+ }
390
+
391
+ // Identity is MERGED INTO the config object rather than passed as its own
392
+ // argument. CognetHost is a published package's public surface, and a
393
+ // compiled bundle inlines whichever copy of it the agent has installed —
394
+ // so widening the call to three arguments would mean a new CLI emitting a
395
+ // call an older installed host cannot answer, shifting `main` into
396
+ // `config` and killing the brain at load(). Spread last: identity is the
397
+ // resolved fact, and a config that somehow still carries a stale name
398
+ // must not win over it.
399
+ const entry = [
400
+ "// generated by axon — composes identity + plugins + script into the definition.",
401
+ `import { CognetHost } from ${JSON.stringify(HOST_SPECIFIER)}`,
402
+ ...plugins.map((p, i) => `import ${specifier(p)} // plugin ${i}`),
403
+ `import config from ${configImport}`,
404
+ `import main from "./main.ts"`,
405
+ `export default CognetHost({ ...config, ...${JSON.stringify(identity)} }, main)`,
406
+ ].join("\n")
407
+ const entryPath = join(buildDir, "entry.ts")
408
+ await Bun.write(entryPath, entry)
409
+
410
+ // 3. bundle — off-process, see runBundleWorker()'s doc comment
411
+ // The cognet's own declared dependencies stay external, resolved from
412
+ // node_modules at runtime rather than inlined. A native addon cannot be
413
+ // inlined at all (see bundle-worker), and a 259MB ONNX runtime should not
414
+ // be even if it could. @arcforge/* is excluded: the host must be the ONE
415
+ // copy the agent runs, and a second nested runtime would give the brain a
416
+ // different ambient scope than the kernel bound.
417
+ const cognetPkg = await fsx.readJson<{ dependencies?: Record<string, string> }>(
418
+ join(opts.sourceDir, "package.json"),
419
+ )
420
+ const external = Object.keys(cognetPkg?.dependencies ?? {})
421
+ .filter(name => !name.startsWith("@arcforge/"))
422
+
423
+ const result = await runBundleWorker(entryPath, external)
424
+ if (!result.ok) {
425
+ throw err("COGNET_BUILD_FAILED", { detail: result.message, context: { sourceDir: opts.sourceDir } })
426
+ }
427
+
428
+ const contents = result.code
429
+ await Bun.write(outFile, contents)
430
+
431
+ if (result.mapCode) await Bun.write(`${outFile}.map`, result.mapCode)
432
+
433
+ const hash = createHash("sha256").update(contents).digest("hex")
434
+
435
+ // read identity off the artifact itself — hash-busted import, fresh module
436
+ const module = (await import(`${pathToFileURL(outFile).href}?v=${hash}`)) as { default?: CognetDefinition }
437
+ const definition = module.default
438
+ if (!definition || typeof definition.load !== "function" || typeof definition.wake !== "function") {
439
+ throw err("COGNET_INVALID", { detail: `${opts.sourceDir} — compile did not yield a cognet definition`, context: { sourceDir: opts.sourceDir } })
440
+ }
441
+
442
+ const blueprint: CognetArtifact["blueprint"] = {
443
+ name: definition.name,
444
+ version: definition.version,
445
+ abi: definition.abi,
446
+ ...(definition.wakeOn ? { wakeOn: definition.wakeOn } : {}),
447
+ path: outFile,
448
+ hash,
449
+ }
450
+
451
+ // `sourceDir` rides along so a LATER Cognet() instance can answer "where
452
+ // did this brain come from" without being told. The dev watcher needs it
453
+ // and is constructed from a different instance than the one that
454
+ // compiled, so in-memory state cannot serve it — and guessing the
455
+ // registry default there silently watched (and reported) the wrong cognet.
456
+ await Bun.write(manifestFile, JSON.stringify({ ...blueprint, inputHash, sourceDir: opts.sourceDir }, null, 4))
457
+
458
+ await publishSharedArtifact(inputHash, outFile, blueprint)
459
+
460
+ return { blueprint }
461
+ }
462
+
463
+ // ── machine-wide artifact cache ───────────────────────────────────────────────
464
+
465
+ /**
466
+ * Compiled brains, shared across projects on this machine.
467
+ *
468
+ * The per-project gate above (manifest inputHash) makes a REcompile free, but
469
+ * a fresh project has no manifest and so always paid full price — every
470
+ * scaffold recompiled a brain that is byte-identical to one already sitting
471
+ * in another project's frame. The input hash is portable, so it can address a
472
+ * machine-wide entry just as well as a local one.
473
+ *
474
+ * Only the compiled `.mjs` and its identity travel. `path` and `sourceDir`
475
+ * are where THIS project keeps things, so each consumer writes its own
476
+ * manifest around the shared artifact rather than copying one in.
477
+ */
478
+ const ARTIFACT_CACHE = join(homedir(), ".axon", "cache", "cognets")
479
+
480
+ type SharedArtifact = { code: ArrayBuffer; blueprint: CognetArtifact["blueprint"] }
481
+
482
+ /** A previously compiled brain with this input hash, or null. */
483
+ async function readSharedArtifact(inputHash: string): Promise<SharedArtifact | null> {
484
+ const dir = join(ARTIFACT_CACHE, inputHash)
485
+ const code = Bun.file(join(dir, "cognet.mjs"))
486
+ const meta = Bun.file(join(dir, "blueprint.json"))
487
+ if (!(await code.exists()) || !(await meta.exists())) return null
488
+
489
+ try {
490
+ return { code: await code.arrayBuffer(), blueprint: JSON.parse(await meta.text()) }
491
+ } catch {
492
+ // A truncated or half-written entry reads as a miss; the caller
493
+ // compiles and republishes over it.
494
+ return null
495
+ }
496
+ }
497
+
498
+ /**
499
+ * Store a compiled brain under its input hash, atomically.
500
+ *
501
+ * Written beside the cache and renamed in, so a reader sees a complete entry
502
+ * or none. Failures are swallowed deliberately: the caller already has a
503
+ * valid artifact in its own frame, and an unwritable cache must slow a build
504
+ * down rather than break it.
505
+ */
506
+ async function publishSharedArtifact(
507
+ inputHash: string,
508
+ outFile: string,
509
+ blueprint: CognetArtifact["blueprint"],
510
+ ): Promise<void> {
511
+ const final = join(ARTIFACT_CACHE, inputHash)
512
+ if (existsSync(final)) return
513
+
514
+ const pending = `${final}.pending-${crypto.randomUUID().slice(0, 8)}`
515
+ try {
516
+ await Bun.write(join(pending, "cognet.mjs"), Bun.file(outFile))
517
+ // `path` is deliberately dropped — it names the frame of whichever
518
+ // project happened to compile first, and every consumer overwrites it
519
+ // with its own. Storing it would invite someone to trust it.
520
+ const { path: _local, ...portable } = blueprint
521
+ await Bun.write(join(pending, "blueprint.json"), JSON.stringify(portable))
522
+ await rename(pending, final)
523
+ } catch {
524
+ await rm(pending, { recursive: true, force: true }).catch(() => {})
525
+ }
526
+ }
527
+
528
+ // ── rebuild gating ────────────────────────────────────────────────────────────
529
+
530
+ /**
531
+ * Hash everything a compile actually reads: the cognet's WHOLE source tree,
532
+ * plus the VERSION of the runtime it fuses to.
533
+ *
534
+ * The tree, not a list of known entrypoints. This used to hash exactly
535
+ * `cognet.config.ts`, `src/main.ts` and `plugins/*`, on the claim that
536
+ * "nothing else can affect the output" — which was false the moment a brain
537
+ * imported anything. `main.ts` importing `../config` is ordinary TypeScript
538
+ * and the bundler inlines it, so editing that file changed the bundle without
539
+ * changing the key: the cache served a stale brain forever, and every edit
540
+ * appeared to do nothing. Tuning a constant and watching the vehicle ignore
541
+ * you is exactly the kind of silent staleness a content-addressed cache
542
+ * exists to prevent.
543
+ *
544
+ * Hashing the tree is the conservative direction. Following the real import
545
+ * graph would be tighter, but a false MISS only costs a recompile while a
546
+ * false HIT ships the wrong brain — so when in doubt, rebuild.
547
+ */
548
+ async function hashCognetInputs(sourceDir: string, agentRoot: string): Promise<string> {
549
+ const hash = createHash("sha256")
550
+
551
+ hash.update(`${HOST_SPECIFIER}@${await hostVersion(agentRoot)}\0`)
552
+
553
+ // Everything compilable under the cognet root, minus the build's own
554
+ // output and installed dependencies (whose identity rides on the runtime
555
+ // version above, not on their bytes).
556
+ const walked = await fsx.walk(sourceDir, { skipDirs: ["node_modules", ".cognet", ".git"] })
557
+ const files = walked
558
+ .filter(({ relPath }) => /\.(ts|tsx|js|mjs|json)$/.test(relPath))
559
+ .map(({ absPath }) => absPath)
560
+ .sort()
561
+
562
+ for (const file of files) {
563
+ const text = await Bun.file(file).text().catch(() => null)
564
+ // Path RELATIVE to the cognet root, never absolute: the same brain
565
+ // installed under two different projects is the same brain, and
566
+ // hashing where it happens to sit made every fresh scaffold a
567
+ // guaranteed miss even though the bytes were identical.
568
+ if (text !== null) hash.update(`${relative(sourceDir, file)}\0${text}`)
569
+ }
570
+
571
+ return hash.digest("hex")
572
+ }
573
+
574
+ /** The last compile's manifest, if its recorded input hash matches and the artifact it points to still exists. */
575
+ async function readCachedArtifact(manifestFile: string, outFile: string, inputHash: string): Promise<CognetArtifact | null> {
576
+ if (!existsSync(manifestFile) || !existsSync(outFile)) return null
577
+
578
+ const text = await Bun.file(manifestFile).text().catch(() => null)
579
+ if (text === null) return null
580
+
581
+ let manifest: (CognetArtifact["blueprint"] & { inputHash?: string }) | null = null
582
+ try {
583
+ manifest = JSON.parse(text)
584
+ } catch {
585
+ return null
586
+ }
587
+ if (!manifest || manifest.inputHash !== inputHash) return null
588
+
589
+ const { inputHash: _drop, ...blueprint } = manifest
590
+ return { blueprint }
591
+ }
592
+
593
+ // ── the wrap transform ────────────────────────────────────────────────────────
594
+
595
+ /**
596
+ * Split a raw script into its top-level import statements and everything
597
+ * else. Relative specifiers are re-anchored to the script's own directory
598
+ * (the wrapped file lives in .agent/cognet/.build/) so `./context` keeps
599
+ * working. Static top-level imports only — the honest limitation of the
600
+ * v1 transform; a lexer replaces the regex when someone actually hits it.
601
+ */
602
+ function splitImports(source: string, sourceDir: string): { imports: string; body: string } {
603
+ // One import per match: the clause segment excludes quotes, so a match
604
+ // can never lazily swallow a following import's specifier; the tail
605
+ // absorbs `;` and trailing comments to end-of-line. Multiline named
606
+ // imports (braces spanning lines) still match — the exclusion spans \n.
607
+ const importPattern = /^import\s[^'"]*?["'][^"']+["'][^\n]*$|^import\s*["'][^"']+["'][^\n]*$/gm
608
+
609
+ const imports: string[] = []
610
+ const body = source.replace(importPattern, (statement) => {
611
+ imports.push(reanchor(statement, sourceDir))
612
+ return ""
613
+ })
614
+
615
+ return { imports: imports.join("\n"), body }
616
+ }
617
+
618
+ /**
619
+ * An absolute path as a module specifier literal, ready to splice into
620
+ * generated source.
621
+ *
622
+ * THE ONE WAY a path enters generated code. Forward slashes, because ESM
623
+ * accepts them on every platform and a raw win32 path inside a TS string
624
+ * literal is not a path at all — `C:\Users\tester\.axon\...` parses as
625
+ * `\t`/`\b`/`\n` escapes, and the bundler then reports an unresolvable import
626
+ * against a mangled specifier. That broke cognet compilation for every
627
+ * Windows install (AX-COGNET-012), and it broke it in the one place that
628
+ * hand-rolled the splice while its neighbours used JSON.stringify. Normalizing
629
+ * here removes the escaping question instead of answering it three times.
630
+ */
631
+ function specifier(path: string): string {
632
+ return JSON.stringify(path.split(sep).join("/"))
633
+ }
634
+
635
+ /** `./x` and `../x` specifiers → absolute paths (the wrapped file moved). */
636
+ function reanchor(statement: string, sourceDir: string): string {
637
+ return statement.replace(/(["'])((?:\.\.?\/)[^"']+)\1/, (_match, _quote: string, spec: string) => {
638
+ const absolute = isAbsolute(spec) ? spec : resolve(sourceDir, spec)
639
+ return specifier(absolute)
640
+ })
641
+ }
642
+
643
+ // ── plugin discovery ──────────────────────────────────────────────────────────
644
+
645
+ /**
646
+ * Absolute paths of the cognet's lifecycle plugins — plugins/*.ts, sorted
647
+ * for deterministic import order. Each is imported into the entry AFTER the
648
+ * host (so definePlugin exists) and BEFORE main (so hooks are registered
649
+ * before "boot" fires). Convention over config: no manifest, the folder IS
650
+ * the registry — same as agents/modules.
651
+ */
652
+ async function discoverPlugins(sourceDir: string): Promise<string[]> {
653
+ const dir = join(sourceDir, "plugins")
654
+ let names: string[]
655
+ try {
656
+ names = await readdir(dir)
657
+ } catch {
658
+ return []
659
+ }
660
+ return names
661
+ .filter(n => n.endsWith(".ts") && !n.endsWith(".d.ts") && !n.endsWith(".test.ts"))
662
+ .sort()
663
+ .map(n => join(dir, n))
664
+ }