@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,729 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { existsSync, readdirSync, readFileSync } from "node:fs"
3
+ import { homedir } from "node:os"
4
+ import { basename, join, resolve } from "node:path"
5
+ import { err } from "@arcforge/err"
6
+ import { policyGlobMatch } from "@arcforge/types"
7
+ import type { Distribution } from "../cloud"
8
+ import { Disk } from "./disk"
9
+ import type { ActiveProfile, AppIntent, AppState, EnvTarget, HistoryEntry, PolicyGrant, PolicyRequest, ProfileRecord, ProfileSettings, UpdateRecord } from "./types"
10
+
11
+
12
+ type StoreOpts = {
13
+ /** Override the store root — tests point this at a scratch dir. */
14
+ root?: string
15
+ /**
16
+ * The active profile's declared settings, read fresh per call.
17
+ *
18
+ * A thunk because settings live in `profile.config.ts`, which is
19
+ * TypeScript — parsing it is `build/extensions`' job, and Store is
20
+ * constructed long before that exists. Handing the values in keeps the
21
+ * dependency pointing the right way: the store never learns what a config
22
+ * file is, and the config never learns where the store keeps things.
23
+ *
24
+ * Synchronous, so `extraRoots()` stays synchronous — every caller of it is.
25
+ * Whoever supplies this caches; see useSettings.
26
+ */
27
+ settings?: () => { paths?: string[] }
28
+ /**
29
+ * Persist a settings change. Same reasoning as `settings` above — the
30
+ * write lands in `profile.config.ts`, which only build/extensions can edit.
31
+ *
32
+ * Omitted by a store with no config behind it (tests, a first boot before
33
+ * login): `watch()` then throws rather than writing somewhere the read
34
+ * path would never look, which is the failure that made `paths` silently
35
+ * do nothing.
36
+ */
37
+ setSetting?: (key: string, value: unknown) => Promise<unknown>
38
+ }
39
+
40
+ /**
41
+ * The app-written area of a profile — profiles/<email>/store/.
42
+ *
43
+ * Named once and joined everywhere rather than spelled into each path, because
44
+ * it was spelled seven times and the profile root has since become a directory
45
+ * a USER authors (main.ts, profile.config.ts, plugins/, extensions/). Keeping
46
+ * the app's own files in one named room is what keeps that root readable, and
47
+ * one constant is what stops half of them drifting back out.
48
+ */
49
+ const STORE_DIR = "store"
50
+
51
+ /** profiles/<id>/store — the app-written area of one profile. */
52
+ function storeDir(id: string): string {
53
+ return `profiles/${id}/${STORE_DIR}`
54
+ }
55
+
56
+ /**
57
+ * Store — the ONE interface to ~/.axon. A typed client over the dotdir:
58
+ * profiles (identity, credentials, settings), sent-message history,
59
+ * app-remembered continuity state, the environment target, and registry
60
+ * caches. Nothing else in the platform reads or writes .axon.
61
+ *
62
+ * Layout owned here:
63
+ * env — "local" | "cloud"
64
+ * profiles/<email>/profile.config.ts — which extensions load (user-authored)
65
+ * profiles/<email>/main.ts — the user's own TUI config (user-authored)
66
+ * profiles/<email>/plugins/ — the user's own lifecycle plugins
67
+ * profiles/<email>/extensions/ — extension source, local and installed
68
+ * profiles/<email>/agents/ — the user's agent projects
69
+ * profiles/<email>/.axon/ — generated type frame
70
+ * profiles/<email>/store/ — everything the APP writes (see STORE_DIR)
71
+ * cache/running/<sessionId>.json — liveness record for a local agent process
72
+ * cache/active-profile.json — who is logged in
73
+ * cache/<name>.json — registry caches
74
+ *
75
+ * A profile root is now authored-vs-generated, not a flat bag: everything at
76
+ * the top level is written by a person, and everything the app writes for
77
+ * itself lives under store/. That split is the same one the build frames make
78
+ * (see build/frame) — grouping by what a file IS, rather than by its format,
79
+ * is what tells a user which files are safe to edit.
80
+ *
81
+ * Profiles are keyed by email, not the backend's user id — this directory
82
+ * is meant to be navigated by hand, and a UUID tells a developer nothing.
83
+ * Every caller above this layer (Cloud(), useAuth()) still calls it "id";
84
+ * that's fine, they never depend on it being a UUID, only on it being a
85
+ * stable, unique key per person — which email already is (no email-change
86
+ * feature exists on the backend, so this holds for the app's current scope).
87
+ */
88
+ export function Store(opts: StoreOpts = {}) {
89
+ const root = opts.root ?? join(homedir(), ".axon")
90
+ const disk = Disk({ root })
91
+
92
+ /**
93
+ * Who is logged in — app state, so it lives under cache/ rather than in
94
+ * profiles/.
95
+ *
96
+ * `profiles/` is a USER SURFACE now: it holds main.ts, plugins/,
97
+ * profile.config.ts and agents — files a person opens and edits. An
98
+ * index.json the app wrote for itself, sitting among them, is one more
99
+ * thing a reader has to work out is not theirs. Same split the frames make
100
+ * (see build/frame) and the same reason a profile's own app state lives
101
+ * under `store/`.
102
+ *
103
+ * Migrated from the old location on first read rather than on a version
104
+ * check: the old file is the only evidence the old layout existed, so
105
+ * moving it when it is seen is both the detection and the fix. Without it,
106
+ * upgrading would silently log every user out.
107
+ */
108
+ const active = disk.json<ActiveProfile>("cache/active-profile.json")
109
+ const legacyActive = disk.json<ActiveProfile>("profiles/index.json")
110
+ if (!active.get()) {
111
+ const previous = legacyActive.get()
112
+ if (previous) {
113
+ active.set(previous)
114
+ legacyActive.delete()
115
+ }
116
+ }
117
+ const env = disk.text("env")
118
+
119
+ function profile(id: string) {
120
+ const base = `profiles/${id}`
121
+ const store = storeDir(id)
122
+ return {
123
+ id,
124
+ /** The profile root — where the user's own main.ts and profile.config.ts live. */
125
+ root: join(root, base),
126
+ record: disk.json<ProfileRecord>(`${store}/profile.json`),
127
+ settings: disk.json<ProfileSettings>(`${store}/settings.json`),
128
+ /** Absolute path to settings.json — `axon settings` opens this in $EDITOR. */
129
+ settingsPath: join(root, store, "settings.json"),
130
+ history: disk.jsonl<HistoryEntry>(`${store}/history.jsonl`),
131
+
132
+ /**
133
+ * Escalations raised on this profile — the audit trail, and the
134
+ * queue any surface answers from.
135
+ *
136
+ * Append-only like grants and for the same reason: a request and
137
+ * its outcome are two facts in time, and rewriting the first to
138
+ * carry the second loses when each happened.
139
+ */
140
+ requests: (() => {
141
+ const file = disk.jsonl<PolicyRequest>(`${store}/requests.jsonl`)
142
+ return {
143
+ /** Record a raised escalation. Returns it, so the caller can report the id. */
144
+ raise(request: Omit<PolicyRequest, "id" | "raisedAt">): PolicyRequest {
145
+ const entry: PolicyRequest = { ...request, id: randomUUID(), raisedAt: Date.now() }
146
+ file.append(entry)
147
+ return entry
148
+ },
149
+
150
+ /**
151
+ * Record how one settled. Appended as a second entry
152
+ * naming the same id — folded on read, never rewritten.
153
+ */
154
+ settle(id: string, outcome: NonNullable<PolicyRequest["outcome"]>): void {
155
+ const raised = this.all().find(entry => entry.id === id)
156
+ if (!raised) return
157
+ file.append({ ...raised, outcome })
158
+ },
159
+
160
+ /**
161
+ * Every request, latest state per id, newest first.
162
+ *
163
+ * A settled entry supersedes the raise it names, so a
164
+ * caller sees one row per request rather than the raw
165
+ * append log.
166
+ */
167
+ list(): PolicyRequest[] {
168
+ const latest = new Map<string, PolicyRequest>()
169
+ for (const entry of file.read()) latest.set(entry.id, entry)
170
+ return [...latest.values()].reverse()
171
+ },
172
+
173
+ /** Requests still awaiting an answer. */
174
+ open(): PolicyRequest[] {
175
+ return this.list().filter(entry => !entry.outcome)
176
+ },
177
+
178
+ /** The raw log, including superseded raises — for an audit view. */
179
+ all: file.read,
180
+ }
181
+ })(),
182
+
183
+ /**
184
+ * Standing policy approvals — what "allow always" writes.
185
+ *
186
+ * Append-only, including revocation: a decision made and later
187
+ * withdrawn is two facts, not zero, and this file is the audit
188
+ * trail for every capability a person handed an agent.
189
+ *
190
+ * Owns MATCHING as well as storage, deliberately. Whether a grant
191
+ * covers a call is policy semantics — the same glob rules the
192
+ * mediator applies — and a caller re-deriving it is how the two
193
+ * drift into disagreeing about what was approved.
194
+ */
195
+ grants: (() => {
196
+ const file = disk.jsonl<PolicyGrant>(`${store}/grants.jsonl`)
197
+ return {
198
+ /**
199
+ * Every grant still in force, newest first.
200
+ *
201
+ * Revocations are folded here rather than at the write, so
202
+ * the file keeps the full history while callers only ever
203
+ * see what is live.
204
+ */
205
+ active(): PolicyGrant[] {
206
+ const all = file.read()
207
+ const revoked = new Set(all.map(entry => entry.revokes).filter(Boolean))
208
+ return all
209
+ .filter(entry => !entry.revokes && !revoked.has(entry.id))
210
+ .reverse()
211
+ },
212
+
213
+ /**
214
+ * Does a live grant cover this call?
215
+ *
216
+ * An agent matches its own grants and any written for
217
+ * `"*"`. The subject is matched with the SAME matcher
218
+ * policy uses, so a grant reads exactly like the rule it
219
+ * satisfies rather than being a second pattern language.
220
+ */
221
+ covers(agent: string, fn: string, subject: string): PolicyGrant | null {
222
+ return this.active().find(grant =>
223
+ (grant.agent === agent || grant.agent === "*")
224
+ && grant.fn === fn
225
+ && policyGlobMatch(grant.subject, subject),
226
+ ) ?? null
227
+ },
228
+
229
+ /** Record a new grant. Returns it, so a caller can report the id. */
230
+ add(grant: Omit<PolicyGrant, "id" | "grantedAt">): PolicyGrant {
231
+ const entry: PolicyGrant = { ...grant, id: randomUUID(), grantedAt: Date.now() }
232
+ file.append(entry)
233
+ return entry
234
+ },
235
+
236
+ /** Withdraw one, by id. Appends a tombstone; nothing is rewritten. */
237
+ revoke(id: string): void {
238
+ file.append({
239
+ id: randomUUID(),
240
+ agent: "",
241
+ fn: "",
242
+ subject: "",
243
+ grantedAt: Date.now(),
244
+ revokes: id,
245
+ })
246
+ },
247
+
248
+ /** The raw log, including revocations — for an audit view. */
249
+ all: file.read,
250
+ }
251
+ })(),
252
+
253
+ /**
254
+ * Every agent this profile can see, across two kinds of pool:
255
+ * watched directories the user added via settings.paths
256
+ * (`axon watch`), and profiles/<id>/agents/ where installs land.
257
+ * Each is scanned the same way — immediate subdirectories are
258
+ * agent projects.
259
+ *
260
+ * An agent is identified by the name in its package.json, not
261
+ * by the directory holding it, so `@cody/barry` and
262
+ * `@alice/barry` are two agents rather than one collision. A
263
+ * WATCHED pool outranks the installed one: watching a path is
264
+ * the statement that the checkout there is being worked on, and
265
+ * a working tree must beat a cache — otherwise editing an
266
+ * agent's source silently does nothing because a stale install
267
+ * answers first.
268
+ */
269
+ agents: {
270
+ /**
271
+ * The canonical agents directory — profiles/<id>/agents.
272
+ * Where a clone lands by default, and the lowest-priority
273
+ * pool `find()` searches. Exposed because callers that
274
+ * WRITE an agent need the directory itself, and rebuilding
275
+ * it from `store.root` outside this module duplicates the
276
+ * one piece of layout knowledge this object exists to own.
277
+ */
278
+ root: join(root, base, "agents"),
279
+
280
+ /** Extra scan roots from settings, resolved to absolute paths (~ expanded). */
281
+ extraRoots(): string[] {
282
+ // From profile.config.ts via the thunk — settings.json is
283
+ // no longer read. A caller that supplied none gets the
284
+ // canonical agents dir alone, which is the correct answer
285
+ // for a store with no profile loaded yet.
286
+ const paths = opts.settings?.().paths ?? []
287
+ return paths.map((p: string) => (p.startsWith("~") ? join(homedir(), p.slice(1)) : resolve(p)))
288
+ },
289
+
290
+ /**
291
+ * Register an extra scan root (`axon watch`). Stored ~-collapsed
292
+ * when under the home dir, so a config stays portable across
293
+ * machines with different usernames — a no-op if already
294
+ * watched.
295
+ */
296
+ async watch(path: string): Promise<void> {
297
+ if (!opts.setSetting) throw err("SETTINGS_NOT_WRITABLE")
298
+ const stored = collapseHome(resolve(path))
299
+ const existing = opts.settings?.().paths ?? []
300
+ if (existing.includes(stored)) return
301
+ await opts.setSetting("paths", [...existing, stored])
302
+ },
303
+
304
+ /** Remove an extra scan root (`axon unwatch`). Matches on resolved path — untouched if it was never watched. */
305
+ async unwatch(path: string): Promise<void> {
306
+ if (!opts.setSetting) throw err("SETTINGS_NOT_WRITABLE")
307
+ const target = resolve(path)
308
+ const existing = opts.settings?.().paths ?? []
309
+ const next = existing.filter((p: string) =>
310
+ resolve(p.startsWith("~") ? join(homedir(), p.slice(1)) : p) !== target)
311
+ if (next.length === existing.length) return
312
+ await opts.setSetting("paths", next)
313
+ },
314
+
315
+ /**
316
+ * Every pool this profile searches, nearest first.
317
+ *
318
+ * Watched roots outrank the canonical agents dir, and that
319
+ * order is the whole point: `axon watch <path>` is a
320
+ * deliberate statement that an agent is being DEVELOPED
321
+ * there, while profiles/<id>/agents is where installs land
322
+ * — a cache. A working checkout must beat a cache, or
323
+ * editing source silently does nothing because a stale
324
+ * install shadows it.
325
+ */
326
+ pools(): { root: string; kind: "watched" | "installed" }[] {
327
+ return [
328
+ ...this.extraRoots().map(root => ({ root, kind: "watched" as const })),
329
+ { root: this.root, kind: "installed" as const },
330
+ ]
331
+ },
332
+
333
+ /**
334
+ * Find an agent by the name it CALLS ITSELF — package.json's
335
+ * `name`, falling back to the directory name when there is no
336
+ * readable manifest.
337
+ *
338
+ * Matching on identity rather than directory name is what
339
+ * makes a scoped ref mean one specific agent: `@cody/barry`
340
+ * and `@alice/barry` both live in a folder called `barry`,
341
+ * and a directory-name match would silently run whichever
342
+ * was found first. An unscoped ref still matches a scoped
343
+ * agent's trailing segment, so `barry` keeps working as the
344
+ * short form of exactly one installed `@cody/barry`.
345
+ *
346
+ * Returns every match rather than the first. A name that
347
+ * resolves two ways is a question for the caller, not
348
+ * something to settle by search order.
349
+ */
350
+ find(ref: string): { root: string; name: string; kind: "watched" | "installed" }[] {
351
+ const found: { root: string; name: string; kind: "watched" | "installed" }[] = []
352
+ const seen = new Set<string>()
353
+ // `@cody/barry@1.4.0` — a pin is a constraint on WHICH
354
+ // version, never part of the identity. Local resolution
355
+ // has exactly one copy of an agent, so the pin narrows
356
+ // nothing here; stripping it keeps a pinned ref from
357
+ // silently matching nothing.
358
+ const wanted = ref.startsWith("@")
359
+ ? "@" + (ref.slice(1).split("@")[0] ?? "")
360
+ : (ref.split("@")[0] ?? ref)
361
+
362
+ for (const pool of this.pools()) {
363
+ for (const dir of listDir(pool.root)) {
364
+ const root = join(pool.root, dir)
365
+ // The same directory reachable through two pools
366
+ // (a watched root that contains agents/) is one
367
+ // agent, not an ambiguity.
368
+ if (seen.has(root)) continue
369
+ seen.add(root)
370
+
371
+ const name = identity(root)
372
+ if (name === wanted || (!wanted.startsWith("@") && name.split("/").pop() === wanted)) {
373
+ found.push({ root, name, kind: pool.kind })
374
+ }
375
+ }
376
+ }
377
+
378
+ return found
379
+ },
380
+
381
+ /**
382
+ * Every agent visible to this profile, nearest pool first.
383
+ *
384
+ * Returns resolved entries, not bare directory names: every
385
+ * caller needs the root, and handing back a name they then
386
+ * have to look up again is what let two different lookups
387
+ * disagree about which `barry` was meant.
388
+ *
389
+ * Deduped by identity — a watched checkout and an installed
390
+ * copy of the same agent are one entry, and the watched one
391
+ * wins, matching find()'s precedence.
392
+ */
393
+ /**
394
+ * Every agent DIRECTORY across every pool, deduped by path.
395
+ *
396
+ * `list()` answers "which agents can I run", so it dedupes by
397
+ * IDENTITY and lets a watched checkout shadow an installed
398
+ * copy of the same name — correct, because running the stale
399
+ * install instead of the source you are editing is the bug
400
+ * that precedence exists to prevent.
401
+ *
402
+ * History is a different question. A shadowed install still
403
+ * holds the sessions that were recorded against it, and those
404
+ * conversations happened: dropping the directory drops them
405
+ * from every listing with nothing to say they existed. That is
406
+ * how a LIVE agent could be missing from the sessions shelf —
407
+ * it was running out of an installed copy whose name a
408
+ * checkout had claimed.
409
+ *
410
+ * So: same pools, same order, deduped by ROOT instead of name.
411
+ * Anything asking "where could an agent have written" uses
412
+ * this; anything asking "which agent do I run" uses list().
413
+ */
414
+ locations(): { root: string; name: string; kind: "watched" | "installed" }[] {
415
+ const entries: { root: string; name: string; kind: "watched" | "installed" }[] = []
416
+ const seen = new Set<string>()
417
+
418
+ for (const pool of this.pools()) {
419
+ for (const dir of listDir(pool.root)) {
420
+ const root = join(pool.root, dir)
421
+ // One directory reachable through two pools (a
422
+ // watched root that contains agents/) is one
423
+ // location, not two.
424
+ if (seen.has(root)) continue
425
+ seen.add(root)
426
+ entries.push({ root, name: identity(root), kind: pool.kind })
427
+ }
428
+ }
429
+
430
+ return entries
431
+ },
432
+
433
+ list(): { root: string; name: string; kind: "watched" | "installed" }[] {
434
+ const entries: { root: string; name: string; kind: "watched" | "installed" }[] = []
435
+ const seen = new Set<string>()
436
+
437
+ for (const pool of this.pools()) {
438
+ for (const dir of listDir(pool.root)) {
439
+ const root = join(pool.root, dir)
440
+ const name = identity(root)
441
+ if (seen.has(name)) continue
442
+ seen.add(name)
443
+ entries.push({ root, name, kind: pool.kind })
444
+ }
445
+ }
446
+
447
+ return entries
448
+ },
449
+ },
450
+ }
451
+ }
452
+
453
+ return {
454
+ root,
455
+
456
+ update: {
457
+ state: disk.json<UpdateRecord>("update.json"),
458
+ statePath: join(root, "update.json"),
459
+ },
460
+
461
+ /**
462
+ * Delete the managed base workspace left behind by the old naked-model
463
+ * flow — profiles/<id>/base/ and its base.json manifest.
464
+ *
465
+ * Models are a property of an agent now, so nothing reads either path;
466
+ * they are dead bytes in a directory meant to be navigated by hand.
467
+ * Safe to remove unconditionally BECAUSE base was platform-authored:
468
+ * the config was regenerated from a template on every model pick and
469
+ * hash-guarded against hand edits, so nothing of the user's could
470
+ * survive there. Anything they wanted to keep had to be copied into a
471
+ * named agent, which is a directory this never touches.
472
+ *
473
+ * Idempotent — a profile that never used the old flow has neither path,
474
+ * and removing a missing path is a no-op.
475
+ */
476
+ pruneLegacyBase(): void {
477
+ for (const id of disk.list("profiles").filter(name => name !== "index.json")) {
478
+ disk.remove(`profiles/${id}/base`)
479
+ disk.remove(`profiles/${id}/base.json`)
480
+ }
481
+ },
482
+
483
+ /** Which backend the CLI targets. Default: cloud. */
484
+ env: {
485
+ get(): EnvTarget {
486
+ return env.get()?.trim() === "local" ? "local" : "cloud"
487
+ },
488
+ set(target: EnvTarget): void {
489
+ env.set(target)
490
+ },
491
+ },
492
+
493
+ profiles: {
494
+ /** The active profile's scoped handle, or null when logged out. */
495
+ active() {
496
+ const pointer = active.get()
497
+ return pointer ? profile(pointer.userId) : null
498
+ },
499
+
500
+ /** The active profile resolved to its record — null when logged out or the record is missing. */
501
+ current(): { id: string; record: ProfileRecord } | null {
502
+ const pointer = active.get()
503
+ if (!pointer) return null
504
+ const record = profile(pointer.userId).record.get()
505
+ return record ? { id: pointer.userId, record } : null
506
+ },
507
+
508
+ /**
509
+ * Write a profile record and point the active pointer at it —
510
+ * the login persistence step. Always keyed by the record's own
511
+ * email, never the caller's `id` param — makes it structurally
512
+ * impossible to end up with two directories (id-keyed and
513
+ * email-keyed) for the same person.
514
+ */
515
+ save(_id: string, record: ProfileRecord): void {
516
+ const key = record.user.email
517
+ profile(key).record.set(record)
518
+ active.set({ userId: key })
519
+ },
520
+
521
+ activate(id: string): void {
522
+ active.set({ userId: id })
523
+ },
524
+
525
+ deactivate(): void {
526
+ active.delete()
527
+ },
528
+
529
+ list(): string[] {
530
+ return disk.list("profiles").filter(name => name !== "index.json")
531
+ },
532
+
533
+ get: profile,
534
+
535
+ delete(id: string): void {
536
+ const pointer = active.get()
537
+ if (pointer?.userId === id) active.delete()
538
+ disk.remove(`profiles/${id}`)
539
+ },
540
+ },
541
+
542
+ /** Registry caches — typed json files under cache/. */
543
+ cache: {
544
+ file<T>(name: string) {
545
+ return disk.json<T>(`cache/${name}.json`)
546
+ },
547
+ },
548
+
549
+ /**
550
+ * Sent-message history for the active profile — one flat log
551
+ * (not per-agent, a user picking a past message cares about "what
552
+ * did I type recently," not which agent it went to). Always scoped
553
+ * to whichever profile is currently active, same resolution
554
+ * profiles.active() already does — never takes an id param.
555
+ */
556
+ history: {
557
+ /** Appends a sent message. Throws when logged out — losing the record of a message that really was sent is a real loss, not a no-op. */
558
+ append(content: string, agentName: string | null): void {
559
+ const profile = active.get()
560
+ if (!profile) throw err("NOT_AUTHENTICATED")
561
+
562
+ const entry: HistoryEntry = {
563
+ id: crypto.randomUUID(),
564
+ content,
565
+ agentName,
566
+ createdAt: new Date().toISOString(),
567
+ }
568
+ disk.jsonl<HistoryEntry>(`${storeDir(profile.userId)}/history.jsonl`).append(entry)
569
+ },
570
+
571
+ /**
572
+ * Most recent entries first, capped at `limit`, deduped exactly
573
+ * like zsh's HIST_IGNORE_ALL_DUPS: each unique `content` appears
574
+ * once, at its most-recent position. The on-disk log stays
575
+ * append-only (every send is a real record) — dedup is a read-time
576
+ * view over it, same log-is-truth / recent()-is-the-view split the
577
+ * rest of Store uses. Match is raw (no trim), like zsh. Dedup runs
578
+ * across the whole log BEFORE the limit, so `limit` means "50 unique
579
+ * commands", never a raw window that could hide an older unique one.
580
+ * Empty when logged out or nothing sent yet.
581
+ */
582
+ recent(limit = 50): HistoryEntry[] {
583
+ const profile = active.get()
584
+ if (!profile) return []
585
+ const all = disk.jsonl<HistoryEntry>(`${storeDir(profile.userId)}/history.jsonl`).read()
586
+ const seen = new Set<string>()
587
+ const deduped: HistoryEntry[] = []
588
+ for (let i = all.length - 1; i >= 0; i--) {
589
+ const entry = all[i]!
590
+ if (seen.has(entry.content)) continue
591
+ seen.add(entry.content)
592
+ deduped.push(entry)
593
+ if (deduped.length >= limit) break
594
+ }
595
+ return deduped
596
+ },
597
+ },
598
+
599
+ /**
600
+ * The running-agent registry moved to the DAEMON.
601
+ *
602
+ * It lived here while the platform spawned agents and therefore wrote
603
+ * the record. The daemon supervises now — it owns the process, knows
604
+ * its pid, and is still running when the record needs removing — so it
605
+ * owns the registry too. `@arcforge/axond`'s `agents.registry` reads
606
+ * the same directories, including this store's, so nothing that was
607
+ * observable stopped being so.
608
+ */
609
+
610
+ /**
611
+ * App-remembered continuity state for the active profile (e.g. last
612
+ * selected agent) — distinct from settings (user-configured
613
+ * preferences the user edits directly). Always scoped to whichever
614
+ * profile is currently active, same resolution profiles.active()
615
+ * already does — never takes an id param. Deciding WHAT to do with
616
+ * this on boot (e.g. auto-selecting the last agent) is a frontend
617
+ * concern, not the platform's — this only reads/writes the file.
618
+ */
619
+ state: {
620
+ /** Null when logged out or nothing has been recorded yet. */
621
+ get(): AppState | null {
622
+ const profile = active.get()
623
+ if (!profile) return null
624
+ return disk.json<AppState>(`${storeDir(profile.userId)}/state.json`).get() ?? {}
625
+ },
626
+
627
+ /** Merges fields into the active profile's state. Throws when logged out. */
628
+ update(fn: (current: AppState) => AppState): void {
629
+ const profile = active.get()
630
+ if (!profile) throw err("NOT_AUTHENTICATED")
631
+ disk.json<AppState>(`${storeDir(profile.userId)}/state.json`).update({}, fn)
632
+ },
633
+ },
634
+
635
+ /**
636
+ * What the TUI should open on its next boot — written by a CLI
637
+ * command, consumed once by the app.
638
+ *
639
+ * A separate file from state.json, not a field in it. The two have
640
+ * opposite lifetimes: state is remembered forever and re-read every
641
+ * launch, an intent is carried out once and must not survive. Sharing
642
+ * a file would make "clear the intent" a rewrite of unrelated
643
+ * continuity data, and a crash between read and write would either
644
+ * lose the last agent or re-fire the intent.
645
+ */
646
+ intent: {
647
+ /** Record what the next TUI boot should do. Throws when logged out. */
648
+ set(intent: AppIntent): void {
649
+ const profile = active.get()
650
+ if (!profile) throw err("NOT_AUTHENTICATED")
651
+ disk.json<AppIntent>(`${storeDir(profile.userId)}/intent.json`).set(intent)
652
+ },
653
+
654
+ /**
655
+ * Read the pending intent and clear it, in one call.
656
+ *
657
+ * Never a bare `get`: an intent read but not cleared re-fires on
658
+ * every subsequent boot, which for `attach` means silently
659
+ * reconnecting to a URL the user visited once. Taking is the only
660
+ * correct way to observe one, so it is the only way offered.
661
+ *
662
+ * Cleared BEFORE the caller acts on it. A failed attach must not
663
+ * leave the intent behind to retry forever — the user sees the
664
+ * error and decides, exactly as they would inside the app.
665
+ */
666
+ take(): AppIntent | null {
667
+ const profile = active.get()
668
+ if (!profile) return null
669
+ const file = disk.json<AppIntent>(`${storeDir(profile.userId)}/intent.json`)
670
+ const pending = file.get()
671
+ if (pending) file.delete()
672
+ return pending ?? null
673
+ },
674
+ },
675
+ }
676
+ }
677
+
678
+ export type StoreT = ReturnType<typeof Store>
679
+ export type ProfileT = ReturnType<StoreT["profiles"]["get"]>
680
+
681
+ /**
682
+ * Where ~/.axon lives for a given build.
683
+ *
684
+ * Development uses a SEPARATE directory (.axon-dev): an installed production
685
+ * app and a source checkout must never share credentials, or logging into
686
+ * staging from source silently re-points the installed app.
687
+ */
688
+ export function storeRoot(distribution: Distribution): string {
689
+ return join(homedir(), distribution === "production" ? ".axon" : ".axon-dev")
690
+ }
691
+
692
+ /** Immediate subdirectory names of an absolute path outside ~/.axon. Missing/non-dir = []. */
693
+ function listDir(absolutePath: string): string[] {
694
+ if (!existsSync(absolutePath)) return []
695
+ return readdirSync(absolutePath, { withFileTypes: true })
696
+ .filter(entry => entry.isDirectory())
697
+ .map(entry => entry.name)
698
+ }
699
+
700
+ /**
701
+ * What an agent directory calls itself: package.json's `name`, else the
702
+ * directory name.
703
+ *
704
+ * The fallback is deliberate rather than a swallowed failure. A directory
705
+ * with no manifest is not yet an agent and simply will not match a scoped
706
+ * ref; a directory whose manifest is malformed still has a true, usable
707
+ * identity in its folder name, and blanking it would make an agent
708
+ * unreachable because of a stray comma. Neither case is a state this
709
+ * function can repair — opening the project is what surfaces a broken
710
+ * manifest, with the error that actually explains it.
711
+ */
712
+ function identity(root: string): string {
713
+ const manifest = join(root, "package.json")
714
+ if (!existsSync(manifest)) return basename(root)
715
+ try {
716
+ const name = (JSON.parse(readFileSync(manifest, "utf-8")) as { name?: string }).name
717
+ return name ?? basename(root)
718
+ } catch {
719
+ return basename(root)
720
+ }
721
+ }
722
+
723
+ /** Rewrites a path under the home dir back to its `~`-prefixed form, so settings.json stays portable across machines/usernames. Paths outside home pass through unchanged. */
724
+ function collapseHome(absolutePath: string): string {
725
+ const home = homedir()
726
+ return absolutePath === home || absolutePath.startsWith(home + "/")
727
+ ? "~" + absolutePath.slice(home.length)
728
+ : absolutePath
729
+ }