geneseed 4.30.1 → 4.32.0

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 (97) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/SHIPPED.md +1 -1
  3. package/adapters/opencode/plugins/geneseed-context.js +136 -1
  4. package/adapters/opencode/plugins/geneseed-guard.js +145 -2
  5. package/docs/concepts/exclusions.md +1 -1
  6. package/docs/concepts/footprint.md +1 -1
  7. package/docs/concepts/hook-gates.md +1 -1
  8. package/docs/concepts/hooks.md +6 -4
  9. package/docs/concepts/host-matrix.md +1 -1
  10. package/docs/concepts/loop-bricks.md +1 -1
  11. package/docs/concepts/loop-notes.md +4 -2
  12. package/docs/concepts/loop-templates.md +7 -4
  13. package/docs/concepts/loops.md +3 -0
  14. package/docs/concepts/ownership.md +1 -1
  15. package/docs/guides/run-a-loop.md +1 -1
  16. package/docs/guides/set-up-ownership.md +1 -1
  17. package/docs/reference/loop-actions.md +1 -1
  18. package/docs/reference/plugin-activity.md +1 -1
  19. package/docs/reference/plugin-context.md +4 -0
  20. package/docs/reference/plugin-guard.md +1 -1
  21. package/docs/understand/enforced-vs-asked.md +3 -2
  22. package/docs/understand/machine-bob.md +1 -1
  23. package/docs/web-ui.md +85 -26
  24. package/harness.config.json +1 -1
  25. package/js/README.md +3 -3
  26. package/js/hosts/hooks-context.mjs +22 -1
  27. package/js/hosts/hooks-done.mjs +97 -31
  28. package/js/hosts/hooks-prims.mjs +65 -0
  29. package/js/hosts/hooks.mjs +188 -27
  30. package/js/loop/state.mjs +15 -5
  31. package/js/web/actions.mjs +17 -27
  32. package/js/web/activity.mjs +139 -23
  33. package/js/web/api.mjs +31 -13
  34. package/js/web/catalog.mjs +108 -23
  35. package/js/web/handler.mjs +4 -3
  36. package/js/web/routes.mjs +47 -14
  37. package/js/web/server.mjs +14 -13
  38. package/js/web/state.mjs +36 -15
  39. package/js/web/usage-api.mjs +7 -3
  40. package/package.json +1 -1
  41. package/src/agents/_template.md +3 -0
  42. package/src/agents/developer.md +5 -2
  43. package/src/agents/tester.md +4 -1
  44. package/src/bricks/apply.md +3 -0
  45. package/src/bricks/test.md +6 -4
  46. package/src/loops/bugfix.json +11 -5
  47. package/src/loops/feature.json +7 -4
  48. package/src/skills/loop.md +1 -0
  49. package/src/skills/ship.md +9 -1
  50. package/web/dist/assets/Activity-Bjy64wHC.js +1 -0
  51. package/web/dist/assets/ActivityDetail-B0AaipP8.js +1 -0
  52. package/web/dist/assets/{Bonsai-CN4rRAHc.js → Bonsai-CJniRqaH.js} +1 -1
  53. package/web/dist/assets/{CopyButton-CYljsnLo.js → CopyButton-C5Li6awl.js} +1 -1
  54. package/web/dist/assets/Dashboard-B-6DTmae.js +2 -0
  55. package/web/dist/assets/{DataTable-BWbUx4bY.js → DataTable-b9zTShqJ.js} +1 -1
  56. package/web/dist/assets/{Docs-DE04qOKj.js → Docs-LRc30XL9.js} +2 -2
  57. package/web/dist/assets/{EmptyState-1sPNleqv.js → EmptyState-CY5Pm2xy.js} +1 -1
  58. package/web/dist/assets/FilterInput-qGKNSlxv.js +1 -0
  59. package/web/dist/assets/{GreenhouseView-DPwhFO_j.js → GreenhouseView-CcoYlaWo.js} +1 -1
  60. package/web/dist/assets/Installs-dp1epTcE.js +3 -0
  61. package/web/dist/assets/JournalView-nFP4poCf.js +1 -0
  62. package/web/dist/assets/{KitApply-BN2Az7dc.js → KitApply-DwyZUj57.js} +1 -1
  63. package/web/dist/assets/{Kits-C9qVd466.js → Kits-C0IEdZXe.js} +1 -1
  64. package/web/dist/assets/Laws-CkykmQWu.js +3 -0
  65. package/web/dist/assets/Library-Guh9HBZU.js +2 -0
  66. package/web/dist/assets/Loops-CzitjxGV.js +2 -0
  67. package/web/dist/assets/Markdown-C4S4tTA7.js +69 -0
  68. package/web/dist/assets/{OperatorHudView-CLN6Qn25.js → OperatorHudView-DLGNulIY.js} +1 -1
  69. package/web/dist/assets/Personal-BMtberL8.js +2 -0
  70. package/web/dist/assets/RailCats-D5weYPCS.js +1 -0
  71. package/web/dist/assets/Tabs-uYJqfuQt.js +1 -0
  72. package/web/dist/assets/api-BxjLd7Qd.js +1 -0
  73. package/web/dist/assets/index-DA7BiaE5.js +3 -0
  74. package/web/dist/assets/index-dbbDGFDq.css +1 -0
  75. package/web/dist/assets/{motion-CXaUMNkg.js → motion-Bccx3zE8.js} +1 -1
  76. package/web/dist/assets/react-C1iE8mnY.js +9 -0
  77. package/web/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  78. package/web/dist/assets/{usePoll-bDFN-Hr6.js → usePoll-o8ul-Sog.js} +1 -1
  79. package/web/dist/index.html +6 -6
  80. package/web/dist/assets/Activity-C8pQvnos.js +0 -1
  81. package/web/dist/assets/ActivityDetail-D_8Bx-QO.js +0 -1
  82. package/web/dist/assets/Dashboard-DkUm4XMu.js +0 -2
  83. package/web/dist/assets/FilterInput-CZREvrjX.js +0 -1
  84. package/web/dist/assets/Installs-DmPzD4BW.js +0 -3
  85. package/web/dist/assets/JournalView-DQlDC-7i.js +0 -1
  86. package/web/dist/assets/Laws-T2wbwMmB.js +0 -3
  87. package/web/dist/assets/Library-t3KocV0-.js +0 -2
  88. package/web/dist/assets/Loops-6lNY-9uR.js +0 -2
  89. package/web/dist/assets/Markdown-DpmmtW2Y.js +0 -65
  90. package/web/dist/assets/Personal-xjoSqCzr.js +0 -2
  91. package/web/dist/assets/RailCats-BuJD4Jou.js +0 -1
  92. package/web/dist/assets/Tabs-DaExAgql.js +0 -1
  93. package/web/dist/assets/api-LvBC0CnK.js +0 -1
  94. package/web/dist/assets/index-DhNNxhfg.js +0 -3
  95. package/web/dist/assets/index-XTGBLKQr.css +0 -1
  96. package/web/dist/assets/react-DlYQp10C.js +0 -9
  97. package/web/dist/assets/rolldown-runtime-hePW80VL.js +0 -1
@@ -17,6 +17,17 @@
17
17
  * returned, to the archive's own rule (the newest `ARCHIVE_KEEP`, none older than
18
18
  * `ARCHIVE_MAX_AGE_SECONDS`) — without touching a file.
19
19
  *
20
+ * ONE GARDEN OVER EVERY ACTIVE INSTALL. `apiActivity` is machine-wide, like `/api/usage`: it reads
21
+ * `<viewCfg(install)>/activity` of each active install (`activeInstalls`) and merges the cards.
22
+ * Each card, ended row and collision writer carries `install`, the same `host:scope:root` string
23
+ * `/api/usage` keys its rows by; the top-level `installs[]` maps it to `{host, scope, path,
24
+ * enabled}`, `path` being the root verbatim, so a client names the install back (`?host=&path=`)
25
+ * without parsing a key whose Windows root holds a `:`. One session two installs both recorded
26
+ * is one card (`mergeCopies`), which lists them in `installs`. Collisions and the loop join run ONCE over
27
+ * the merged live list, so a claude and an opencode session on one file are a collision. The
28
+ * on/off flag stays per install: the detail (`/api/activity/<sid>`) and the toggle read the
29
+ * install the request names, through `installView`.
30
+ *
20
31
  * `/api/activity` answers a GET through `apiActivity` and a POST through `apiActivityToggle`
21
32
  * at the bottom of this file. It is the one POST route whose result is sent at 200 whatever
22
33
  * `ok` says, which is why `POST_ROUTES` in `js/web/routes.mjs` carries a 409 COLUMN rather
@@ -43,9 +54,11 @@ import { readText, writeText, isDir, isFile } from '../lib/fs.mjs';
43
54
  import { parseJson, isTruthy } from '../lib/json.mjs';
44
55
  import { normcase } from '../lib/paths.mjs';
45
56
  import { stripWhitespace } from '../lib/text.mjs';
46
- import { ARCHIVE_KEEP, ARCHIVE_MAX_AGE_SECONDS, isLive, safeStem } from '../hosts/activity.mjs';
57
+ import { ARCHIVE_KEEP, ARCHIVE_MAX_AGE_SECONDS, isLive, safeStem, sweepActivity } from '../hosts/activity.mjs';
58
+ import { installState, installTargets } from '../hosts/installs.mjs';
47
59
  import { runningLoops } from '../loop/registry.mjs';
48
60
  import { NotFound, stemOf } from './catalog.mjs';
61
+ import { fleetSort, viewCfg } from './state.mjs';
49
62
 
50
63
  const nowSeconds = () => Date.now() / 1000;
51
64
 
@@ -59,6 +72,30 @@ const activityDir = (state) => path.join(state.target, 'activity');
59
72
  /** The runtime on/off flag — the same path the plugin resolves. */
60
73
  const activityFlag = (state) => path.join(state.target, '.geneseed-activity');
61
74
 
75
+ /**
76
+ * Each active install that records activity, as `{install, host, scope, path, dir}`; `install` is
77
+ * usage-api's key. An OpenCode PROJECT install is left out: the OpenCode plugin writes its cards and
78
+ * reads its `.geneseed-activity` flag in the GLOBAL OpenCode config dir whichever install loaded it,
79
+ * so a project row would hold an empty dir and a switch nobody reads. Its sessions appear under, and
80
+ * follow the switch of, the OpenCode global row. `installState` runs per install inside a catch: one
81
+ * broken install is skipped, never a blank garden. Rows come in the fixed order below.
82
+ */
83
+ function installRows(targets) {
84
+ const rows = [];
85
+ for (const [host, scope, root] of targets) {
86
+ if (host === 'opencode' && scope !== 'global') continue;
87
+ let active;
88
+ try { active = installState(root, host, scope) === 'active'; } catch { continue; }
89
+ if (active) {
90
+ rows.push({ install: `${host}:${scope}:${root}`, host, scope, path: String(root),
91
+ dir: viewCfg(host, scope, root) });
92
+ }
93
+ }
94
+ // The fleet's FIXED order (`fleetSort`). A merged card's primary install is the first of its
95
+ // installs in it.
96
+ return fleetSort(rows, (r) => [r.host, r.scope]);
97
+ }
98
+
62
99
  /**
63
100
  * On unless the flag file explicitly says off. An absent (or unreadable) file is the
64
101
  * default every user who has never toggled is in. An undecodable flag file is not treated
@@ -169,7 +206,8 @@ function loopsByRoot(sessions) {
169
206
  */
170
207
  function collisionsOf(sessions) {
171
208
  const byFile = new Map();
172
- const ordered = [...sessions].sort((a, b) => (String(a.session_id) < String(b.session_id) ? -1 : 1));
209
+ const idOf = (s) => s.key ?? `${s.install ?? ''}\0${s.session_id}`;
210
+ const ordered = [...sessions].sort((a, b) => (idOf(a) < idOf(b) ? -1 : 1));
173
211
  for (const s of ordered) {
174
212
  const repo = typeof s.repo === 'string' ? s.repo : s.root;
175
213
  if (typeof repo !== 'string') continue;
@@ -178,14 +216,17 @@ function collisionsOf(sessions) {
178
216
  const key = `${normcase(repo)}\0${normcase(f.path)}`;
179
217
  if (!byFile.has(key)) byFile.set(key, { repo, path: f.path, writers: new Map() });
180
218
  const by = f.by ?? null;
181
- byFile.get(key).writers.set(`${s.session_id}\0${by}`, { sid: s.session_id, by, root: s.root });
219
+ // Keyed by install too. Copies of one session in one checkout are already one card
220
+ // (`mergeCopies`); an id left in two installs is two checkouts, so two writers.
221
+ byFile.get(key).writers.set(`${idOf(s)}\0${by}`,
222
+ { sid: s.session_id, by, root: s.root, install: s.install ?? null, key: s.key ?? null });
182
223
  }
183
224
  }
184
225
  const out = [];
185
226
  for (const { repo, path: p, writers } of byFile.values()) {
186
227
  if (writers.size < 2) continue;
187
- const list = [...writers.values()].sort((a, b) => (
188
- `${a.sid}\0${a.by ?? ''}` < `${b.sid}\0${b.by ?? ''}` ? -1 : 1));
228
+ const wk = (w) => `${w.sid}\0${w.install ?? ''}\0${w.by ?? ''}`;
229
+ const list = [...writers.values()].sort((a, b) => (wk(a) < wk(b) ? -1 : 1));
189
230
  const roots = list.map((w) => (typeof w.root === 'string' ? normcase(w.root) : null));
190
231
  const shared = roots.some((r, i) => r !== null && roots.indexOf(r) !== i);
191
232
  out.push({ repo, path: p, writers: list, kind: shared ? 'same-worktree' : 'cross-worktree' });
@@ -228,28 +269,38 @@ function snapshots(d) {
228
269
  const newestFirst = (list) => list.sort((a, b) => Number(b.updated_at) - Number(a.updated_at));
229
270
 
230
271
  /**
231
- * `{activity, ended}`: the live sessions, and the ones that are not — still in the directory
232
- * or already archived — each listed once, the live copy and then the directory's winning.
272
+ * A session's identity across installs, and the card's `key`: its id plus its checkout, `root`
273
+ * (else `cwd`) case-folded where the platform folds and with any trailing separator dropped, so
274
+ * `C:\w\main\` is `C:\w\main`. It never names an install, so it holds still when the shown copy moves.
233
275
  */
234
- function activityEntries(state) {
235
- const d = activityDir(state);
236
- const now = nowSeconds();
276
+ const sessionKey = (e) => {
277
+ const w = typeof e.root === 'string' ? e.root : e.cwd;
278
+ return `${e.session_id}\0${typeof w === 'string' ? normcase(w).replace(/[\\/]+$/, '') : ''}`;
279
+ };
280
+
281
+ /**
282
+ * `{live, ended}` of ONE activity dir, each card tagged with `install`: the live sessions, and
283
+ * the ones that are not — still in the directory or already archived — each listed once, the
284
+ * live copy and then the directory's winning. Per install, so a live claude `s1` never hides an
285
+ * ended opencode `s1`. Neither loops nor collisions here: those join the merged list.
286
+ */
287
+ function dirEntries(d, install, now) {
237
288
  const live = [];
238
289
  const ended = [];
239
290
  const seen = new Set();
240
291
  const rest = [];
241
292
  for (const [name, entry] of snapshots(d)) {
242
- const e = normalizeEntry(entry, stemOf(name));
293
+ const n = normalizeEntry(entry, stemOf(name));
294
+ const e = /** @type {Record<string, any>} */ ({ ...n, install, installs: [install], key: sessionKey(n) });
243
295
  if (isLive(entry, now)) {
244
296
  e.files_all = allFiles(d, stemOf(name), e);
245
297
  live.push(e);
246
298
  seen.add(String(e.session_id));
247
299
  } else rest.push(e);
248
300
  }
249
- const loops = loopsByRoot(live);
250
- for (const e of live) e.loops = typeof e.root === 'string' ? loops.get(loopKey(e.root)) ?? [] : [];
251
301
  for (const [name, entry] of snapshots(path.join(d, 'archive'))) {
252
- rest.push(normalizeEntry(entry, stemOf(name)));
302
+ const n = normalizeEntry(entry, stemOf(name));
303
+ rest.push({ ...n, install, installs: [install], key: sessionKey(n) });
253
304
  }
254
305
  for (const e of rest) {
255
306
  if (seen.has(String(e.session_id))) continue;
@@ -257,21 +308,86 @@ function activityEntries(state) {
257
308
  if (now - Number(e.updated_at) > ARCHIVE_MAX_AGE_SECONDS) continue;
258
309
  ended.push({ ...e, ended: true });
259
310
  }
260
- return {
261
- activity: newestFirst(live),
262
- ended: newestFirst(ended).slice(0, ARCHIVE_KEEP),
263
- collisions: collisionsOf(live),
264
- };
311
+ return { live, ended };
265
312
  }
266
313
 
267
- export function apiActivity(state) {
268
- const enabled = activityEnabled(state);
314
+ /**
315
+ * One card per session. A global and a project install of one Claude-shaped host both run
316
+ * `geneseed-hook activity --root <own install>` for the same session, so the same session lands in
317
+ * two dirs. Copies with an equal `key` (`sessionKey`: id and checkout) are ONE card. Its DATA is
318
+ * the newest `updated_at`'s copy; its `installs` are every install that saw it and its `install`
319
+ * (the chip, and the install the detail link reads) the first of them, both in the fixed order of
320
+ * `rank` (`installRows`'s order) — never by recency, since two installs write one session within
321
+ * milliseconds and the newest copy can change between two polls. A live copy also absorbs an ended
322
+ * copy elsewhere, but a live card's `install` is the first install holding a LIVE copy: a stale
323
+ * ended copy would send the detail link to a session shown as ended. Without this the session
324
+ * would collide with itself.
325
+ */
326
+ function mergeCopies(live, ended, rank) {
327
+ const by = new Map();
328
+ const keep = (list) => newestFirst(list).filter((e) => {
329
+ const had = by.get(e.key);
330
+ if (!had) { by.set(e.key, e); return true; }
331
+ if (!had.installs.includes(e.install)) had.installs.push(e.install);
332
+ return false;
333
+ });
334
+ const byRank = (x, y) => rank.get(x) - rank.get(y);
335
+ const out = { live: keep(live) };
336
+ const liveIn = new Map(out.live.map((e) => [e.key, [...e.installs]]));
337
+ out.ended = keep(ended);
338
+ for (const e of by.values()) {
339
+ e.installs.sort(byRank);
340
+ e.install = (liveIn.get(e.key)?.sort(byRank) ?? e.installs)[0];
341
+ }
342
+ return out;
343
+ }
344
+ /**
345
+ * GET /api/activity, machine-wide: `{enabled, installs[], activity, ended, collisions}` over every
346
+ * active install in `targets`. An install whose flag is off contributes no card. `enabled` is
347
+ * true when ANY install tracks (or none is active), so the Overview's "tracking is off" notice
348
+ * fires only once every install is off. `ended` is capped after the merge, to one archive's rule.
349
+ */
350
+ export function activitySummary({ targets = installTargets() } = {}) {
351
+ const now = nowSeconds();
352
+ const installs = [];
353
+ const live = [];
354
+ const ended = [];
355
+ for (const { dir, ...row } of installRows(targets)) {
356
+ const enabled = activityEnabled({ target: dir });
357
+ installs.push({ ...row, enabled });
358
+ if (!enabled) continue;
359
+ const got = dirEntries(path.join(dir, 'activity'), row.install, now);
360
+ live.push(...got.live);
361
+ ended.push(...got.ended);
362
+ }
363
+ const one = mergeCopies(live, ended, new Map(installs.map((i, n) => [i.install, n])));
364
+ const loops = loopsByRoot(one.live);
365
+ for (const e of one.live) e.loops = typeof e.root === 'string' ? loops.get(loopKey(e.root)) ?? [] : [];
269
366
  return {
270
- enabled,
271
- ...(enabled ? activityEntries(state) : { activity: [], ended: [], collisions: [] }),
367
+ enabled: installs.length === 0 || installs.some((i) => i.enabled),
368
+ installs,
369
+ activity: one.live,
370
+ ended: one.ended.slice(0, ARCHIVE_KEEP),
371
+ collisions: collisionsOf(one.live),
272
372
  };
273
373
  }
274
374
 
375
+ export const apiActivity = () => activitySummary();
376
+
377
+ /**
378
+ * Archive the ended sessions of every active install (`sweepActivity`), each on its own: one
379
+ * unreadable dir never skips the rest. The daemon runs it at start and every 10 minutes, and
380
+ * re-reads the installs each time, so an install added since is swept too. Only ACTIVE installs are
381
+ * swept (installRows): a disabled or absent install's `activity/` is left as it is.
382
+ */
383
+ export function sweepInstalls({ targets = installTargets() } = {}) {
384
+ let rows;
385
+ try { rows = installRows(targets); } catch { return; }
386
+ for (const { dir } of rows) {
387
+ try { sweepActivity(path.join(dir, 'activity')); } catch { /* best-effort */ }
388
+ }
389
+ }
390
+
275
391
  /**
276
392
  * One session's snapshot plus its step timeline and its UNCAPPED files/todos. A session that is
277
393
  * no longer live — still in the directory, or archived — is returned too, with `ended: true`.
package/js/web/api.mjs CHANGED
@@ -18,7 +18,7 @@ import { alwaysOnCost } from '../inspect/cost.mjs';
18
18
  import { installProfile } from '../build/generate.mjs';
19
19
  import { diffCollect, renderMemo } from '../inspect/diff.mjs';
20
20
  import { excludesSnapshot } from '../inspect/excludes.mjs';
21
- import { VERSION_MARKER, resolvePath } from '../hosts/hosts.mjs';
21
+ import { VERSION_MARKER } from '../hosts/hosts.mjs';
22
22
  import { autostartPaths } from '../hosts/shim.mjs';
23
23
  import {
24
24
  footprintOfDir, gatesOfDir, installState, installTargets, legacyProcessCarrierOfDir, modeOfDir,
@@ -31,11 +31,11 @@ import { activeLoops } from '../loop/registry.mjs';
31
31
  import { EMIT_OPTIONS, themeOptions } from '../maintain/setup.mjs';
32
32
  import { accentFor, keptKitFiles, statusData } from '../inspect/status.mjs';
33
33
  import { isFile } from '../lib/fs.mjs';
34
- import { comparePaths, normcase } from '../lib/paths.mjs';
34
+ import { comparePaths } from '../lib/paths.mjs';
35
35
  import {
36
36
  configItems, deployed, dget, memoryItems, notebookItems, wikiItems,
37
37
  } from './catalog.mjs';
38
- import { stampMinute, viewCfg } from './state.mjs';
38
+ import { defaultView, samePath, stampMinute, viewCfg } from './state.mjs';
39
39
  import { MANUAL_UPDATE, gitBehind, installKind, updateStatus } from './update-check.mjs';
40
40
 
41
41
  /**
@@ -44,9 +44,6 @@ import { MANUAL_UPDATE, gitBehind, installKind, updateStatus } from './update-ch
44
44
  */
45
45
  export { NotFound, deployed, resolveLinks } from './catalog.mjs';
46
46
 
47
- /** Two resolved paths, compared case-folded on Windows. */
48
- const samePath = (a, b) => normcase(resolvePath(a)) === normcase(resolvePath(b));
49
-
50
47
  // ---- the eight endpoints -------------------------------------------------------------
51
48
 
52
49
  /** `buildOverride` in `actions.mjs` is a third reader of this. */
@@ -156,6 +153,19 @@ const driftCounts = (files) => ({
156
153
  stale: files.filter((f) => f.status === 'stale').length,
157
154
  });
158
155
 
156
+ /**
157
+ * How many memory facts an install's data dir holds: the `.md` files of `<dir>/memory` (where
158
+ * `memoryItems` reads them), minus its index and README (the console's furniture), any case.
159
+ * No folder is no facts (0); a folder that cannot be listed is null, so a row says "not read"
160
+ * rather than "no facts".
161
+ */
162
+ export function memoryFactCount(dir) {
163
+ try {
164
+ return readdirSync(path.join(dir, 'memory'))
165
+ .filter((f) => /\.md$/i.test(f) && !/^(memory|readme)\.md$/i.test(f)).length;
166
+ } catch (e) { return e?.code === 'ENOENT' ? 0 : null; }
167
+ }
168
+
159
169
  /**
160
170
  * The fields every install row opens with, in this order. Theme is narrowed to this row's own
161
171
  * host (host-compat B1): a shared repo otherwise answers every row with whichever host's
@@ -176,13 +186,19 @@ const installRowBase = (host, scope, root, state) => ({
176
186
  */
177
187
  export function apiInstalls(state) {
178
188
  const out = [];
179
- for (const [host, scope, root] of installTargets()) {
189
+ const targets = installTargets();
190
+ const def = defaultView(targets);
191
+ // The row marked `default` must be the install an unnamed request reads, so the daemon state
192
+ // follows the marker here, where the console reads it, rather than only on a full refresh.
193
+ if (def && state?.selectView && !state.pinned && !samePath(def[0], state.target)) state.selectView(...def);
194
+ for (const [host, scope, root] of targets) {
180
195
  out.push({
181
196
  ...installRowBase(host, scope, root, installState(root, host, scope)),
182
197
  posture: postureOfDir(root, host),
183
198
  mode: modeOfDir(root, host),
184
199
  trust: trustOfDir(root, host),
185
- selected: samePath(viewCfg(host, scope, root), state.target),
200
+ // The install a request naming none reads (`defaultView`): the console's pickers start on it.
201
+ default: !!def && samePath(viewCfg(host, scope, root), def[0]),
186
202
  });
187
203
  }
188
204
  return { installs: out, postures: discoverNames('postures', 'peer'),
@@ -232,9 +248,11 @@ export function apiFleet(state) {
232
248
  diffable: drift !== null,
233
249
  drift,
234
250
  built_epoch: built,
235
- // The install the console is viewing (the topbar picker), as `/api/installs` marks it: the
236
- // Overview's root-file card follows it rather than the fleet's worst.
237
- selected: samePath(dir, state.target),
251
+ // Each install's own settings, on its row: the Overview has no viewed install to read them off.
252
+ posture: postureOfDir(root, host),
253
+ mode: modeOfDir(root, host),
254
+ // Its memory facts: one directory listing (`memoryFactCount`), no file read.
255
+ facts: memoryFactCount(dir),
238
256
  // What this install injects every session, by part (characters); null when its carrier
239
257
  // is missing, so the console says "not measured" rather than drawing an empty bar.
240
258
  cost: alwaysOnCost({ host, root, dir, footprint: footprintOfDir(root) }),
@@ -355,8 +373,8 @@ export function apiOverview(state) {
355
373
  for (const [host, scope, root] of installTargets()) {
356
374
  try {
357
375
  if (samePath(viewCfg(host, scope, root), state.target)) {
358
- // `deletionGate`/`secretsGate`/`doneGate`: the gate switches, for the Constitution
359
- // page's toggles on rows IV, I and III.
376
+ // `deletionGate`/`secretsGate`/`doneGate`/`ownershipGate`: the gate switches, for the
377
+ // Constitution page's toggles on rows IV, I, III and inside the Credo's Ownership row.
360
378
  install = { host, scope, path: root, footprint: footprintOfDir(root),
361
379
  ...gatesOfDir(root, host) };
362
380
  break;
@@ -2,7 +2,9 @@
2
2
  * The Library's READ MODEL — what the console lists and opens: the agent/skill inventory (read
3
3
  * off the deployed install, else rendered from source), the constitution's three tiers, and the
4
4
  * hand-written stores beside the install (memory, notebook, wiki, the two setup manifests).
5
- * `apiCatalog` and `apiItem` are its two endpoints; `routes.mjs` binds them to paths.
5
+ * `apiCatalog` and `apiItem` are its two endpoints; `routes.mjs` binds them to paths. Skills and
6
+ * agents are read across every active install (`FLEET_SECTIONS`, the fleet `routes.mjs` builds);
7
+ * the other sections, one install's.
6
8
  *
7
9
  * `NotFound` lives here because this is where it is raised most, and because `state.mjs` imports
8
10
  * this file (for the inventory it caches) and nothing here imports `state.mjs` back.
@@ -36,10 +38,25 @@ export class BadRequest extends Error {}
36
38
  /** `??` would also swallow an explicit `null` the file declared; this does not. */
37
39
  export const dget = (obj, key, dflt) => (Object.hasOwn(obj, key) ? obj[key] : dflt);
38
40
 
39
- export function deployed(state) {
40
- return existsSync(path.join(state.target, GLOBAL_MANIFEST));
41
+ /**
42
+ * The dir holding the viewed install's manifest — its host layer — or null when none is deployed.
43
+ *
44
+ * `state.target` itself for a global install and a Claude-style project one (whose target IS
45
+ * `<repo>/.claude|.bob|.openclaude`). An OpenCode PROJECT install is viewed at the repo root,
46
+ * where its memory, rules and markers live, but writes its manifest and the layer the host loads
47
+ * (`skills/<name>/SKILL.md`, `agents/`) under `<repo>/.opencode/`; the root `skills/` is the
48
+ * plain bundle's flat `<name>.md`. Checking the target alone read every such install as "not
49
+ * deployed" and listed the source render instead of what it has.
50
+ */
51
+ export function deployedLayer(state) {
52
+ for (const dir of [state.target, path.join(state.target, '.opencode')]) {
53
+ if (existsSync(path.join(dir, GLOBAL_MANIFEST))) return dir;
54
+ }
55
+ return null;
41
56
  }
42
57
 
58
+ export const deployed = (state) => deployedLayer(state) !== null;
59
+
43
60
  /**
44
61
  * A deployed spec's one-line purpose.
45
62
  *
@@ -94,7 +111,8 @@ function specEntries(root, nested) {
94
111
  }
95
112
 
96
113
  /**
97
- * The agents and skills actually installed at `state.target`, not a fresh render of `src/`.
114
+ * The agents and skills actually installed in the install's host layer (`deployedLayer`), not
115
+ * a fresh render of `src/`.
98
116
  *
99
117
  * All three constitutional tiers still come from the render: once deployed they live inside
100
118
  * AGENT.md rather than as separate files, so the deployed arm replaces the two ENTITY rosters
@@ -114,13 +132,14 @@ function deployedInventory(state) {
114
132
  const render = tuiInventory(state.theme, doctrinesForBuild(state.target),
115
133
  excludedRulesOfDir(state.target));
116
134
  const registry = loadRegistry();
117
- const skills = specEntries(path.join(state.target, 'skills'), true);
135
+ const layer = deployedLayer(state);
136
+ const skills = specEntries(path.join(layer, 'skills'), true);
118
137
  for (const e of skills) {
119
138
  e.status = entityStatus(registry, `skills/${e.name}`);
120
139
  e.klass = e.status === 'personal' ? 'personal'
121
140
  : (Object.hasOwn(SKILL_CLASS, e.name) ? SKILL_CLASS[e.name] : 'build');
122
141
  }
123
- const agents = specEntries(path.join(state.target, 'agents'), false);
142
+ const agents = specEntries(path.join(layer, 'agents'), false);
124
143
  for (const e of agents) e.status = entityStatus(registry, `agents/${e.name}`);
125
144
  return { agents,
126
145
  skills,
@@ -509,23 +528,71 @@ function tierNouns(theme) {
509
528
  return { ontology: t.ONTOLOGY, law: t.LAW, laws: t.LAWS, doctrines: t.DOCTRINES };
510
529
  }
511
530
 
512
- export function apiCatalog(state, section) {
531
+ /**
532
+ * The sections listed across every install (`fleet`), not off one: skills, agents, and the
533
+ * personal memory and notebook (each entry tagged with the installs that hold it, so a forget or
534
+ * a promote names its own). The other sections are one install's own wiki manifest, config or
535
+ * constitution.
536
+ */
537
+ export const FLEET_SECTIONS = ['agents', 'skills', 'memory', 'notebook'];
538
+
539
+ /**
540
+ * A per-install item list (`read(state)`) over `fleet`, one row per name with the `installs` that
541
+ * hold it, in fleet order; the row's own fields are the FIRST holder's (`apiItem` serves the
542
+ * others). A name a later install adds lands after the first install's rows.
543
+ */
544
+ function fleetItems(fleet, read) {
545
+ const rows = new Map();
546
+ for (const { install, state } of fleet) {
547
+ for (const it of read(state)) {
548
+ let r = rows.get(it.name);
549
+ if (r === undefined) rows.set(it.name, r = { ...it, installs: [] });
550
+ if (install !== null) r.installs.push(install);
551
+ }
552
+ }
553
+ return [...rows.values()];
554
+ }
555
+
556
+ /**
557
+ * One row per name over `fleet` — `[{install, state}]`, `install` the usage ledger's
558
+ * `host:scope:root` key (`usage-api.mjs`), or `null` for a lone state that is no detected
559
+ * install — with the keys of the installs that have it, in fleet order. A name only some
560
+ * installs have lists only those, so an exclusion stays visible. The row's own fields
561
+ * (description, source) are the FIRST install's: each install renders in its own theme, and
562
+ * `apiItem` serves the other copies.
563
+ */
564
+ function fleetEntries(fleet, section) {
565
+ const rows = new Map();
566
+ for (const { install, state } of fleet) {
567
+ for (const e of state.inventory[section]) {
568
+ let r = rows.get(e.name);
569
+ if (r === undefined) rows.set(e.name, r = { e, installs: [] });
570
+ if (install !== null) r.installs.push(install);
571
+ }
572
+ }
573
+ return [...rows.values()].sort((a, b) => (a.e.name < b.e.name ? -1 : a.e.name > b.e.name ? 1 : 0));
574
+ }
575
+
576
+ /**
577
+ * `fleet` defaults to `state` alone, which answers as one install did before the console
578
+ * listed the fleet; the `/api/catalog/` route passes every active install for `FLEET_SECTIONS`.
579
+ */
580
+ export function apiCatalog(state, section, fleet = [{ install: null, state }]) {
513
581
  if (!SECTIONS.includes(section)) throw new NotFound(section);
514
- const inv = state.inventory;
515
582
  let items;
516
583
  const owner = kitOwners();
517
584
  if (section === 'agents') {
518
- items = inv.agents.map((e) => ({ name: e.name, title: e.name, desc: e.desc,
519
- source: e.source ?? null, status: e.status ?? 'unknown', kit: owner.get(`agent:${e.name}`) ?? null }));
585
+ items = fleetEntries(fleet, 'agents').map(({ e, installs }) => ({ name: e.name, title: e.name, desc: e.desc,
586
+ source: e.source ?? null, status: e.status ?? 'unknown', kit: owner.get(`agent:${e.name}`) ?? null, installs }));
520
587
  } else if (section === 'skills') {
521
- items = inv.skills.map((e) => ({ name: e.name, title: e.name, desc: e.desc,
522
- source: e.source ?? null, klass: e.klass ?? 'build', status: e.status ?? 'unknown', kit: owner.get(`skill:${e.name}`) ?? null }));
588
+ items = fleetEntries(fleet, 'skills').map(({ e, installs }) => ({ name: e.name, title: e.name, desc: e.desc,
589
+ source: e.source ?? null, klass: e.klass ?? 'build', status: e.status ?? 'unknown', kit: owner.get(`skill:${e.name}`) ?? null, installs }));
523
590
  } else if (section === 'laws') {
524
- return { section, items: constitutionItems(inv), nouns: tierNouns(state.theme) };
591
+ return { section, items: constitutionItems(state.inventory), nouns: tierNouns(state.theme) };
525
592
  } else if (section === 'memory') {
526
- items = memoryItems(state);
593
+ items = fleetItems(fleet, memoryItems);
527
594
  } else if (section === 'notebook') {
528
- items = notebookItems(state);
595
+ items = fleetItems(fleet, notebookItems);
529
596
  } else if (section === 'wiki') {
530
597
  items = wikiItems(state);
531
598
  } else {
@@ -534,18 +601,32 @@ export function apiCatalog(state, section) {
534
601
  return { section, items };
535
602
  }
536
603
 
537
- export function apiItem(state, type, name) {
538
- const inv = state.inventory;
604
+ /**
605
+ * One entry. A skill or agent is served from ONE install's copy, since each install renders in
606
+ * its own theme and footprint: the install the request named (`state` is then its view, found
607
+ * in `fleet` by identity, and an id that install lacks is a 404 even when another has it), else
608
+ * the first install in `fleet` order that has the id. `install` says whose copy this is and
609
+ * `installs` every install that has the id, so the reader can offer the others. `fleet` defaults
610
+ * to `state` alone, which answers as one install did before.
611
+ */
612
+ export function apiItem(state, type, name, fleet = [{ install: null, state }]) {
539
613
  if (type === 'agent' || type === 'skill') {
540
- const e = (type === 'agent' ? inv.agents : inv.skills).find((x) => x.name === name);
614
+ const sec = type === 'agent' ? 'agents' : 'skills';
615
+ const has = fleet.filter((v) => v.state.inventory[sec].some((x) => x.name === name));
616
+ // A named install that is not active is not in the fleet: it answers for itself.
617
+ const from = fleet.find((v) => v.state === state) ?? (state.pinned ? { install: null, state } : has[0]);
618
+ const e = from?.state.inventory[sec].find((x) => x.name === name);
541
619
  if (!e) throw new NotFound(name);
542
620
  const out = { type, name, title: name, desc: e.desc, body: e.body,
543
- links: resolveLinks(state, e.body), source: e.source ?? null };
621
+ links: resolveLinks(from.state, e.body), source: e.source ?? null };
544
622
  if (type === 'skill') out.klass = e.klass ?? 'build';
545
623
  out.status = e.status ?? 'unknown';
546
624
  out.kit = kitOwners().get(`${type}:${name}`) ?? null;
625
+ out.install = from.install;
626
+ out.installs = has.map((v) => v.install).filter((k) => k !== null);
547
627
  return out;
548
628
  }
629
+ const inv = state.inventory;
549
630
  if (type === 'law') {
550
631
  // ONE ARM FOR THREE TIERS, resolved off the same list the catalogue publishes — so a name
551
632
  // that appears in `/api/catalog/laws` always opens, and one that does not always 404s.
@@ -565,12 +646,16 @@ export function apiItem(state, type, name) {
565
646
  }
566
647
  if (type === 'memory' || type === 'notebook') {
567
648
  flatName(name);
568
- const d = type === 'notebook' ? notebookDir(state) : memoryDir(state);
569
- const p = path.join(d, `${name}.md`);
570
- if (!isFile(p)) throw new NotFound(name);
649
+ const fileOf = (st) => path.join(type === 'notebook' ? notebookDir(st) : memoryDir(st), `${name}.md`);
650
+ // As a skill: the named install's copy, else the first holder in fleet order.
651
+ const has = fleet.filter((v) => isFile(fileOf(v.state)));
652
+ const from = fleet.find((v) => v.state === state) ?? (state.pinned ? { install: null, state } : has[0]);
653
+ const p = from ? fileOf(from.state) : null;
654
+ if (!p || !isFile(p)) throw new NotFound(name);
571
655
  const body = readMaybe(p) ?? '';
572
656
  return { type, name, title: name, desc: '', body,
573
- links: resolveLinks(state, body), source: resolvePath(p) };
657
+ links: resolveLinks(from.state, body), source: resolvePath(p),
658
+ install: from.install, installs: has.map((v) => v.install).filter((k) => k !== null) };
574
659
  }
575
660
  if (type === 'wiki') return apiWikiItem(state, name);
576
661
  if (type === 'config') {
@@ -201,7 +201,8 @@ export function makeHandler(state, jm, token, dist, holder = null) {
201
201
  }
202
202
 
203
203
  function doGet(req, res, path, ae) {
204
- // The install the request names (`?host=&path=`), else the daemon's view; an unknown pair
204
+ // The install the request names (`?host=&path=`), else the daemon's state (the default
205
+ // install, `defaultView`); an unknown pair
205
206
  // throws `NotFound` here, before any route reads a dir. Not for ping, jobs, static files or
206
207
  // the machine-wide reads (`MACHINE_GETS`), which ignore the pair.
207
208
  const st = (path.startsWith('/api/') && path !== '/api/ping' && !path.startsWith('/api/jobs')
@@ -214,7 +215,7 @@ export function makeHandler(state, jm, token, dist, holder = null) {
214
215
  return sendJson(res, { ok: true, theme: state.theme, pid: process.pid }, 200, ae);
215
216
  }
216
217
  for (const [prefix, handler] of PREFIX_ROUTES) {
217
- if (path.startsWith(prefix)) return sendJson(res, handler(st, path), 200, ae);
218
+ if (path.startsWith(prefix)) return sendJson(res, handler(st, path, state), 200, ae);
218
219
  }
219
220
  if (path === '/api/docs') {
220
221
  return sendJson(res, apiDocs(st, harnessParam(req.url)), 200, ae);
@@ -468,7 +469,7 @@ export function makeHandler(state, jm, token, dist, holder = null) {
468
469
  try {
469
470
  return doPost(req, res, path, ae, buf);
470
471
  } catch (e) {
471
- // `apiSelectView`, `apiMemoryDelete`, `apiRulesMutate` and `apiRulesPromote` all
472
+ // `installView`, `apiMemoryDelete`, `apiRulesMutate` and `apiRulesPromote` all
472
473
  // raise `NotFound` for an unknown target, mapped to 404
473
474
  // here; anything else falls to the generic 500 (`SERVER_FAULT`, below).
474
475
  if (e instanceof NotFound) {