@awebai/oats 0.66.0 → 0.68.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 (81) hide show
  1. package/bin/oats.mjs +166 -17
  2. package/docs/capabilities.md +58 -9
  3. package/docs/capability-manifest.schema.json +5 -1
  4. package/docs/design/2026-10-22-module-upgrade.md +192 -0
  5. package/docs/design/README.md +4 -0
  6. package/docs/desktop-cli-api.md +463 -13
  7. package/docs/desktop.md +363 -67
  8. package/docs/first-team.md +5 -3
  9. package/docs/implementation.md +46 -6
  10. package/docs/integrations.md +16 -4
  11. package/docs/knowledge.md +44 -27
  12. package/docs/layers.md +2 -2
  13. package/docs/official-catalog.md +5 -5
  14. package/docs/packages.md +14 -14
  15. package/docs/release-lane.md +16 -0
  16. package/docs/release-notes/v0.67.0.md +366 -0
  17. package/docs/release-notes/v0.67.1.md +64 -0
  18. package/docs/release-notes/v0.68.0.md +504 -0
  19. package/docs/servers.md +8 -2
  20. package/docs/souls-and-instances.md +58 -6
  21. package/docs/tui.md +1033 -237
  22. package/docs/upgrading.md +164 -26
  23. package/docs/workspaces.md +2 -2
  24. package/lib/capability-contract.mjs +8 -7
  25. package/lib/core.mjs +331 -75
  26. package/lib/instance-color.mjs +58 -0
  27. package/lib/instance-events.mjs +1 -1
  28. package/lib/instance-inspect.mjs +107 -23
  29. package/lib/instance-lifecycle.mjs +21 -1
  30. package/lib/instance-naming.mjs +187 -0
  31. package/lib/instance-resolution.mjs +10 -6
  32. package/lib/instance-upgrade.mjs +1445 -0
  33. package/lib/materialize.mjs +287 -89
  34. package/lib/servers.mjs +24 -11
  35. package/lib/soul-composition.mjs +7 -3
  36. package/lib/upgrade-state.mjs +101 -0
  37. package/lib/workspace.mjs +4 -1
  38. package/lib/worktree.mjs +103 -12
  39. package/package-catalog.json +5 -4
  40. package/package.json +1 -1
  41. package/packages/client/cli-adapter.mjs +52 -6
  42. package/packages/client/cli-locator.mjs +2 -2
  43. package/packages/client/composed-gate.mjs +10 -2
  44. package/packages/client/deployment-data.mjs +5 -0
  45. package/packages/client/deployment-identity.mjs +40 -0
  46. package/packages/client/deployment-panel.mjs +9 -3
  47. package/packages/client/inspect-boundary.mjs +11 -7
  48. package/packages/client/inspect-cache.mjs +2 -2
  49. package/packages/client/instance-name.mjs +28 -0
  50. package/packages/client/instance-presentation.mjs +11 -0
  51. package/packages/client/keymap.mjs +133 -28
  52. package/packages/client/keys-file.mjs +126 -0
  53. package/packages/client/own-codes.mjs +4 -2
  54. package/packages/client/panel-views.mjs +78 -12
  55. package/packages/client/spawn-naming.mjs +32 -0
  56. package/packages/client/spawn-preview-cli.mjs +58 -7
  57. package/packages/client/spawn-preview-contract.mjs +59 -0
  58. package/packages/client/spawn-preview-facts.mjs +8 -4
  59. package/packages/client/spawn-preview.mjs +81 -3
  60. package/packages/client/team-members.mjs +4 -1
  61. package/packages/client/workspace-step.mjs +25 -0
  62. package/packages/tui/README.md +7 -7
  63. package/packages/tui/lib/actions.mjs +92 -25
  64. package/packages/tui/lib/client.mjs +9 -4
  65. package/packages/tui/lib/config.mjs +50 -9
  66. package/packages/tui/lib/main.mjs +65 -24
  67. package/packages/tui/lib/model.mjs +292 -75
  68. package/packages/tui/lib/read.mjs +53 -1
  69. package/packages/tui/lib/store.mjs +469 -100
  70. package/packages/tui/lib/term/keys.mjs +22 -6
  71. package/packages/tui/lib/term/kitty.mjs +54 -11
  72. package/packages/tui/lib/term/screen.mjs +15 -6
  73. package/packages/tui/lib/term/through.mjs +66 -28
  74. package/packages/tui/lib/views/frame.mjs +223 -165
  75. package/packages/tui/lib/views/help.mjs +134 -29
  76. package/packages/tui/lib/views/instances.mjs +63 -22
  77. package/packages/tui/lib/views/palette.mjs +14 -4
  78. package/packages/tui/lib/views/souls.mjs +2 -2
  79. package/packages/tui/lib/views/switcher.mjs +6 -1
  80. package/packages/tui/lib/views/workspaces.mjs +55 -0
  81. package/skills/oats-getting-started/SKILL.md +96 -42
@@ -23,7 +23,10 @@
23
23
  * rollback journal: should any step fail, everything already placed is undone and the
24
24
  * previous AGENTS.md / instance.json restored before a named error (E_MATERIALIZE_HOME)
25
25
  * propagates. A second materialization racing on the same home surfaces as
26
- * E_MATERIALIZE_HOME { why: "busy" }, never a raw ENOTEMPTY.
26
+ * E_MATERIALIZE_HOME { why: "busy" }, never a raw ENOTEMPTY. stageMaterialize exposes
27
+ * that same composer before commit, including complete-root replacement for stopped
28
+ * homes. Its durable rename journal can finish forward after provider adoption; ordinary
29
+ * materialize calls continue to roll back a failed commit and discard staging.
27
30
  *
28
31
  * SOURCES. A module is fetched from its repository at `from.commit` at the capability
29
32
  * directory the RESOLVER recorded (`module.dir`: the manifest-listed directory — for a
@@ -186,15 +189,20 @@ function moduleSource(module, { lock, catalog, remote }) {
186
189
  /* ───────────────────────────── copying ─────────────────────────────── */
187
190
 
188
191
  /** Full copy of a fetched tree: regular files and directories only, exec bit preserved as 0o755 / 0o644. */
189
- function copyTree(src, dest, shownRoot) {
192
+ function copyTree(src, dest, shownRoot, allowAliases = false, root = src) {
190
193
  const st = lstatSync(src);
191
194
  if (st.isSymbolicLink()) throw fail("E_REMOTE_TREE_UNSAFE", `${shownRoot} is a symlink`, { path: shownRoot, why: "symlink" });
192
195
  if (!st.isDirectory()) throw fail("E_MATERIALIZE_RESOLUTION", `${shownRoot} is not a directory`, { path: shownRoot });
193
196
  mkdirSync(dest, { recursive: true, mode: 0o755 });
194
197
  for (const name of readdirSync(src).sort()) {
195
198
  const from = join(src, name), to = join(dest, name), shown = `${shownRoot}/${name}`, s = lstatSync(from);
196
- if (s.isSymbolicLink()) throw fail("E_REMOTE_TREE_UNSAFE", `${shown} is a symlink`, { path: shown, why: "symlink" });
197
- if (s.isDirectory()) { copyTree(from, to, shown); continue; }
199
+ if (s.isSymbolicLink()) {
200
+ if (allowAliases && defaultRemote.OATS_ALIAS_SYMLINK(relative(root, from).split(sep).join("/")) && readlinkSync(from) === "AGENTS.md") {
201
+ symlinkSync("AGENTS.md", to); continue;
202
+ }
203
+ throw fail("E_REMOTE_TREE_UNSAFE", `${shown} is a symlink`, { path: shown, why: "symlink" });
204
+ }
205
+ if (s.isDirectory()) { copyTree(from, to, shown, allowAliases, root); continue; }
198
206
  if (!s.isFile()) throw fail("E_REMOTE_TREE_UNSAFE", `${shown} is not a regular file`, { path: shown, why: "device" });
199
207
  copyFileSync(from, to);
200
208
  chmodSync(to, (s.mode & 0o111) ? 0o755 : 0o644);
@@ -209,6 +217,40 @@ function hasSkillDoc(dir) {
209
217
  * Precedence: resolution.skills rows for the module; else manifest.skills; else every
210
218
  * skills/<dir>/SKILL.md in the fetched tree. */
211
219
  export function moduleSkills(resolution, module, moduleDir) {
220
+ return skillRowsOf(resolution, module, fsTree(moduleDir), { verify: true });
221
+ }
222
+
223
+ /** The fetched module tree as skillRowsOf reads it: paths relative to the module root, POSIX. */
224
+ function fsTree(moduleDir) {
225
+ const abs = (rel) => join(moduleDir, ...rel.split("/"));
226
+ return {
227
+ isSkill: (rel) => hasSkillDoc(abs(rel)),
228
+ isDir: (rel) => existsSync(abs(rel)) && lstatSync(abs(rel)).isDirectory(),
229
+ children: (rel) => readdirSync(abs(rel)).sort(),
230
+ };
231
+ }
232
+
233
+ /** A remote listing of the module's `skills/` (listRemoteTree, depth 2, relative to it) as skillRowsOf reads
234
+ * a tree: only the fallback branch reads one (a module whose manifest declares no `skills`). A listed
235
+ * symlink is not a SKILL.md. */
236
+ function listedSkillsTree(entries) {
237
+ const blobs = new Set(), trees = new Set();
238
+ for (const e of entries) {
239
+ if (e.type === "blob") blobs.add(`skills/${e.path}`);
240
+ else if (e.type === "tree") trees.add(`skills/${e.path}`);
241
+ }
242
+ return {
243
+ isSkill: (rel) => blobs.has(`${rel}/SKILL.md`),
244
+ // listRemoteTree answers [] for a missing `skills/`, one that is not a directory and an empty one alike.
245
+ isDir: (rel) => (rel === "skills" ? entries.length > 0 : trees.has(rel)),
246
+ children: (rel) => [...trees].filter((t) => t.startsWith(`${rel}/`) && !t.slice(rel.length + 1).includes("/")).map((t) => t.slice(rel.length + 1)).sort(),
247
+ };
248
+ }
249
+
250
+ /** moduleSkills' precedence over `tree` ({ isSkill, isDir, children }, module-relative). `verify` checks
251
+ * each row has a readable SKILL.md (a fetched tree); the preview's rows from the resolution were checked
252
+ * over the remote by the resolver, and its fallback rows are SKILL.md holders by construction. */
253
+ function skillRowsOf(resolution, module, tree, { verify }) {
212
254
  const declared = (resolution.skills || []).filter((s) => s && s.module === module.name);
213
255
  const rows = [];
214
256
  if (declared.length) {
@@ -220,29 +262,46 @@ export function moduleSkills(resolution, module, moduleDir) {
220
262
  } else if (Array.isArray(module.manifest?.skills)) {
221
263
  for (const entry of module.manifest.skills) {
222
264
  const rel = modulePath(entry, module.name, "skill");
223
- const abs = join(moduleDir, ...rel.split("/"));
224
- if (hasSkillDoc(abs)) { rows.push({ name: posix.basename(rel), path: rel }); continue; }
265
+ if (tree.isSkill(rel)) { rows.push({ name: posix.basename(rel), path: rel }); continue; }
225
266
  // A directory of skills (manifest `skills: ["skills"]`): each child with a SKILL.md is one skill.
226
- if (existsSync(abs) && lstatSync(abs).isDirectory()) {
227
- for (const child of readdirSync(abs).sort()) if (hasSkillDoc(join(abs, child))) rows.push({ name: child, path: `${rel}/${child}` });
267
+ if (tree.isDir(rel)) {
268
+ for (const child of tree.children(rel)) if (tree.isSkill(`${rel}/${child}`)) rows.push({ name: child, path: `${rel}/${child}` });
228
269
  } else {
229
270
  throw fail("E_MATERIALIZE_RESOLUTION", `module ${module.name}: declared skills path ${JSON.stringify(entry)} is missing from the fetched capability`, { module: module.name, path: entry });
230
271
  }
231
272
  }
232
- } else {
233
- const skillsRoot = join(moduleDir, "skills");
234
- if (existsSync(skillsRoot) && lstatSync(skillsRoot).isDirectory()) {
235
- for (const child of readdirSync(skillsRoot).sort()) if (hasSkillDoc(join(skillsRoot, child))) rows.push({ name: child, path: `skills/${child}` });
236
- }
273
+ } else if (tree.isDir("skills")) {
274
+ for (const child of tree.children("skills")) if (tree.isSkill(`skills/${child}`)) rows.push({ name: child, path: `skills/${child}` });
237
275
  }
238
276
  for (const r of rows) {
239
277
  if (!SAFE_COMPONENT_RE.test(r.name)) throw fail("E_MATERIALIZE_RESOLUTION", `module ${module.name}: skill name ${JSON.stringify(r.name)} is not a safe directory name`, { module: module.name, skill: r.name });
240
- const abs = join(moduleDir, ...r.path.split("/"));
241
- if (!hasSkillDoc(abs)) throw fail("E_MATERIALIZE_RESOLUTION", `module ${module.name}: skill ${r.name} (${r.path}) has no readable SKILL.md in the fetched capability`, { module: module.name, skill: r.name, path: r.path });
278
+ if (verify && !tree.isSkill(r.path)) throw fail("E_MATERIALIZE_RESOLUTION", `module ${module.name}: skill ${r.name} (${r.path}) has no readable SKILL.md in the fetched capability`, { module: module.name, skill: r.name, path: r.path });
242
279
  }
243
280
  return rows;
244
281
  }
245
282
 
283
+ /** The skills materialize WOULD copy for every module of `resolution`, before anything is fetched (the spawn
284
+ * preview): moduleSkills' precedence, the fallback branch read over a remote listing of the module's
285
+ * `skills/` at the commit materialize fetches (moduleSource). → [{ module, name, path }], in module order.
286
+ * Only a module whose manifest declares no `skills` is listed; the others need no read. */
287
+ export async function plannedModuleSkills(resolution, { lock, catalog, remote = defaultRemote, remoteOptions } = {}) {
288
+ const out = [];
289
+ for (const module of resolution.modules) {
290
+ let tree = { isSkill: () => false, isDir: () => false, children: () => [] };
291
+ const declared = (resolution.skills || []).some((s) => s && s.module === module.name);
292
+ if (!declared && !Array.isArray(module.manifest?.skills)) {
293
+ const source = moduleSource(module, { lock, catalog, remote });
294
+ const at = posix.join(source.dir, "skills");
295
+ const options = remoteOptions || {};
296
+ const list = () => remote.listRemoteTree(source.ref, source.commit, at, { depth: 2, ...options });
297
+ // A listing at a commit never changes: the parsed cache keeps it, as the resolver's skill listings.
298
+ tree = listedSkillsTree(typeof remote.memoAtCommit === "function" ? await remote.memoAtCommit(source.ref, source.commit, `list\0${at}\0${2}`, list, options) : await list());
299
+ }
300
+ for (const r of skillRowsOf(resolution, module, tree, { verify: false })) out.push({ module: module.name, ...r });
301
+ }
302
+ return out;
303
+ }
304
+
246
305
  /** The inject files a module contributes → [relative path]. resolution.injects rows first, else manifest.inject. */
247
306
  function moduleInjects(resolution, module, moduleDir) {
248
307
  const declared = (resolution.injects || []).filter((i) => i && i.module === module.name);
@@ -315,8 +374,29 @@ function ensureOatsDir(home) {
315
374
  * blocks pre-rendered blocks [{ source, file, content }] placed BEFORE the capability injects
316
375
  * (the kernel's own kernel:… and work-mode:… blocks, composed by core.mjs)
317
376
  * now() ISO timestamp source (tests)
377
+ *
378
+ * stageMaterialize adds `replace` (complete roots), `staging` (explicit scratch
379
+ * directory), `existingModules` (name → frozen source path), and `instanceJson`
380
+ * (derived metadata transform). Its commit({preserveOnFailure:true}) retains
381
+ * forward progress and can be reopened with {staging, resume:true}. Add
382
+ * retainStaging:true until the caller has durably recorded its remaining lifecycle steps.
318
383
  */
319
384
  export async function materialize(resolution, home, options = {}) {
385
+ const transaction = await stageMaterialize(resolution, home, options);
386
+ return transaction.commit();
387
+ }
388
+
389
+ /** Build the same composition as spawn without publishing it. Replacement transactions
390
+ * swap complete module/skill roots; a caller holds the lifecycle claim while using them.
391
+ * `staging` may be outside the home for a read-only preview. `resume` reopens a staged
392
+ * transaction after an interrupted forward-only commit; no resolution or fetch is needed.
393
+ * `existingModules` names verified frozen copies to retain instead of fetching them.
394
+ * `instanceJson(merged, outcome)` supplies the caller's derived metadata; updateInstance
395
+ * can subsequently record provider hook results before commit. rollback() restores
396
+ * a retained swap when no provider hook has adopted the new version.
397
+ */
398
+ export async function stageMaterialize(resolution, home, options = {}) {
399
+ if (options.resume) return resumeMaterialization(home, options.staging);
320
400
  assertResolution(resolution);
321
401
  const homeAbs = assertHome(home);
322
402
  const remote = options.remote ?? defaultRemote;
@@ -329,7 +409,12 @@ export async function materialize(resolution, home, options = {}) {
329
409
  const { lock, catalog } = options;
330
410
 
331
411
  // Everything that can be decided without touching the network or the disk, first.
332
- const sources = resolution.modules.map((m) => ({ module: m, source: moduleSource(m, { lock, catalog, remote }) }));
412
+ const sources = resolution.modules.map((m) => {
413
+ const existing = Object.hasOwn(options.existingModules ?? {}, m.name) ? options.existingModules[m.name] : undefined;
414
+ return { module: m, existing,
415
+ source: existing ? { commit: m.from.commit, key: m.from.repoKey } : moduleSource(m, { lock, catalog, remote }),
416
+ };
417
+ });
333
418
  const body = soulBody(homeAbs, options);
334
419
  const instanceFile = join(homeAbs, "instance.json");
335
420
  const previous = readInstanceJson(instanceFile);
@@ -347,13 +432,13 @@ export async function materialize(resolution, home, options = {}) {
347
432
  const target = join(modulesRoot, module.name);
348
433
  let st = null;
349
434
  try { st = lstatSync(target); } catch {}
350
- if (st) throw fail("E_MATERIALIZE_HOME", `${target} already exists — the instance already carries module ${module.name}; materialize never overwrites a module in place`, { home: homeAbs, module: module.name, path: target });
435
+ if (st && !options.replace) throw fail("E_MATERIALIZE_HOME", `${target} already exists — the instance already carries module ${module.name}; materialize never overwrites a module in place`, { home: homeAbs, module: module.name, path: target });
351
436
  }
352
437
  for (const owner of skillOwners.values()) {
353
438
  const name = owner.name, target = join(skillsRoot, name);
354
439
  let st = null;
355
440
  try { st = lstatSync(target); } catch {}
356
- if (st) throw fail("E_MATERIALIZE_HOME", `${target} already exists — the instance already carries a skill named ${name}; materialize never overwrites a skill in place`, { home: homeAbs, module: owner.module, skill: name, path: target });
441
+ if (st && !options.replace) throw fail("E_MATERIALIZE_HOME", `${target} already exists — the instance already carries a skill named ${name}; materialize never overwrites a skill in place`, { home: homeAbs, module: owner.module, skill: name, path: target });
357
442
  }
358
443
  for (const p of parents) {
359
444
  let st = null;
@@ -368,33 +453,39 @@ export async function materialize(resolution, home, options = {}) {
368
453
  };
369
454
  assertHomeShape();
370
455
 
371
- const oats = ensureOatsDir(homeAbs);
456
+ const oats = options.staging ? { dir: join(homeAbs, ".oats"), created: false } : ensureOatsDir(homeAbs);
372
457
  // Unique per call: two materializations of one home in one process (or across processes) never share staging.
373
- const staging = join(oats.dir, `.staging-${process.pid}-${randomBytes(6).toString("hex")}`);
458
+ const staging = options.staging ? resolve(options.staging) : join(oats.dir, `.staging-${process.pid}-${randomBytes(6).toString("hex")}`);
459
+ assertStagingPath(staging, homeAbs);
460
+ if (linkPresent(staging)) throw fail("E_MATERIALIZE_HOME", `staging directory ${staging} already exists; resume it explicitly or choose another path`, { path: staging, why: "busy" });
461
+ let stagingOwned = false;
374
462
  const discard = () => {
375
- try { rmSync(staging, { recursive: true, force: true }); } catch { /* an unremovable staging dir must not mask the original error */ }
463
+ try { if (stagingOwned) rmSync(staging, { recursive: true, force: true }); } catch { /* an unremovable staging dir must not mask the original error */ }
376
464
  if (oats.created) { try { rmdirSync(oats.dir); } catch { /* something else appeared; leave it */ } }
377
465
  };
378
- /** A real directory at `p` (mkdir without following a symlink; EEXIST on a non-directory → refusal). */
379
- const ensureDir = (p) => {
380
- try { mkdirSync(p, { mode: 0o755 }); }
381
- catch (e) {
382
- if (e?.code !== "EEXIST") throw e;
383
- if (!lstatSync(p).isDirectory()) throw fail("E_MATERIALIZE_HOME", `${p} exists and is not a directory`, { home: homeAbs, path: p, why: "not-a-directory" });
384
- }
385
- };
386
466
 
387
467
  let outcome;
388
468
  try {
389
- mkdirSync(join(staging, "modules"), { recursive: true, mode: 0o755 });
390
- mkdirSync(join(staging, "skills"), { recursive: true, mode: 0o755 });
469
+ try { mkdirSync(staging, { mode: 0o755 }); }
470
+ catch (e) {
471
+ if (e?.code === "EEXIST") throw fail("E_MATERIALIZE_HOME", `${staging} appeared while materializing`, { path: staging, why: "busy" });
472
+ throw e;
473
+ }
474
+ stagingOwned = true;
475
+ mkdirSync(join(staging, "modules"), { mode: 0o755 });
476
+ mkdirSync(join(staging, "skills"), { mode: 0o755 });
391
477
 
392
478
  const moduleRows = [], skillRows = [], capabilityBlocks = [], recorded = {};
393
- for (const { module, source } of sources) {
479
+ for (const { module, source, existing } of sources) {
394
480
  const stagedModule = join(staging, "modules", module.name);
395
481
  const finalModule = join(modulesRoot, module.name);
396
482
  let fetched;
397
- try { fetched = await fetch(source.ref, source.commit, source.dir, stagedModule, { ...(options.remoteOptions || {}), allowSymlinks: defaultRemote.OATS_ALIAS_SYMLINK }); }
483
+ try {
484
+ if (existing) {
485
+ copyTree(existing, stagedModule, module.name, true);
486
+ fetched = { digest: remote.contentDigest(stagedModule, { allowSymlinks: defaultRemote.OATS_ALIAS_SYMLINK }) };
487
+ } else fetched = await fetch(source.ref, source.commit, source.dir, stagedModule, { ...(options.remoteOptions || {}), allowSymlinks: defaultRemote.OATS_ALIAS_SYMLINK });
488
+ }
398
489
  catch (e) {
399
490
  if (e?.code === "E_REMOTE_PATH_MISSING") {
400
491
  throw fail("E_CAPABILITY_MISSING", `module ${module.name}: ${source.dir} is not present in ${source.key}@${source.commit.slice(0, 12)}`,
@@ -417,9 +508,10 @@ export async function materialize(resolution, home, options = {}) {
417
508
  throw fail("E_MATERIALIZE_INTEGRITY", `module ${module.name}: the copy digests ${digest} but the fetch reported ${fetched.digest}`,
418
509
  { module: module.name, repoKey: source.key, commit: source.commit, expected: fetched.digest, actual: digest, why: "copy" });
419
510
  }
420
- if (module.digest && module.digest !== digest) {
421
- throw fail("E_MATERIALIZE_INTEGRITY", `module ${module.name}: content digest ${digest} does not match the resolution's ${module.digest}`,
422
- { module: module.name, repoKey: source.key, commit: source.commit, expected: module.digest, actual: digest, why: "resolution" });
511
+ const expectedDigest = module.digest ?? (existing ? previous.modules?.[module.name]?.digest : null);
512
+ if (expectedDigest && expectedDigest !== digest) {
513
+ throw fail("E_MATERIALIZE_INTEGRITY", `module ${module.name}: content digest ${digest} does not match the recorded ${expectedDigest}`,
514
+ { module: module.name, repoKey: source.key, commit: source.commit, expected: expectedDigest, actual: digest, why: "resolution" });
423
515
  }
424
516
 
425
517
  for (const skill of moduleSkills(resolution, module, stagedModule)) {
@@ -447,7 +539,8 @@ export async function materialize(resolution, home, options = {}) {
447
539
 
448
540
  const at = now();
449
541
  const from = clone(module.from);
450
- recorded[module.name] = { from, commit: source.commit, digest, materializedAt: at };
542
+ recorded[module.name] = existing && previous.modules?.[module.name]?.digest === digest && previous.modules[module.name].commit === source.commit
543
+ ? clone(previous.modules[module.name]) : { from, commit: source.commit, digest, materializedAt: at };
451
544
  moduleRows.push({ name: module.name, from, commit: source.commit, digest, files: fetched.files ?? null, bytes: fetched.bytes ?? null, path: finalModule, materializedAt: at });
452
545
  }
453
546
 
@@ -460,65 +553,170 @@ export async function materialize(resolution, home, options = {}) {
460
553
  const agentsText = renderInstructionText(body.text, blocks);
461
554
  writeFileSync(join(staging, "AGENTS.md"), agentsText, { mode: 0o644 });
462
555
 
463
- const merged = { ...previous, modules: recorded, providers: clone(resolution.payloads ?? {}) };
556
+ let merged = { ...previous, modules: recorded, providers: clone(resolution.payloads ?? {}) };
464
557
  if (typeof resolution.revision === "string" && resolution.revision) merged.resolutionRevision = resolution.revision;
558
+ outcome = { modules: moduleRows, skills: skillRows, agentsMd: join(homeAbs, "AGENTS.md"), instanceJson: merged, blocks };
559
+ if (typeof options.instanceJson === "function") merged = options.instanceJson(merged, outcome);
560
+ if (!plainObject(merged)) throw fail("E_MATERIALIZE_RESOLUTION", "options.instanceJson must return an object");
561
+ outcome.instanceJson = merged;
465
562
  writeFileSync(join(staging, "instance.json"), JSON.stringify(merged, null, 2) + "\n", { mode: 0o644 });
563
+ const state = { api: 1, home: homeAbs, replace: options.replace === true, outcome, operations: [], initialParents: [".claude", SKILLS_DIR, ".agents", MODULES_DIR].filter(p => linkPresent(join(homeAbs, p))) };
564
+ saveMaterialization(staging, state);
565
+ return materializationTransaction(staging, state, { assertHomeShape, discard });
566
+ } catch (error) {
567
+ discard();
568
+ throw error;
569
+ }
570
+ }
466
571
 
467
- // ── commit: re-check the home (TOCTOU), then a short sequence of renames with a rollback journal ──
468
- assertHomeShape();
469
- const undo = []; // LIFO: () => void
470
- const backupDir = join(staging, "previous");
471
- mkdirSync(backupDir, { mode: 0o755 });
472
- const swapIn = (src, dest, label) => {
473
- // Preserve whatever was at dest (file or symlink) in staging so a later failure can restore it.
474
- let had = false;
475
- try { lstatSync(dest); had = true; } catch {}
476
- if (had) { renameSync(dest, join(backupDir, label)); undo.push(() => renameSync(join(backupDir, label), dest)); }
477
- renameSync(src, dest);
478
- undo.push(() => rmSync(dest, { recursive: true, force: true }));
479
- };
480
- const placeDir = (src, dest) => {
481
- try { renameSync(src, dest); }
482
- catch (e) {
483
- if (e?.code === "EEXIST" || e?.code === "ENOTEMPTY" || e?.code === "EISDIR") {
484
- throw fail("E_MATERIALIZE_HOME", `${dest} appeared while materializing — another materialization of this home is in flight, or the home changed under us`, { home: homeAbs, path: dest, why: "busy" });
485
- }
486
- throw e;
487
- }
488
- undo.push(() => rmSync(dest, { recursive: true, force: true }));
489
- };
490
- const mkdirTracked = (p) => {
491
- let existed = true;
492
- try { lstatSync(p); } catch { existed = false; }
493
- ensureDir(p);
494
- if (!existed) undo.push(() => { try { rmdirSync(p); } catch { /* not empty: someone else's */ } });
495
- };
572
+ const TRANSACTION_FILE = ".materialize-transaction.json";
573
+
574
+ /** Refuse path aliases before creating or reopening staging. Staging cannot cover the
575
+ * home itself or any published composition path. Ancestors inside the home must be
576
+ * real directories; system ancestors such as macOS /tmp may be directory aliases. */
577
+ function assertStagingPath(staging, home) {
578
+ if (!isAbsolute(staging) || staging === home || relative(staging, home).split(sep)[0] !== "..") {
579
+ throw fail("E_MATERIALIZE_HOME", `unsafe staging directory ${staging}`, { path: staging });
580
+ }
581
+ if ([".oats", ".agents", ".claude", "AGENTS.md", "instance.json", "CLAUDE.md"].some(p => join(home, p) === staging)) throw fail("E_MATERIALIZE_HOME", `staging directory overlaps the home composition: ${staging}`, { path: staging });
582
+ for (const published of [join(home, MODULES_DIR), join(home, SKILLS_DIR)]) {
583
+ const rel = relative(published, staging);
584
+ if (!rel || (!rel.startsWith(`..${sep}`) && rel !== "..")) throw fail("E_MATERIALIZE_HOME", `staging directory is inside ${published}`, { path: staging });
585
+ }
586
+ let at = resolve(staging, "..");
587
+ const insideHome = !relative(home, staging).startsWith(`..${sep}`);
588
+ while (insideHome && at !== home) {
589
+ if (linkPresent(at) && !lstatSync(at).isDirectory()) throw fail("E_MATERIALIZE_HOME", `${at} exists and is not a directory`, { path: at });
590
+ const parent = resolve(at, "..");
591
+ if (parent === at) break;
592
+ at = parent;
593
+ }
594
+ }
595
+
596
+ function saveMaterialization(staging, state) {
597
+ const file = join(staging, TRANSACTION_FILE), temp = `${file}.tmp`;
598
+ writeFileSync(temp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
599
+ renameSync(temp, file);
600
+ }
601
+
602
+ function resumeMaterialization(home, stagingPath) {
603
+ const homeAbs = assertHome(home);
604
+ if (typeof stagingPath !== "string" || !isAbsolute(stagingPath)) throw fail("E_MATERIALIZE_HOME", "resuming materialization requires an absolute staging path");
605
+ const staging = resolve(stagingPath);
606
+ assertStagingPath(staging, homeAbs);
607
+ if (!lstatSync(staging).isDirectory() || !lstatSync(join(staging, TRANSACTION_FILE)).isFile()) throw fail("E_MATERIALIZE_HOME", `invalid materialization staging directory ${staging}`);
608
+ const state = readInstanceJson(join(staging, TRANSACTION_FILE));
609
+ if (state.api !== 1 || state.home !== homeAbs || typeof state.replace !== "boolean" || !plainObject(state.outcome) || !Array.isArray(state.outcome.modules) || !Array.isArray(state.outcome.skills) || !Array.isArray(state.operations)) throw fail("E_MATERIALIZE_HOME", `invalid materialization transaction in ${staging}`);
610
+ return materializationTransaction(staging, state);
611
+ }
612
+
613
+ /** A durable intent before each rename makes an interrupted swap distinguishable from
614
+ * a pending one. Forward-only failures keep both copies and retry the remaining moves;
615
+ * ordinary spawn failures reverse the same journal and discard staging. */
616
+ function materializationTransaction(staging, state, callbacks = {}) {
617
+ const home = state.home, outcome = state.outcome;
618
+ const discard = callbacks.discard ?? (() => { try { rmSync(staging, { recursive: true, force: true }); } catch { /* cleanup must not turn success into rollback */ } });
619
+ let committed = false;
620
+ const operations = () => state.replace
621
+ ? [{ label: "modules", dest: join(home, MODULES_DIR) }, { label: "skills", dest: join(home, SKILLS_DIR) }, { label: "AGENTS.md", dest: join(home, "AGENTS.md") }, { label: "instance.json", dest: join(home, "instance.json") }]
622
+ : [...outcome.modules.map(m => ({ label: `modules/${safeName(m.name)}`, dest: join(home, MODULES_DIR, m.name) })),
623
+ ...outcome.skills.map(s => ({ label: `skills/${safeName(s.name)}`, dest: join(home, SKILLS_DIR, s.name) })),
624
+ { label: "AGENTS.md", dest: join(home, "AGENTS.md") }, { label: "instance.json", dest: join(home, "instance.json") }];
625
+ const allowedLabels = new Set(operations().map(op => op.label));
626
+ if (state.operations.some(op => !plainObject(op) || !allowedLabels.has(op.label) || typeof op.had !== "boolean" || !["pending", "backed", "placed"].includes(op.phase)) ||
627
+ (state.aliases !== undefined && (!Array.isArray(state.aliases) || state.aliases.some(alias => !["CLAUDE.md", ".claude/skills"].includes(alias))))) {
628
+ throw fail("E_MATERIALIZE_HOME", `invalid materialization journal in ${staging}`, { path: staging });
629
+ }
630
+ const ensureDir = (p) => {
631
+ if (linkPresent(p)) {
632
+ if (!lstatSync(p).isDirectory()) throw fail("E_MATERIALIZE_HOME", `${p} exists and is not a directory`, { path: p });
633
+ } else mkdirSync(p, { mode: 0o755 });
634
+ };
635
+ const checkParents = () => {
636
+ for (const p of [join(home, ".oats"), join(home, ".agents"), join(home, ".claude")]) ensureDir(p);
637
+ for (const p of [join(home, MODULES_DIR), join(home, SKILLS_DIR)]) if (linkPresent(p) && !lstatSync(p).isDirectory()) throw fail("E_MATERIALIZE_HOME", `${p} exists and is not a directory`, { path: p });
638
+ if (!state.replace) { ensureDir(join(home, MODULES_DIR)); ensureDir(join(home, SKILLS_DIR)); }
639
+ };
640
+ const safeBackup = (label) => join(staging, "previous", ...label.split("/"));
641
+ const safeSource = (label) => join(staging, ...label.split("/"));
642
+ const updateInstance = (json) => {
643
+ if (!plainObject(json) || state.operations.length || committed) throw fail("E_MATERIALIZE_HOME", "instance metadata can only be updated before the materialization swap");
644
+ outcome.instanceJson = clone(json);
645
+ writeFileSync(join(staging, "instance.json"), JSON.stringify(json, null, 2) + "\n", { mode: 0o644 });
646
+ saveMaterialization(staging, state);
647
+ };
648
+ const rollback = ({ suppressErrors = false } = {}) => {
649
+ if (!linkPresent(staging)) throw fail("E_MATERIALIZE_HOME", "materialization staging is gone; rollback requires retainStaging:true", { path: staging });
650
+ const failures = [];
651
+ for (const alias of state.aliases ?? []) {
652
+ try { rmSync(join(home, alias), { force: true }); } catch (e) { failures.push(e.message); }
653
+ }
654
+ for (const op of operations().reverse()) {
655
+ const saved = state.operations.find(row => row.label === op.label);
656
+ if (!saved) continue;
657
+ const src = safeSource(op.label), backup = safeBackup(op.label);
658
+ try {
659
+ if (!linkPresent(src) && linkPresent(op.dest)) { mkdirSync(resolve(src, ".."), { recursive: true }); renameSync(op.dest, src); }
660
+ if (linkPresent(backup)) renameSync(backup, op.dest);
661
+ } catch (e) { failures.push(e.message); }
662
+ }
663
+ // Only remove parents created by this materialization, and only if empty.
664
+ for (const rel of [".claude", SKILLS_DIR, ".agents", MODULES_DIR]) {
665
+ try { if (!state.initialParents?.includes(rel)) rmdirSync(join(home, rel)); } catch {}
666
+ }
667
+ if (!failures.length) discard();
668
+ else if (!suppressErrors) throw fail("E_MATERIALIZE_HOME", `cannot fully roll back materialization; staging retained at ${staging}: ${failures.join("; ")}`, { path: staging, why: "rollback" });
669
+ committed = false;
670
+ };
671
+ const commit = ({ preserveOnFailure = false, retainStaging = false } = {}) => {
672
+ if (committed) return outcome;
496
673
  try {
497
- for (const p of [join(homeAbs, ".oats"), modulesRoot, join(homeAbs, ".agents"), skillsRoot, join(homeAbs, ".claude")]) mkdirTracked(p);
498
- for (const { module } of sources) placeDir(join(staging, "modules", module.name), join(modulesRoot, module.name));
499
- for (const row of skillRows) placeDir(join(staging, "skills", row.name), row.path);
500
- swapIn(join(staging, "AGENTS.md"), join(homeAbs, "AGENTS.md"), "AGENTS.md");
501
- swapIn(join(staging, "instance.json"), instanceFile, "instance.json");
502
- // Aliases (relative symlinks), only when absent — the canonical-plus-alias construction stays; inside the transaction.
503
- const claudeMd = join(homeAbs, "CLAUDE.md");
504
- if (!linkPresent(claudeMd)) { symlinkSync("AGENTS.md", claudeMd); undo.push(() => rmSync(claudeMd, { force: true })); }
505
- const claudeSkills = join(homeAbs, ".claude", "skills");
506
- if (!linkPresent(claudeSkills)) { symlinkSync(join("..", ".agents", "skills"), claudeSkills); undo.push(() => rmSync(claudeSkills, { force: true })); }
507
- } catch (e) {
508
- for (const step of undo.reverse()) { try { step(); } catch { /* best effort: the original error is what matters */ } }
509
- if (e?.code === "EACCES" || e?.code === "EPERM" || e?.code === "EROFS" || e?.code === "EISDIR" || e?.code === "ENOTDIR") {
510
- throw fail("E_MATERIALIZE_HOME", `cannot write the instance home ${homeAbs}: ${e.message}`, { home: homeAbs, why: "unwritable", cause: e.code });
674
+ // Spawn retains its original pre-commit race checks. A resumed replacement
675
+ // may already have published roots, so only its parent shape is checked.
676
+ if (!state.operations.length) callbacks.assertHomeShape?.();
677
+ checkParents();
678
+ for (const op of operations()) {
679
+ let saved = state.operations.find(row => row.label === op.label);
680
+ const src = safeSource(op.label), backup = safeBackup(op.label);
681
+ if (!saved) {
682
+ saved = { label: op.label, had: linkPresent(op.dest), phase: "pending" };
683
+ if (!state.replace && (op.label.startsWith("modules/") || op.label.startsWith("skills/")) && saved.had) throw fail("E_MATERIALIZE_HOME", `${op.dest} appeared while materializing`, { path: op.dest, why: "busy" });
684
+ state.operations.push(saved); saveMaterialization(staging, state);
685
+ }
686
+ if (saved.phase === "pending") {
687
+ if (saved.had && !linkPresent(backup)) {
688
+ mkdirSync(resolve(backup, ".."), { recursive: true });
689
+ renameSync(op.dest, backup);
690
+ }
691
+ saved.phase = "backed"; saveMaterialization(staging, state);
692
+ }
693
+ if (saved.phase === "backed") {
694
+ if (linkPresent(src)) {
695
+ if (linkPresent(op.dest)) throw fail("E_MATERIALIZE_HOME", `${op.dest} appeared while materializing`, { path: op.dest, why: "busy" });
696
+ renameSync(src, op.dest);
697
+ }
698
+ else if (!linkPresent(op.dest)) throw fail("E_MATERIALIZE_HOME", `staged materialization is missing ${src}`, { path: src });
699
+ saved.phase = "placed"; saveMaterialization(staging, state);
700
+ }
511
701
  }
512
- throw e;
702
+ const claudeMd = join(home, "CLAUDE.md"), claudeSkills = join(home, ".claude", "skills");
703
+ if (!linkPresent(claudeMd)) { symlinkSync("AGENTS.md", claudeMd); state.aliases = [...(state.aliases ?? []), "CLAUDE.md"]; saveMaterialization(staging, state); }
704
+ if (!linkPresent(claudeSkills)) { symlinkSync(join("..", ".agents", "skills"), claudeSkills); state.aliases = [...(state.aliases ?? []), ".claude/skills"]; saveMaterialization(staging, state); }
705
+ committed = true;
706
+ if (!retainStaging) discard();
707
+ return outcome;
708
+ } catch (error) {
709
+ if (!preserveOnFailure) rollback({ suppressErrors: true });
710
+ if (["EACCES", "EPERM", "EROFS", "EISDIR", "ENOTDIR"].includes(error?.code)) throw fail("E_MATERIALIZE_HOME", `cannot write the instance home ${home}: ${error.message}`, { home, why: "unwritable", cause: error.code });
711
+ throw error;
513
712
  }
514
- discard();
713
+ };
714
+ return { outcome, staging, commit, discard, rollback, updateInstance };
715
+ }
515
716
 
516
- outcome = { modules: moduleRows, skills: skillRows, agentsMd: join(homeAbs, "AGENTS.md"), instanceJson: merged, blocks };
517
- } catch (error) {
518
- discard();
519
- throw error;
520
- }
521
- return outcome;
717
+ function safeName(name) {
718
+ if (typeof name !== "string" || !SAFE_COMPONENT_RE.test(name)) throw fail("E_MATERIALIZE_HOME", "invalid name in materialization transaction", { name });
719
+ return name;
522
720
  }
523
721
 
524
722
  /** Every entry under `dir` is a regular file or a directory (no symlinks, devices, sockets) — E_REMOTE_TREE_UNSAFE. */
package/lib/servers.mjs CHANGED
@@ -25,6 +25,7 @@ import { parseStrictJson } from "./canonical-json.mjs";
25
25
  import { noteRuntimeName } from "./deprecation.mjs";
26
26
  import { readWaitingClaim } from "./instance-events.mjs";
27
27
  import { readRetireState } from "./retire-state.mjs";
28
+ import { paletteColor } from "./instance-color.mjs";
28
29
  import { withDirLock } from "./dir-lock.mjs";
29
30
  import { shellWord } from "./core.mjs";
30
31
  import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
@@ -644,11 +645,11 @@ export function routeCommand(serverId, cmd, oatsArgs, io = {}) {
644
645
  }
645
646
  const remote = checkRemote(target, io);
646
647
  // A saved route is keyed by name under its server id. An explicit name
647
- // that already has one here would overwrite that route on success: refuse
648
- // before the mutation (the roster shows the existing route; forget or
649
- // retire it first).
650
- const ii = oatsArgs.indexOf("--instance");
651
- const explicitName = ii >= 0 && oatsArgs[ii + 1] && !oatsArgs[ii + 1].startsWith("--") ? oatsArgs[ii + 1] : undefined;
648
+ // (--name, or --instance) that already has one here would overwrite that
649
+ // route on success: refuse before the mutation (the roster shows the
650
+ // existing route; forget or retire it first).
651
+ const valueOf = (flag) => { const i = oatsArgs.indexOf(flag); return i >= 0 && oatsArgs[i + 1] && !oatsArgs[i + 1].startsWith("--") ? oatsArgs[i + 1] : undefined; };
652
+ const explicitName = valueOf("--name") ?? valueOf("--instance");
652
653
  if (explicitName && readSnapshot(serverId, explicitName)) throw serverError("E_ROUTE_EXISTS", `a saved route for ${explicitName} through server ${serverId} already exists (${readSnapshot(serverId, explicitName).home}); retire it (oats retire ${explicitName} --server ${serverId}) or drop it (oats server forget ${serverId} --instance ${explicitName}) before spawning that name again`);
653
654
  // The remote roster: the soul's harness default for the support check,
654
655
  // and the remote agents root for the snapshot (the kernel's spawn result
@@ -661,6 +662,12 @@ export function routeCommand(serverId, cmd, oatsArgs, io = {}) {
661
662
  // spawn-preview-2 is proven to answer --preview without spawning.
662
663
  const preview = oatsArgs.includes("--preview");
663
664
  if (preview) requireRemoteFeature(remote, target, "spawn-preview-2");
665
+ // #1421 §3, #1490 §3: the naming call runs on the host, through its routed preview or apply. An
666
+ // older host is told nothing: a caller that would rather number the instance checks the host's
667
+ // features and does not send the flag; the route never drops it.
668
+ if (oatsArgs.includes("--suggest-name")) requireRemoteFeature(remote, target, preview ? "spawn-suggest-name" : "spawn-apply-suggest-name");
669
+ // An exact name is the host's to take: a host without spawn-name would refuse the flag, or worse.
670
+ if (oatsArgs.includes("--name")) requireRemoteFeature(remote, target, "spawn-name");
664
671
  const { envelope, stderr } = runRemote(target, json(withScope(["spawn", ...hostHarnessArgs(remote, oatsArgs)])), io);
665
672
  if (preview && envelope.ok && envelope.result?.preview === true && envelope.result.spawnPreviewApi === 2) {
666
673
  // The host's preview with the two fields a routed spawn adds; never a
@@ -785,6 +792,8 @@ export function routeCommand(serverId, cmd, oatsArgs, io = {}) {
785
792
  if (cmd === "inspect" && args.includes("--instructions")) requireRemoteFeature(remote, target, "soul-composed-instructions");
786
793
  // `inspect --skills` (feature soul-skills): the same, for the soul's own skills.
787
794
  if (cmd === "inspect" && args.includes("--skills")) requireRemoteFeature(remote, target, "soul-skills");
795
+ // `inspect --composed-skills` (feature soul-composed-skills): the same, for every skill a spawn would give.
796
+ if (cmd === "inspect" && args.includes("--composed-skills")) requireRemoteFeature(remote, target, "soul-composed-skills");
788
797
  const scoped = args.includes("--dir") || args.includes("--home") ? args : [...args, "--dir", target.workspace];
789
798
  const { envelope, stderr } = runRemote(target, json([cmd, ...scoped]), io);
790
799
  return { envelope: envelope.result && typeof envelope.result === "object" ? { ...envelope, result: { ...envelope.result, server: serverId, ...(route ? { route: { home: route.home, instance: route.snapshot?.instance || null, frozen: !!route.snapshot } } : {}) } } : envelope, stderr };
@@ -801,15 +810,17 @@ const HOST_SURFACES = {
801
810
  "instance diff": { feature: "instance-git", api: "instanceGitApi", version: 1 },
802
811
  "instance stop": { feature: "lifecycle-plans", api: "lifecycleApi", version: 1 },
803
812
  "retire plan": { feature: "lifecycle-plans", api: "lifecycleApi", version: 1 },
813
+ // Feature instance-color: the feature alone (its answer's instanceColorApi is not a probe key).
814
+ "instance color": { feature: "instance-color" },
804
815
  };
805
816
 
806
817
  function requireSurface(remote, target, surface) {
807
- if (!remote.features.includes(surface.feature) || remote[surface.api] !== surface.version) {
808
- throw serverError("E_REMOTE_INCOMPATIBLE", `remote oats ${remote.version} at ${target.sshHost} does not advertise ${surface.feature} (${surface.api} ${surface.version}); upgrade it there; nothing was sent`);
818
+ if (!remote.features.includes(surface.feature) || (surface.api !== undefined && remote[surface.api] !== surface.version)) {
819
+ throw serverError("E_REMOTE_INCOMPATIBLE", `remote oats ${remote.version} at ${target.sshHost} does not advertise ${surface.feature}${surface.api !== undefined ? ` (${surface.api} ${surface.version})` : ""}; upgrade it there; nothing was sent`);
809
820
  }
810
821
  }
811
822
 
812
- /** `readiness`, `instance events|git|diff|stop` and `retire --plan` on the
823
+ /** `readiness`, `instance events|git|diff|stop|color` and `retire --plan` on the
813
824
  * host: the instance is addressed as every routed session command addresses
814
825
  * it (its name through a saved route or the host's roster, or an exact
815
826
  * --home), the scope is an explicit --dir on the host or the registered
@@ -818,7 +829,7 @@ function requireSurface(remote, target, surface) {
818
829
  function routeHostSurface(serverId, cmd, oatsArgs, io) {
819
830
  const key = cmd === "instance" ? `instance ${oatsArgs[0]}` : cmd === "retire" ? "retire plan" : cmd;
820
831
  const surface = HOST_SURFACES[key];
821
- if (!surface) throw serverError("E_USAGE", `--server routes instance events, git, diff and stop only (not ${key})`);
832
+ if (!surface) throw serverError("E_USAGE", `--server routes instance events, git, diff, stop and color only (not ${key})`);
822
833
  const args = [...oatsArgs];
823
834
  const valueOf = (flag) => { const i = args.indexOf(flag); return i >= 0 && args[i + 1] !== undefined && !args[i + 1].startsWith("--") ? args[i + 1] : undefined; };
824
835
  const name = cmd === "readiness" ? undefined : args[cmd === "instance" ? 1 : 0];
@@ -864,8 +875,10 @@ function listSnapshotServers() {
864
875
  * record (`repo` is a path on the host, never read here); `soul` and `modules`
865
876
  * carry the host's drift observation against its own members and lock, not
866
877
  * recomputed here (#675). */
867
- export const REMOTE_ROW_FACTS = ["identity", "identityAddress", "teams", "startedAt", "createdAt", "model", "runtimeState", "parentInstance", "siblingInstance", "relation", "relativeTo", "spawnOrigin", "work", "repo", "branch", "modelFrom", "soul", "modules"];
868
- const rowFacts = (i = {}) => Object.fromEntries(REMOTE_ROW_FACTS.map((k) => [k, i[k] ?? null]));
878
+ export const REMOTE_ROW_FACTS = ["identity", "identityAddress", "teams", "startedAt", "createdAt", "model", "runtimeState", "parentInstance", "siblingInstance", "relation", "relativeTo", "spawnOrigin", "work", "repo", "branch", "modelFrom", "soul", "modules", "color"];
879
+ /** Each fact as the host answered it, null when it did not; `color` (feature instance-color) only as a palette
880
+ * name (lib/instance-color.mjs paletteColor), anything else null. */
881
+ const rowFacts = (i = {}) => Object.fromEntries(REMOTE_ROW_FACTS.map((k) => [k, k === "color" ? paletteColor(i[k]) : i[k] ?? null]));
869
882
  /** `waitingOnYou` (feature waiting-on-you) is relayed ONLY when the host's row has the
870
883
  * key, so it is not one of REMOTE_ROW_FACTS: a host whose kernel predates the feature
871
884
  * omits it, and absent ("not reported") must stay distinct from null ("no claim"). The
@@ -40,8 +40,11 @@ function clampSpan({ start, end }, length) {
40
40
  * home-relative and `materialized: true`);
41
41
  * - composedInstructions: inspect's `{ file: null, text, truncated, resolution, body, sources }`,
42
42
  * `text` capped at `cap` and every range clamped to it.
43
- * Throws an E_ coded error when the soul cannot be composed here. `materialize` is a test seam. */
44
- export async function composeSoulInstructions({ deployment, prepared, soulDir, cap = COMPOSED_TEXT_CAP, materialize = materializePrepared }) {
43
+ * Throws an E_ coded error when the soul cannot be composed here. `materialize` is a test seam.
44
+ * `inScratch({ outcome, scratch })`, when given, runs once the composition is proven and before the
45
+ * scratch home is removed, so another read of the same materialization (inspect's composedSkills)
46
+ * needs no second one; its value is returned as `scratchResult`. */
47
+ export async function composeSoulInstructions({ deployment, prepared, soulDir, cap = COMPOSED_TEXT_CAP, materialize = materializePrepared, inScratch }) {
45
48
  const soulName = prepared.soulEntry?.name ?? agentDirOf(prepared.soulEntry);
46
49
  let agent, composition, body;
47
50
  try {
@@ -78,8 +81,9 @@ export async function composeSoulInstructions({ deployment, prepared, soulDir, c
78
81
  const parts = renderInstructionParts(body, blocks);
79
82
  const length = Math.min(parts.text.length, cap);
80
83
  const kernelBlocks = composition.blocks.length;
84
+ const scratchResult = inScratch ? await inScratch({ outcome, scratch }) : undefined;
81
85
  return {
82
- text: parts.text, blocks, resolved: composition.resolved, oatsCoreDeclared: composition.oatsCoreDeclared,
86
+ text: parts.text, blocks, resolved: composition.resolved, oatsCoreDeclared: composition.oatsCoreDeclared, scratchResult,
83
87
  composedInstructions: {
84
88
  file: null, text: parts.text.slice(0, length), truncated: parts.text.length > length,
85
89
  resolution: prepared.resolution?.revision ?? null,