@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,122 @@
1
+ import { err } from "@arcforge/err"
2
+ import { Child, invalidFrameError } from "./child"
3
+ import { Events } from "./events"
4
+ import { resolveTestFiles } from "./files"
5
+ import type { TestRunOptions, TestRunResult } from "./types"
6
+
7
+ /**
8
+ * TestRunner — native Bun test execution, projected into a structured event
9
+ * stream.
10
+ *
11
+ * The point is not to reimplement a test runner. Bun already runs the tests;
12
+ * this makes the run OBSERVABLE — every suite, case, hook and console line
13
+ * arrives as an event on the same log the runtime writes to, so one session
14
+ * shows a request and the tests that covered it in one ordered timeline.
15
+ *
16
+ * Composition only. The concerns underneath it:
17
+ * files glob and path resolution
18
+ * child one `bun test` subprocess, watched (spawn, IPC, abort)
19
+ * events the authoritative ordered stream, liveness and delivery
20
+ *
21
+ * Files run sequentially. The instrumented bun:test API is installed
22
+ * per-process, so two files sharing a child would interleave into one
23
+ * ambiguous stream.
24
+ */
25
+ export function TestRunner() {
26
+ return {
27
+ async run(options: TestRunOptions): Promise<TestRunResult> {
28
+ const cwd = options.cwd ?? process.cwd()
29
+ const files = await resolveTestFiles(options.files, cwd)
30
+ if (files.length === 0) throw err("TEST_FILES_NOT_FOUND")
31
+
32
+ const runId = Bun.randomUUIDv7()
33
+ const startedAt = performance.now()
34
+
35
+ const events = Events({
36
+ runId: runId,
37
+ ...(options.onEvent ? { onEvent: options.onEvent } : {}),
38
+ })
39
+
40
+ const child = Child({
41
+ cwd: cwd,
42
+ ...(options.env ? { env: options.env } : {}),
43
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
44
+ ...(options.preloads ? { preloads: options.preloads } : {}),
45
+ ...(options.onMessage ? { onMessage: options.onMessage } : {}),
46
+ onFrame: frame => events.record(frame.type, frame.data as never, frame.context),
47
+ onInvalid: () => events.record("test:process:fault", { kind: "protocol", error: invalidFrameError() }),
48
+ })
49
+
50
+ events.record("test:run:start", { files })
51
+
52
+ let stdout = ""
53
+ let stderr = ""
54
+ let exitCode: number | null = 0
55
+ let cancelled = options.signal?.aborted ?? false
56
+
57
+ for (const file of files) {
58
+ if (cancelled) break
59
+
60
+ const fileStarted = performance.now()
61
+ events.record("test:file:start", {}, { file })
62
+
63
+ const outcome = await child.run(file, options.signal)
64
+ stdout += outcome.stdout
65
+ stderr += outcome.stderr
66
+ cancelled = outcome.cancelled
67
+ if (outcome.exitCode !== 0) exitCode = outcome.exitCode
68
+
69
+ // A case that started and never reported a terminal result owes
70
+ // the stream an answer: the process died holding it. Record the
71
+ // failure the child could not, or the run reports fewer cases
72
+ // than it actually attempted.
73
+ for (const context of events.orphaned(file)) {
74
+ events.record("test:case:fail", {
75
+ durationMs: performance.now() - fileStarted,
76
+ error: err("UNKNOWN", {
77
+ detail: cancelled
78
+ ? "test process cancelled before producing a terminal result"
79
+ : "test process exited before producing a terminal result",
80
+ }),
81
+ }, context)
82
+ }
83
+
84
+ // A nonzero exit with no recorded failure means the process died
85
+ // for a reason the test protocol never saw — a crash in a
86
+ // preload, a native fault. Without this the run would report
87
+ // "passed" on an exit code that says otherwise.
88
+ if (outcome.exitCode !== 0 && !events.failed(file) && !cancelled) {
89
+ events.record("test:process:fault", {
90
+ kind: "exit",
91
+ error: err("UNKNOWN", { detail: `bun test exited with code ${outcome.exitCode}` }),
92
+ }, { file })
93
+ }
94
+
95
+ events.record("test:file:complete", {
96
+ exitCode: outcome.exitCode,
97
+ durationMs: performance.now() - fileStarted,
98
+ }, { file })
99
+ }
100
+
101
+ const tally = events.tally()
102
+ const status = cancelled ? "cancelled" : tally.failed > 0 || exitCode !== 0 ? "failed" : "passed"
103
+ const durationMs = performance.now() - startedAt
104
+
105
+ events.record("test:run:complete", { status, durationMs, ...tally })
106
+ await events.settle()
107
+
108
+ return {
109
+ runId: runId,
110
+ status: status,
111
+ exitCode: exitCode,
112
+ durationMs: durationMs,
113
+ files: files,
114
+ events: events.all,
115
+ stdout: stdout,
116
+ stderr: stderr,
117
+ }
118
+ },
119
+ }
120
+ }
121
+
122
+ export type TestRunnerT = ReturnType<typeof TestRunner>
@@ -0,0 +1,26 @@
1
+ import type { AxonTestEvent } from "@arcforge/types"
2
+
3
+ export type TestRunOptions = {
4
+ files: string | string[]
5
+ cwd?: string
6
+ env?: Record<string, string | undefined>
7
+ timeoutMs?: number
8
+ signal?: AbortSignal
9
+ /** Called synchronously in authoritative event order. */
10
+ onEvent?: (event: AxonTestEvent) => void | Promise<void>
11
+ /** Additional child preloads. Test instrumentation always loads first. */
12
+ preloads?: string[]
13
+ /** Domain extensions may consume their own validated IPC channels. */
14
+ onMessage?: (message: unknown) => void | Promise<void>
15
+ }
16
+
17
+ export type TestRunResult = {
18
+ runId: string
19
+ status: "passed" | "failed" | "cancelled"
20
+ exitCode: number | null
21
+ durationMs: number
22
+ files: string[]
23
+ events: AxonTestEvent[]
24
+ stdout: string
25
+ stderr: string
26
+ }
@@ -0,0 +1,77 @@
1
+ import { err } from "@arcforge/err"
2
+
3
+ /**
4
+ * The three-process update handshake.
5
+ *
6
+ * Updating cannot happen inside the running app — a package manager cannot
7
+ * replace the binary of a live program — so it is spread across three
8
+ * processes that only ever agree on what is in this file:
9
+ *
10
+ * bin/supervisor.ts the real CLI entrypoint; spawns the app, and on
11
+ * EXIT_CODE spawns the helper
12
+ * the app Updates().handoff() writes a request to REQUEST_ENV's
13
+ * path and exits with EXIT_CODE
14
+ * bin/update-helper.ts reads the request off argv, installs, verifies,
15
+ * rolls back on failure
16
+ *
17
+ * Nothing else is shared between them: no imports across the boundary, no
18
+ * assumptions about each other's internals. Change anything here and all three
19
+ * must be rebuilt together, which is exactly why it is one small file.
20
+ */
21
+
22
+ /** The app exits with this to tell the supervisor an update was requested. */
23
+ export const UPDATE_REQUEST_EXIT_CODE = 75
24
+
25
+ /** Env var carrying the path the app writes its request to. Absent = updates unsupported. */
26
+ export const UPDATE_REQUEST_ENV = "AXON_UPDATE_REQUEST"
27
+
28
+ export type UpdateRequest = {
29
+ from: string
30
+ to: string
31
+ /** Absolute path to the bun binary that will perform the install. */
32
+ bun: string
33
+ /** Absolute path to the axon binary, used to verify the installed version. */
34
+ axon: string
35
+ /** Absolute path to the state file both the helper and the next launch read. */
36
+ state: string
37
+ }
38
+
39
+ const FIELDS = ["from", "to", "bun", "axon", "state"] as const
40
+
41
+ /** A request → the argv the supervisor passes the helper. */
42
+ export function toArgv(request: UpdateRequest): string[] {
43
+ return FIELDS.flatMap(field => [`--${field}`, request[field]])
44
+ }
45
+
46
+ /**
47
+ * The helper's argv → a request.
48
+ *
49
+ * Validates semver on both versions before returning: these values reach a
50
+ * shell command, and the helper is spawned against a request file living in a
51
+ * world-writable temp directory. A version that is not a version is refused
52
+ * here rather than interpolated into `bun add`.
53
+ */
54
+ export function fromArgv(argv: string[]): UpdateRequest {
55
+ const values = new Map<string, string>()
56
+ for (let i = 0; i < argv.length; i += 2) {
57
+ const key = argv[i]
58
+ const value = argv[i + 1]
59
+ if (!key?.startsWith("--") || value === undefined) throw err("UPDATE_HELPER_ARGS_INVALID")
60
+ values.set(key.slice(2), value)
61
+ }
62
+
63
+ const missing = FIELDS.filter(field => !values.get(field))
64
+ if (missing.length > 0) {
65
+ throw err("UPDATE_HELPER_ARGS_INVALID", { detail: `missing ${missing.map(field => `--${field}`).join(", ")}` })
66
+ }
67
+
68
+ const request = Object.fromEntries(FIELDS.map(field => [field, values.get(field)!])) as UpdateRequest
69
+ if (!isSemver(request.from) || !isSemver(request.to)) {
70
+ throw err("UPDATE_HELPER_VERSION_INVALID", { context: { from: request.from, to: request.to } })
71
+ }
72
+ return request
73
+ }
74
+
75
+ function isSemver(value: string): boolean {
76
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value)
77
+ }
@@ -0,0 +1,12 @@
1
+ // update — Axon's self-update, split across three processes.
2
+ // Updates() is the in-app service; contract.ts is the handshake all three share.
3
+
4
+ export { Updates, packagedHelperPath, type UpdatesT, type UpdateCheck } from "./updates"
5
+ export { Installer, type InstallerT, type InstallerIo } from "./installer"
6
+ export {
7
+ UPDATE_REQUEST_ENV,
8
+ UPDATE_REQUEST_EXIT_CODE,
9
+ toArgv,
10
+ fromArgv,
11
+ type UpdateRequest,
12
+ } from "./contract"
@@ -0,0 +1,139 @@
1
+ import { mkdir, rename, writeFile } from "node:fs/promises"
2
+ import { dirname } from "node:path"
3
+ import type { UpdateRecord } from "../store/types"
4
+ import type { UpdateRequest } from "./contract"
5
+ import { withPropagationRetry } from "../../build/project/propagation"
6
+
7
+ /** How the installer reaches the outside world. Injected so tests drive it without spawning. */
8
+ export type InstallerIo = {
9
+ run?: (command: string[]) => Promise<{ code: number; stdout: string }>
10
+ sleep?: (milliseconds: number) => Promise<void>
11
+ out?: (message: string) => void
12
+ err?: (message: string) => void
13
+ }
14
+
15
+ /**
16
+ * Installer — replace the globally installed Axon with a named version.
17
+ *
18
+ * Runs in the update-helper process, AFTER the app has exited: a package
19
+ * manager cannot replace the binary of a running program, which is the whole
20
+ * reason this is a separate process rather than a method on Updates().
21
+ *
22
+ * Every outcome is recorded to the state file before returning, because the
23
+ * next app launch reads that file to tell the user what happened while it was
24
+ * gone. Failure rolls back to the previous version and says so — an update that
25
+ * half-applied and left nothing runnable is the one outcome worth real effort
26
+ * to avoid.
27
+ */
28
+ export function Installer(io: InstallerIo = {}) {
29
+ const run = io.run ?? runCommand
30
+ const sleep = io.sleep ?? Bun.sleep
31
+ const out = io.out ?? (message => process.stdout.write(message))
32
+ const report = io.err ?? (message => process.stderr.write(message))
33
+
34
+ /** Write the state file atomically — the next launch reads it to explain itself. */
35
+ async function record(path: string, value: UpdateRecord): Promise<void> {
36
+ await mkdir(dirname(path), { recursive: true })
37
+ const temporary = `${path}.${process.pid}.tmp`
38
+ await writeFile(temporary, JSON.stringify(value, null, 2) + "\n", "utf-8")
39
+ await rename(temporary, path)
40
+ }
41
+
42
+ /**
43
+ * Install the target, retrying while the version is still propagating.
44
+ *
45
+ * The policy lives in project/propagation.ts, shared with the dependency
46
+ * installer — this path had it right and that one did not, so `axon update`
47
+ * succeeded and the next `axon init` failed against the same registry
48
+ * seconds later.
49
+ *
50
+ * `--no-cache` bypasses Bun's manifest cache; the BACKOFF is what actually
51
+ * waits for the edge to catch up. Both are needed and only together.
52
+ */
53
+ async function install(request: UpdateRequest): Promise<boolean> {
54
+ const outcome = await withPropagationRetry(
55
+ async () => {
56
+ const result = await run([request.bun, "add", "-g", "--no-cache", `@arcforge/axon@${request.to}`])
57
+ // No `output`: bun's stderr is inherited so the user sees the
58
+ // install directly, which means the text to classify on never
59
+ // reaches here. Retries unconditionally — see PropagationAttempt.
60
+ return { ok: result.code === 0 }
61
+ },
62
+ {
63
+ sleep,
64
+ onRetry: delay => report(
65
+ `Axon ${request.to} is not available from this npm edge yet; retrying in ${delay / 1_000}s…\n`,
66
+ ),
67
+ },
68
+ )
69
+ return outcome.ok
70
+ }
71
+
72
+ /** The installed binary must report the version we asked for — anything else is a failed install. */
73
+ async function verify(request: UpdateRequest): Promise<boolean> {
74
+ const result = await run([request.axon, "--version"])
75
+ return result.code === 0 && result.stdout.trim() === request.to
76
+ }
77
+
78
+ async function rollback(request: UpdateRequest): Promise<boolean> {
79
+ report("Axon update failed verification; restoring the previous version…\n")
80
+ const result = await run([request.bun, "add", "-g", `@arcforge/axon@${request.from}`])
81
+ return result.code === 0
82
+ }
83
+
84
+ return {
85
+ /** Apply the update. Returns the process exit code: 0 installed, 1 rolled back or failed. */
86
+ async apply(request: UpdateRequest): Promise<number> {
87
+ await record(request.state, {
88
+ status: "running",
89
+ from: request.from,
90
+ to: request.to,
91
+ updatedAt: new Date().toISOString(),
92
+ })
93
+ out(`\nUpdating Axon ${request.from} → ${request.to}…\n`)
94
+
95
+ if (await install(request) && await verify(request)) {
96
+ await record(request.state, {
97
+ status: "complete",
98
+ from: request.from,
99
+ to: request.to,
100
+ updatedAt: new Date().toISOString(),
101
+ })
102
+ out(`✓ Axon ${request.to} installed. Run axon to continue.\n\n`)
103
+ return 0
104
+ }
105
+
106
+ const restored = await rollback(request)
107
+ const error = restored
108
+ ? `update to ${request.to} failed verification; restored ${request.from}`
109
+ : `update to ${request.to} failed and rollback to ${request.from} also failed`
110
+
111
+ await record(request.state, {
112
+ status: restored ? "rolled-back" : "failed",
113
+ from: request.from,
114
+ to: request.to,
115
+ updatedAt: new Date().toISOString(),
116
+ error: error,
117
+ })
118
+
119
+ const recovery = process.platform === "win32"
120
+ ? "irm https://axon.arclabs.it/install.ps1 | iex"
121
+ : "curl -fsSL https://axon.arclabs.it/install | bash"
122
+ report(`${error}. Run ${recovery} to recover.\n\n`)
123
+ return 1
124
+ },
125
+ }
126
+ }
127
+
128
+ export type InstallerT = ReturnType<typeof Installer>
129
+
130
+ async function runCommand(command: string[]): Promise<{ code: number; stdout: string }> {
131
+ const proc = Bun.spawn(command, {
132
+ stdin: "ignore",
133
+ stdout: "pipe",
134
+ stderr: "inherit",
135
+ env: process.env,
136
+ })
137
+ const [code, stdout] = await Promise.all([proc.exited, new Response(proc.stdout).text()])
138
+ return { code: code, stdout: stdout }
139
+ }
@@ -0,0 +1,137 @@
1
+ import { existsSync, realpathSync } from "node:fs"
2
+ import { mkdir, rename, writeFile } from "node:fs/promises"
3
+ import { dirname, join } from "node:path"
4
+ import { gt, valid } from "semver"
5
+ import type { AxonCloudClient } from "@arcforge/cloud"
6
+ import type { StoreT } from "../store"
7
+ import { UPDATE_REQUEST_ENV, type UpdateRequest } from "./contract"
8
+ import { err } from "@arcforge/err"
9
+
10
+ export type UpdateCheck =
11
+ | { status: "current"; current: string; latest: string }
12
+ | { status: "available"; current: string; latest: string }
13
+
14
+ type UpdatesOpts = {
15
+ cloud: AxonCloudClient
16
+ store: StoreT
17
+ /**
18
+ * The running app's version. Supplied by the caller rather than read
19
+ * from a package.json here — this package is a library, and the
20
+ * version that matters is the shipped app's, not its own.
21
+ */
22
+ currentVersion: string
23
+ helperPath?: string
24
+ bunPath?: string
25
+ axonPath?: string
26
+ requestPath?: string
27
+ }
28
+
29
+ /** Headless Axon self-update orchestration shared by the CLI and TUI. */
30
+ export function Updates(opts: UpdatesOpts) {
31
+ const currentVersion = opts.currentVersion
32
+ // Global package managers expose `axon` through a symlink/shim. Resolve the
33
+ // real entry file before looking beside it for the packaged helper.
34
+ const invokedEntryPath = process.argv[1] ?? import.meta.path
35
+ const helperPath = opts.helperPath ?? packagedHelperPath(invokedEntryPath)
36
+ const bunPath = opts.bunPath ?? process.execPath
37
+ // Resolved lazily: construction is wiring, and Bun.which() both shells
38
+ // out and is undefined under Node — which is what the Fleet extension
39
+ // host runs, so eagerly calling it here threw before the platform
40
+ // finished constructing and took the whole extension down with it.
41
+ const axonPath = opts.axonPath ?? (typeof Bun === "undefined" ? "axon" : Bun.which("axon") ?? "axon")
42
+ const requestPath = opts.requestPath ?? process.env[UPDATE_REQUEST_ENV]
43
+
44
+ function supported(): boolean {
45
+ return existsSync(helperPath) && Boolean(requestPath)
46
+ }
47
+
48
+ async function check(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<UpdateCheck> {
49
+ if (!valid(currentVersion)) {
50
+ throw err("UPDATE_CURRENT_VERSION_INVALID", { context: { version: currentVersion } })
51
+ }
52
+ const release = await opts.cloud.cloud.releases.axon(signal, options)
53
+ if (release.package !== "@arcforge/axon" || release.channel !== "latest" || !valid(release.version)) {
54
+ throw err("UPDATE_RELEASE_INVALID", {
55
+ context: { package: release.package, channel: release.channel, version: release.version },
56
+ })
57
+ }
58
+ return {
59
+ status: gt(release.version, currentVersion) ? "available" : "current",
60
+ current: currentVersion,
61
+ latest: release.version,
62
+ }
63
+ }
64
+
65
+ async function handoff(signal?: AbortSignal): Promise<UpdateCheck> {
66
+ // The status indicator is deliberately cacheable. The version handed to
67
+ // the package manager is not: refresh it at the point of commitment so
68
+ // a release published moments ago cannot leave us installing a stale tag.
69
+ const result = await check(signal, { fresh: true })
70
+ if (result.status === "current") return result
71
+ if (!supported()) throw err("UPDATE_UNAVAILABLE_IN_DEVELOPMENT")
72
+
73
+ opts.store.update.state.set({
74
+ status: "pending",
75
+ from: result.current,
76
+ to: result.latest,
77
+ updatedAt: new Date().toISOString(),
78
+ })
79
+
80
+ try {
81
+ const request: UpdateRequest = {
82
+ from: result.current,
83
+ to: result.latest,
84
+ bun: bunPath,
85
+ axon: axonPath,
86
+ state: opts.store.update.statePath,
87
+ }
88
+ if (!requestPath) throw err("UPDATE_SUPERVISOR_UNAVAILABLE")
89
+ await mkdir(dirname(requestPath), { recursive: true })
90
+ const temporary = `${requestPath}.${process.pid}.tmp`
91
+ await writeFile(temporary, JSON.stringify(request, null, 2) + "\n", "utf-8")
92
+ await rename(temporary, requestPath)
93
+ } catch (error) {
94
+ opts.store.update.state.set({
95
+ status: "failed",
96
+ from: result.current,
97
+ to: result.latest,
98
+ updatedAt: new Date().toISOString(),
99
+ error: error instanceof Error ? error.message : String(error),
100
+ })
101
+ throw error
102
+ }
103
+ return result
104
+ }
105
+
106
+ return {
107
+ currentVersion: currentVersion,
108
+ supported: supported,
109
+ check: check,
110
+ handoff: handoff,
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Where the packaged update helper sits — beside the entry file that invoked us.
116
+ *
117
+ * Exported for its own test: the resolution only runs when `helperPath` is NOT
118
+ * injected, and that path reads process.argv[1], which a test cannot set. The
119
+ * symlink case it handles is the difference between updates working and
120
+ * silently reporting unsupported, so it is worth covering directly.
121
+ *
122
+ * Global package managers expose `axon` through a symlink or shim, so the
123
+ * invoked path is resolved to its real location first: looking beside the
124
+ * symlink finds nothing, and updates would silently report unsupported.
125
+ */
126
+ export function packagedHelperPath(entryPath: string): string {
127
+ let real = entryPath
128
+ try {
129
+ real = realpathSync(entryPath)
130
+ } catch {
131
+ // A path we cannot stat is one we cannot resolve past — use it as given
132
+ // and let existsSync() below decide whether the helper is really there.
133
+ }
134
+ return join(dirname(real), "update-helper.js")
135
+ }
136
+
137
+ export type UpdatesT = ReturnType<typeof Updates>
@@ -0,0 +1,148 @@
1
+ import { readdir, stat } from "node:fs/promises"
2
+ import { existsSync, lstatSync, readlinkSync, statSync } from "node:fs"
3
+ import { join } from "node:path"
4
+ import { err } from "@arcforge/err"
5
+
6
+ /**
7
+ * Shared filesystem discovery tools — every blueprint scan leaf walks
8
+ * directories through here instead of hand-rolling readdir recursion.
9
+ * A missing directory is a real state (empty surface), so listing one
10
+ * returns [] — anything else throws.
11
+ */
12
+ export const fsx = {
13
+ exists(path: string): boolean {
14
+ return existsSync(path)
15
+ },
16
+
17
+ /**
18
+ * The target of a symlink, or null when the path is not one.
19
+ *
20
+ * Distinct from exists(), which FOLLOWS links and therefore answers false
21
+ * for a dangling one — losing the very fact a caller needs to explain why.
22
+ * A dependency tree grafted onto a shared cache is entirely symlinks, so
23
+ * "the link is there but its target is gone" is a real and common state
24
+ * that reads as "not installed" without this.
25
+ */
26
+ readLink(path: string): string | null {
27
+ try {
28
+ return lstatSync(path).isSymbolicLink() ? readlinkSync(path) : null
29
+ } catch {
30
+ return null
31
+ }
32
+ },
33
+
34
+ /**
35
+ * Exists AND is a regular file. Distinct from exists() because a path can
36
+ * name a directory: a resolver looking for `./brain/cognet.config.ts` that
37
+ * accepts `./brain` hands its caller a directory where a file was promised.
38
+ *
39
+ * Never throws — a predicate that answers "is this a file" with an
40
+ * exception is unusable in the candidate loops that call it. Note
41
+ * `throwIfNoEntry: false` covers only ENOENT: a path whose PARENT is a
42
+ * regular file (`foo.ts/bar.ts`, which a resolver generates naturally
43
+ * while trying candidates) raises ENOTDIR, which is still just "no".
44
+ */
45
+ isFile(path: string): boolean {
46
+ try {
47
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false
48
+ } catch {
49
+ return false
50
+ }
51
+ },
52
+
53
+ /** Immediate children (names) of a directory. Missing dir = []. */
54
+ async list(dir: string): Promise<string[]> {
55
+ try {
56
+ return await readdir(dir)
57
+ } catch (error) {
58
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return []
59
+ throw error
60
+ }
61
+ },
62
+
63
+ /**
64
+ * Recursive file walk. Returns absolute + relative paths, sorted for
65
+ * determinism. `skipDirs` prunes subtrees by directory name.
66
+ */
67
+ async walk(dir: string, opts?: { skipDirs?: string[] }): Promise<Array<{ absPath: string; relPath: string }>> {
68
+ const results: Array<{ absPath: string; relPath: string }> = []
69
+
70
+ async function descend(current: string, prefix: string): Promise<void> {
71
+ for (const entry of await fsx.list(current)) {
72
+ const absPath = join(current, entry)
73
+ const relPath = prefix ? `${prefix}/${entry}` : entry
74
+ const info = await stat(absPath).catch(() => null)
75
+ if (!info) continue
76
+ if (info.isDirectory()) {
77
+ if (opts?.skipDirs?.includes(entry)) continue
78
+ await descend(absPath, relPath)
79
+ } else {
80
+ results.push({ absPath, relPath })
81
+ }
82
+ }
83
+ }
84
+
85
+ await descend(dir, "")
86
+ return results.sort((a, b) => a.relPath.localeCompare(b.relPath))
87
+ },
88
+
89
+ /**
90
+ * Parse a JSON file, or null when it doesn't exist.
91
+ *
92
+ * Corrupt JSON throws CORRUPT_JSON; an unreadable file throws
93
+ * FILE_UNREADABLE. Only absence is a null.
94
+ */
95
+ async readJson<T = Record<string, unknown>>(path: string): Promise<T | null> {
96
+ const text = await readFile(path)
97
+ if (text === null) return null
98
+
99
+ try {
100
+ return JSON.parse(text) as T
101
+ } catch (cause) {
102
+ throw err("CORRUPT_JSON", {
103
+ detail: `corrupt JSON at ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
104
+ context: { path: path },
105
+ cause: cause,
106
+ })
107
+ }
108
+ },
109
+
110
+ /**
111
+ * Read a text file, or null when it doesn't exist.
112
+ *
113
+ * Null means ABSENT and nothing else. A file that exists but cannot be read
114
+ * throws — see readFile below for why that distinction matters.
115
+ */
116
+ readText(path: string): Promise<string | null> {
117
+ return readFile(path)
118
+ },
119
+ }
120
+
121
+ /**
122
+ * Read a file, distinguishing "not there" from "there but unreadable".
123
+ *
124
+ * Absence is an ordinary state across this package: a project with no README,
125
+ * an agent with no .env, a module with no package.json. Callers read null as
126
+ * "that surface doesn't exist" and carry on, which is correct.
127
+ *
128
+ * Everything else is not. This used to swallow every error and return null, so
129
+ * an axon.config.ts with wrong permissions — or read mid-write, or shadowed by
130
+ * a directory — reported as a MISSING config. The user was then told to create
131
+ * a file that was already there, which is the wrong fix for the problem they
132
+ * actually had. Absence is data; unreadable is a fault, and faults belong at
133
+ * the boundary that detects them.
134
+ */
135
+ async function readFile(path: string): Promise<string | null> {
136
+ try {
137
+ return await Bun.file(path).text()
138
+ } catch (cause) {
139
+ const code = (cause as { code?: string })?.code
140
+ if (code === "ENOENT") return null
141
+
142
+ throw err("FILE_UNREADABLE", {
143
+ detail: `${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
144
+ context: { path: path, ...(code ? { code: code } : {}) },
145
+ cause: cause,
146
+ })
147
+ }
148
+ }