@arcforge/platform 2.0.219 → 2.0.244

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 (127) hide show
  1. package/package.json +27 -19
  2. package/src/build/blueprint/blueprint.ts +48 -64
  3. package/src/build/blueprint/cognet/abi.ts +3 -257
  4. package/src/build/blueprint/cognet/bundle-worker.ts +11 -0
  5. package/src/build/blueprint/cognet/bundle.ts +294 -89
  6. package/src/build/blueprint/cognet/cognet.ts +8 -7
  7. package/src/build/blueprint/cognet/config/config.ts +52 -0
  8. package/src/build/blueprint/cognet/config/index.ts +4 -0
  9. package/src/build/blueprint/cognet/config/literal.ts +83 -0
  10. package/src/build/blueprint/cognet/config/provider.ts +43 -0
  11. package/src/build/blueprint/cognet/config/shape.ts +183 -0
  12. package/src/build/blueprint/cognet/index.ts +4 -2
  13. package/src/build/blueprint/cognet/native/cargo.ts +31 -0
  14. package/src/build/blueprint/cognet/native/crate.ts +126 -0
  15. package/src/build/blueprint/cognet/native/index.ts +2 -0
  16. package/src/build/blueprint/cognet/native/library.ts +125 -0
  17. package/src/build/blueprint/cognet/native/manifest.ts +137 -0
  18. package/src/build/blueprint/cognet/python/index.ts +1 -0
  19. package/src/build/blueprint/cognet/python/project.ts +119 -0
  20. package/src/build/blueprint/cognet/schema/arrays.ts +23 -0
  21. package/src/build/blueprint/cognet/schema/authored.ts +273 -0
  22. package/src/build/blueprint/cognet/schema/compile.ts +78 -0
  23. package/src/build/blueprint/cognet/schema/components/external.ts +15 -0
  24. package/src/build/blueprint/cognet/schema/components/index.ts +3 -0
  25. package/src/build/blueprint/cognet/schema/components/lock.ts +58 -0
  26. package/src/build/blueprint/cognet/schema/components/model.ts +34 -0
  27. package/src/build/blueprint/cognet/schema/components/python.ts +15 -0
  28. package/src/build/blueprint/cognet/schema/components/python_source.py +69 -0
  29. package/src/build/blueprint/cognet/schema/components/rust.ts +33 -0
  30. package/src/build/blueprint/cognet/schema/components/rust_source/Cargo.lock +117 -0
  31. package/src/build/blueprint/cognet/schema/components/rust_source/Cargo.toml +11 -0
  32. package/src/build/blueprint/cognet/schema/components/rust_source/src/main.rs +104 -0
  33. package/src/build/blueprint/cognet/schema/components/source.ts +220 -0
  34. package/src/build/blueprint/cognet/schema/components/tags.ts +66 -0
  35. package/src/build/blueprint/cognet/schema/components/typescript.ts +157 -0
  36. package/src/build/blueprint/cognet/schema/index.ts +5 -0
  37. package/src/build/blueprint/cognet/schema/interfaces/index.ts +3 -0
  38. package/src/build/blueprint/cognet/schema/interfaces/source.ts +218 -0
  39. package/src/build/blueprint/cognet/schema/python.ts +260 -0
  40. package/src/build/blueprint/cognet/schema/rust.ts +316 -0
  41. package/src/build/blueprint/cognet/schema/schema.ts +248 -0
  42. package/src/build/blueprint/cognet/schema/typescript.ts +352 -0
  43. package/src/build/blueprint/index.ts +1 -1
  44. package/src/build/blueprint/modules/index.ts +7 -5
  45. package/src/build/blueprint/modules/meta.ts +47 -3
  46. package/src/build/blueprint/scan/config.ts +22 -16
  47. package/src/build/blueprint/scan/provider-globals.ts +46 -0
  48. package/src/build/blueprint/scan/providers.ts +25 -0
  49. package/src/build/blueprint/scan/tools.ts +21 -15
  50. package/src/build/extensions/edit.ts +66 -2
  51. package/src/build/extensions/extensions.ts +16 -3
  52. package/src/build/extensions/index.ts +1 -1
  53. package/src/build/project/bundle/agent.ts +26 -17
  54. package/src/build/project/bundle/source.ts +2 -2
  55. package/src/build/project/create/cognet.ts +84 -33
  56. package/src/build/project/create/profile.ts +13 -3
  57. package/src/build/project/index.ts +1 -1
  58. package/src/build/project/installer.ts +6 -5
  59. package/src/build/project/kinds.ts +4 -0
  60. package/src/build/project/manifest/env.ts +10 -0
  61. package/src/build/project/models/blobs/blobs.ts +57 -0
  62. package/src/build/project/models/blobs/index.ts +1 -0
  63. package/src/build/project/models/fetch.ts +46 -51
  64. package/src/build/project/models/index.ts +2 -1
  65. package/src/build/project/models/models.ts +12 -38
  66. package/src/build/project/models/onnx.ts +82 -0
  67. package/src/build/project/models/specifier.ts +9 -3
  68. package/src/build/project/models/storage/index-store.ts +27 -0
  69. package/src/build/project/models/storage/index.ts +1 -0
  70. package/src/build/project/models/store.ts +21 -16
  71. package/src/build/project/prepare.ts +82 -27
  72. package/src/build/project/project.ts +8 -14
  73. package/src/build/project/projects.ts +12 -1
  74. package/src/build/project/tree.ts +13 -3
  75. package/src/build/project/treecache.ts +8 -4
  76. package/src/build/project/typegen/axon-dts.ts +18 -0
  77. package/src/build/project/typegen/cognet-dts.ts +248 -59
  78. package/src/build/project/typegen/prompt-dts.ts +2 -3
  79. package/src/build/project/typegen/registry-dts.ts +2 -2
  80. package/src/build/project/typegen/tsconfig.ts +13 -13
  81. package/src/build/project/typegen/tui-dts.ts +3 -4
  82. package/src/build/project/typegen/workspace-scripts.ts +8 -7
  83. package/src/build/project/typegen/write.ts +15 -2
  84. package/src/build/project/watcher.ts +27 -0
  85. package/src/build/runtime/agent.ts +102 -63
  86. package/src/build/runtime/conformance.ts +25 -0
  87. package/src/build/runtime/escalations.ts +3 -8
  88. package/src/build/runtime/index.ts +2 -0
  89. package/src/build/runtime/instances.ts +7 -4
  90. package/src/build/runtime/progress.ts +6 -2
  91. package/src/build/runtime/reload-watch.ts +11 -8
  92. package/src/debug/README.md +398 -0
  93. package/src/debug/debug.ts +101 -0
  94. package/src/debug/events.ts +156 -0
  95. package/src/debug/graph.ts +94 -0
  96. package/src/debug/index.ts +5 -0
  97. package/src/debug/indexer.ts +286 -0
  98. package/src/debug/inference.ts +53 -0
  99. package/src/debug/log.ts +68 -0
  100. package/src/debug/overview.ts +78 -0
  101. package/src/debug/perf.ts +75 -0
  102. package/src/debug/resources.ts +125 -0
  103. package/src/debug/ring.ts +31 -0
  104. package/src/debug/sessions.ts +90 -0
  105. package/src/debug/signs.ts +119 -0
  106. package/src/debug/tally.ts +44 -0
  107. package/src/debug/types.ts +146 -0
  108. package/src/index.ts +9 -0
  109. package/src/link/agent-main.ts +36 -10
  110. package/src/link/index.ts +1 -1
  111. package/src/link/services.ts +88 -57
  112. package/src/platform.ts +17 -25
  113. package/src/services/cloud.ts +1 -4
  114. package/src/services/control/client.ts +1 -1
  115. package/src/services/control/server.ts +1 -1
  116. package/src/services/index.ts +1 -0
  117. package/src/services/ollama/daemon.ts +23 -0
  118. package/src/services/ollama/http.ts +7 -1
  119. package/src/services/ollama/ollama.ts +8 -14
  120. package/src/services/probe/ask.ts +139 -0
  121. package/src/services/probe/index.ts +3 -0
  122. package/src/services/providers.ts +18 -0
  123. package/src/services/resources/hardware.ts +15 -18
  124. package/src/services/resources/resources.ts +4 -5
  125. package/src/services/store/types.ts +3 -0
  126. package/src/services/running/index.ts +0 -1
  127. package/src/services/running/running.ts +0 -216
@@ -1,11 +1,14 @@
1
- import { join } from "node:path"
2
- import { readFileSync, writeFileSync } from "node:fs"
1
+ import { join, relative, sep } from "node:path"
2
+ import { existsSync, readdirSync, readFileSync } from "node:fs"
3
3
  import { Frame, type ProjectKind } from "../../frame"
4
4
  import type { EngineType } from "@arcforge/types"
5
+ import { writeIfChanged } from "./write"
6
+ import { CognetConfigFile, contractOf, SCHEMA_DIR } from "../../blueprint/cognet"
5
7
 
6
8
  /**
7
9
  * The ambient authoring surface for cognet source — what the compile step's
8
- * host installs at runtime (defineCognet, loop, kernel, phase, system, ecs), typed
10
+ * host installs at runtime (defineCognet, definePlugin, defineSystem, component,
11
+ * query, frame, loop, kernel, phase, system, ecs), typed
9
12
  * here for the editor. Written into the owning project's `types/` area by
10
13
  * `axon prepare`: a standalone cognet's own frame, or the AGENT's frame when
11
14
  * the brain is inline at `<agent>/cognet/`.
@@ -23,9 +26,22 @@ import type {
23
26
  KernelAbi,
24
27
  EngineType,
25
28
  } from "@arcforge/types"
26
- import type { EcsT } from "@arcforge/cognet/ecs"
29
+ import type { Component as EcsComponent, ComponentOpts, Definition, EcsT, Frame as EcsFrame, FrameDescriptor, Query, QueryOpts, QueryShape } from "@arcforge/cognet/ecs"
30
+ import type { Component as SchemaComponent, ComponentOptions, Frame as SchemaFrame, FrameOptions, Handle as SchemaHandle, Session as SchemaSession, u32 as SchemaU32, i32 as SchemaI32, f32 as SchemaF32, f64 as SchemaF64 } from "@arcforge/cognet/schema"
31
+ import type { AuthoredSystem, AuthoredSystemSpec, Input, Readable, Run, Trigger } from "@arcforge/cognet/schedule"
27
32
 
28
33
  declare global {
34
+ /** Schema vocabulary for authored type files. Erased after schema generation. */
35
+ type Component<Value, Options extends ComponentOptions> = SchemaComponent<Value, Options>
36
+ type Frame<Options extends FrameOptions> = SchemaFrame<Options>
37
+ type u32 = SchemaU32
38
+ type i32 = SchemaI32
39
+ type f32 = SchemaF32
40
+ type f64 = SchemaF64
41
+ /** Interface vocabulary for interfaces/*.interface.ts: what a provider keeps, and pushes that share state. */
42
+ type Handle<Name extends string> = SchemaHandle<Name>
43
+ type Session<Push, Answer> = SchemaSession<Push, Answer>
44
+
29
45
  /** what this brain declares (mode, wakeOn, engines) — cognet.config.ts only.
30
46
  * Identity is NOT declared: name and version come from package.json. */
31
47
  function defineCognet<T extends CognetConfig>(config: T): T
@@ -39,9 +55,86 @@ declare global {
39
55
  function definePlugin(plugin: CognetPlugin): CognetPlugin
40
56
 
41
57
  /**
42
- * THE entry point — declare the tick pipeline once, in src/main.ts.
43
- * The kernel wakes it per stimulus batch; ticks run until stop() or
44
- * interrupt. Wake-scoped things arrive as args, never as globals.
58
+ * A system — the default export of any \`*.system.ts\` file, wherever it
59
+ * sits. Discovered at compile time, and run in a tick only when what runs
60
+ * it has changed — what it reads, or what it names in \`on\` (\`clock\`:
61
+ * every tick) — ordered by its data: a system that reads a component runs
62
+ * after every system that writes it. Everything it touches must be
63
+ * declared.
64
+ *
65
+ * \`async run()\` makes it an async system: the tick does not wait for it,
66
+ * it reads a snapshot taken when it starts, its writes land at the start
67
+ * of a later tick, and it is not started again while a run is in flight.
68
+ * Model calls belong here.
69
+ */
70
+ function defineSystem<const U extends readonly (keyof CognetServices & string)[] = []>(spec: Omit<AuthoredSystemSpec, "on" | "reads" | "recalls" | "streams" | "writes" | "uses" | "run"> & {
71
+ on?: readonly (Trigger | CognetReadableName | "clock")[]
72
+ reads?: readonly (Readable | CognetReadableName)[]
73
+ recalls?: readonly (Definition | CognetDefinitionName)[]
74
+ streams?: readonly (EcsComponent<unknown> | CognetComponentName)[]
75
+ writes?: readonly (EcsComponent<unknown> | CognetComponentName)[]
76
+ /** The services it calls, by the names cognet.config.ts gives them. Its run's \`services\` holds these and no others. */
77
+ uses?: U
78
+ run(run: Omit<Run, "services"> & { services: { readonly [K in U[number]]: CognetUse<CognetServices[K]> } }): void | Promise<void>
79
+ }): AuthoredSystem
80
+
81
+ /** Every use cognet.config.ts declares, typed by its interface. Generated. */
82
+ interface CognetServices {
83
+ __COGNET_SERVICES__
84
+ }
85
+
86
+ /**
87
+ * One use, as a run holds it: its interface's methods, whether something
88
+ * fills it, and what that reports of itself — null while unavailable.
89
+ */
90
+ type CognetUse<I> = Omit<I, "describe"> & {
91
+ readonly available: boolean
92
+ describe(): (I extends { describe(): infer D } ? D : never) | null
93
+ }
94
+
95
+ /**
96
+ * A component — a typed claim an entity can hold. Write it as
97
+ * \`export const name = component<T>()\`: its name and scope come from
98
+ * the folder it is defined in. Visible to systems in that folder and
99
+ * below unless \`public\`; written by one system unless \`open\`.
100
+ */
101
+ function component<T>(opts?: ComponentOpts): EcsComponent<T>
102
+
103
+ /**
104
+ * A named group of components, to declare as one in \`reads\`:
105
+ * \`export const tracked = query({ place: place, travel: travel })\`.
106
+ * It is a declaration only — a system reads the world with \`ecs.query\`.
107
+ */
108
+ function query<const S extends QueryShape>(shape: S, opts?: QueryOpts): Query<S>
109
+
110
+ /**
111
+ * A frame — a space a component's \`display\` places its value in: a
112
+ * camera's pixels, the body, a map. Write it as
113
+ * \`export const world = frame({ kind: "metric2d", unit: "px" })\`: named
114
+ * from its folder like a component, and declared to readers by the
115
+ * schedule. No system reads or writes it.
116
+ */
117
+ function frame(descriptor: FrameDescriptor): EcsFrame
118
+
119
+ /**
120
+ * The mind's input — every stimulus that arrived since the reading system
121
+ * last ran. Declare it (\`reads: [stimuli]\`) and read \`run({ stimuli })\`;
122
+ * undeclared, it throws. Buffered between ticks, so a slow system misses
123
+ * nothing.
124
+ */
125
+ const stimuli: Input
126
+
127
+ /**
128
+ * The passing of time: changed on every tick. Named only in \`on\` —
129
+ * \`on: [clock]\` runs a system every tick, for what must notice time
130
+ * pass (a silence, a fade) when nothing it reads has changed.
131
+ */
132
+ const clock: Input
133
+
134
+ /**
135
+ * OPTIONAL — a script's tick body, declared once in main.ts. Runs after
136
+ * the systems on every tick, until stop() or interrupt. A brain made only
137
+ * of systems declares none: each wake is then exactly one tick.
45
138
  */
46
139
  function loop(body: (ctx: {
47
140
  /** stimuli committed since the last wake, in seq order — stimulus:* only, the cognet's whole input contract */
@@ -76,13 +169,39 @@ __COGNET_ENGINE_ROLES__
76
169
  * from one tick to the next. Every write commits to the session log with
77
170
  * its value, which is what makes the world reconstructible afterwards.
78
171
  *
79
- * Built on first touch — a cognet that never reaches for it carries no
80
- * entity store. Declare a component's shape once with \`ecs.declare()\` so
81
- * readers can render it honestly.
172
+ * A system reads and writes by component name —
173
+ * \`ecs.query({ components: ["velocity"] })\`,
174
+ * \`ecs.set({ id: id, components: { velocity: value } })\` — typed
175
+ * by CognetComponents below. Built on first touch — a cognet that never
176
+ * reaches for it carries no entity store.
82
177
  */
83
- const ecs: EcsT
178
+ const ecs: EcsT<CognetComponents>
179
+
180
+ /**
181
+ * Every component this cognet defines, name to type, generated from its
182
+ * \`export const name = component<T>()\` lines: each under its full name,
183
+ * and under its export name alone when no other component shares it.
184
+ */
185
+ interface CognetComponents {
186
+ __COGNET_COMPONENTS__
187
+ }
188
+
189
+ interface CognetQueries {
190
+ __COGNET_QUERIES__
191
+ }
84
192
  }
85
193
 
194
+ type CognetComponentName = Extract<keyof CognetComponents, string>
195
+ type CognetQueryName = Extract<keyof CognetQueries, string>
196
+ type CognetDefinitionName = CognetComponentName | CognetQueryName
197
+ type CognetReadableName = CognetDefinitionName | "stimuli"
198
+
199
+ /** A component's value is never null: in \`ecs.set\`, null is what takes a component off. This line fails to compile naming any that is. */
200
+ type CognetNeverNull<Nullable extends never = { [K in keyof CognetComponents]: null extends CognetComponents[K] ? K : never }[keyof CognetComponents]> = Nullable
201
+
202
+ /** The type a component handle carries. */
203
+ type CognetValue<Handle> = Handle extends EcsComponent<infer T> ? T : never
204
+
86
205
  export {}
87
206
  `
88
207
 
@@ -105,60 +224,130 @@ export const COGNET_GLOBALS = "cognet-globals.d.ts"
105
224
  * declarations into `.agent/types/` — one brain's authoring surface, reached
106
225
  * from whichever frame the source happens to live in.
107
226
  */
227
+ /** Each engine role the cognet declares: its name, its type, and what it puts out. */
108
228
  function readCognetEngineTypes(root: string): Array<[string, EngineType, string]> {
109
- const candidates = [
110
- join(root, "cognet.config.ts"),
111
- join(root, "cognet", "cognet.config.ts"),
112
- ]
113
- const source = candidates.map(path => {
114
- try { return readFileSync(path, "utf-8") } catch { return null }
115
- }).find(value => value !== null)
116
-
117
- if (!source) return []
118
-
119
- const opener = source.indexOf("engines")
120
- if (opener < 0) return []
121
- const open = source.indexOf("{", opener)
122
- let depth = 0
123
- let close = -1
124
- let quote: string | null = null
125
- for (let i = open; i < source.length; i++) {
126
- const char = source[i]
127
- if (quote) {
128
- if (char === quote && source[i - 1] !== "\\") quote = null
129
- continue
130
- }
131
- if (char === "\"" || char === "'" || char === "`") quote = char
132
- else if (char === "{") depth++
133
- else if (char === "}" && --depth === 0) {
134
- close = i
135
- break
136
- }
137
- }
138
- if (close < 0) return []
139
- const block = source.slice(open + 1, close)
140
-
141
- const roles: Array<[string, EngineType, string]> = []
142
- const rolePattern = new RegExp("(?:^|\\n)\\s*([A-Za-z_$][\\w$]*)\\s*:\\s*\\{([\\s\\S]*?)(?=\\n\\s*[A-Za-z_$][\\w$]*\\s*:\\s*\\{|$)", "g")
143
- const typePattern = new RegExp("\\btype\\s*:\\s*[\\\"'](generate|transform|stream)[\\\"']")
144
- for (const match of block.matchAll(rolePattern)) {
145
- const body = match[2] ?? ""
146
- const type = typePattern.exec(body)?.[1] as EngineType | undefined
147
- const output = body.match(/\bout\s*:\s*["'`](text|image|audio|video|vector|score|depth)["'`]/)?.[1]
148
- if (type && output) roles.push([match[1]!, type, output])
149
- }
150
- return roles
229
+ const dir = cognetDir(root)
230
+ if (!dir) return []
231
+ const engines = CognetConfigFile({ sourceDir: dir }).read()?.engines ?? {}
232
+ return Object.entries(engines).map(([name, engine]) => [name, engine.type, [engine.out].flat()[0]!])
233
+ }
234
+
235
+ /**
236
+ * Each use the cognet declares, as a field of CognetServices: its name, typed
237
+ * by the interface it names — imported from the file that defines it, the
238
+ * standard library's or the cognet's own.
239
+ */
240
+ function readCognetServices(root: string, types: string): string[] {
241
+ const dir = cognetDir(root)
242
+ if (!dir) return []
243
+ const uses = CognetConfigFile({ sourceDir: dir }).read()?.uses ?? {}
244
+ return Object.entries(uses).map(([name, use]) => {
245
+ const own = use.interface.startsWith("./")
246
+ const file = own ? join(dir, `${use.interface.slice(2)}.interface.ts`) : Bun.resolveSync(`@arcforge/cognet/interfaces/${use.interface}`, dir)
247
+ const near = relative(types, file).split(sep).join("/").replace(/\.ts$/, "")
248
+ const from = own ? (near.startsWith(".") ? near : `./${near}`) : `@arcforge/cognet/interfaces/${use.interface}`
249
+ return ` ${JSON.stringify(name)}: import(${JSON.stringify(from)}).${contractOf(file)}`
250
+ })
251
+ }
252
+
253
+ /** The cognet's source directory: the project itself, or an agent's inline `cognet/`. */
254
+ function cognetDir(root: string): string | undefined {
255
+ return [root, join(root, "cognet")].find(one => existsSync(join(one, "cognet.config.ts")))
151
256
  }
152
257
 
153
258
  export function generateCognetDts(root: string, kind: ProjectKind = "cognet"): void {
259
+ const types = Frame({ root: root, kind: kind }).ensure("types")
154
260
  const declarations = readCognetEngineTypes(root)
155
261
  .map(([name, type, output]) => ` ${name}: { type: "${type}"; out: "${output}" }`)
156
262
  .join("\n")
157
- const generated = COGNET_DTS.replace("__COGNET_ENGINE_ROLES__", declarations)
263
+ const generated = COGNET_DTS
264
+ .replace("__COGNET_ENGINE_ROLES__", declarations)
265
+ .replace("__COGNET_SERVICES__", readCognetServices(root, types).join("\n"))
266
+ .replace("__COGNET_COMPONENTS__", components.declare([...components.found(root), ...components.generated(join(Frame({ root: root, kind: kind }).path("cognet"), SCHEMA_DIR))], types))
267
+ .replace("__COGNET_QUERIES__", components.queries(root))
268
+
269
+ writeIfChanged(join(types, COGNET_GLOBALS), generated)
270
+ }
271
+
272
+ /** One `export const name = component<T>()` in the cognet's source. */
273
+ type FoundComponent = {
274
+ /** `L0/sense/vestibular/gravity` — the name the compile step gives it. */
275
+ name: string
276
+ /** `gravity` — the export. */
277
+ exported: string
278
+ /** The file defining it. */
279
+ file: string
280
+ }
281
+
282
+ /** `export const flow = component<Flow>(...)` — the same line the compile step names components from. */
283
+ const COMPONENT = /^export\s+const\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*component\s*[<(]/gm
284
+ const QUERY = /^export\s+const\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*query\s*\(/gm
285
+
286
+ /** Directories no definition lives under: installed code and build output. */
287
+ const SKIPPED = ["node_modules", ".git", ".cognet", ".agent"]
288
+
289
+ const components = {
290
+ /**
291
+ * Every component the cognet defines, named as the compile step names
292
+ * them: the folder under `src/` when the cognet has one, then the export.
293
+ * A project with no cognet source defines none.
294
+ */
295
+ found(root: string, pattern: RegExp = COMPONENT): FoundComponent[] {
296
+ const source = [join(root, "cognet"), root].find(dir => existsSync(join(dir, "cognet.config.ts")) || existsSync(join(dir, "main.ts")) || existsSync(join(dir, "src", "main.ts")))
297
+ if (!source) return []
298
+ const nested = existsSync(join(source, "src"))
299
+ const found: FoundComponent[] = []
300
+ for (const entry of readdirSync(source, { recursive: true, encoding: "utf8" })) {
301
+ const path = entry.split(sep).join("/")
302
+ if (!path.endsWith(".ts") || path.endsWith(".d.ts") || path.endsWith(".test.ts")) continue
303
+ if (path.split("/").some(part => SKIPPED.includes(part))) continue
304
+ const file = join(source, entry)
305
+ const named = nested && path.startsWith("src/") ? path.slice("src/".length) : path
306
+ const folder = named.includes("/") ? named.slice(0, named.lastIndexOf("/")) : ""
307
+ for (const match of readFileSync(file, "utf8").matchAll(pattern)) {
308
+ found.push({ name: folder ? `${folder}/${match[1]!}` : match[1]!, exported: match[1]!, file: file })
309
+ }
310
+ }
311
+ return found.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
312
+ },
313
+
314
+ /**
315
+ * Every component the cognet's schemas generated into the frame, named as
316
+ * the compile step names them: the path the module mirrors — its
317
+ * schema's — then the export. None before the schemas are first compiled.
318
+ */
319
+ generated(dir: string): FoundComponent[] {
320
+ if (!existsSync(dir)) return []
321
+ const found: FoundComponent[] = []
322
+ for (const entry of readdirSync(dir, { recursive: true, encoding: "utf8" })) {
323
+ const path = entry.split(sep).join("/")
324
+ if (!path.endsWith(".ts") || path.endsWith(".types.ts")) continue
325
+ const folder = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""
326
+ for (const match of readFileSync(join(dir, entry), "utf8").matchAll(COMPONENT)) {
327
+ found.push({ name: folder ? `${folder}/${match[1]!}` : match[1]!, exported: match[1]!, file: join(dir, entry) })
328
+ }
329
+ }
330
+ return found
331
+ },
332
+
333
+ /** The members of CognetComponents, each typed off the handle its file exports. */
334
+ declare(found: FoundComponent[], types: string): string {
335
+ const lines: string[] = []
336
+ for (const one of found) {
337
+ const module = relative(types, one.file).split(sep).join("/").replace(/\.ts$/, "")
338
+ lines.push(` ${JSON.stringify(one.name)}: CognetValue<typeof import(${JSON.stringify(module.startsWith(".") ? module : `./${module}`)}).${one.exported}>`)
339
+ const alone = found.filter(other => other.exported === one.exported).length === 1
340
+ if (alone && one.name !== one.exported) lines.push(` ${JSON.stringify(one.exported)}: CognetComponents[${JSON.stringify(one.name)}]`)
341
+ }
342
+ return lines.join("\n")
343
+ },
158
344
 
159
- writeFileSync(
160
- join(Frame({ root: root, kind: kind }).ensure("types"), COGNET_GLOBALS),
161
- generated,
162
- "utf-8",
163
- )
345
+ queries(root: string): string {
346
+ const found = this.found(root, QUERY)
347
+ return found.flatMap(one => {
348
+ const lines = [` ${JSON.stringify(one.name)}: true`]
349
+ if (found.filter(other => other.exported === one.exported).length === 1 && one.name !== one.exported) lines.push(` ${JSON.stringify(one.exported)}: true`)
350
+ return lines
351
+ }).join("\n")
352
+ },
164
353
  }
@@ -1,6 +1,6 @@
1
1
  import { join } from "node:path"
2
- import { writeFileSync } from "node:fs"
3
2
  import { Frame } from "../../frame"
3
+ import { writeIfChanged } from "./write"
4
4
 
5
5
  /**
6
6
  * globals.d.ts for prompt packages — the ambient surface of
@@ -32,9 +32,8 @@ export {}
32
32
  `
33
33
 
34
34
  export function generatePromptDts(promptPath: string): void {
35
- writeFileSync(
35
+ writeIfChanged(
36
36
  join(Frame({ root: promptPath, kind: "prompt" }).ensure("types"), "globals.d.ts"),
37
37
  PROMPT_DTS,
38
- "utf-8",
39
38
  )
40
39
  }
@@ -1,7 +1,7 @@
1
1
  import { join } from "node:path"
2
- import { writeFileSync } from "node:fs"
3
2
  import { Frame, type ProjectKind } from "../../frame"
4
3
  import { emptyRegistrations, mergeRegistrations, scanSource, type Registration, type Registrations } from "../../extensions/registrations"
4
+ import { writeIfChanged } from "./write"
5
5
 
6
6
  /**
7
7
  * `.axon/types/registry.d.ts` — what a config actually registered, as types.
@@ -105,5 +105,5 @@ export function generateRegistryDts(
105
105
  "",
106
106
  ]
107
107
 
108
- writeFileSync(join(Frame({ root, kind }).ensure("types"), "registry.d.ts"), lines.join("\n"), "utf-8")
108
+ writeIfChanged(join(Frame({ root: root, kind: kind }).ensure("types"), "registry.d.ts"), lines.join("\n"))
109
109
  }
@@ -1,11 +1,12 @@
1
- import { join } from "node:path"
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
1
+ import { join, relative, sep } from "node:path"
2
+ import { existsSync, mkdirSync, readFileSync } from "node:fs"
3
3
  import { err } from "@arcforge/err"
4
4
  import { Tree } from "../tree"
5
5
  import { Frame, FRAME } from "../../frame"
6
- import { INLINE_COGNET_DIR, inlineCognetDir } from "../../blueprint/cognet"
6
+ import { INLINE_COGNET_DIR, inlineCognetDir, SCHEMA_DIR, SCHEMA_SPECIFIER } from "../../blueprint/cognet"
7
7
  import { COGNET_GLOBALS } from "./cognet-dts"
8
8
  import { KINDS, type ProjectKind } from "../kinds"
9
+ import { writeIfChanged } from "./write"
9
10
 
10
11
  // ── Compiler options ──────────────────────────────────────────────────────────
11
12
  //
@@ -107,7 +108,7 @@ function writeStandaloneFrame(root: string, kind: ProjectKind, include: string[]
107
108
  const frame = Frame({ root: root, kind: kind })
108
109
  const typesDir = frame.ensure("types")
109
110
 
110
- writeFileSync(
111
+ writeIfChanged(
111
112
  join(typesDir, "tsconfig.json"),
112
113
  JSON.stringify({
113
114
  compilerOptions: {
@@ -125,7 +126,6 @@ function writeStandaloneFrame(root: string, kind: ProjectKind, include: string[]
125
126
  },
126
127
  include: rebase(include),
127
128
  }, null, 2) + "\n",
128
- "utf-8"
129
129
  )
130
130
 
131
131
  ensureRootPointer(join(root, "tsconfig.json"), `./${frame.name}/${FRAME.types}/tsconfig.json`)
@@ -143,7 +143,7 @@ function ensureRootPointer(rootPath: string, extendsTarget: string): void {
143
143
  }
144
144
  }
145
145
  if (needsWrite) {
146
- writeFileSync(rootPath, JSON.stringify({ extends: extendsTarget }, null, 2) + "\n", "utf-8")
146
+ writeIfChanged(rootPath, JSON.stringify({ extends: extendsTarget }, null, 2) + "\n")
147
147
  }
148
148
  }
149
149
 
@@ -191,18 +191,16 @@ export function ensureProjectTsConfig(root: string, kind: ProjectKind): void {
191
191
  }
192
192
  : {}
193
193
 
194
- writeFileSync(
194
+ writeIfChanged(
195
195
  join(typesDir, "tsconfig.json"),
196
196
  JSON.stringify({ extends: TSCONFIG_BASE, include: rebase(spec.include), ...exclude }, null, 2) + "\n",
197
- "utf-8"
198
197
  )
199
198
 
200
199
  if (kind === "agent") {
201
200
  // tests/ scope — the flip side: sees axon-test.d.ts, never axon.d.ts.
202
- writeFileSync(
201
+ writeIfChanged(
203
202
  join(typesDir, "axon-test.tsconfig.json"),
204
203
  JSON.stringify({ extends: TSCONFIG_BASE, include: rebase(TESTS_INCLUDE), exclude: ["./axon.d.ts"] }, null, 2) + "\n",
205
- "utf-8"
206
204
  )
207
205
 
208
206
  const testsDir = join(root, "tests")
@@ -218,11 +216,14 @@ export function ensureProjectTsConfig(root: string, kind: ProjectKind): void {
218
216
  // Written only when the folder exists, so an agent without one carries no
219
217
  // config pointing at an empty directory.
220
218
  if (inlineCognet) {
221
- writeFileSync(
219
+ const schemaRel = relative(typesDir, join(frame.path("cognet"), SCHEMA_DIR)).split(sep).join("/")
220
+ writeIfChanged(
222
221
  join(typesDir, "cognet.tsconfig.json"),
223
222
  JSON.stringify({
224
223
  extends: TSCONFIG_BASE,
225
- include: rebase(INLINE_COGNET_INCLUDE),
224
+ // The modules generated from the cognet's schemas, imported as `#schema/…` — the bundler resolves the same.
225
+ compilerOptions: { paths: { [`${SCHEMA_SPECIFIER}*`]: [`${schemaRel}/*`] } },
226
+ include: [...rebase(INLINE_COGNET_INCLUDE), `${schemaRel}/**/*.ts`],
226
227
  // Everything generated for the AGENT. Listed by name rather
227
228
  // than by a glob, because `./**/*.d.ts` in the include above is
228
229
  // what picks up the cognet's own declarations — an exclusion
@@ -231,7 +232,6 @@ export function ensureProjectTsConfig(root: string, kind: ProjectKind): void {
231
232
  "./prompts.d.ts", "./scripts.d.ts", "./components.d.ts",
232
233
  "./env.d.ts", "./hooks.d.ts"],
233
234
  }, null, 2) + "\n",
234
- "utf-8"
235
235
  )
236
236
  ensureRootPointer(
237
237
  join(inlineCognet, "tsconfig.json"),
@@ -1,7 +1,7 @@
1
1
  import { join } from "node:path"
2
- import { writeFileSync } from "node:fs"
3
2
  import { TUI_CONTRACT } from "@arcforge/types/tui-contract"
4
3
  import { Frame, type ProjectKind } from "../../frame"
4
+ import { writeIfChanged } from "./write"
5
5
 
6
6
  /**
7
7
  * The ambient authoring surface for a PROFILE and for EXTENSIONS — the ten
@@ -114,9 +114,8 @@ export {}
114
114
  * writer rather than a privileged internal surface and a reduced public one.
115
115
  */
116
116
  export function generateTuiDts(root: string, kind: ProjectKind): void {
117
- writeFileSync(
118
- join(Frame({ root, kind }).ensure("types"), "globals.d.ts"),
117
+ writeIfChanged(
118
+ join(Frame({ root: root, kind: kind }).ensure("types"), "globals.d.ts"),
119
119
  tuiDts(),
120
- "utf-8",
121
120
  )
122
121
  }
@@ -1,6 +1,7 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
1
+ import { existsSync, mkdirSync, readFileSync } from "node:fs"
2
2
  import { join, relative } from "node:path"
3
3
  import type { AxonPrompt, AxonScript } from "@arcforge/types"
4
+ import { writeIfChanged } from "./write"
4
5
 
5
6
  /**
6
7
  * Give repository-authored workspace scripts the same ambient frame as the
@@ -31,7 +32,7 @@ export function generateWorkspaceScriptFrame(
31
32
  }
32
33
  })()
33
34
  if (!existsSync(config) || legacyConfig) {
34
- writeFileSync(config, JSON.stringify({
35
+ writeIfChanged(config, JSON.stringify({
35
36
  compilerOptions: {
36
37
  // Workspace scripts are Bun modules even when a script has no
37
38
  // imports/exports. This makes top-level await valid without
@@ -48,7 +49,7 @@ export function generateWorkspaceScriptFrame(
48
49
  allowImportingTsExtensions: true,
49
50
  },
50
51
  include: ["scripts/**/*.ts", ".axon/**/*.d.ts"],
51
- }, null, 2) + "\n", "utf-8")
52
+ }, null, 2) + "\n")
52
53
  }
53
54
 
54
55
  const toolGlobals = join(agentRoot, ".agent", "types", "tool-globals.d.ts")
@@ -92,7 +93,7 @@ export function generateWorkspaceScriptFrame(
92
93
  .filter(script => script.name.startsWith("workspace:"))
93
94
  .map(script => script.name)
94
95
 
95
- writeFileSync(join(output, "globals.d.ts"), [
96
+ writeIfChanged(join(output, "globals.d.ts"), [
96
97
  "// .agents/.axon/globals.d.ts — generated by axon prepare, do not edit",
97
98
  "// The selected agent supplies the runtime globals and tool surface.",
98
99
  ...references,
@@ -100,13 +101,13 @@ export function generateWorkspaceScriptFrame(
100
101
  "",
101
102
  "export {}",
102
103
  "",
103
- ].join("\n"), "utf-8")
104
+ ].join("\n"))
104
105
 
105
- writeFileSync(join(output, "scripts.d.ts"), [
106
+ writeIfChanged(join(output, "scripts.d.ts"), [
106
107
  "// .agents/.axon/scripts.d.ts — generated by axon prepare, do not edit",
107
108
  `// Workspace scripts: ${workspaceNames.join(", ") || "none"}`,
108
109
  "",
109
110
  "export {}",
110
111
  "",
111
- ].join("\n"), "utf-8")
112
+ ].join("\n"))
112
113
  }
@@ -1,4 +1,4 @@
1
- import { writeFileSync } from "node:fs"
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs"
2
2
  import { join } from "node:path"
3
3
  import { Frame, type ProjectKind } from "../../frame"
4
4
 
@@ -28,7 +28,20 @@ export function ensureOutDir(root: string, kind: TypegenKind = "agent"): string
28
28
 
29
29
  /** Write one declaration file into the project's generated-types dir. */
30
30
  export function writeDts(root: string, filename: string, content: string, kind: TypegenKind = "agent"): void {
31
- writeFileSync(join(ensureOutDir(root, kind), filename), content, "utf-8")
31
+ writeIfChanged(join(ensureOutDir(root, kind), filename), content)
32
+ }
33
+
34
+ /**
35
+ * Materialize derived text only when its bytes changed.
36
+ *
37
+ * Type declarations are inputs to editors and watchers. Rewriting identical
38
+ * bytes turns every ordinary boot into a source change, needlessly waking
39
+ * those consumers and making a warm prepare do real filesystem work.
40
+ */
41
+ export function writeIfChanged(path: string, content: string): boolean {
42
+ if (existsSync(path) && readFileSync(path, "utf-8") === content) return false
43
+ writeFileSync(path, content, "utf-8")
44
+ return true
32
45
  }
33
46
 
34
47
  /** kebab-case → PascalCase. */
@@ -93,6 +93,7 @@ export function Watcher(opts: WatcherOpts) {
93
93
  let fsWatcher: FSWatcher | null = null
94
94
  let timer: ReturnType<typeof setTimeout> | null = null
95
95
  const listeners = new Set<(path: string) => void>()
96
+ let retained = 0
96
97
 
97
98
  /**
98
99
  * Nesting depth of suspend() calls, and the one change seen while
@@ -173,6 +174,32 @@ export function Watcher(opts: WatcherOpts) {
173
174
  await Bun.sleep(75)
174
175
  },
175
176
 
177
+ /**
178
+ * Keep the watcher alive until the returned release is called.
179
+ *
180
+ * A prepared build cache is only valid while its inputs have been
181
+ * continuously watched. A live runtime is another owner. Ref-counting
182
+ * keeps either from stopping the other and makes that lifetime an
183
+ * explicit contract rather than an accident of call order.
184
+ */
185
+ async retain(): Promise<() => void> {
186
+ retained++
187
+ try {
188
+ await this.start()
189
+ } catch (cause) {
190
+ retained--
191
+ throw cause
192
+ }
193
+
194
+ let released = false
195
+ return () => {
196
+ if (released) return
197
+ released = true
198
+ retained--
199
+ if (retained === 0) this.stop()
200
+ }
201
+ },
202
+
176
203
  /** Stop watching. Idempotent. */
177
204
  stop(): void {
178
205
  fsWatcher?.close()