@awebai/oats 0.69.12 → 0.69.15

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 (92) hide show
  1. package/README.md +216 -178
  2. package/bin/oats.mjs +254 -201
  3. package/docs/capabilities.md +58 -13
  4. package/docs/configuration.md +63 -5
  5. package/docs/container.md +291 -0
  6. package/docs/design/2026-09-23-workspace-module-contracts.md +2 -0
  7. package/docs/desktop-cli-api.md +590 -55
  8. package/docs/desktop-instance-start.md +4 -1
  9. package/docs/desktop.md +58 -12
  10. package/docs/execution-targets.md +84 -9
  11. package/docs/first-team.md +4 -3
  12. package/docs/implementation.md +99 -32
  13. package/docs/integrations.md +3 -2
  14. package/docs/knowledge-and-learning.md +72 -0
  15. package/docs/oats-local.schema.json +11 -2
  16. package/docs/official-catalog.md +39 -5
  17. package/docs/packages.md +93 -14
  18. package/docs/release-lane.md +2 -1
  19. package/docs/release-notes/v0.69.13.md +767 -0
  20. package/docs/release-notes/v0.69.14.md +83 -0
  21. package/docs/release-notes/v0.69.15.md +444 -0
  22. package/docs/schedules.md +159 -5
  23. package/docs/servers.md +241 -7
  24. package/docs/souls-and-instances.md +223 -14
  25. package/docs/tui.md +1 -1
  26. package/docs/upgrading.md +36 -5
  27. package/docs/workspaces.md +31 -5
  28. package/lib/claim.mjs +20 -5
  29. package/lib/command-flags.mjs +240 -0
  30. package/lib/core.mjs +1004 -633
  31. package/lib/deployments.mjs +4 -3
  32. package/lib/dir-lock.mjs +145 -33
  33. package/lib/errors.mjs +3 -2
  34. package/lib/harness-token.mjs +110 -0
  35. package/lib/host-run.mjs +218 -0
  36. package/lib/host-stop-child.mjs +21 -0
  37. package/lib/hot-reads.mjs +4 -3
  38. package/lib/instance-events.mjs +28 -6
  39. package/lib/instance-git.mjs +165 -14
  40. package/lib/instance-inspect.mjs +6 -1
  41. package/lib/instance-lifecycle.mjs +4 -3
  42. package/lib/instance-listing.mjs +114 -43
  43. package/lib/instance-resolution.mjs +56 -3
  44. package/lib/instance-upgrade.mjs +16 -20
  45. package/lib/kernel-features.mjs +4 -1
  46. package/lib/launch-env-exec.sh +7 -0
  47. package/lib/launch-env.mjs +74 -0
  48. package/lib/launch-preference.mjs +19 -12
  49. package/lib/member-clone.mjs +7 -1
  50. package/lib/packages.mjs +74 -2
  51. package/lib/read-call.mjs +4 -1
  52. package/lib/reader.mjs +3 -2
  53. package/lib/refused-text.mjs +3 -2
  54. package/lib/remote.mjs +126 -31
  55. package/lib/retained-after-retire.mjs +2 -7
  56. package/lib/retire-git-forms.mjs +41 -0
  57. package/lib/retire-incomplete.mjs +96 -0
  58. package/lib/schedule.mjs +239 -21
  59. package/lib/servers.mjs +161 -28
  60. package/lib/session-end.mjs +28 -8
  61. package/lib/session-resume.mjs +63 -56
  62. package/lib/session-seen.mjs +3 -14
  63. package/lib/start-env.mjs +13 -7
  64. package/lib/status-words.mjs +11 -4
  65. package/lib/system-tools.mjs +1 -36
  66. package/lib/teams.mjs +11 -4
  67. package/lib/upgrade-state.mjs +13 -2
  68. package/lib/worktree-hooks.mjs +6 -175
  69. package/lib/worktree.mjs +68 -10
  70. package/package-catalog.json +1 -1
  71. package/package.json +5 -1
  72. package/packages/client/instance-lifecycle.mjs +1 -1
  73. package/packages/client/lifecycle-contract.mjs +3 -1
  74. package/packages/client/session-resume-cli.mjs +2 -1
  75. package/packages/client/session-start.mjs +10 -7
  76. package/packages/client/workspace-cli.mjs +5 -1
  77. package/packages/record/README.md +56 -21
  78. package/packages/record/docs/capture-service.md +8 -5
  79. package/packages/record/docs/turn-record-sot.md +9 -0
  80. package/packages/record/lib/capture-health.mjs +6 -4
  81. package/packages/record/lib/capture-lock.mjs +31 -27
  82. package/packages/record/lib/capture-retained-scratch.mjs +4 -3
  83. package/packages/record/lib/capture-scratch.mjs +2 -1
  84. package/packages/record/lib/derived-state.mjs +4 -2
  85. package/packages/record/lib/index-db.mjs +4 -2
  86. package/packages/record/lib/lock-holder.mjs +21 -0
  87. package/packages/record/lib/private-files.mjs +18 -0
  88. package/packages/record/lib/process-identity.mjs +310 -0
  89. package/packages/record/lib/store.mjs +31 -25
  90. package/share/oats-login-receive +204 -0
  91. package/skills/oats-getting-started/SKILL.md +93 -26
  92. package/lib/tmux-config.mjs +0 -35
@@ -19,16 +19,16 @@
19
19
  import { existsSync, readFileSync, readdirSync, lstatSync, readlinkSync, realpathSync } from "node:fs";
20
20
  import { join, resolve as resolvePath, dirname, relative, isAbsolute, sep } from "node:path";
21
21
  import { loadLocal, observeWorkspace } from "./workspace.mjs";
22
- import { resolveSoul, kernelCompatibility } from "./resolve.mjs";
22
+ import { resolveSoul, kernelCompatibility, packageRef } from "./resolve.mjs";
23
23
  import { BY_TEAM_REMOVED, isRemovedTeamKeys, isTeamRefusal, memberNameOf, recordedTeams, reportRows, soulKeyOf, soulTeams, teamKeyOf, teamModel } from "./teams.mjs";
24
- import { launchLayers } from "./launch-preference.mjs";
24
+ import { LOCAL_FILE, launchLayers, nearestSoulKeys } from "./launch-preference.mjs";
25
25
  import { APPROVED_HOOKS, declaredSettings, locatedContractWarnings } from "./capability-contract.mjs";
26
26
  import { materialize, moduleSkills, MODULES_DIR, plannedModuleSkills, SKILLS_DIR } from "./materialize.mjs";
27
27
  import { contentDigest, fetchRemoteTree } from "./remote.mjs";
28
28
  import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync, symlinkSync } from "node:fs";
29
29
  import { tmpdir } from "node:os";
30
30
  import { randomBytes } from "node:crypto";
31
- import { readLockIfPresent, SOUL_ALIAS_SYMLINK } from "./packages.mjs";
31
+ import { readLockIfPresent, SOUL_ALIAS_SYMLINK, verifyLockedPackage } from "./packages.mjs";
32
32
  import { parseRepoRef } from "./remote.mjs";
33
33
  import { cloneRemotes, conventionCloneDir, discoverOrStandalone, err, resolveMemberClone, sameRepoKey } from "./member-clone.mjs";
34
34
  import { sameRepo } from "./repo-moves.mjs";
@@ -217,6 +217,44 @@ export function disabledEntry(local, soulEntry) {
217
217
  return list.find((d) => d === soulEntry.name || d === qualified) ?? null;
218
218
  }
219
219
 
220
+ /**
221
+ * THE function that decides which entries of oats-local.yaml souls.disabled name no soul
222
+ * (oats-project/oats#1772): every reader asks it and none computes the answer itself. Such an entry
223
+ * keeps nothing off this machine, so the soul it was meant for spawns again: it fails open.
224
+ * `local` is the oats-local.yaml value; `discovery` one read of the workspace.
225
+ * MATCHED: disabledEntry holds for at least one offered soul (soulCandidates; a soul in
226
+ * souls.disabled is still offered). Spawn's own rule, not findSoulEntry's looser one (key
227
+ * suffixes, external sources): an entry a spawn would not match is not matched.
228
+ * UNCHECKED: it matches nothing, and the source that could hold its soul was not read (soulsOffered's
229
+ * `unread`, the reasons of the souls.launch check): every entry under `all`; an entry under a
230
+ * package of `unread.packages` for that package's reason; an entry under the package of an
231
+ * offered package soul is checked whatever a member left unread; any other (a bare name,
232
+ * `<member>/<soul>`, or a prefix that is neither, which may be a member's name) under `bare`.
233
+ * UNMATCHED: every other entry, with at most three qualified names of offered souls, ranked as the
234
+ * launch check ranks (nearestSoulKeys): each is a valid entry that names one soul.
235
+ * A souls.disabled that is not a list is no entry, as disabledEntry reads it; the schema admits only
236
+ * names, so an entry that is not a string is no name and is passed over.
237
+ * → { unmatched: [{ entry, at, suggestions }], unchecked: [{ entry, at, reason }] }, in file order.
238
+ */
239
+ export function disabledEntriesUnmatched({ local, discovery }) {
240
+ const list = Array.isArray(local?.souls?.disabled) ? local.souls.disabled : [];
241
+ const unmatched = [], unchecked = [];
242
+ if (!list.length) return { unmatched, unchecked };
243
+ const offered = soulCandidates(discovery).map((c) => c.entry);
244
+ const { unread } = soulsOffered(discovery);
245
+ const names = [...new Set(offered.map(qualifiedSoulName))];
246
+ const packages = new Set(offered.filter((e) => typeof e.package === "string").map((e) => e.package));
247
+ list.forEach((entry, index) => {
248
+ if (typeof entry !== "string" || offered.some((soul) => disabledEntry({ souls: { disabled: [entry] } }, soul) !== null)) return;
249
+ const at = `${LOCAL_FILE}#/souls/disabled/${index}`;
250
+ const prefix = entry.includes("/") ? entry.slice(0, entry.lastIndexOf("/")) : null;
251
+ const reason = unread.all ?? (prefix !== null && Object.hasOwn(unread.packages, prefix) ? unread.packages[prefix] : prefix !== null && packages.has(prefix) ? null : unread.bare);
252
+ if (reason !== null) unchecked.push({ entry, at, reason });
253
+ else unmatched.push({ entry, at, suggestions: nearestSoulKeys(entry, names) });
254
+ });
255
+ return { unmatched, unchecked };
256
+ }
257
+
220
258
  /**
221
259
  * A home's LIVE teams (team model v2): the committed shared teams (the workspace host read now) and the
222
260
  * deployment's oats-local.yaml as it is now, resolved for the home's soul key (its name, or
@@ -492,6 +530,21 @@ export async function prepareInstance(contextDir, soulName, { spawn = {}, remote
492
530
  return { local, deployment, lock, discovery, soulEntry, resolution, remoteOptions, spawn, launch };
493
531
  }
494
532
 
533
+ /** Every package a prepared resolution takes a module from is the content the lock records (lib/packages.mjs
534
+ * verifyLockedPackage: the digest of the package tree at the locked commit is the lock's `integrity`), else
535
+ * E_PACKAGE_INTEGRITY. A spawn runs it on what prepareInstance returned, before its first write: the modules
536
+ * a spawn copies are parts of that tree, fetched one by one. Each package is read from the repo its manifests
537
+ * were resolved from (resolveSoul). */
538
+ export async function verifyPreparedPackages(prepared) {
539
+ const verified = new Set();
540
+ for (const { from } of prepared.resolution.modules) {
541
+ if (from.kind !== "package" || verified.has(from.package)) continue;
542
+ const entry = prepared.lock.packages[from.package];
543
+ await verifyLockedPackage(from.package, entry, packageRef(from.package, entry, null, { parseRepoRef }), prepared.remoteOptions);
544
+ verified.add(from.package);
545
+ }
546
+ }
547
+
495
548
  /** The first soul of the deployment, by name (then qualified name), not disabled here, whose
496
549
  * resolution `provides(resolution)`: each soul is prepared in turn over one discovery, and the search
497
550
  * stops at the first that does. A soul whose resolution is refused cannot provide anything and is
@@ -58,7 +58,7 @@ import {
58
58
  revisionOf,
59
59
  kernelCompatibility,
60
60
  } from "./resolve.mjs";
61
- import { readLock, writeFileAtomic } from "./packages.mjs";
61
+ import { fetchLockedPackage, readLock, writeFileAtomic } from "./packages.mjs";
62
62
  import { loadLocal, memberSoulPath } from "./workspace.mjs";
63
63
  import { copyTreeSafe, treeDisagreement } from "./tree-copy.mjs";
64
64
  import { appendEvent, readEvents } from "./instance-events.mjs";
@@ -525,22 +525,13 @@ async function prepare(ctx, root, name, opts, { own = false } = {}) {
525
525
  remoteOptions: opts.remoteOptions,
526
526
  });
527
527
  const tree = join(scratch, `package-${packages.size}`);
528
- await remote.fetchRemoteTree(
528
+ await fetchLockedPackage(
529
+ pkgid,
530
+ entry,
529
531
  found.ref,
530
- entry.commit,
531
- entry.path,
532
532
  tree,
533
- { ...opts.remoteOptions, allowSymlinks: remote.OATS_ALIAS_SYMLINK },
533
+ opts.remoteOptions,
534
534
  );
535
- const digest = remote.contentDigest(tree, {
536
- allowSymlinks: remote.OATS_ALIAS_SYMLINK,
537
- });
538
- if (digest !== entry.integrity)
539
- throw fail(
540
- "E_PACKAGE_INTEGRITY",
541
- `package ${pkgid} does not match locked integrity`,
542
- { package: pkgid, expected: entry.integrity, actual: digest },
543
- );
544
535
  packages.set(pkgid, { ...found, tree });
545
536
  }
546
537
  const pkg = packages.get(pkgid),
@@ -1020,10 +1011,15 @@ function reclaimUpgradeMutex(home, name) {
1020
1011
  if (error.code === "ENOENT") return;
1021
1012
  throw error;
1022
1013
  }
1014
+ if (stat.isDirectory())
1015
+ throw fail(
1016
+ "E_SESSION_RUNNING",
1017
+ `${name}: ${path} is a start lock left by an earlier OATS; upgrade never removes it. Once no earlier oats is running, remove that directory and retry`,
1018
+ );
1023
1019
  if (!stat.isFile())
1024
1020
  throw fail(
1025
1021
  "E_SESSION_RUNNING",
1026
- `${name} has a start in progress; its directory mutex is never reclaimed by upgrade`,
1022
+ `${name}: ${path} is neither an upgrade's file nor a start lock left by an earlier OATS; upgrade never removes it. Remove it and retry`,
1027
1023
  );
1028
1024
  rmSync(path);
1029
1025
  }
@@ -1113,10 +1109,10 @@ export async function applyUpgrade(ctx, root, name, opts = {}) {
1113
1109
  writeJson(path, receipt);
1114
1110
  }
1115
1111
  stopped(home, name, opts, stored?.priorMeta);
1116
- // One path, two atomic shapes: start owns a mkdir directory; upgrade owns
1117
- // an exclusive regular file. Under our lifecycle claim a prior upgrade
1118
- // cannot still run, so even an empty interrupted wx file is reclaimable.
1119
- // A directory or symlink is never reclaimed by this act.
1112
+ // The upgrade owns an exclusive regular file at this path; a start makes
1113
+ // nothing here. Under our lifecycle claim a prior upgrade cannot still run,
1114
+ // so even an empty interrupted wx file is reclaimable. A directory (an
1115
+ // earlier OATS's start lock) or a symlink is never reclaimed by this act.
1120
1116
  reclaimUpgradeMutex(home, name);
1121
1117
  const startMutex = join(home, ".oats-start.lock");
1122
1118
  let fd;
@@ -1138,7 +1134,7 @@ export async function applyUpgrade(ctx, root, name, opts = {}) {
1138
1134
  if (error.code === "EEXIST")
1139
1135
  throw fail(
1140
1136
  "E_SESSION_RUNNING",
1141
- `${name} has a start in progress; wait for it to finish before upgrading`,
1137
+ `${name}: ${startMutex} appeared after the upgrade checked it: a start lock left by an earlier OATS, or a file made there between the check and the create. Once no earlier oats is running, remove it and retry`,
1142
1138
  );
1143
1139
  throw error;
1144
1140
  } finally {
@@ -5,6 +5,9 @@
5
5
  * (test/cli-json-contract.test.mjs). Kernel-private, not exported from `./core`. Dependency-free. */
6
6
  import { SESSION_RESUME_FEATURE } from "./session-resume-contract.mjs";
7
7
 
8
- export const KERNEL_FEATURES = Object.freeze(["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources", "session-attach-detach-key", "lifecycle-kernel-codes", "schedule-run-warnings", "lifecycle-claim-stop", "launch-prompt-dev-channel", "soul-launch", "retire-plan-own-worktree", "spawn-kernel-codes", "soul-skills", "roster-workspace-key", "spawn-apply-max-age", "status-retire-state", "session-inspect-size", "session-inspect-running", "deployments-list", "soul-composed-skills", "instance-color", "spawn-suggest-name", "instance-upgrade", "session-attach-no-status-line", "session-attach-prefix-scroll", "instance-suggest-name", "spawn-apply-suggest-name", SESSION_RESUME_FEATURE, "instance-background", "instance-same-work", "warm-reader", "status-liveness", "lifecycle-claim-start", "wake-hold", "spawn-attribution", "workspace-tasks-payload", "settings-committed-only"]);
8
+ /** `oats spawn --task-file -` reads the task from standard input: how a routed spawn's task reaches
9
+ * its host (lib/servers.mjs routeCommand); a host that does not list this gets it as an argument. */
10
+ export const SPAWN_TASK_STDIN_FEATURE = "spawn-task-stdin";
11
+ export const KERNEL_FEATURES = Object.freeze(["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources", "session-attach-detach-key", "lifecycle-kernel-codes", "schedule-run-warnings", "lifecycle-claim-stop", "launch-prompt-dev-channel", "soul-launch", "retire-plan-own-worktree", "spawn-kernel-codes", "soul-skills", "roster-workspace-key", "spawn-apply-max-age", "status-retire-state", "session-inspect-size", "session-inspect-running", "deployments-list", "soul-composed-skills", "instance-color", "spawn-suggest-name", "instance-upgrade", "session-attach-no-status-line", "session-attach-prefix-scroll", "instance-suggest-name", "spawn-apply-suggest-name", SESSION_RESUME_FEATURE, "instance-background", "instance-same-work", "warm-reader", "status-liveness", "lifecycle-claim-start", "wake-hold", "spawn-attribution", "workspace-tasks-payload", "settings-committed-only", "schedule-host-register-only", SPAWN_TASK_STDIN_FEATURE]);
9
12
  /** The warm reader's protocol (`oats reader --stdio`, lib/reader.mjs): `readerApi` in the probe and in the reader's hello. */
10
13
  export const READER_API = 1;
@@ -0,0 +1,7 @@
1
+ #!/bin/sh
2
+ # The kernel writes only quoted exports to this private, per-start file.
3
+ # Do not enable tracing: the environment can contain credentials.
4
+ . "$1" || exit 1
5
+ /bin/rm -f -- "$1" || exit 1
6
+ shift
7
+ exec "$@"
@@ -0,0 +1,74 @@
1
+ /** Launch references stay references in recipes. Values live only on the execution host. */
2
+ import { closeSync, constants, fstatSync, openSync, readSync, readdirSync, writeFileSync, rmSync } from "node:fs";
3
+ import { TextDecoder } from "node:util";
4
+ import { fileURLToPath } from "node:url";
5
+ import { isAbsolute, join } from "node:path";
6
+ import { shellWord } from "./shell-word.mjs";
7
+
8
+ /** The same reference grammar validates declarations and recorded launch recipes. */
9
+ export function isLaunchEnvReference(value) {
10
+ return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 1
11
+ && ((typeof value.fromEnv === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(value.fromEnv))
12
+ || (typeof value.fromFile === "string" && isAbsolute(value.fromFile) && !value.fromFile.includes("\0")));
13
+ }
14
+
15
+ export const referenceSource = (ref) => ref.fromFile !== undefined ? `file:${ref.fromFile}` : ref.fromEnv;
16
+ const FILE_MAX_BYTES = 64 * 1024;
17
+ /** Resolve a reference without ever putting its bytes in a diagnostic. */
18
+ export function readLaunchReference(ref, env) {
19
+ if (ref.fromFile === undefined) return { value: env[ref.fromEnv] };
20
+ let fd;
21
+ const tooLarge = { problem: "is larger than 64 KiB; fromFile holds a credential value, not a file's contents" };
22
+ try {
23
+ fd = openSync(ref.fromFile, constants.O_RDONLY | constants.O_NONBLOCK);
24
+ const before = fstatSync(fd);
25
+ if (!before.isFile()) return { problem: "is not a regular file" };
26
+ if (before.size > FILE_MAX_BYTES) return tooLarge;
27
+ // One extra byte detects growth during this bounded read, without ever reading a log whole.
28
+ const bytes = Buffer.alloc(FILE_MAX_BYTES + 1);
29
+ let length = 0;
30
+ while (length < bytes.length) {
31
+ const count = readSync(fd, bytes, length, bytes.length - length, null);
32
+ if (!count) break;
33
+ length += count;
34
+ }
35
+ if (length > FILE_MAX_BYTES || fstatSync(fd).size > FILE_MAX_BYTES) return tooLarge;
36
+ let text;
37
+ try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)); }
38
+ catch { return { problem: "is not UTF-8" }; }
39
+ return text.includes("\0") ? { problem: "contains NUL" } : { value: text.replace(/\r?\n$/, "") };
40
+ } catch (error) { return { problem: error.code === "ENOENT" ? "is missing" : "cannot be read" }; }
41
+ finally { if (fd !== undefined) closeSync(fd); }
42
+ }
43
+ export const referenceValue = (ref, env) => readLaunchReference(ref, env).value;
44
+ export function fileReferenceProblems(names) {
45
+ return names.filter((name) => name.startsWith("file:")).map((name) => {
46
+ const path = name.slice(5), { problem } = readLaunchReference({ fromFile: path }, {});
47
+ return `file reference ${path} ${problem || "is unavailable"}`;
48
+ });
49
+ }
50
+ export function fileReferenceRemedy(names, harness = "<harness>") {
51
+ return names.some((name) => name.startsWith("file:")) ? `; restore the readable credential file with oats harness token set ${harness} --server <id>, or ask the operator to provision it on this host` : "";
52
+ }
53
+
54
+ /** Private, one-use reference handoff. Never put values in tmux argv or its command string. */
55
+ export const LAUNCH_ENV_HANDOFF = /^\.oats-launch-env-[A-Za-z0-9-]+\.sh$/;
56
+ export function launchEnvHandoff(home, startId, refs) {
57
+ if (!/^[A-Za-z0-9-]+$/.test(startId)) throw new Error("invalid launch environment start id");
58
+ const current = `.oats-launch-env-${startId}.sh`;
59
+ // Starts are serialized by the home's lifecycle claim. A previous pane may have died
60
+ // before consuming its handoff; remove that plaintext before this start dispatches.
61
+ for (const name of readdirSync(home)) if (LAUNCH_ENV_HANDOFF.test(name) && name !== current) rmSync(join(home, name), { force: true });
62
+ if (!refs.length) return { wrap: (command) => command, remove: () => {} };
63
+ const file = join(home, current);
64
+ const content = refs.map((ref) => {
65
+ if (!/^OATS_LAUNCH_REF_[A-Za-z_][A-Za-z0-9_]*$/.test(ref.name) || ref.value.includes("\0")) throw new Error("invalid launch environment reference");
66
+ return `export ${ref.name}=${shellWord(ref.value)}\n`;
67
+ }).join("");
68
+ writeFileSync(file, content, { mode: 0o600, flag: "wx" });
69
+ const launcher = fileURLToPath(new URL("./launch-env-exec.sh", import.meta.url));
70
+ return {
71
+ wrap: (command) => `/bin/sh ${shellWord(launcher)} ${shellWord(file)} /bin/sh -c ${shellWord(command)}`,
72
+ remove: () => rmSync(file, { force: true }),
73
+ };
74
+ }
@@ -87,8 +87,10 @@ function editDistance(a, b, max, over = max + 1) {
87
87
  }
88
88
  const SUGGESTIONS = 3, NEAR = 2;
89
89
  /** The offered soul keys nearest to `key`, at most three: first those with its bare name (the part after
90
- * the last `/`), then those whose bare name is within two edits, by distance then by code point. */
91
- function nearestSoulKeys(key, offered) {
90
+ * the last `/`), then those whose bare name is within two edits, by distance then by code point. Any
91
+ * names of offered souls rank the same way: souls.disabled's check ranks their qualified names
92
+ * (lib/instance-resolution.mjs disabledEntriesUnmatched). */
93
+ export function nearestSoulKeys(key, offered) {
92
94
  const bare = bareName(key);
93
95
  const ranked = [];
94
96
  for (const k of offered) { const d = editDistance(bareName(k), bare, NEAR); if (d <= NEAR) ranked.push([d, k]); }
@@ -128,16 +130,21 @@ export function launchKeysUnmatched({ local, offered }) {
128
130
  return { unmatched, unchecked };
129
131
  }
130
132
 
131
- /** Why a key of souls.launch was not checked, one sentence per reason launchKeysUnmatched can give
132
- * (soulsOffered's): what `oats doctor` says after the key. */
133
- export const LAUNCH_KEY_UNCHECKED = Object.freeze({
134
- standalone: "this deployment sees a standalone view (the workspace's host could not be read), so the workspace's souls are not known",
135
- unrecorded: "the read of the workspace kept no record of the souls it could not read, so it established nothing about this key",
136
- "member-unconfirmed": "a member of the workspace is not confirmed, and the key may be a soul of it",
137
- "soul-unread": "a member's or an external soul could not be read, and the key may be that soul's",
138
- "package-unlocked": "its package is declared and not locked (oats sync)",
139
- "package-soul-unread": "a soul of its package could not be read, and the key may be that soul's",
140
- });
133
+ /** Why a name in oats-local.yaml was not checked against the souls a read offers, one sentence per
134
+ * reason soulsOffered gives, said of `noun`: what `oats doctor` says after the name. One set of reasons
135
+ * for every check that reads soulsOffered: "key" for souls.launch, "entry" for souls.disabled. */
136
+ export function uncheckedSentences(noun) {
137
+ return Object.freeze({
138
+ standalone: "this deployment sees a standalone view (the workspace's host could not be read), so the workspace's souls are not known",
139
+ unrecorded: `the read of the workspace kept no record of the souls it could not read, so it established nothing about this ${noun}`,
140
+ "member-unconfirmed": `a member of the workspace is not confirmed, and the ${noun} may be a soul of it`,
141
+ "soul-unread": `a member's or an external soul could not be read, and the ${noun} may be that soul's`,
142
+ "package-unlocked": "its package is declared and not locked (oats sync)",
143
+ "package-soul-unread": `a soul of its package could not be read, and the ${noun} may be that soul's`,
144
+ });
145
+ }
146
+ /** Why a key of souls.launch was not checked, by each reason launchKeysUnmatched can give (soulsOffered's). */
147
+ export const LAUNCH_KEY_UNCHECKED = uncheckedSentences("key");
141
148
 
142
149
  /** A key or a name from outside the kernel, as a sentence of a launch answer carries it: every character
143
150
  * the kernel never prints (lib/refused-text.mjs REFUSED_TEXT) replaced. `safeText` and not `terminalText`:
@@ -29,12 +29,18 @@ export function conventionCloneDir(deployment, key) {
29
29
  * `https://…`, `git@host:…`, `/abs/bare.git`) — to the canonical key. A key that
30
30
  * parses no way is returned as written (it can then only match literally). */
31
31
  export function canonicalCloneKey(written) {
32
+ return parsedCloneKey(written) ?? String(written).trim();
33
+ }
34
+
35
+ /** canonicalCloneKey's answer when `written` is a repository reference, or null when it parses no
36
+ * way (a member's name, `org/name`): such a string can match no remote. */
37
+ export function parsedCloneKey(written) {
32
38
  const s = String(written).trim();
33
39
  if (s.startsWith("local/")) return s; // a local key is already canonical
34
40
  for (const candidate of [s, `git:${s}`]) {
35
41
  try { return parseRepoRef(candidate).key; } catch { /* next form */ }
36
42
  }
37
- return s;
43
+ return null;
38
44
  }
39
45
 
40
46
  /** The remotes a clone carries (any remote, not only origin), each with its url parsed
package/lib/packages.mjs CHANGED
@@ -50,6 +50,7 @@ import * as defaultRemote from "./remote.mjs";
50
50
  import { manifestContractProblems } from "./capability-contract.mjs";
51
51
  import { writeFileAtomic } from "./write-file-atomic.mjs";
52
52
  import { sameRepo } from "./repo-moves.mjs";
53
+ import { PACKAGE_ID_RE } from "./package-catalog.mjs";
53
54
  export { writeFileAtomic } from "./write-file-atomic.mjs";
54
55
 
55
56
  export const LOCK_FILE = "oats-lock.json";
@@ -429,6 +430,36 @@ async function packageIntegrity(remote, remoteRef, commit, path) {
429
430
  } finally { rmSync(scratch, { recursive: true, force: true }); }
430
431
  }
431
432
 
433
+ /** The package tree of a lock entry copied to `dest` (which must not exist), only when its content is what
434
+ * the lock records: the content digest of the copy must be the entry's `integrity`, else E_PACKAGE_INTEGRITY
435
+ * { package, version, commit, expected, actual } (the copy is left for the caller to remove). `ref` is the
436
+ * repo the package is read from (lib/resolve.mjs packageRef). The one comparison of a package tree with the
437
+ * lock behind a spawn (verifyLockedPackage) and an in-place module move (lib/instance-upgrade.mjs). */
438
+ export async function fetchLockedPackage(id, entry, ref, dest, remoteOptions) {
439
+ const allowSymlinks = defaultRemote.OATS_ALIAS_SYMLINK;
440
+ await defaultRemote.fetchRemoteTree(ref, entry.commit, entry.path, dest, { ...remoteOptions, allowSymlinks });
441
+ const observed = defaultRemote.contentDigest(dest, { allowSymlinks });
442
+ if (observed !== entry.integrity) {
443
+ throw oatsError("E_PACKAGE_INTEGRITY",
444
+ `package ${id} v${entry.version}: ${entry.path} at commit ${entry.commit} digests ${observed}, and oats-lock.json records ${entry.integrity} for it — either the lock was edited (restore it: only \`oats sync\` writes it), or this computer's cached copy of the package changed (remove the remote cache: the next read fetches it again)`,
445
+ { package: id, version: entry.version, commit: entry.commit, expected: entry.integrity, actual: observed });
446
+ }
447
+ }
448
+
449
+ /** A spawn's check that a locked package is the content the lock records, before the spawn has any effect:
450
+ * fetchLockedPackage into a scratch directory, once per (repo, commit, path, integrity) and state of the
451
+ * package's cache repo on this computer (lib/remote.mjs treeVerification): a recorded verification the cache
452
+ * repo has not changed under is believed, and nothing is fetched. A cache repo that changed while its tree
453
+ * was read (the first fetch of the package's blobs) records nothing: the next spawn reads the tree again. */
454
+ export async function verifyLockedPackage(id, entry, ref, remoteOptions) {
455
+ const verification = defaultRemote.treeVerification(ref, entry.commit, entry.path, entry.integrity, remoteOptions);
456
+ if (verification.holds()) return;
457
+ const scratch = mkdtempSync(join(tmpdir(), "oats-pkg-"));
458
+ try { await fetchLockedPackage(id, entry, ref, join(scratch, "tree"), remoteOptions); }
459
+ finally { rmSync(scratch, { recursive: true, force: true }); }
460
+ verification.record();
461
+ }
462
+
432
463
  // ---------- resolvePackages ----------
433
464
 
434
465
  function assertDigest(what, value, details) {
@@ -436,6 +467,42 @@ function assertDigest(what, value, details) {
436
467
  return value;
437
468
  }
438
469
 
470
+ /** A package is locked under its own id (#1759): the manifest's `package` must equal the `packages:` key it
471
+ * is pinned under, or its souls would be named after the wrong package. A mismatch is
472
+ * E_PACKAGE_INTEGRITY { why: "package-id", manifestPackage, commit } whose message names the line to write.
473
+ * The fix line is built from displayed parts: a catalog url may carry user information (displayRepoRef
474
+ * drops it), except the `git@host:` ssh form, whose `git` user is part of the address and which a `git:`
475
+ * value accepts as written; a `git:` value carries no other user information (classifyPackageValue
476
+ * refuses it), so it is repeated as written. */
477
+ function assertManifestNamesId(id, manifest, { req, value, catalog, commit, details }) {
478
+ const named = manifest.package;
479
+ if (named === id) return;
480
+ const text = value.trim();
481
+ const ssh = req.kind === "catalog" && /^git@[^@/:]+:/.test(req.remoteRef);
482
+ const repo = req.kind !== "catalog" ? null : ssh ? req.remoteRef : defaultRemote.displayRepoRef(req.remoteRef);
483
+ const pinned = req.kind === "catalog" ? `${text} resolves to ${repo}@${req.at} (${commit.slice(0, 12)})` : `${text} resolves to ${commit.slice(0, 12)}`;
484
+ let fix = null, note = "";
485
+ if (!PACKAGE_ID_RE.test(named)) note = ", which is not a package id";
486
+ else if (req.kind === "git" || plainObject(catalogPackages(catalog)[named])) fix = text; // the catalog decides where a catalog package lives
487
+ else if (req.path !== DEFAULT_PACKAGE_PATH) note = ` (a git: pin reads ${DEFAULT_PACKAGE_PATH}/ and this package is at ${req.path}/, so no git: line can name it)`;
488
+ else fix = gitValueFor(repo, req.at);
489
+ const shown = JSON.stringify(!fix && named.length > 64 ? `${named.slice(0, 64)}…` : named);
490
+ const way = fix ? `declare ${named}: ${fix} in packages: in place of ${id}, or pin` : "pin";
491
+ const message = `packages.${id}: ${pinned}, whose ${PACKAGE_MANIFEST} names package ${shown}, not ${JSON.stringify(id)}${note}`
492
+ + ` — a package is locked under its own id: ${way} a version of ${id} whose manifest names ${id}; then run \`oats sync\``;
493
+ throw oatsError("E_PACKAGE_INTEGRITY", defaultRemote.displayDiagnosticText(message, req.kind === "catalog" && !ssh ? req.remoteRef : null, { refusal: true }),
494
+ { ...details, why: "package-id", manifestPackage: named, commit });
495
+ }
496
+
497
+ /** The `git:<repo>@<ref>` value for a displayed repo, or the placeholder when that value would not resolve
498
+ * (a withheld display, or a form a git: value cannot carry). */
499
+ function gitValueFor(repo, at) {
500
+ const composed = `git:${repo.startsWith("git:") ? repo.slice(4) : repo}@${at}`;
501
+ const c = classifyPackageValue(composed);
502
+ try { if (!c.problem) { defaultRemote.parseRepoRef(c.repo); return composed; } } catch { /* placeholder below */ }
503
+ return `git:<repo>@${at}`;
504
+ }
505
+
439
506
  /** A remote whose reads at a commit are shared for one command (feature desktop-facts): the souls and
440
507
  * capabilities listings resolve many souls over the same package manifests and skill listings, and a read at
441
508
  * an immutable commit gives the same answer every time. A failed read is not kept (it is retried). */
@@ -488,6 +555,8 @@ export function bindRemote(remote, remoteOptions) {
488
555
  * - A locked entry whose version string is unchanged but whose commit or
489
556
  * integrity moved → E_PACKAGE_INTEGRITY { id, version, locked, observed }.
490
557
  * - A value resolving to a BRANCH → E_PACKAGE_INTEGRITY { why: "branch" }: versions are immutable.
558
+ * - A manifest whose `package` is not the entry's key, fresh or already locked →
559
+ * E_PACKAGE_INTEGRITY { why: "package-id", manifestPackage, commit } (assertManifestNamesId).
491
560
  */
492
561
  export async function resolvePackages(workspace, { catalog = {}, lock = emptyLock(), remote = defaultRemote, remoteOptions } = {}) {
493
562
  if (!remote || typeof remote.observeRemote !== "function" || typeof remote.readRemoteFile !== "function") {
@@ -532,7 +601,9 @@ export async function resolvePackages(workspace, { catalog = {}, lock = emptyLoc
532
601
  // The lock's capability list must still be what the package declares at that commit —
533
602
  // spawn refuses a mismatch (E_PACKAGE_INTEGRITY why:capabilities), so sync must too, or
534
603
  // a bad list would pass every sync and fail every spawn.
535
- const { capabilities, souls: soulDirs } = await readPackageManifests(remote, req.remoteRef, obs.commit, old.path, details);
604
+ const { manifest, capabilities, souls: soulDirs } = await readPackageManifests(remote, req.remoteRef, obs.commit, old.path, details);
605
+ // A lock an older kernel wrote under another package's id is refused here too (#1759).
606
+ assertManifestNamesId(id, manifest, { req, value: requests[id], catalog, commit: obs.commit, details });
536
607
  const listed = capabilities.map((c) => c.name).sort(), locked = [...old.capabilities].sort();
537
608
  if (listed.length !== locked.length || listed.some((c, i) => c !== locked[i])) {
538
609
  throw oatsError("E_PACKAGE_INTEGRITY",
@@ -555,7 +626,8 @@ export async function resolvePackages(workspace, { catalog = {}, lock = emptyLoc
555
626
  continue;
556
627
  }
557
628
 
558
- const { capabilities, souls: soulDirs } = await readPackageManifests(remote, req.remoteRef, obs.commit, req.path, details);
629
+ const { manifest, capabilities, souls: soulDirs } = await readPackageManifests(remote, req.remoteRef, obs.commit, req.path, details);
630
+ assertManifestNamesId(id, manifest, { req, value: requests[id], catalog, commit: obs.commit, details });
559
631
  const integrity = assertDigest(`packages.${id} integrity`, await packageIntegrity(remote, req.remoteRef, obs.commit, req.path), details);
560
632
  const souls = await packageSoulDigests(remote, req.remoteRef, obs.commit, soulDirs, details);
561
633
  nextPackages[id] = {
package/lib/read-call.mjs CHANGED
@@ -42,7 +42,10 @@ export const READ_STATE = [
42
42
  { module: "lib/remote.mjs", binding: "liveChildren", how: "safe", why: "a registry of live git process groups, each leaving on 'close': empty once a call's session is closed, never cleared (that would lose exit reaping)" },
43
43
  { module: "lib/remote.mjs", binding: "cacheLocks", how: "safe", why: "an in-process mutex per cache repo; an entry is removed when its holder releases it" },
44
44
  { module: "lib/remote.mjs", binding: "fingerprintMemo", how: "safe", why: "the kernel code's fingerprint, install data: a process that runs a changed install exits first (the warm reader's install stamp)" },
45
- { module: "lib/session-seen.mjs", binding: "processBoot", how: "safe", why: "the boot id: a process never outlives its boot" },
45
+ { module: "lib/dir-lock.mjs", binding: "sections", how: "safe", why: "how many locked sections run now: a section is synchronous, so it is 0 between calls" },
46
+ { module: "lib/dir-lock.mjs", binding: "listening", how: "safe", why: "whether the lock's signal listeners are on: they hold a signal back around a section and decide no answer" },
47
+ { module: "lib/dir-lock.mjs", binding: "idle", how: "safe", why: "the pending removal of those listeners, run once the event loop turns" },
48
+ { module: "packages/record/lib/process-identity.mjs", binding: "processBoot", how: "safe", why: "the boot id: a process never outlives its boot" },
46
49
  { module: "lib/session-viewer.mjs", binding: "probed", how: "safe", why: "only an attach's preparation reads it; readSessionViewer asks tmux -V at every call" },
47
50
  { module: "lib/session-viewer.mjs", binding: "onQuit", how: "safe", why: "only an attach (attachSessionTarget) sets it" },
48
51
  { module: "lib/session-viewer.mjs", binding: "quitHeld", how: "safe", why: "only an attach (attachSessionTarget) sets it" },
package/lib/reader.mjs CHANGED
@@ -17,7 +17,8 @@
17
17
  * reader exits 0.
18
18
  * - Its lifetime is the client's: stdin EOF or error, EPIPE on stdout, SIGTERM/SIGINT/SIGHUP end it. A request in
19
19
  * flight is not answered, and its read session is closed from the `exit` handler, which kills its git
20
- * children (a deployments-list lock, lib/dir-lock.mjs, exits from its own signal handler).
20
+ * children (a deployments-list lock, lib/dir-lock.mjs, raises a signal that arrived inside its
21
+ * section again once the lock is released, and this handler then ends the reader).
21
22
  * - Its stdout carries protocol lines only: anything else written there (console.log) goes to stderr, and every
22
23
  * child on the read path pipes or ignores its stdout.
23
24
  * Kernel-private, not exported from `./core`. Dependency-free. */
@@ -69,7 +70,7 @@ export async function runReader({ stamp }) {
69
70
  let inFlight = null;
70
71
  process.on("exit", () => inFlight?.closeNow());
71
72
  for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]) process.on(signal, () => {
72
- // A deployments-list lock (lib/dir-lock.mjs) holds its own handler, which releases the lock and exits.
73
+ // Any other handler still listening ends the reader itself after this one.
73
74
  if (process.listenerCount(signal) === 1) end(code);
74
75
  });
75
76
  process.stdout.on("error", () => end(0)); // EPIPE: the client is gone
@@ -4,8 +4,9 @@
4
4
  * invisible hiders U+200B, U+2060 and U+FEFF, and the tag characters (U+E0000-E007F).
5
5
  * Everything else is allowed, ZWJ and ZWNJ (U+200C/D, emoji sequences, Persian and Indic text)
6
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. */
7
+ * claim's message (lib/instance-events.mjs) refuses it, a warning row's message (the same
8
+ * module) and a trigger source's text (lib/triggers.mjs) have it replaced. The Desktop keeps its
9
+ * own identical copy. */
9
10
  export const REFUSED_TEXT = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069\u200B\u2060\uFEFF\u{E0000}-\u{E007F}]/u;
10
11
  const REFUSED_TEXT_ALL = new RegExp(REFUSED_TEXT.source, "gu");
11
12