@awebai/oats 0.48.0 → 0.50.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 (47) hide show
  1. package/bin/oats.mjs +326 -28
  2. package/docs/capabilities.md +425 -8
  3. package/docs/capability-manifest.schema.json +60 -5
  4. package/docs/configuration.md +103 -0
  5. package/docs/desktop-cli-api.md +542 -47
  6. package/docs/desktop.md +85 -5
  7. package/docs/execution-targets.md +50 -9
  8. package/docs/implementation.md +74 -1
  9. package/docs/integrations.md +7 -5
  10. package/docs/knowledge.md +167 -197
  11. package/docs/official-catalog.md +4 -4
  12. package/docs/packages.md +28 -14
  13. package/docs/release-lane.md +41 -0
  14. package/docs/release-notes/v0.49.0.md +770 -0
  15. package/docs/release-notes/v0.50.0.md +279 -0
  16. package/docs/schedules.md +289 -53
  17. package/docs/servers.md +7 -0
  18. package/docs/souls-and-instances.md +450 -60
  19. package/docs/workspaces.md +3 -3
  20. package/injects/work-checkout.md +17 -11
  21. package/injects/work-worktree.md +19 -13
  22. package/lib/capability-contract.mjs +100 -11
  23. package/lib/capability-show.mjs +18 -2
  24. package/lib/core.mjs +1374 -394
  25. package/lib/instance-events.mjs +9 -10
  26. package/lib/instance-git.mjs +19 -10
  27. package/lib/instance-inspect.mjs +58 -18
  28. package/lib/instance-lifecycle.mjs +106 -16
  29. package/lib/instance-resolution.mjs +15 -3
  30. package/lib/launch-prompt-policy.mjs +17 -3
  31. package/lib/packages.mjs +1 -0
  32. package/lib/real-path.mjs +27 -0
  33. package/lib/refused-text.mjs +17 -0
  34. package/lib/resolve.mjs +4 -4
  35. package/lib/retained-after-retire.mjs +387 -0
  36. package/lib/retire-output.mjs +6 -1
  37. package/lib/schedule.mjs +9 -2
  38. package/lib/servers.mjs +32 -6
  39. package/lib/tree-copy.mjs +18 -7
  40. package/lib/trigger-sources.mjs +234 -0
  41. package/lib/triggers.mjs +705 -108
  42. package/lib/workspace.mjs +20 -5
  43. package/lib/worktree-hooks.mjs +392 -0
  44. package/lib/worktree.mjs +655 -0
  45. package/package-catalog.json +3 -3
  46. package/package.json +1 -1
  47. package/skills/oats-getting-started/SKILL.md +1 -1
@@ -40,12 +40,13 @@
40
40
  * that checks "the rows' home is the home I asked for" keeps holding. */
41
41
  import { appendFileSync, closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync } from "node:fs";
42
42
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
43
+ import { REFUSED_TEXT } from "./refused-text.mjs";
43
44
 
44
45
  export const EVENTS_API = 2;
45
46
  const HOME_LOG = ".oats-events.jsonl";
46
47
  const MAX_BYTES = 4 * 1024 * 1024;
47
48
 
48
- export const EVENT_KINDS = ["spawned", "launched", "restarted", "stopped", "stop-refused", "retire-planned", "retired", "worktree-retained", "worktree-removed", "branch-deleted", "child-spawn-refused", "launch-warning", "launch-prompt", "recomposed", "waiting"];
49
+ export const EVENT_KINDS = ["spawned", "launched", "restarted", "stopped", "stop-refused", "retire-planned", "retired", "worktree-retained", "worktree-removed", "worktree-added", "branch-deleted", "child-spawn-refused", "launch-warning", "launch-prompt", "recomposed", "waiting"];
49
50
 
50
51
  /** Kernel rows that end or begin a session: a waiting claim older than the
51
52
  * incarnation's latest one is not live. */
@@ -55,13 +56,8 @@ export const WAITING_REASONS = ["permission", "question", "attention"];
55
56
  /** A producer id: what `--producer` accepts (`kernel` is reserved). */
56
57
  export const WAITING_PRODUCER_RE = /^[a-z0-9][a-z0-9._/-]{0,63}$/;
57
58
  export const WAITING_MESSAGE_MAX = 200;
58
- /** Characters a claim's message may not contain (the maintainer's set): control
59
- * characters (Cc: C0, DEL, C1), the Unicode line and paragraph separators, the bidi
60
- * embeddings, overrides and isolates (U+202A-202E, U+2066-2069), the invisible hiders
61
- * U+200B, U+2060 and U+FEFF, and the tag characters (U+E0000-E007F). Everything else is
62
- * allowed, ZWJ and ZWNJ (U+200C/D, emoji sequences, Persian and Indic text) and the marks
63
- * LRM, RLM and ALM (U+200E/F, U+061C) included. The Desktop uses the identical set. */
64
- const WAITING_MESSAGE_REFUSED = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069\u200B\u2060\uFEFF\u{E0000}-\u{E007F}]/u;
59
+ /** Characters a claim's message may not contain: the kernel's refused set (lib/refused-text.mjs). */
60
+ const WAITING_MESSAGE_REFUSED = REFUSED_TEXT;
65
61
  /** A claim's message: a non-empty string of 1 to 200 code points with none of
66
62
  * WAITING_MESSAGE_REFUSED. The writer refuses anything else; the reader turns a stored
67
63
  * message that fails it (a hand-edited log) into null. */
@@ -267,9 +263,12 @@ const waitingShape = (c) => (c ? { since: c.since, producer: c.producer, reason:
267
263
 
268
264
  /** Events for one instance ADDRESS, newest last, from both logs, with a bounded
269
265
  * window; integrity is reported independently of the selected rows. The answer's
270
- * `home`, and each returned row's, is the home as the caller spelled it. */
271
- export function readEvents(given, { limit = 200, since = null } = {}) {
266
+ * `home`, and each returned row's, is the home as the caller spelled it: `given`,
267
+ * or `asked` when the caller resolved its own spelling to `given` (a removed home
268
+ * named through an alias of the agents root, whose logs `given` locates). */
269
+ export function readEvents(given, { limit = 200, since = null, asked } = {}) {
272
270
  const address = addressOf(given);
271
+ if (asked !== undefined) address.asked = asked;
273
272
  const { home, instance, incarnation, homeLog, workspaceLog } = address;
274
273
  const a = readLog(homeLog, "home"), b = readLog(workspaceLog, "workspace");
275
274
  const { rows, foreign } = admit(home, [a, b]);
@@ -18,14 +18,18 @@ export const INSTANCE_GIT_API = 1;
18
18
 
19
19
  /** Every invocation is read-only and helper-free: the tree being observed may
20
20
  * carry a hostile repo config (an agent works there), so external diff /
21
- * textconv drivers, fsmonitor and hooks are disabled explicitly, the caller's
22
- * Git environment is not inherited, and optional locks are off so status/diff
23
- * never refresh (write) the index. */
21
+ * textconv drivers, fsmonitor, hooks and lazy fetch are disabled explicitly,
22
+ * the caller's Git environment is not inherited, and optional locks are off
23
+ * so status/diff never refresh (write) the index. Lazy fetch
24
+ * (GIT_NO_LAZY_FETCH=1): an object a promisor repository lacks is a failed
25
+ * read, never fetched through the remote, helper, ssh command or credential
26
+ * helper the repository's configuration names, and never written into it.
27
+ * Git before 2.44 ignores the variable. */
24
28
  const READ_ONLY_GIT = ["--no-optional-locks",
25
29
  "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "diff.external=", "-c", "core.pager=cat",
26
30
  "-c", "core.untrackedCache=false", "-c", "index.threads=1", "-c", "safe.bareRepository=explicit"];
27
31
  function gitEnv() {
28
- const env = { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", LANG: "C", LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" };
32
+ const env = { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", LANG: "C", LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" };
29
33
  // The user's global config may name helpers too; observations do not need it.
30
34
  env.GIT_CONFIG_GLOBAL = "/dev/null";
31
35
  return env;
@@ -46,12 +50,15 @@ const trim = (s) => (s === null ? null : s.trim());
46
50
  /** One helper-free Git probe run like the module's other reads
47
51
  * (READ_ONLY_GIT, gitEnv, argv, no shell) → { ok, out, err }. `out` is text.
48
52
  * Never throws: the caller decides what a failure means. `cwd`: the tree
49
- * `-C` names; gitRepoRead names the repository by its Git directory instead. */
50
- export function gitRead(cwd, argv) { return gitProbe(["-C", cwd], argv); }
53
+ * `-C` names; gitRepoRead names the repository by its Git directory instead.
54
+ * `input`: text for the command's standard input (`--stdin`), else none.
55
+ * `encoding`: how `out` is decoded ("latin1" keeps every byte as one
56
+ * character, for an exact comparison of names), "utf8" by default. */
57
+ export function gitRead(cwd, argv, { input, encoding } = {}) { return gitProbe(["-C", cwd], argv, input, encoding); }
51
58
  /** gitRead against the repository whose (common) Git directory is `gitDir`,
52
59
  * named explicitly (`--git-dir`), so that a bare repository is read too
53
60
  * (READ_ONLY_GIT sets safe.bareRepository=explicit). */
54
- export function gitRepoRead(gitDir, argv) { return gitProbe(["--git-dir", gitDir], argv); }
61
+ export function gitRepoRead(gitDir, argv, { input, encoding } = {}) { return gitProbe(["--git-dir", gitDir], argv, input, encoding); }
55
62
  /** A Git command that changes the repository whose Git directory is `gitDir`
56
63
  * (a worktree move, remove or prune), under the same discipline as the
57
64
  * reads: the repository's own configuration names no helper that runs
@@ -61,8 +68,8 @@ export function gitRepoRead(gitDir, argv) { return gitProbe(["--git-dir", gitDir
61
68
  export function gitRepoRun(gitDir, argv) {
62
69
  return execFileSync("git", ["--git-dir", gitDir, ...READ_ONLY_GIT, ...argv], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 120_000, env: gitEnv() });
63
70
  }
64
- function gitProbe(where, argv) {
65
- const r = spawnSync("git", [...where, ...READ_ONLY_GIT, ...argv], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env: gitEnv() });
71
+ function gitProbe(where, argv, input, encoding = "utf8") {
72
+ const r = spawnSync("git", [...where, ...READ_ONLY_GIT, ...argv], { encoding, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env: gitEnv() });
66
73
  return !r.error && r.status === 0 ? { ok: true, out: r.stdout } : { ok: false, out: "", err: String(r.error?.message ?? r.stderr ?? "").trim() || `git ${argv[0]} exited with ${r.status}` };
67
74
  }
68
75
 
@@ -326,11 +333,13 @@ export function observeInstanceGit(home) {
326
333
  const files = entries.filter((e) => e.kind !== "ignored").map((e) => ({ id: fileId(revision, indexOid, e), ...e, ...countsOf(counts, e) }));
327
334
  const summary = { changed: 0, renamed: 0, copied: 0, unmerged: 0, untracked: 0 };
328
335
  for (const f of files) summary[f.kind]++;
336
+ // A home spawned before #641 may record the word "HEAD" for a detached HEAD; no branch is named that, so it reads as none.
337
+ const recordedBranch = meta.branch === "HEAD" ? null : meta.branch ?? null;
329
338
  return {
330
339
  instanceGitApi: INSTANCE_GIT_API,
331
340
  instance: meta.instance ?? null, agent: meta.agent ?? null, home, workMode: mode,
332
341
  observation: { revision, indexRevision: indexOid, at, worktree: work, branch: head.branch, detached: head.detached && headOid !== null, unborn: headOid === null },
333
- recorded: { branch: meta.branch ?? null, repo: meta.repo ?? null, drift: meta.branch !== undefined && meta.branch !== null && head.branch !== meta.branch },
342
+ recorded: { branch: recordedBranch, repo: meta.repo ?? null, drift: recordedBranch !== null && head.branch !== recordedBranch },
334
343
  upstream, base: baseComparison,
335
344
  remote: remoteOf(work, head.branch),
336
345
  summary, files,
@@ -15,8 +15,8 @@ import { accessSync, constants as fsConstants, existsSync, readFileSync, realpat
15
15
  import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { capabilityManifests, sessionDefaults, homeLaunchLayers, instanceSoulDir, launchConfigsAt, preparedSoulIdOf, stableSoulId, launchFolderTrust, launchReportFor, manifestOperations, parseYamlNested, servedIdentityOf, teamEnv, upgradeHomeMeta, withConfigFile } from "./core.mjs";
18
- import { agentDirOf, discoverOrStandalone, ensureWorkspaceSoul, findSoulEntry, liveTeams, prepareInstance, soulCopyDigests } from "./instance-resolution.mjs";
19
- import { declaredSettings } from "./capability-contract.mjs";
18
+ import { agentDirOf, discoverOrStandalone, ensureWorkspaceSoul, findSoulEntry, liveTeams, prepareInstance, resolutionContractWarnings, soulCopyDigests } from "./instance-resolution.mjs";
19
+ import { declaredSettings, locatedContractWarnings } from "./capability-contract.mjs";
20
20
  import { kernelCompatibility } from "./resolve.mjs";
21
21
  import { discoveredTeamKeys, isRemovedTeamKeys, isTeamRefusal, recordedTeams, reportRows, soulKeyOf, teamKeyOf, soulTeams, teamModel, teamProblems } from "./teams.mjs";
22
22
  import { launchLayers, launchReport } from "./launch-preference.mjs";
@@ -151,8 +151,11 @@ export async function homeTarget(home, meta, { remoteOptions, discover = true, l
151
151
 
152
152
  /** The soul target, resolved exactly as a spawn of `soul` would be. A resolution
153
153
  * refusal that is a readiness fact is kept as `resolutionError` (callers that
154
- * must answer — inspect, operation run — refuse with it). */
155
- export async function soulTarget(contextDir, soul, { remoteOptions } = {}) {
154
+ * must answer — inspect, operation run — refuse with it). `materialize: false`
155
+ * resolves only: it writes nothing under the deployment's agents root, and names the
156
+ * soul's per-commit copy only when an earlier resolution left one
157
+ * (materializeSoulTarget makes it, later, for a caller that then goes on). */
158
+ export async function soulTarget(contextDir, soul, { remoteOptions, materialize = true } = {}) {
156
159
  let prepared = null, resolutionError = null;
157
160
  try { prepared = await prepareInstance(contextDir, soul, { remoteOptions }); }
158
161
  catch (e) {
@@ -180,7 +183,7 @@ export async function soulTarget(contextDir, soul, { remoteOptions } = {}) {
180
183
  // commit answered a false negative. A failure is a readiness fact (soulCopyError), never a silent null.
181
184
  // A refused resolution has nothing to materialise: the cached copy, when there is one.
182
185
  let soulDir = null, soulCopyError = null;
183
- if (prepared) {
186
+ if (prepared && materialize) {
184
187
  try { soulDir = await ensureWorkspaceSoul(prepared, join(deployment, "agents")); }
185
188
  catch (e) { soulCopyError = { code: e?.code || "E_SOUL_COPY_FAILED", message: e?.message || String(e) }; }
186
189
  } else {
@@ -207,6 +210,16 @@ export async function soulTarget(contextDir, soul, { remoteOptions } = {}) {
207
210
  };
208
211
  }
209
212
 
213
+ /** Materialise the soul of a target resolved with `materialize: false`, as soulTarget itself does:
214
+ * the per-commit copy its checks and commands get as OATS_SOUL. A failure is the same readiness
215
+ * fact (`soul.copyError`). → the target, updated in place */
216
+ export async function materializeSoulTarget(t) {
217
+ if (!t.prepared) return t;
218
+ try { t.soul.soulDir = await ensureWorkspaceSoul(t.prepared, t.agentsRoot); delete t.soul.copyError; }
219
+ catch (e) { t.soul.copyError = { code: e?.code || "E_SOUL_COPY_FAILED", message: e?.message || String(e) }; }
220
+ return t;
221
+ }
222
+
210
223
  /** The tmux session a NEW tmux spawn here would open in ({tmuxSession}, 0.31); null when the
211
224
  * deployment's oats-local.yaml cannot be read. */
212
225
  function newSessionDefaults(deployment) {
@@ -271,6 +284,15 @@ export async function withComposedInstructions(t, { compose = composeSoulInstruc
271
284
  }
272
285
 
273
286
  /** `oats inspect --json` on the workspace model. */
287
+ /** What the target's capabilities declare and this kernel ignores (an unknown hook event):
288
+ * [{ code, capability, path, message }]. A soul's from its resolution, where each manifest is read
289
+ * (`<repoKey>:<dir>/oats.json`, `package:<id>:<dir>/oats.json`); a home's from its module copies,
290
+ * at their path in the home (`.oats/modules/<name>/oats.json`: the source directory is not recorded). */
291
+ export function targetWarnings(t) {
292
+ if (!t.home) return resolutionContractWarnings(t.prepared?.resolution);
293
+ return t.modules.filter((x) => x.manifest).flatMap((x) => locatedContractWarnings(x.manifest, `.oats/modules/${x.name}/oats.json`));
294
+ }
295
+
274
296
  export function inspectDocument(t, { kernel }) {
275
297
  const capabilities = capabilityRows(t);
276
298
  // `from` (feature layers-from): where the slot's capability came from; null for an empty slot, and for a
@@ -302,6 +324,7 @@ export function inspectDocument(t, { kernel }) {
302
324
  problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.composedInstructionsProblem ? [t.composedInstructionsProblem] : []), ...(t.discoveryError ? [t.discoveryError] : []),
303
325
  ...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 })),
304
326
  ...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 }))],
327
+ warnings: targetWarnings(t),
305
328
  };
306
329
  }
307
330
 
@@ -401,6 +424,26 @@ function moduleExecutable(dir, script) {
401
424
  if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;
402
425
  try { return statSync(file).isFile() ? file : null; } catch { return null; }
403
426
  }
427
+ /** Run one of a capability's own commands the way a provider check runs (the binding wire's
428
+ * runner, shared with trigger sources, lib/triggers.mjs): `node <script> <args>` from the module
429
+ * directory, the script contained in it (moduleExecutable), one JSON `request` on stdin, the
430
+ * environment providerEnv's for the request's `settings`, SIGKILL at `timeoutMs`, at most
431
+ * BINDING_LIMITS of stdout, decoded as exactly one strict JSON document (whitespace around it
432
+ * allowed). → { doc } or { failure: "no-command" | "no-executable" (script) | "incomplete"
433
+ * (timedOut, signal, overflow) | "exit" (status) | "invalid" }. The caller judges the document. */
434
+ export function runModuleCommand(t, mod, dir, command, request, { timeoutMs = 30000 } = {}) {
435
+ const spec = command ? mod.manifest?.commands?.[command] : null;
436
+ if (typeof spec !== "string" || !spec.trim()) return { failure: "no-command" };
437
+ const [script, ...args] = spec.trim().split(/\s+/);
438
+ const file = dir ? moduleExecutable(dir, script) : null;
439
+ if (!file) return { failure: "no-executable", script };
440
+ // The environment is providerEnv's: ambient OATS_/OAS_/PI_ identity removed, the rest
441
+ // inherited.
442
+ const r = spawnSync(process.execPath, [file, ...args], { cwd: dir, env: providerEnv(t, mod.name, request.settings), input: JSON.stringify(request), encoding: "utf8", timeout: Math.max(1, timeoutMs), killSignal: "SIGKILL", maxBuffer: BINDING_LIMITS.maxBytes, stdio: ["pipe", "pipe", "pipe"] });
443
+ if (r.error || r.signal) return { failure: "incomplete", timedOut: r.error?.code === "ETIMEDOUT", signal: r.signal ?? null, overflow: r.error?.code === "ENOBUFS" };
444
+ if (r.status !== 0) return { failure: "exit", status: r.status };
445
+ try { return { doc: parseStrictJson(r.stdout || "", BINDING_LIMITS) }; } catch { return { failure: "invalid" }; }
446
+ }
404
447
  /** The four check statuses of the binding wire, and what each means for readiness. */
405
448
  const PROVIDER_STATUS_ITEM = Object.freeze({ ready: "pass", "needs-configuration": "fail", "authorization-required": "fail", unavailable: "unknown" });
406
449
  const ENVELOPE_KEYS = ["schemaVersion", "phase", "slot", "capability", "ok"];
@@ -415,27 +458,23 @@ const codeMessages = (p) => p.map((x) => ({ code: x.code, message: x.message }))
415
458
  * are the provider's own (not checked against binding.reasons, which are refusal
416
459
  * sentences); problems and the optional warnings must be {code, message} strings. */
417
460
  export function runProviderCheck(t, mod, dir, { timeoutMs = 30000 } = {}) {
418
- const m = mod.manifest, check = m?.binding?.check, spec = check ? m.commands?.[check] : null;
461
+ const m = mod.manifest, check = m?.binding?.check;
419
462
  const unavailable = (code, message) => ({ outcome: "unknown", problems: [{ code, message }] });
420
- if (typeof spec !== "string" || !spec.trim()) return unavailable("provider-not-qualified", `${mod.name} declares binding.check but no command ${JSON.stringify(check)}`);
421
- const [script, ...args] = spec.trim().split(/\s+/);
422
- const file = dir ? moduleExecutable(dir, script) : null;
423
- if (!file) return unavailable("resource-not-found", `${mod.name}: the check executable ${script} is unavailable`);
424
463
  const settings = obj(t.payloads[mod.name]) ? t.payloads[mod.name] : {};
425
464
  // The released binding wire, key for key: providers decode it strictly (oats.aweb 1.13.1
426
465
  // refuses any other key). The teams reach the check through its environment
427
466
  // (OATS_DEFAULT_TEAM* / OATS_TEAMS / OATS_TEAMS_SOURCE, providerEnv), never on stdin.
428
467
  const request = { schemaVersion: 1, phase: "check", slot: m.layer ?? null, capability: mod.name, settings,
429
468
  input: { context: { kind: "workspace", workspace: t.workspace.key, deployment: t.deployment, soul: t.soul.name, instance: t.meta?.instance ?? null, home: t.home }, action: { kind: "readiness" } } };
430
- // The environment is providerEnv's: ambient OATS_/OAS_/PI_ identity removed, the rest
431
- // inherited.
432
- const r = spawnSync(process.execPath, [file, ...args], { cwd: dir, env: providerEnv(t, mod.name, settings), input: JSON.stringify(request), encoding: "utf8", timeout: Math.max(1, timeoutMs), killSignal: "SIGKILL", maxBuffer: BINDING_LIMITS.maxBytes, stdio: ["pipe", "pipe", "pipe"] });
433
- if (r.error || r.signal) return unavailable("provider-unavailable", `${mod.name} check did not complete${r.error?.code === "ETIMEDOUT" || r.signal ? " in time" : ""}`);
434
- if (r.status !== 0) return unavailable("provider-unavailable", `${mod.name} check exited ${r.status}`);
469
+ const run = runModuleCommand(t, mod, dir, check, request, { timeoutMs });
470
+ if (run.failure === "no-command") return unavailable("provider-not-qualified", `${mod.name} declares binding.check but no command ${JSON.stringify(check)}`);
471
+ if (run.failure === "no-executable") return unavailable("resource-not-found", `${mod.name}: the check executable ${run.script} is unavailable`);
472
+ if (run.failure === "incomplete") return unavailable("provider-unavailable", `${mod.name} check did not complete${run.timedOut || run.signal ? " in time" : ""}`);
473
+ if (run.failure === "exit") return unavailable("provider-unavailable", `${mod.name} check exited ${run.status}`);
435
474
  const invalid = () => unavailable("provider-unavailable", `${mod.name} check answered invalid binding data`);
436
- let doc;
475
+ if (run.failure === "invalid") return invalid();
476
+ const doc = run.doc;
437
477
  try {
438
- doc = parseStrictJson(r.stdout || "", BINDING_LIMITS);
439
478
  if (!obj(doc)) return invalid();
440
479
  const allowed = [...ENVELOPE_KEYS, doc.ok === true ? "result" : "error"];
441
480
  if (Object.keys(doc).some((k) => !allowed.includes(k)) || allowed.some((k) => !Object.hasOwn(doc, k))) return invalid();
@@ -573,7 +612,8 @@ export async function readinessDocument(t, { selector = null, remoteOptions, cat
573
612
  pass: requiredStatuses.filter((s) => s === "pass").length, fail: requiredStatuses.filter((s) => s === "fail").length, unknown: requiredStatuses.filter((s) => s === "unknown").length, byCapability, subjectBlockers },
574
613
  notes: ["ready means every REQUIRED check passes; it is never inferred from an empty set",
575
614
  "member is the soul's member repository confirmed in the workspace (oats-membership.yaml), never login or team registration",
576
- "providers relays each provider's own binding check verbatim; the spawn's fail-closed hooks are unchanged"] };
615
+ "providers relays each provider's own binding check verbatim; the spawn's fail-closed hooks are unchanged"],
616
+ warnings: targetWarnings(t) };
577
617
  }
578
618
 
579
619
  /** Enforced policy for an instance (from its recorded metadata) or a soul
@@ -10,7 +10,7 @@
10
10
  import { createHash } from "node:crypto";
11
11
  import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
12
  import { basename, join } from "node:path";
13
- import { extraWorktreePlan, findInstanceHomes, inspectInstanceSession, listAgents, listInstances, observeSessionWithoutReceipt, retirePendingMarkerPath, retirementRecoveryFacts, stopInstanceSession } from "./core.mjs";
13
+ import { attachedWorkLink, extraWorktreePlan, findInstanceHomes, inspectInstanceSession, listAgents, listInstances, observeSessionWithoutReceipt, retirePendingMarkerPath, retirementRecoveryFacts, stopInstanceSession } 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";
@@ -165,12 +165,89 @@ function writeFileSyncAtomic(path, value) {
165
165
  writeFileSync(tmp, JSON.stringify(value, null, 2)); renameSync(tmp, path);
166
166
  }
167
167
 
168
- /** A retire plan's note for one extra tree (core extraWorktreePlan row). */
168
+ /** What the Desktop reads of a plan's notes (packages/desktop/renderer/lifecycle-contract.mjs): at
169
+ * most 64, each at most 4096 characters; it refuses a plan with more, so every note is built to fit
170
+ * (#658). A path is never cut: what does not fit is left to the plan JSON or the receipt. */
171
+ const PLAN_NOTES_MAX = 64;
172
+ const PLAN_NOTE_MAX = 4096;
173
+ /** The characters a note spends listing names (declared roots, attached children) before `, and N more`. */
174
+ const PLAN_LIST_BUDGET = 1024;
175
+ const SEE_EXTRA = "facts.extraWorktrees in the plan JSON";
176
+ /** The first `max` of `items` that fit `budget` characters as `render(shown)`, the rest counted as
177
+ * `, and N more`. → the text, or null when not even one fits. */
178
+ function listWithin(items, render, budget, max = items.length) {
179
+ for (let n = Math.min(items.length, max); n > 0; n--) {
180
+ const text = `${render(items.slice(0, n))}${n < items.length ? `, and ${items.length - n} more` : ""}`;
181
+ if (text.length <= budget) return text;
182
+ }
183
+ return null;
184
+ }
185
+
186
+ /** `render(parts)` within PLAN_NOTE_MAX: `parts` maps each name to [its full text, a pointer to where
187
+ * the plan JSON holds it]; while the note is too long, the longest part that a pointer shortens is
188
+ * replaced by it. → the note, or null when it still does not fit. */
189
+ function fitParts(render, parts) {
190
+ const shown = Object.fromEntries(Object.entries(parts).map(([key, [full]]) => [key, full]));
191
+ let note = render(shown);
192
+ for (const key of Object.keys(parts).sort((a, b) => String(parts[b][0]).length - String(parts[a][0]).length)) {
193
+ if (note.length <= PLAN_NOTE_MAX) return note;
194
+ if (String(parts[key][0]).length <= parts[key][1].length) continue; // the pointer would not shorten it
195
+ shown[key] = parts[key][1];
196
+ note = render(shown);
197
+ }
198
+ return note.length <= PLAN_NOTE_MAX ? note : null;
199
+ }
200
+
201
+ /** A retire plan's note for one extra tree (core extraWorktreePlan row). Too long for the Desktop, its
202
+ * longest parts go to the plan JSON, longest first; the tree's path stays whole, or the note says it
203
+ * is too long and where it is. */
169
204
  function extraWorktreeNote(t) {
170
- const at = t.branch ? `branch ${t.branch}` : t.detachedAt ? `detached at ${t.detachedAt.slice(0, 12)}` : "a HEAD that could not be read";
171
- if (t.disposition === "remove") return `extra worktree ${t.path} (${at}) is clean and would be removed; its branch and commits stay in ${t.repo}`;
172
- if (t.disposition === "retain") return `extra worktree ${t.path} (${at}) would be re-homed to ${t.movedTo}: ${t.reason}`;
173
- return `extra worktree ${t.path} (${at}): retire refuses, ${t.reason}`;
205
+ const parts = {
206
+ at: [t.branch ? `branch ${t.branch}` : t.detachedAt ? `detached at ${t.detachedAt.slice(0, 12)}` : "a HEAD that could not be read", `its HEAD: see ${SEE_EXTRA}`],
207
+ repo: [t.repo, `its repository (see ${SEE_EXTRA})`],
208
+ movedTo: [t.movedTo, `the path ${SEE_EXTRA} names`],
209
+ reason: [t.reason, `${SEE_EXTRA} says why`],
210
+ };
211
+ const render = (p) => t.disposition === "remove" ? `extra worktree ${t.path} (${p.at}) is clean and would be removed; its branch and commits stay in ${p.repo}`
212
+ : t.disposition === "retain" ? `extra worktree ${t.path} (${p.at}) would be re-homed to ${p.movedTo}: ${p.reason}`
213
+ : `extra worktree ${t.path} (${p.at}): retire refuses, ${p.reason}`;
214
+ const note = fitParts(render, parts);
215
+ if (note !== null) return note;
216
+ const outcome = t.disposition === "remove" ? "would be removed" : t.disposition === "retain" ? "would be re-homed" : "makes retire refuse";
217
+ return `an extra worktree whose path is too long for this note ${outcome}; ${SEE_EXTRA} lists it`;
218
+ }
219
+ /** The plan's note when the worktree is not on the recorded branch: both names, or, too long for the
220
+ * note, pointers to the plan JSON fields that hold them. */
221
+ function driftNote(work, recordedBranch) {
222
+ const on = work.branch ?? (work.detached ? "a detached HEAD" : "a ref OATS carries no branch name for");
223
+ return fitParts((p) => `the worktree is on ${p.on}, not the recorded ${p.recorded}`, {
224
+ on: [on, "the branch facts.work.branch in the plan JSON names"],
225
+ recorded: [recordedBranch, "branch, which facts.recordedBranch in the plan JSON names"],
226
+ }) ?? "the worktree is not on the recorded branch; facts.work.branch and facts.recordedBranch in the plan JSON name both";
227
+ }
228
+ /** The plan's note on a home without its session receipt: the observation's reason, or, too long
229
+ * for the note (a process's command line, a tmux error), a pointer to facts.session.note. */
230
+ function sessionNote(session) {
231
+ const [head, tail] = session.established ? ["session absent", "nothing needs quiescing"] : ["session not observably absent", "retire refuses until it is stopped"];
232
+ const note = `${head}: ${session.note}; ${tail}`;
233
+ return note.length <= PLAN_NOTE_MAX ? note : `${head}: the reason is too long for this note (facts.session.note in the plan JSON); ${tail}`;
234
+ }
235
+ /** The plan's recovery note: where a recovery would be written, and the declared roots it leaves
236
+ * out, listed within PLAN_LIST_BUDGET (at most 16). A recovery path too long for the note is named
237
+ * by where to find it instead. */
238
+ function recoveryNote(recovery) {
239
+ const roots = recovery.disposableHome;
240
+ const notCopied = (head) => {
241
+ if (!roots.length) return "";
242
+ const room = Math.min(PLAN_LIST_BUDGET, PLAN_NOTE_MAX - head.length - "; not copied: ".length);
243
+ const listed = room > 0 ? listWithin(roots, (shown) => groupedByOwner(shown, "root"), room, PLAN_NOT_COPIED_CAP) : null;
244
+ return `; not copied: ${listed ?? `${roots.length} declared root${roots.length === 1 ? "" : "s"}, too long to list here`}`;
245
+ };
246
+ const head = `recovery: the home is copied to ${recovery.recoveryRoot} before the home is removed, when it changed since spawn`;
247
+ const note = `${head}${notCopied(head)}`;
248
+ if (note.length <= PLAN_NOTE_MAX) return note;
249
+ const elsewhere = "recovery: the home is copied to the recovery directory beside the home before the home is removed, when it changed since spawn (its path is too long for this note: the retire receipt names it as workRecovery.path, and the retire summary prints it)";
250
+ return `${elsewhere}${notCopied(elsewhere)}`;
174
251
  }
175
252
  /** How many declared roots a retire plan's recovery note lists before `, and N more`. */
176
253
  const PLAN_NOT_COPIED_CAP = 16;
@@ -189,7 +266,8 @@ export function planRetire(ctx, root, name, { home } = {}) {
189
266
  // into the revision (below), so that an apply refuses as stale when a tree
190
267
  // was created, removed, dirtied or cleaned, or its target was taken.
191
268
  const extraWorktrees = extraWorktreePlan(me.home, me.root);
192
- const facts = { session: target.session, work: target.work, workMode: meta.work ?? null, repo: meta.repo ?? null, recordedBranch: meta.branch ?? null,
269
+ // A home spawned before #641 may record the word "HEAD" for a detached checkout: not a branch name.
270
+ const facts = { session: target.session, work: target.work, workMode: meta.work ?? null, repo: meta.repo ?? null, recordedBranch: meta.branch === "HEAD" ? null : meta.branch ?? null,
193
271
  extraWorktrees,
194
272
  children: kids.map((c) => ({ instance: c.instance, agent: c.agent, home: c.home, session: sessionFacts(c.home) })),
195
273
  ambiguous: (kids.ambiguous || []).map((c) => ({ instance: c.instance, agent: c.agent, home: c.home, reason: c.reason })),
@@ -200,21 +278,33 @@ export function planRetire(ctx, root, name, { home } = {}) {
200
278
  ...(extraWorktrees.length ? [extraWorktrees] : [])];
201
279
  // What retire would preserve and where, read from the spawn baseline and the
202
280
  // work mode: nothing is hashed, and the plan revision does not depend on it.
203
- // The declared roots are listed as written, capped so one note stays short.
281
+ // The declared roots are listed as written, bounded so one note stays short.
204
282
  const recovery = retirementRecoveryFacts(me.home);
205
- const declared = recovery.disposableHome.slice(0, PLAN_NOT_COPIED_CAP);
206
- const notCopied = declared.length ? `; not copied: ${groupedByOwner(declared, "root")}${recovery.disposableHome.length > declared.length ? `, and ${recovery.disposableHome.length - declared.length} more` : ""}` : "";
283
+ // Attached children whose work is this home's work/ (#718): a retire that keeps the worktree
284
+ // repoints them to it. One note holds whatever the dialog then picks.
285
+ const attached = meta.work === "worktree" ? kids.filter((c) => attachedWorkLink(c.home, me.home) !== null) : [];
207
286
  appendEvent(me.home, { kind: "retire-planned", data: { planRevision: planRevision(safety), children: kids.length, dirty: facts.work.observed ? facts.work.changed + facts.work.untracked : null } }, { workspaceOnly: true });
208
287
  return { lifecycleApi: LIFECYCLE_API, action: "retire", instance: name, home: me.home, at: new Date().toISOString(), facts, defaults, planRevision: planRevision(safety),
209
- notes: [
210
- ...(facts.work.observed && facts.work.drift ? [`the worktree is on ${facts.work.branch ?? (facts.work.detached ? "a detached HEAD" : "a ref OATS carries no branch name for")}, not the recorded ${facts.recordedBranch}`] : []),
288
+ notes: boundedNotes(extraWorktrees.map(extraWorktreeNote), [
289
+ ...(facts.work.observed && facts.work.drift ? [driftNote(facts.work, facts.recordedBranch)] : []),
211
290
  ...(facts.work.observed && facts.work.changed + facts.work.untracked > 0 ? [`${facts.work.changed} changed and ${facts.work.untracked} untracked file(s) would be retained with the worktree`] : []),
212
- ...extraWorktrees.map(extraWorktreeNote),
291
+ ], [
213
292
  ...(kids.length ? [`${kids.length} recorded child instance(s) are stopped first (bounded SIGTERM, never escalated) and retained (their homes are not removed); a child still running after the grace refuses the retirement`] : []),
293
+ ...(attached.length ? [`attached child instance(s) ${listWithin(attached.map((c) => c.instance), (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? attached.length} use this home's work/ as their work: a retire that keeps the worktree repoints their work link to it; with --discard-worktree the worktree is removed and their work link will dangle`] : []),
214
294
  ...((kids.ambiguous || []).length ? [`${kids.ambiguous.length} instance(s) record this name as parent but the name is not unique under this root; they are listed under ambiguous and NOT acted on`] : []),
215
- ...(target.session.note ? [target.session.established ? `session absent: ${target.session.note}; nothing needs quiescing` : `session not observably absent: ${target.session.note}; retire refuses until it is stopped`] : []),
295
+ ...(target.session.note ? [sessionNote(target.session)] : []),
216
296
  "pull request state is unknown to the kernel; the ADE reports it when a forge connection exists",
217
- `recovery: the home is copied to ${recovery.recoveryRoot} before the home is removed, when it changed since spawn${notCopied}`,
297
+ recoveryNote(recovery),
218
298
  ...(meta.work === "worktree" ? ["recovery: uncommitted worktree state is copied there too"] : meta.work === "directory" ? ["recovery: work/ is copied there when it is not empty"] : []),
219
- ] };
299
+ ]) };
300
+ }
301
+
302
+ /** A retire plan's notes in order: `before`, one per extra tree, `after`. The extra trees are the
303
+ * only notes without a fixed count: past PLAN_NOTES_MAX the last one kept counts the rest. Each note
304
+ * is built to fit PLAN_NOTE_MAX; one that still does not (a new note that forgot to) is replaced
305
+ * rather than let the Desktop refuse the whole plan. */
306
+ function boundedNotes(trees, before, after) {
307
+ const room = PLAN_NOTES_MAX - before.length - after.length;
308
+ const shown = trees.length <= room ? trees : [...trees.slice(0, room - 1), `and ${trees.length - room + 1} more extra worktrees (${SEE_EXTRA} lists every one)`];
309
+ return [...before, ...shown, ...after].map((note) => note.length <= PLAN_NOTE_MAX ? note : "a note too long for this plan was left out; the plan JSON's facts hold what it said");
220
310
  }
@@ -23,7 +23,7 @@ import { loadLocal, discoverWorkspace, discoverRepo, standaloneRepo, observeWork
23
23
  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
- import { declaredSettings } from "./capability-contract.mjs";
26
+ import { APPROVED_HOOKS, declaredSettings, locatedContractWarnings } from "./capability-contract.mjs";
27
27
  import { materialize, moduleSkills, MODULES_DIR, 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";
@@ -351,7 +351,7 @@ export function conventionCloneDir(deployment, key) {
351
351
  * (`github.com/org/repo`), or any ref form parseRepoRef understands (`git:…`,
352
352
  * `https://…`, `git@host:…`, `/abs/bare.git`) — to the canonical key. A key that
353
353
  * parses no way is returned as written (it can then only match literally). */
354
- function canonicalCloneKey(written) {
354
+ export function canonicalCloneKey(written) {
355
355
  const s = String(written).trim();
356
356
  if (s.startsWith("local/")) return s; // a local key is already canonical
357
357
  for (const candidate of [s, `git:${s}`]) {
@@ -643,10 +643,22 @@ export function toCapabilityRows(resolution, home) {
643
643
  return rows;
644
644
  }
645
645
 
646
+ /** A resolution's contract warnings (an unknown, non-required hook event): its modules'
647
+ * [{ code, capability, path, message }] by module name (as a replayed spawn reads them from the home),
648
+ * each module's manifest where it was read (`<repoKey>:<dir>/oats.json`, a package's
649
+ * `package:<id>:<dir>/oats.json`). */
650
+ export function resolutionContractWarnings(resolution) {
651
+ return [...(resolution?.modules || [])].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)).flatMap((m) => locatedContractWarnings(m.manifest,
652
+ m.from?.kind === "package" ? `package:${m.from.package}:${m.dir}/oats.json` : `${m.from?.repoKey}:${m.dir}/oats.json`));
653
+ }
654
+
655
+ /** The hooks a row carries: the events this kernel runs. An unknown event (a newer
656
+ * kernel's, accepted with a warning by the manifest contract) never reaches a row. */
646
657
  function hookCommandsOf(manifest, dir) {
647
658
  const out = {};
648
659
  const hooks = manifest.hooks && typeof manifest.hooks === "object" ? manifest.hooks : {};
649
660
  for (const [event, spec] of Object.entries(hooks)) {
661
+ if (!APPROVED_HOOKS.has(event)) continue;
650
662
  const cmd = typeof spec === "string" ? spec : spec?.command;
651
663
  if (typeof cmd === "string" && cmd) out[event] = { command: cmd, cwd: dir, required: spec?.required === true };
652
664
  }
@@ -654,7 +666,7 @@ function hookCommandsOf(manifest, dir) {
654
666
  }
655
667
  function requiredHooksOf(manifest) {
656
668
  const hooks = manifest.hooks && typeof manifest.hooks === "object" ? manifest.hooks : {};
657
- return Object.entries(hooks).filter(([, s]) => s && typeof s === "object" && s.required === true).map(([e]) => e);
669
+ return Object.entries(hooks).filter(([e, s]) => APPROVED_HOOKS.has(e) && s && typeof s === "object" && s.required === true).map(([e]) => e);
658
670
  }
659
671
 
660
672
  /** What a preview shows about modules: from/commit/digest per module, whether
@@ -2,6 +2,7 @@
2
2
  import { lstatSync, realpathSync, statSync } from "node:fs";
3
3
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { oatsError } from "./errors.mjs";
5
+ import { canonicalHomePath } from "./real-path.mjs";
5
6
 
6
7
  const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7
8
  const pointer = (value) => value.replace(/~/g, "~0").replace(/\//g, "~1");
@@ -54,6 +55,18 @@ export function launchPromptPolicyProblems(policy) {
54
55
  return problems;
55
56
  }
56
57
 
58
+ /** The configured key that names `home`: the key spelled exactly as `home`, else the one key that
59
+ * names the same directory in its on-disk spelling (on a case-insensitive filesystem a key may be
60
+ * written in another letter case and still be valid). Several such keys and no exact one decide
61
+ * nothing: no consent. */
62
+ function consentKey(homes, home) {
63
+ if (!homes) return undefined;
64
+ if (Object.hasOwn(homes, home)) return home;
65
+ const onDisk = canonicalHomePath(home);
66
+ const same = Object.keys(homes).filter((key) => canonicalHomePath(key) === onDisk);
67
+ return same.length === 1 ? same[0] : undefined;
68
+ }
69
+
57
70
  /** Exact-home consent + config JSON-pointer provenance for previews/controllers.
58
71
  * Call again after home creation; the controller must separately retain and
59
72
  * recheck directory identity before each input. No captured policy is authority. */
@@ -64,10 +77,11 @@ export function effectiveLaunchPromptPolicy(local, home, source) {
64
77
  if (problems.length) throw oatsError("E_WORKSPACE_SCHEMA", `invalid launchPromptAnswers: ${problems.map((p) => `${p.path}: ${p.message}`).join("; ")}`, { problems });
65
78
  try { canonicalLaunchPromptHome(home); } catch { return disabled; }
66
79
  const homes = local.launchPromptAnswers.homes;
67
- if (!homes || !Object.hasOwn(homes, home)) return disabled;
68
- const consent = homes[home];
80
+ const key = consentKey(homes, home);
81
+ if (key === undefined) return disabled;
82
+ const consent = homes[key];
69
83
  return {
70
84
  awebDevelopmentChannel: consent.awebDevelopmentChannel === true,
71
- consentSource: typeof source === "string" && source.length ? `${source}#${root}/homes/${pointer(home)}` : null,
85
+ consentSource: typeof source === "string" && source.length ? `${source}#${root}/homes/${pointer(key)}` : null,
72
86
  };
73
87
  }
package/lib/packages.mjs CHANGED
@@ -344,6 +344,7 @@ async function readPackageManifestsAt(remote, remoteRef, commit, path, details)
344
344
  if (seen.has(capManifest.capability)) {
345
345
  throw oatsError("E_PACKAGE_MANIFEST", `package ${manifest.package} declares capability ${JSON.stringify(capManifest.capability)} twice (${seen.get(capManifest.capability)} and ${dir})`, { ...details, path: dir, duplicate: capManifest.capability, other: seen.get(capManifest.capability) });
346
346
  }
347
+ // What it declares and this kernel ignores (an unknown hook event) is its readers' warning, not a refusal.
347
348
  const [problem] = manifestContractProblems(capManifest);
348
349
  if (problem) throw oatsError("E_PACKAGE_MANIFEST", `${pjoin(dir, CAPABILITY_MANIFEST)}#${problem.pointer}: ${problem.message}`, { ...details, path: dir, capability: capManifest.capability, pointer: problem.pointer });
349
350
  seen.set(capManifest.capability, dir);
@@ -0,0 +1,27 @@
1
+ // The real path of a location that may not exist yet, in the caller's spelling or the one on disk.
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+
5
+ /** realpath of `p`, or — when `p` does not exist yet — the realpath of its
6
+ * nearest existing ancestor with the remaining segments re-appended. Any path
7
+ * decision about WHERE something will be created has to go through this: a
8
+ * lexical path says nothing about the destination once a symlink sits anywhere
9
+ * along it. */
10
+ export function realPathOrNearest(p) {
11
+ return nearestRealPath(p, realpathSync);
12
+ }
13
+ /** realPathOrNearest with the operating system's realpath: the one spelling of a path. On a
14
+ * case-insensitive filesystem (APFS, the macOS default) JS realpathSync keeps the caller's
15
+ * letter case, so `.../agents/x` and `.../Agents/x` (one directory) come back as two strings;
16
+ * realpathSync.native returns each existing component as it is on disk. On a case-sensitive
17
+ * filesystem the two agree: two spellings are two directories, and this changes nothing. (On
18
+ * APFS it can also return a name's on-disk Unicode normalization.) */
19
+ export function canonicalHomePath(p) {
20
+ return nearestRealPath(p, realpathSync.native);
21
+ }
22
+ function nearestRealPath(p, realpath) {
23
+ try { return realpath(p); } catch { /* not created yet — resolve what exists */ }
24
+ let d = resolve(p); const tail = [];
25
+ while (!existsSync(d) && dirname(d) !== d) { tail.unshift(basename(d)); d = dirname(d); }
26
+ try { return join(realpath(d), ...tail); } catch { return resolve(p); }
27
+ }
@@ -0,0 +1,17 @@
1
+ /** The characters the kernel never stores or prints in text it did not write itself (the
2
+ * maintainer's set): control characters (Cc: C0, DEL, C1), the Unicode line and paragraph
3
+ * separators, the bidi embeddings, overrides and isolates (U+202A-202E, U+2066-2069), the
4
+ * invisible hiders U+200B, U+2060 and U+FEFF, and the tag characters (U+E0000-E007F).
5
+ * Everything else is allowed, ZWJ and ZWNJ (U+200C/D, emoji sequences, Persian and Indic text)
6
+ * and the marks LRM, RLM and ALM (U+200E/F, U+061C) included. One set for the kernel: a waiting
7
+ * claim's message (lib/instance-events.mjs) refuses it, a trigger source's text
8
+ * (lib/triggers.mjs) has it replaced. The Desktop keeps its own identical copy. */
9
+ export const REFUSED_TEXT = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069\u200B\u2060\uFEFF\u{E0000}-\u{E007F}]/u;
10
+ const REFUSED_TEXT_ALL = new RegExp(REFUSED_TEXT.source, "gu");
11
+
12
+ /** Text from outside the kernel, made safe to store and print: every REFUSED_TEXT character
13
+ * replaced with U+FFFD, then cut to `max` code points, ending in `…` when cut. */
14
+ export function safeText(text, max) {
15
+ const points = [...String(text).replace(REFUSED_TEXT_ALL, "\uFFFD")];
16
+ return points.length > max ? `${points.slice(0, max - 1).join("")}…` : points.join("");
17
+ }
package/lib/resolve.mjs CHANGED
@@ -59,7 +59,7 @@ import { oatsError as baseOatsError } from "./errors.mjs";
59
59
  import * as defaultRemote from "./remote.mjs";
60
60
  import { BY_TEAM_REMOVED, reportRows, soulTeams, teamKeyOf, teamModel } from "./teams.mjs";
61
61
  import { bindRemote, packageProviding, readPackageManifests, validateLock } from "./packages.mjs";
62
- import { settingValueProblems } from "./capability-contract.mjs";
62
+ import { APPROVED_HOOKS, settingValueProblems } from "./capability-contract.mjs";
63
63
  import { memberRowByKey } from "./workspace.mjs";
64
64
 
65
65
  export const RESOLUTION_API = 1;
@@ -539,12 +539,12 @@ async function enumerateSkills({ remote, ref, commit, dir, manifest, listing, mo
539
539
  }
540
540
 
541
541
  /** What a capability provides, by name (feature desktop-facts): its skills (enumerated exactly as a spawn
542
- * would), commands and hooks. `skills` is null when its declared skills cannot be listed (a spawn of it
543
- * would refuse; the listing does not). */
542
+ * would), commands and hooks (the events this kernel runs: an unknown one never runs here). `skills` is
543
+ * null when its declared skills cannot be listed (a spawn of it would refuse; the listing does not). */
544
544
  export async function capabilityProvides({ ref, commit, dir, manifest, remote: injected, remoteOptions }) {
545
545
  const keys = (o) => (isObject(o) ? Object.keys(o).sort(byCodepoint) : []);
546
546
  const { skills } = await capabilitySkills({ ref, commit, dir, manifest, remote: injected, remoteOptions });
547
- return { skills: skills && skills.map((s) => s.name), commands: keys(manifest.commands), hooks: keys(manifest.hooks) };
547
+ return { skills: skills && skills.map((s) => s.name), commands: keys(manifest.commands), hooks: keys(manifest.hooks).filter((event) => APPROVED_HOOKS.has(event)) };
548
548
  }
549
549
 
550
550
  /** A capability's skills as a spawn enumerates them (enumerateSkills), sorted by name in codepoint order: