@awebai/oats 0.65.0 → 0.67.1

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 (75) hide show
  1. package/README.md +11 -5
  2. package/bin/oats.mjs +74 -20
  3. package/docs/capabilities.md +4 -4
  4. package/docs/capability-manifest.schema.json +1 -1
  5. package/docs/desktop-cli-api.md +222 -10
  6. package/docs/desktop.md +101 -22
  7. package/docs/implementation.md +16 -6
  8. package/docs/integrations.md +1 -1
  9. package/docs/official-catalog.md +2 -2
  10. package/docs/packages.md +7 -7
  11. package/docs/release-lane.md +16 -0
  12. package/docs/release-notes/v0.66.0.md +183 -0
  13. package/docs/release-notes/v0.67.0.md +366 -0
  14. package/docs/release-notes/v0.67.1.md +64 -0
  15. package/docs/servers.md +5 -4
  16. package/docs/souls-and-instances.md +20 -3
  17. package/docs/tui.md +658 -143
  18. package/docs/upgrading.md +107 -25
  19. package/docs/workspaces.md +9 -2
  20. package/lib/capability-contract.mjs +2 -2
  21. package/lib/core.mjs +126 -54
  22. package/lib/deployments.mjs +21 -5
  23. package/lib/instance-color.mjs +58 -0
  24. package/lib/instance-inspect.mjs +107 -23
  25. package/lib/instance-lifecycle.mjs +21 -1
  26. package/lib/instance-naming.mjs +187 -0
  27. package/lib/instance-resolution.mjs +5 -1
  28. package/lib/materialize.mjs +62 -11
  29. package/lib/servers.mjs +15 -6
  30. package/lib/soul-composition.mjs +7 -3
  31. package/package-catalog.json +2 -2
  32. package/package.json +1 -1
  33. package/packages/client/cli-adapter.mjs +37 -5
  34. package/packages/client/cli-locator.mjs +2 -2
  35. package/packages/client/composed-gate.mjs +10 -2
  36. package/packages/client/deployment-data.mjs +5 -0
  37. package/packages/client/deployment-identity.mjs +40 -0
  38. package/packages/client/deployment-panel.mjs +3 -1
  39. package/packages/client/inspect-boundary.mjs +11 -7
  40. package/packages/client/inspect-cache.mjs +2 -2
  41. package/packages/client/instance-name.mjs +28 -0
  42. package/packages/client/instance-presentation.mjs +11 -0
  43. package/packages/client/keymap.mjs +99 -11
  44. package/packages/client/keys-file.mjs +122 -0
  45. package/packages/client/machine-contract.mjs +1 -5
  46. package/packages/client/own-codes.mjs +4 -2
  47. package/packages/client/panel-views.mjs +62 -9
  48. package/packages/client/spawn-naming.mjs +31 -0
  49. package/packages/client/spawn-preview-cli.mjs +22 -7
  50. package/packages/client/spawn-preview-contract.mjs +24 -0
  51. package/packages/client/spawn-preview-facts.mjs +8 -4
  52. package/packages/client/spawn-preview.mjs +47 -2
  53. package/packages/record/bin/setup.mjs +10 -2
  54. package/packages/record/docs/capture-service.md +45 -6
  55. package/packages/record/lib/capture-service-install.mjs +6 -95
  56. package/packages/record/lib/capture-setup-write.mjs +233 -0
  57. package/packages/tui/README.md +9 -8
  58. package/packages/tui/lib/actions.mjs +108 -64
  59. package/packages/tui/lib/client.mjs +8 -3
  60. package/packages/tui/lib/config.mjs +208 -26
  61. package/packages/tui/lib/main.mjs +91 -20
  62. package/packages/tui/lib/model.mjs +167 -61
  63. package/packages/tui/lib/read.mjs +53 -1
  64. package/packages/tui/lib/store.mjs +156 -47
  65. package/packages/tui/lib/term/keys.mjs +150 -34
  66. package/packages/tui/lib/term/kitty.mjs +223 -0
  67. package/packages/tui/lib/term/through.mjs +174 -27
  68. package/packages/tui/lib/term/tty.mjs +43 -12
  69. package/packages/tui/lib/views/frame.mjs +158 -79
  70. package/packages/tui/lib/views/help.mjs +143 -21
  71. package/packages/tui/lib/views/instances.mjs +59 -20
  72. package/packages/tui/lib/views/palette.mjs +14 -4
  73. package/packages/tui/lib/views/souls.mjs +2 -2
  74. package/packages/tui/lib/views/switcher.mjs +6 -1
  75. package/skills/oats-getting-started/SKILL.md +107 -34
@@ -0,0 +1,58 @@
1
+ /** An instance's colour (feature instance-color, awebai/oats#1421 §2): presentation, never identity
2
+ * or an address. Anyone may set it at any time; it is a home file of its own, `<home>/.oats-color.json`,
3
+ * so that a start or restart, which rewrites instance.json, can never lose it.
4
+ *
5
+ * The record is `{ colorApi: 1, color, at }`, written atomically (writeThroughPrivateFile) at mode
6
+ * 0600; clearing removes the file. A reader takes a regular file only, without following a link, up
7
+ * to RECORD_MAX bytes: anything that is not a valid record reads as no colour (null), never an
8
+ * error. Dependency-free: the status rows, inspect and the command all read it through here. */
9
+ import { lstatSync, rmSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { readFileHead } from "./bounded-read.mjs";
12
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
13
+
14
+ /** The closed palette, the clients' own (packages/client/soul-colors.mjs SOUL_COLORS): the kernel
15
+ * imports nothing from packages/, so it keeps this copy, which test/instance-color.test.mjs pins equal. */
16
+ export const INSTANCE_COLORS = Object.freeze(["sand", "sage", "slate", "mauve", "clay", "olive"]);
17
+ /** The record's own version, and the command answer's. */
18
+ export const COLOR_API = 1;
19
+ export const INSTANCE_COLOR_API = 1;
20
+ /** The home file, kernel-owned: in KERNEL_HOME_NAME_PREFIXES (lib/capability-contract.mjs), the retire
21
+ * fingerprint's receipts (lib/core.mjs KERNEL_HOME_RECEIPTS) and the manifest schema. */
22
+ export const COLOR_FILE = ".oats-color.json";
23
+ /** A record larger than this is not one. */
24
+ export const RECORD_MAX = 4096;
25
+
26
+ /** A palette name exactly, else null: what a reader keeps of any value (a relayed row's included). */
27
+ export const paletteColor = (value) => (typeof value === "string" && INSTANCE_COLORS.includes(value) ? value : null);
28
+
29
+ /** The colour `home` records, or null: no file, not a regular file (a link is never followed), over
30
+ * RECORD_MAX bytes, unreadable, not JSON, another colorApi or a name outside the palette. Never throws. */
31
+ export function readInstanceColor(home) {
32
+ try {
33
+ const { bytes, size } = readFileHead(join(home, COLOR_FILE), RECORD_MAX + 1);
34
+ if (size > RECORD_MAX) return null;
35
+ const record = JSON.parse(bytes.toString("utf8"));
36
+ if (!record || typeof record !== "object" || Array.isArray(record) || record.colorApi !== COLOR_API) return null;
37
+ return paletteColor(record.color);
38
+ } catch { return null; }
39
+ }
40
+
41
+ /** Record `color` (a palette name) for `home`, or remove the record when `color` is null.
42
+ * → `{ color, changed }`. The colour the home already shows is no change: nothing is written. A clear
43
+ * removes whatever file stands at the name (an unreadable one included) and is a change only when a
44
+ * colour was shown. The caller validated `color` and holds the right to change the home. */
45
+ export function writeInstanceColor(home, color, { now = () => new Date() } = {}) {
46
+ const path = join(home, COLOR_FILE);
47
+ const before = readInstanceColor(home);
48
+ if (color === null) {
49
+ let present = false;
50
+ try { lstatSync(path); present = true; } catch (e) { if (e?.code !== "ENOENT") throw e; }
51
+ if (present) rmSync(path, { force: true });
52
+ return { color: null, changed: before !== null };
53
+ }
54
+ if (before === color) return { color, changed: false };
55
+ const bytes = JSON.stringify({ colorApi: COLOR_API, color, at: now().toISOString() }) + "\n";
56
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, bytes, 0o600);
57
+ return { color, changed: true };
58
+ }
@@ -28,6 +28,7 @@ import { ensureModuleTree } from "./operator-dispatch.mjs";
28
28
  import { operatorCoverage, operatorProblems } from "./operator-coverage.mjs";
29
29
  import { readLockIfPresent } from "./packages.mjs";
30
30
  import { composeSoulInstructions } from "./soul-composition.mjs";
31
+ import { readInstanceColor } from "./instance-color.mjs";
31
32
  /** Bounds of a provider check's answer (bytes, nesting, entries), as the released binding wire set them. */
32
33
  const BINDING_LIMITS = Object.freeze({ maxBytes: 1024 * 1024, maxDepth: 32, maxEntries: 16384 });
33
34
  import { parseStrictJson } from "./canonical-json.mjs";
@@ -269,7 +270,9 @@ function soulRow(t) {
269
270
  // Feature soul-composed-instructions: only on a soul target that asked (inspect --instructions).
270
271
  ...(t.kind === "soul" && t.composedInstructions !== undefined ? { composedInstructions: t.composedInstructions } : {}),
271
272
  // Feature soul-skills: only on a soul target that asked (inspect --skills).
272
- ...(t.kind === "soul" && t.skills !== undefined ? { skills: t.skills } : {}) };
273
+ ...(t.kind === "soul" && t.skills !== undefined ? { skills: t.skills } : {}),
274
+ // Feature soul-composed-skills: only on a soul target that asked (inspect --composed-skills).
275
+ ...(t.kind === "soul" && t.composedSkills !== undefined ? { composedSkills: t.composedSkills } : {}) };
273
276
  }
274
277
 
275
278
  /** The soul target with `composedInstructions` (feature soul-composed-instructions): the AGENTS.md a
@@ -277,14 +280,35 @@ function soulRow(t) {
277
280
  * resolves but cannot be composed here — with the kernel's refusal as a problem naming
278
281
  * composedInstructions, unless the soul copy's own problem (copyError) already says why. */
279
282
  export async function withComposedInstructions(t, { compose = composeSoulInstructions } = {}) {
280
- if (t.kind !== "soul") return t;
281
- if (t.soul.copyError || !t.soul.soulDir || !t.prepared) return { ...t, composedInstructions: null };
283
+ return withComposition(t, { instructions: true, compose });
284
+ }
285
+
286
+ /** The soul target with what `--instructions` (composedInstructions) and `--composed-skills` (composedSkills,
287
+ * feature soul-composed-skills) ask for, from ONE scratch materialization of the soul (composeSoulInstructions).
288
+ * A soul that cannot be composed makes each asked field null, each with the kernel's refusal as a problem
289
+ * naming that field, unless the soul copy's own problem (copyError) already says why. */
290
+ export async function withComposition(t, { instructions = false, skills = false, compose = composeSoulInstructions } = {}) {
291
+ if (t.kind !== "soul" || (!instructions && !skills)) return t;
292
+ const fields = (v) => ({ ...(instructions ? { composedInstructions: v } : {}), ...(skills ? { composedSkills: v } : {}) });
293
+ if (t.soul.copyError || !t.soul.soulDir || !t.prepared) return { ...t, ...fields(null) };
294
+ const soulDir = t.soul.soulDir;
282
295
  try {
283
- const { composedInstructions } = await compose({ deployment: t.deployment, prepared: t.prepared, soulDir: t.soul.soulDir });
284
- return { ...t, composedInstructions };
296
+ // The scratch read only when composedSkills is asked for: --instructions alone composes as it always did.
297
+ const inScratch = ({ outcome, scratch }) => composedSkillsIn(soulDir, scratch, Array.isArray(outcome?.skills) ? outcome.skills : []);
298
+ const { composedInstructions, scratchResult } = await compose({ deployment: t.deployment, prepared: t.prepared, soulDir, ...(skills ? { inScratch } : {}) });
299
+ return {
300
+ ...t,
301
+ ...(instructions ? { composedInstructions } : {}),
302
+ ...(skills ? { composedSkills: scratchResult.composedSkills, ...(scratchResult.problems.length ? { composedSkillsProblems: scratchResult.problems } : {}) } : {}),
303
+ };
285
304
  } catch (e) {
286
305
  if (typeof e?.code !== "string" || !e.code.startsWith("E_")) throw e;
287
- return { ...t, composedInstructions: null, composedInstructionsProblem: { code: e.code, message: `composedInstructions: ${e.message}` } };
306
+ const problem = (field) => ({ code: e.code, message: `${field}: ${e.message}` });
307
+ return {
308
+ ...t, ...fields(null),
309
+ ...(instructions ? { composedInstructionsProblem: problem("composedInstructions") } : {}),
310
+ ...(skills ? { composedSkillsProblems: [problem("composedSkills")] } : {}),
311
+ };
288
312
  }
289
313
  }
290
314
 
@@ -348,15 +372,17 @@ function readSkillFile(dir, realSkill, path, rel, max) {
348
372
  return readFileHead(abs, max);
349
373
  }
350
374
 
351
- /** One skill's row. Its files are listed and read in order against `budget` ({used, spent}); the budget is
352
- * charged only when the skill's files are listed (a `files: null` skill is not in the answer's text). */
353
- function soulSkillRow(soulDir, realSoul, { name, src }, budget) {
354
- const path = relative(soulDir, src).split(sep).join("/");
355
- const row = { name, path, description: null, files: null, filesTruncated: false };
356
- const problem = (reason) => ({ row, problem: { code: SKILL_FILES_UNREADABLE, message: `skills: ${path}: could not list its files: ${reason}` } });
375
+ /** One skill's row. Its files are listed and read in order against `budget` ({used, spent, limit}); the budget
376
+ * is charged only when the skill's files are listed (a `files: null` skill is not in the answer's text).
377
+ * `root` is what `path` is relative to and must contain the skill (the soul directory; for composedSkills'
378
+ * capability skills, the scratch home); `field` opens each problem message; `source`, when given, is the row's. */
379
+ function soulSkillRow(root, realRoot, { name, src }, budget, { field = "skills", where = "the soul", source } = {}) {
380
+ const path = relative(root, src).split(sep).join("/");
381
+ const row = { name, ...(source !== undefined ? { source } : {}), path, description: null, files: null, filesTruncated: false };
382
+ const problem = (reason) => ({ row, problem: { code: SKILL_FILES_UNREADABLE, message: `${field}: ${path}: could not list its files: ${reason}` } });
357
383
  if (unsafeName(name)) return problem(`${JSON.stringify(name)} is not a safe skill name`);
358
384
  let realSkill;
359
- try { realSkill = insideOf(realpathSync(src), realSoul, path, "the soul"); } catch (e) { return problem(unlistedReason(e, path)); }
385
+ try { realSkill = insideOf(realpathSync(src), realRoot, path, where); } catch (e) { return problem(unlistedReason(e, path)); }
360
386
  // The description by capabilities show's rule (skillDocDescription): SKILL.md read up to SKILL_DOC_BUDGET; null
361
387
  // when it cannot be read, is a symlink, is binary or is larger.
362
388
  let doc = null;
@@ -376,7 +402,7 @@ function soulSkillRow(soulDir, realSoul, { name, src }, budget) {
376
402
  if (spent) { files.push(omitted); continue; }
377
403
  const decoded = decodeText(read.bytes);
378
404
  const cost = decoded.text === null ? 0 : Buffer.byteLength(decoded.text, "utf8");
379
- if (used + cost > SOUL_SKILLS_TEXT_BUDGET) { spent = true; files.push(omitted); continue; }
405
+ if (used + cost > (budget.limit ?? SOUL_SKILLS_TEXT_BUDGET)) { spent = true; files.push(omitted); continue; }
380
406
  used += cost;
381
407
  files.push({ path: filePath, bytes: read.size, ...decoded });
382
408
  }
@@ -390,17 +416,11 @@ function soulSkillRow(soulDir, realSoul, { name, src }, budget) {
390
416
  * cannot be listed (a symlinked `skills/` included, which is never followed). Read-only. */
391
417
  export function soulSkills(soulDir) {
392
418
  const unreadable = (reason) => ({ skills: null, problems: [{ code: SKILLS_UNREADABLE, message: `skills: ${reason}` }] });
393
- const tree = join(soulDir, "skills");
394
419
  try {
395
- let st;
396
- try { st = lstatSync(tree); } catch (e) { if (e?.code === "ENOENT") return { skills: [], problems: [] }; throw e; }
397
- if (st.isSymbolicLink()) return unreadable("the soul's skills/ is a symbolic link, which is not followed");
398
- if (!st.isDirectory()) return unreadable("the soul's skills is not a directory");
399
- const realSoul = realpathSync(soulDir);
400
- insideOf(realpathSync(tree), realSoul, "skills/", "the soul");
420
+ const { entries, realSoul } = soulSkillEntries(soulDir);
401
421
  const budget = { used: 0, spent: false };
402
422
  const skills = [], problems = [];
403
- for (const entry of skillEntriesIn(tree, { strict: true }).sort((a, b) => compareCodepoints(a.name, b.name))) {
423
+ for (const entry of entries) {
404
424
  const { row, problem } = soulSkillRow(soulDir, realSoul, entry, budget);
405
425
  skills.push(row);
406
426
  if (problem) problems.push(problem);
@@ -409,6 +429,68 @@ export function soulSkills(soulDir) {
409
429
  } catch (e) { return unreadable(unlistedReason(e, "skills/")); }
410
430
  }
411
431
 
432
+ /** The soul's own skill entries, in codepoint order, by spawn's enumerator run strict: → { entries, realSoul }.
433
+ * No `skills/` is no entries. Throws Unlisted (a symlinked or non-directory `skills/`, one resolving outside
434
+ * the soul), or what the filesystem throws: the caller says which field could not be listed. */
435
+ function soulSkillEntries(soulDir) {
436
+ const tree = join(soulDir, "skills");
437
+ let st;
438
+ try { st = lstatSync(tree); } catch (e) { if (e?.code === "ENOENT") return { entries: [], realSoul: null }; throw e; }
439
+ if (st.isSymbolicLink()) throw new Unlisted("the soul's skills/ is a symbolic link, which is not followed");
440
+ if (!st.isDirectory()) throw new Unlisted("the soul's skills is not a directory");
441
+ const realSoul = realpathSync(soulDir);
442
+ insideOf(realpathSync(tree), realSoul, "skills/", "the soul");
443
+ return { entries: skillEntriesIn(tree, { strict: true }).sort((a, b) => compareCodepoints(a.name, b.name)), realSoul };
444
+ }
445
+
446
+ // ---------- the composed skills (feature soul-composed-skills) ----------
447
+ /** The whole `composedSkills` field carries at most this many UTF-8 bytes of `text`, summed in answer order. */
448
+ export const COMPOSED_SKILLS_TEXT_BUDGET = 2 * 1024 * 1024;
449
+
450
+ /** The skill a spawn would refuse as a duplicate, by spawn's rule (spawnInstance's `offer`): names compare
451
+ * case-insensitively, a soul skill against the capability skills materialize placed and against the soul's
452
+ * others. → `{ name, message }` with spawn's sentence, or null. */
453
+ export function composedSkillCollision(soulEntries, moduleSkills) {
454
+ const moduleOwner = new Map(moduleSkills.map((s) => [s.name.toLowerCase(), s.module]));
455
+ const seen = new Set();
456
+ for (const { name } of soulEntries) {
457
+ const key = name.toLowerCase();
458
+ if (seen.has(key) || moduleOwner.has(key)) {
459
+ const other = seen.has(key) ? "soul" : `module ${moduleOwner.get(key)}'s skill`;
460
+ return { name, message: `skill "${name}" from soul collides with ${other}` };
461
+ }
462
+ seen.add(key);
463
+ }
464
+ return null;
465
+ }
466
+
467
+ /** Every skill an instance of the soul gets, as `inspect --soul --composed-skills` reports them: → { composedSkills,
468
+ * problems }. The soul's own skills from the soul copy (soulSkillEntries, `path` relative to the soul) and the
469
+ * capability skills materialize placed in the scratch home `scratch` (`moduleSkills`, its outcome.skills, read
470
+ * from their module copies there, `path` home-relative as `from` has it), one list in codepoint order by name
471
+ * under one text budget. Null, with spawn's E_SKILL_DUPLICATE, when a spawn would refuse a collision; null with
472
+ * soul-skills-unreadable when the soul's skills cannot be listed. Read-only. */
473
+ export function composedSkillsIn(soulDir, scratch, moduleSkills) {
474
+ const unreadable = (reason) => ({ composedSkills: null, problems: [{ code: SKILLS_UNREADABLE, message: `composedSkills: ${reason}` }] });
475
+ let soul, realScratch;
476
+ try { soul = soulSkillEntries(soulDir); realScratch = realpathSync(scratch); }
477
+ catch (e) { return unreadable(unlistedReason(e, "skills/")); }
478
+ const collision = composedSkillCollision(soul.entries, moduleSkills);
479
+ if (collision) return { composedSkills: null, problems: [{ code: "E_SKILL_DUPLICATE", message: `composedSkills: ${collision.message}` }] };
480
+ const rows = [
481
+ ...soul.entries.map((entry) => ({ entry, root: soulDir, realRoot: soul.realSoul, where: "the soul", source: "soul" })),
482
+ ...moduleSkills.map((s) => ({ entry: { name: s.name, src: join(scratch, ...s.from.split("/")) }, root: scratch, realRoot: realScratch, where: "the composed home", source: `module:${s.module}` })),
483
+ ].sort((a, b) => compareCodepoints(a.entry.name, b.entry.name));
484
+ const budget = { used: 0, spent: false, limit: COMPOSED_SKILLS_TEXT_BUDGET };
485
+ const composedSkills = [], problems = [];
486
+ for (const { entry, root, realRoot, where, source } of rows) {
487
+ const { row, problem } = soulSkillRow(root, realRoot, entry, budget, { field: "composedSkills", where, source });
488
+ composedSkills.push(row);
489
+ if (problem) problems.push(problem);
490
+ }
491
+ return { composedSkills, problems };
492
+ }
493
+
412
494
  /** The soul target with `skills` (feature soul-skills): the soul's own skills from the soul copy inspect
413
495
  * materialised (soulSkills). Null when that copy failed (its copyError already says why) or the soul does not
414
496
  * resolve; reading problems are `skillsProblems`. */
@@ -455,9 +537,11 @@ export function inspectDocument(t, { kernel }) {
455
537
  knowledge: kcap ? { provider: kcap.id, version: kcap.version, operations: kcap.operations.map((o) => ({ name: o.name, kind: o.kind, available: o.available, reason: o.reason })) } : { provider: null, version: null, operations: [] },
456
538
  instance: m ? { home: t.home, instance: m.instance, agent: m.agent, harness: m.harness || null, model: m.model ?? null, yolo: m.yolo ?? null,
457
539
  launchConfig: m.launch?.launchConfig ?? null, launchConfigDefault: m.launch?.launchConfigDefault === true, launched: !!m.launched, createdAt: m.createdAt || null,
540
+ // Feature instance-color: the home's colour record (lib/instance-color.mjs), a palette name or null.
541
+ color: readInstanceColor(t.home),
458
542
  resolution: m.workspace?.resolution ?? null, soulDir: t.soul.soulDir, instructions: { ...readTextCapped(join(t.home, "AGENTS.md")), sources: m.instructions || [] } } : null,
459
543
  ...(m ? { identity: servedIdentityOf(m) } : {}),
460
- problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.composedInstructionsProblem ? [t.composedInstructionsProblem] : []), ...(t.skillsProblems || []), ...(t.discoveryError ? [t.discoveryError] : []),
544
+ problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.composedInstructionsProblem ? [t.composedInstructionsProblem] : []), ...(t.skillsProblems || []), ...(t.composedSkillsProblems || []), ...(t.discoveryError ? [t.discoveryError] : []),
461
545
  ...t.modules.filter((x) => !x.manifest).map((x) => ({ code: "module-missing", message: `${x.name} is recorded but its module copy has no readable oats.json`, capability: x.name })),
462
546
  ...capabilities.filter((c) => !c.compatibility.ok).map((c) => ({ code: "capability-incompatible", message: `${c.id} requires oats ${c.compatibility.range}; this kernel is ${c.compatibility.kernel} (re-spawn from the deployment with a release whose range admits it)`, capability: c.id, range: c.compatibility.range, kernel: c.compatibility.kernel }))],
463
547
  warnings: targetWarnings(t),
@@ -10,12 +10,13 @@
10
10
  import { createHash } from "node:crypto";
11
11
  import { existsSync, lstatSync, readFileSync, rmSync } from "node:fs";
12
12
  import { basename, join } from "node:path";
13
- import { attachedWorkLink, claimHomeFor, extraWorktreePlan, findInstanceHomes, homeClaimHolder, identifiedHomeRecord, inspectInstanceSession, instanceWork, listAgents, listInstances, observeSessionWithoutReceipt, readHomeRecord, READ_CLAIM_WHEN_UNWRITABLE, releaseHomeClaim, requireStopGrace, retireClaimPath, retirePendingMarkerPath, retirementRecoveryFacts, shq, stillRunningOf, stopInstanceSession, STOP_UNDER_CLAIM } from "./core.mjs";
13
+ import { attachedWorkLink, claimHomeFor, extraWorktreePlan, findInstanceHomes, homeClaimHolder, identifiedHomeRecord, refuseBesideRetire, inspectInstanceSession, instanceWork, listAgents, listInstances, observeSessionWithoutReceipt, readHomeRecord, READ_CLAIM_WHEN_UNWRITABLE, releaseHomeClaim, requireStopGrace, retireClaimPath, retirePendingMarkerPath, retirementRecoveryFacts, shq, stillRunningOf, stopInstanceSession, STOP_UNDER_CLAIM } from "./core.mjs";
14
14
  import { groupedByOwner } from "./retire-output.mjs";
15
15
  import { observeInstanceGit } from "./instance-git.mjs";
16
16
  import { appendEvent } from "./instance-events.mjs";
17
17
  import { afterFirstEffect, isAnswerCode, kernelCode, lifecycleBusy, oatsError, reportDefect } from "./errors.mjs";
18
18
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
19
+ import { INSTANCE_COLOR_API, INSTANCE_COLORS, writeInstanceColor } from "./instance-color.mjs";
19
20
 
20
21
  export const LIFECYCLE_API = 1;
21
22
  const KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -68,6 +69,25 @@ function otherRecord(home) {
68
69
  return record.state === "record" ? record.meta : undefined;
69
70
  }
70
71
 
72
+ /** The words a colour that is not in the palette is refused with (E_BAD_ARGS), awebai/oats#1421 §2. */
73
+ export const instanceColorRefusal = (value) => `${JSON.stringify(value)} is not an instance colour: use one of ${INSTANCE_COLORS.join(", ")}, or --clear`;
74
+
75
+ /** `oats instance color <instance> (<color> | --clear)` (feature instance-color): set or clear the colour of
76
+ * the home `name` resolves to, addressed as `oats instance stop` addresses it (resolveTarget: not found,
77
+ * ambiguous, --home mismatch, an unreadable record). A home on its way out is refused before anything is
78
+ * written: a retire in flight (its pending marker, or the home's lifecycle claim, read and never taken, as
79
+ * `oats worktree add` reads it) is E_INSTANCE_RETIRING, as is a quarantined home. `color` is a palette name
80
+ * or null (--clear); the caller refused anything else. → `{ instanceColorApi, instance, home, color, changed }`. */
81
+ export function setInstanceColor(ctx, root, name, { home, color }) {
82
+ if (color !== null && !INSTANCE_COLORS.includes(color)) throw oatsError("E_BAD_ARGS", instanceColorRefusal(color));
83
+ const me = resolveTarget(ctx, root, name, { home });
84
+ if (existsSync(join(me.home, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${me.home} is a quarantined home (or a spawn still in progress); finish its retirement (oats retire); the colour was not changed`);
85
+ if (existsSync(retirePendingMarkerPath(me.home))) throw oatsError("E_INSTANCE_RETIRING", `${name} is being retired; the colour was not changed`);
86
+ refuseBesideRetire("instance color", me.home);
87
+ const { changed } = writeInstanceColor(me.home, color);
88
+ return { instanceColorApi: INSTANCE_COLOR_API, instance: name, home: me.home, color, changed };
89
+ }
90
+
71
91
  /** Every instance under the roots whose recorded parent chain reaches `name`,
72
92
  * deepest first (children are acted on before their parent). Recorded
73
93
  * parentage is the only relation the kernel knows; it is reported as such. */
@@ -0,0 +1,187 @@
1
+ /** The suggested instance name (feature spawn-suggest-name, awebai/oats#1421 §3): `oats spawn <soul>
2
+ * --preview --suggest-name` asks the soul's own harness, in one isolated non-interactive call, for a
3
+ * descriptive name for the task, and names the instance `<descriptive>-<role>`. A failure is never an
4
+ * error: the preview numbers the instance as before and says why (`naming.reason`, a closed set).
5
+ *
6
+ * The call starts nothing that runs code: no MCP server, hook, plugin, extension or project setting
7
+ * (the maintainer's condition). NAMING_CALLS holds the argv of each harness where that is proven
8
+ * (scripts/naming-isolation-proof.mjs, a recorded run per harness); a harness not in it answers
9
+ * `unsupported-harness`. The prompt goes on stdin, never in argv (argv is readable by local users),
10
+ * from a fresh empty working directory, without a shell, in its own process group, with no
11
+ * `OATS_INSTANCE*` variable, for at most NAMING_TIMEOUT_MS, reading at most NAMING_OUTPUT_MAX bytes.
12
+ *
13
+ * Dependency-free: lib/core.mjs's spawn preview drives it (spawnBody, where the name is decided). */
14
+ import { spawn } from "node:child_process";
15
+ import { mkdtempSync, rmSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { killGroup } from "./process-group.mjs";
19
+
20
+ /** The prompt's fixed words (the maintainer's wording); the task follows. */
21
+ export const NAMING_PROMPT = "Name an agent for this task: 2–4 lowercase words joined by hyphens, describing the work, not the role. Reply with the name only.";
22
+ /** The task text the prompt carries, in characters (code points). */
23
+ export const NAMING_TASK_MAX = 4000;
24
+ /** The call's limits: the time after which its process group is killed, and the stdout read. */
25
+ export const NAMING_TIMEOUT_MS = 20_000;
26
+ export const NAMING_OUTPUT_MAX = 4096;
27
+ /** The closed set of `naming.reason`. */
28
+ export const NAMING_REASONS = Object.freeze(["no-task", "unsupported-harness", "timeout", "harness-failed", "invalid-reply"]);
29
+ /** Instance names are at most this long (lib/core.mjs MAX_INSTANCE_NAME, the messaging alias's limit). */
30
+ const NAME_MAX = 64;
31
+ /** The descriptive part keeps at most this many words. */
32
+ const WORDS_MAX = 4;
33
+
34
+ /** The prompt for `task`: the fixed words, then the task, cut to NAMING_TASK_MAX characters. */
35
+ export function namingPrompt(task) {
36
+ return `${NAMING_PROMPT}\n\nTask:\n${Array.from(String(task)).slice(0, NAMING_TASK_MAX).join("")}`;
37
+ }
38
+
39
+ /** The role of a soul name: its last `-`-separated word after any package qualifier (what follows the
40
+ * last `/` or `--`); '' when there is none. The clients' rule (packages/client/instance-name.mjs
41
+ * soulRole), kept here because the kernel imports nothing from packages/: test/instance-naming.test.mjs
42
+ * pins it to the clients' cases (test/client-instance-name.test.mjs ROLE_CASES). */
43
+ export function soulRole(soulName) {
44
+ if (typeof soulName !== "string") return "";
45
+ const slash = soulName.lastIndexOf("/"), dashes = soulName.lastIndexOf("--");
46
+ const bare = soulName.slice(Math.max(slash < 0 ? 0 : slash + 1, dashes < 0 ? 0 : dashes + 2));
47
+ return bare.slice(bare.lastIndexOf("-") + 1);
48
+ }
49
+
50
+ /** lib/core.mjs slug() without its "agent" fallback: lowercase letters and digits, single dashes. */
51
+ const slugWords = (text) => String(text).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").split("-").filter(Boolean);
52
+
53
+ /** The descriptive words of a reply: its first non-empty line as a slug, without one or more trailing
54
+ * `-<role>` (a role the model adds is not doubled; a reply that is only the role describes no work),
55
+ * at most WORDS_MAX words, cut at a word boundary to fit `NAME_MAX − 1 − len(role)`. [] when nothing
56
+ * is left: an invalid reply. */
57
+ export function descriptiveWords(reply, role) {
58
+ const line = String(reply ?? "").split(/\r?\n/).find((l) => l.trim()) ?? "";
59
+ const words = slugWords(line);
60
+ while (role && words.length && words[words.length - 1] === role) words.pop();
61
+ const kept = words.slice(0, WORDS_MAX);
62
+ const budget = NAME_MAX - (role ? role.length + 1 : 0);
63
+ while (kept.length && kept.join("-").length > budget) kept.pop();
64
+ return kept;
65
+ }
66
+
67
+ /** The name for `words` and `role`: `<descriptive>-<role>`, made unique by `-2`, `-3`, … while
68
+ * `taken(name)` (an instance or a soul of the deployment, or a live window: what an explicit name
69
+ * is refused for). A suffix that would pass NAME_MAX drops a descriptive word first, and cuts the
70
+ * last one only when one word is left. null for no words. */
71
+ export function uniqueName(words, role, taken) {
72
+ if (!words.length) return null;
73
+ let kept = [...words];
74
+ for (let i = 1; ; i++) {
75
+ const suffix = i === 1 ? "" : `-${i}`;
76
+ const fixed = (role ? role.length + 1 : 0) + suffix.length;
77
+ while (kept.length > 1 && kept.join("-").length + fixed > NAME_MAX) kept.pop();
78
+ if (kept.join("-").length + fixed > NAME_MAX) kept = [kept[0].slice(0, NAME_MAX - fixed).replace(/-+$/, "")];
79
+ const name = `${kept.join("-")}${role ? `-${role}` : ""}${suffix}`;
80
+ if (!taken(name)) return name;
81
+ }
82
+ }
83
+
84
+ /** The naming call of each harness where it is proven to start nothing that runs code: `model` picks
85
+ * the naming model from the model the instance would run on (null: the harness's own default), and
86
+ * `argv` renders the call for it. The prompt is on stdin. A launch configuration's `args` are not
87
+ * passed (they could load what these flags keep out); its executable and environment are.
88
+ * - claude: the faster model, the alias `haiku`. `--tools ""` (no tools), `--strict-mcp-config`
89
+ * with no `--mcp-config` (no MCP server or connector), `--setting-sources ""` (no user, project or
90
+ * local settings: no hook, no plugin), `--disable-slash-commands` (no skill). Native authentication
91
+ * is kept: `--bare` would read no OAuth. A login through `apiKeyHelper` is not read: such a user
92
+ * gets harness-failed and a numbered name. Claude Code's own built-in plugins (`cc-plugin-*@builtin`)
93
+ * load as they always do, `--bare` included; none of the user's plugins, hooks or MCP servers do.
94
+ * Managed-policy hooks still apply: they are the host admin's.
95
+ * - pi: the instance's model. No tools, extensions (packages and built-ins), MCP, skills, prompt
96
+ * templates, themes, context files or project-local files. pi runs its own credential commands
97
+ * (`!command` keys and headers in models.json), as every pi launch does: they are its login (the
98
+ * decided exception, kept by harness-native authentication).
99
+ * - codex is not here: `-c mcp_servers={}` does not remove a user's MCP server, only
100
+ * `--ignore-user-config` does (and drops the user's provider settings), and its logged-in surfaces
101
+ * are unproven. It answers `unsupported-harness`; the proof script keeps its argv. */
102
+ export const NAMING_CALLS = Object.freeze({
103
+ claude: Object.freeze({
104
+ model: () => "haiku",
105
+ argv: (model) => ["-p", "--tools", "", "--strict-mcp-config", "--setting-sources", "", "--disable-slash-commands", "--no-session-persistence", "--output-format", "text", "--model", model],
106
+ }),
107
+ pi: Object.freeze({
108
+ model: (instanceModel) => (typeof instanceModel === "string" && instanceModel ? instanceModel : null),
109
+ argv: (model) => ["-p", "--no-session", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-approve", ...(model ? ["--model", model] : [])],
110
+ }),
111
+ });
112
+
113
+ /** The naming call's environment: `env` without any `OATS_INSTANCE*` variable (the caller's own
114
+ * identity, when an instance spawns, is not the new instance's and is nobody's to pass on). */
115
+ export function namingEnvironment(env) {
116
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith("OATS_INSTANCE")));
117
+ }
118
+
119
+ /** A numbered answer for `reason`, with its message and the time spent. */
120
+ const numbered = (reason, message, ms) => ({ source: "numbered", reason, message, ms });
121
+
122
+ /** Ask `harness` (its executable `bin`) for a name for `task`, under `env` (a function: the launch's
123
+ * environment, built only when a call is made), within `timeoutMs`. → Promise of
124
+ * `{ answer, reply? }`: `answer` is `naming` with `source: "numbered"` and its reason, or the
125
+ * suggested answer's facts without the name; `reply` the stdout read when the harness answered.
126
+ * Never rejects. `spawnImpl` is a seam for the tests. */
127
+ export async function namingCall({ harness, bin, instanceModel, env, task, timeoutMs = NAMING_TIMEOUT_MS, spawnImpl = spawn }) {
128
+ const started = Date.now();
129
+ const ms = () => Date.now() - started;
130
+ if (typeof task !== "string" || !task.trim()) return { answer: numbered("no-task", "the task is empty: there is nothing to name the instance from", 0) };
131
+ const call = Object.hasOwn(NAMING_CALLS, harness) ? NAMING_CALLS[harness] : null;
132
+ if (!call) return { answer: numbered("unsupported-harness", `${harness} has no naming call that is proven to start nothing (suggested names work on ${Object.keys(NAMING_CALLS).join(" and ")})`, 0) };
133
+ if (!(timeoutMs > 0)) return { answer: numbered("timeout", "the preview's preflight budget was spent before the naming call", 0) };
134
+ if (typeof bin !== "string" || !bin) return { answer: numbered("harness-failed", `${harness} could not be run: no executable for it here`, 0) };
135
+ const model = call.model(instanceModel);
136
+ let environment;
137
+ try { environment = namingEnvironment(env()); }
138
+ catch (e) { return { answer: numbered("harness-failed", `${harness} could not be run: its launch's environment is not known (${e?.code || "error"})`, ms()) }; }
139
+ let cwd;
140
+ try { cwd = mkdtempSync(join(tmpdir(), "oats-naming-")); }
141
+ catch (e) { return { answer: numbered("harness-failed", `${harness} could not be run: no working directory (${e?.code || "error"})`, ms()) }; }
142
+ const outcome = await new Promise((settle) => {
143
+ let child, timer, timedOut = false, done = false, size = 0;
144
+ const chunks = [];
145
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
146
+ // The kernel's process ends with its caller, and the call with it: its group is killed on exit
147
+ // and on a signal, which is then raised again with the default action.
148
+ const onExit = () => killGroup(child);
149
+ const onSignal = (sig) => { killGroup(child); cleanup(); process.kill(process.pid, sig); };
150
+ const cleanup = () => { process.off("exit", onExit); for (const s of signals) process.off(s, onSignal); };
151
+ const finish = (value) => { if (done) return; done = true; clearTimeout(timer); cleanup(); settle(value); };
152
+ try {
153
+ child = spawnImpl(bin, call.argv(model), { cwd, env: environment, detached: true, stdio: ["pipe", "pipe", "ignore"], shell: false });
154
+ } catch (e) { return finish({ error: e }); }
155
+ process.once("exit", onExit);
156
+ for (const s of signals) process.once(s, onSignal);
157
+ timer = setTimeout(() => { timedOut = true; killGroup(child); }, timeoutMs);
158
+ child.on("error", (e) => finish({ error: e }));
159
+ child.stdout.on("data", (chunk) => {
160
+ if (size >= NAMING_OUTPUT_MAX) return;
161
+ const take = chunk.subarray(0, NAMING_OUTPUT_MAX - size);
162
+ chunks.push(take); size += take.length;
163
+ });
164
+ child.on("close", (code, signal) => finish({ code, signal, timedOut, stdout: Buffer.concat(chunks).toString("utf8") }));
165
+ child.stdin.on("error", () => { /* a harness that exits before reading answers by its exit */ });
166
+ child.stdin.end(namingPrompt(task));
167
+ });
168
+ try { rmSync(cwd, { recursive: true, force: true }); } catch { /* a temporary directory */ }
169
+ // The message gives the exit or the signal, never the output.
170
+ if (outcome.timedOut) return { answer: numbered("timeout", `${harness} gave no name within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`, ms()) };
171
+ if (outcome.error) return { answer: numbered("harness-failed", `${harness} could not be run (${outcome.error.code || "error"})`, ms()) };
172
+ if (outcome.signal) return { answer: numbered("harness-failed", `${harness} was ended by ${outcome.signal}`, ms()) };
173
+ if (outcome.code !== 0) return { answer: numbered("harness-failed", `${harness} exited with ${outcome.code}`, ms()) };
174
+ return { answer: { source: "suggested", ms: ms(), harness, model }, reply: outcome.stdout };
175
+ }
176
+
177
+ /** The suggested name for `task`: the call, then the name built from its reply for `soulName`'s role,
178
+ * unique by `taken`. → Promise of `{ naming, name? }`: `name` only when `naming.source` is
179
+ * "suggested". Never rejects. */
180
+ export async function suggestInstanceName({ soulName, taken, ...call }) {
181
+ const { answer, reply } = await namingCall(call);
182
+ if (answer.source !== "suggested") return { naming: answer };
183
+ const role = soulRole(soulName);
184
+ const name = uniqueName(descriptiveWords(reply, role), role, taken);
185
+ if (!name) return { naming: numbered("invalid-reply", `${call.harness}'s reply holds no name`, answer.ms) };
186
+ return { naming: answer, name };
187
+ }
@@ -24,7 +24,7 @@ import { resolveSoul, kernelCompatibility } from "./resolve.mjs";
24
24
  import { BY_TEAM_REMOVED, isRemovedTeamKeys, isTeamRefusal, memberNameOf, recordedTeams, reportRows, soulKeyOf, soulTeams, teamKeyOf, teamModel } from "./teams.mjs";
25
25
  import { launchLayers } from "./launch-preference.mjs";
26
26
  import { APPROVED_HOOKS, declaredSettings, locatedContractWarnings } from "./capability-contract.mjs";
27
- import { materialize, moduleSkills, MODULES_DIR, SKILLS_DIR } from "./materialize.mjs";
27
+ import { materialize, moduleSkills, MODULES_DIR, plannedModuleSkills, SKILLS_DIR } from "./materialize.mjs";
28
28
  import { contentDigest, fetchRemoteTree } from "./remote.mjs";
29
29
  import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync, symlinkSync, statSync } from "node:fs";
30
30
  import { tmpdir } from "node:os";
@@ -658,6 +658,10 @@ export async function discoverOrStandalone(local, { lock, deployment, remoteOpti
658
658
  export async function materializePrepared(prepared, home) {
659
659
  return materialize(prepared.resolution, home, { lock: prepared.lock, remoteOptions: prepared.remoteOptions, soulAgentsMd: prepared.soulAgentsMd, soulDir: prepared.soulDir });
660
660
  }
661
+ /** The capability skills materializePrepared would copy, named before anything is fetched (the spawn preview). */
662
+ export async function plannedPreparedSkills(prepared) {
663
+ return plannedModuleSkills(prepared.resolution, { lock: prepared.lock, remoteOptions: prepared.remoteOptions });
664
+ }
661
665
 
662
666
 
663
667
  /** Turn a Resolution's modules (already materialized under `home`) into the
@@ -209,6 +209,40 @@ function hasSkillDoc(dir) {
209
209
  * Precedence: resolution.skills rows for the module; else manifest.skills; else every
210
210
  * skills/<dir>/SKILL.md in the fetched tree. */
211
211
  export function moduleSkills(resolution, module, moduleDir) {
212
+ return skillRowsOf(resolution, module, fsTree(moduleDir), { verify: true });
213
+ }
214
+
215
+ /** The fetched module tree as skillRowsOf reads it: paths relative to the module root, POSIX. */
216
+ function fsTree(moduleDir) {
217
+ const abs = (rel) => join(moduleDir, ...rel.split("/"));
218
+ return {
219
+ isSkill: (rel) => hasSkillDoc(abs(rel)),
220
+ isDir: (rel) => existsSync(abs(rel)) && lstatSync(abs(rel)).isDirectory(),
221
+ children: (rel) => readdirSync(abs(rel)).sort(),
222
+ };
223
+ }
224
+
225
+ /** A remote listing of the module's `skills/` (listRemoteTree, depth 2, relative to it) as skillRowsOf reads
226
+ * a tree: only the fallback branch reads one (a module whose manifest declares no `skills`). A listed
227
+ * symlink is not a SKILL.md. */
228
+ function listedSkillsTree(entries) {
229
+ const blobs = new Set(), trees = new Set();
230
+ for (const e of entries) {
231
+ if (e.type === "blob") blobs.add(`skills/${e.path}`);
232
+ else if (e.type === "tree") trees.add(`skills/${e.path}`);
233
+ }
234
+ return {
235
+ isSkill: (rel) => blobs.has(`${rel}/SKILL.md`),
236
+ // listRemoteTree answers [] for a missing `skills/`, one that is not a directory and an empty one alike.
237
+ isDir: (rel) => (rel === "skills" ? entries.length > 0 : trees.has(rel)),
238
+ children: (rel) => [...trees].filter((t) => t.startsWith(`${rel}/`) && !t.slice(rel.length + 1).includes("/")).map((t) => t.slice(rel.length + 1)).sort(),
239
+ };
240
+ }
241
+
242
+ /** moduleSkills' precedence over `tree` ({ isSkill, isDir, children }, module-relative). `verify` checks
243
+ * each row has a readable SKILL.md (a fetched tree); the preview's rows from the resolution were checked
244
+ * over the remote by the resolver, and its fallback rows are SKILL.md holders by construction. */
245
+ function skillRowsOf(resolution, module, tree, { verify }) {
212
246
  const declared = (resolution.skills || []).filter((s) => s && s.module === module.name);
213
247
  const rows = [];
214
248
  if (declared.length) {
@@ -220,29 +254,46 @@ export function moduleSkills(resolution, module, moduleDir) {
220
254
  } else if (Array.isArray(module.manifest?.skills)) {
221
255
  for (const entry of module.manifest.skills) {
222
256
  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; }
257
+ if (tree.isSkill(rel)) { rows.push({ name: posix.basename(rel), path: rel }); continue; }
225
258
  // 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}` });
259
+ if (tree.isDir(rel)) {
260
+ for (const child of tree.children(rel)) if (tree.isSkill(`${rel}/${child}`)) rows.push({ name: child, path: `${rel}/${child}` });
228
261
  } else {
229
262
  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
263
  }
231
264
  }
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
- }
265
+ } else if (tree.isDir("skills")) {
266
+ for (const child of tree.children("skills")) if (tree.isSkill(`skills/${child}`)) rows.push({ name: child, path: `skills/${child}` });
237
267
  }
238
268
  for (const r of rows) {
239
269
  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 });
270
+ 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
271
  }
243
272
  return rows;
244
273
  }
245
274
 
275
+ /** The skills materialize WOULD copy for every module of `resolution`, before anything is fetched (the spawn
276
+ * preview): moduleSkills' precedence, the fallback branch read over a remote listing of the module's
277
+ * `skills/` at the commit materialize fetches (moduleSource). → [{ module, name, path }], in module order.
278
+ * Only a module whose manifest declares no `skills` is listed; the others need no read. */
279
+ export async function plannedModuleSkills(resolution, { lock, catalog, remote = defaultRemote, remoteOptions } = {}) {
280
+ const out = [];
281
+ for (const module of resolution.modules) {
282
+ let tree = { isSkill: () => false, isDir: () => false, children: () => [] };
283
+ const declared = (resolution.skills || []).some((s) => s && s.module === module.name);
284
+ if (!declared && !Array.isArray(module.manifest?.skills)) {
285
+ const source = moduleSource(module, { lock, catalog, remote });
286
+ const at = posix.join(source.dir, "skills");
287
+ const options = remoteOptions || {};
288
+ const list = () => remote.listRemoteTree(source.ref, source.commit, at, { depth: 2, ...options });
289
+ // A listing at a commit never changes: the parsed cache keeps it, as the resolver's skill listings.
290
+ tree = listedSkillsTree(typeof remote.memoAtCommit === "function" ? await remote.memoAtCommit(source.ref, source.commit, `list\0${at}\0${2}`, list, options) : await list());
291
+ }
292
+ for (const r of skillRowsOf(resolution, module, tree, { verify: false })) out.push({ module: module.name, ...r });
293
+ }
294
+ return out;
295
+ }
296
+
246
297
  /** The inject files a module contributes → [relative path]. resolution.injects rows first, else manifest.inject. */
247
298
  function moduleInjects(resolution, module, moduleDir) {
248
299
  const declared = (resolution.injects || []).filter((i) => i && i.module === module.name);