@awebai/oats 0.69.21 → 0.69.23

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 (73) hide show
  1. package/bin/oats.mjs +131 -23
  2. package/docs/capabilities.md +12 -2
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/container.md +290 -5
  5. package/docs/design/2026-11-18-kernel-test-ownership.md +82 -0
  6. package/docs/design/2026-11-19-aweb-suite-retirement.md +123 -0
  7. package/docs/design/2026-11-19-sandboxes.md +878 -0
  8. package/docs/design/README.md +3 -0
  9. package/docs/desktop-cli-api.md +416 -72
  10. package/docs/desktop.md +377 -148
  11. package/docs/implementation.md +15 -2
  12. package/docs/integrations.md +3 -3
  13. package/docs/knowledge-capability-authoring.md +10 -7
  14. package/docs/knowledge-reference/acceptance.md +21 -19
  15. package/docs/knowledge-reference/adoption.md +18 -4
  16. package/docs/knowledge-reference/model.md +11 -9
  17. package/docs/knowledge-reference/package-craft.md +2 -2
  18. package/docs/knowledge-reference/proposal.md +117 -0
  19. package/docs/knowledge-reference/provider-mapping.md +10 -10
  20. package/docs/knowledge-reference/reader-capture.md +26 -22
  21. package/docs/knowledge-theory.md +1 -1
  22. package/docs/knowledge.md +5 -5
  23. package/docs/official-catalog.md +47 -4
  24. package/docs/packages.md +13 -13
  25. package/docs/release-lane.md +8 -6
  26. package/docs/release-notes/v0.69.22.md +221 -0
  27. package/docs/release-notes/v0.69.23.md +231 -0
  28. package/docs/servers.md +10 -6
  29. package/docs/souls-and-instances.md +51 -22
  30. package/docs/tui.md +48 -7
  31. package/docs/upgrading.md +17 -5
  32. package/docs/workspaces.md +2 -2
  33. package/lib/argv.mjs +6 -2
  34. package/lib/capability-contract.mjs +2 -2
  35. package/lib/command-flags.mjs +39 -2
  36. package/lib/core.mjs +25 -14
  37. package/lib/instance-board.mjs +337 -0
  38. package/lib/instance-events.mjs +48 -10
  39. package/lib/instance-lifecycle.mjs +19 -15
  40. package/lib/instance-listing.mjs +18 -10
  41. package/lib/instance-related-work.mjs +143 -0
  42. package/lib/kernel-features.mjs +4 -1
  43. package/lib/servers.mjs +123 -13
  44. package/package-catalog.json +3 -3
  45. package/package.json +1 -1
  46. package/packages/client/above-tested.mjs +3 -2
  47. package/packages/client/capability-list.mjs +69 -0
  48. package/packages/client/capability-origin.mjs +54 -0
  49. package/packages/client/cli-adapter.mjs +9 -1
  50. package/packages/client/deployment-data.mjs +7 -2
  51. package/packages/client/deployment-panel.mjs +4 -1
  52. package/packages/client/home-board.mjs +50 -0
  53. package/packages/client/instance-pin.mjs +28 -0
  54. package/packages/client/instance-record-outcome.mjs +31 -0
  55. package/packages/client/instance-tree.mjs +96 -24
  56. package/packages/client/keymap.mjs +16 -3
  57. package/packages/client/mail-contract.mjs +130 -0
  58. package/packages/client/panel-views.mjs +7 -7
  59. package/packages/client/related-work.mjs +84 -0
  60. package/packages/client/remote-roster.mjs +11 -3
  61. package/packages/client/roster-sections.mjs +10 -7
  62. package/packages/client/soul-role.mjs +44 -0
  63. package/packages/client/waiting-on-you.mjs +10 -0
  64. package/packages/client/workspace-cli.mjs +13 -2
  65. package/packages/tui/lib/actions.mjs +11 -4
  66. package/packages/tui/lib/client.mjs +3 -1
  67. package/packages/tui/lib/main.mjs +16 -2
  68. package/packages/tui/lib/model.mjs +48 -5
  69. package/packages/tui/lib/store.mjs +28 -2
  70. package/skills/oats-getting-started/SKILL.md +97 -24
  71. package/docs/knowledge-reference/harvester.md +0 -109
  72. package/lib/instance-same-work.mjs +0 -67
  73. package/packages/client/same-work.mjs +0 -49
@@ -6,8 +6,28 @@
6
6
  * missing here is not checked. Kernel-private, not exported from `./core`. Dependency-free. */
7
7
 
8
8
  export const RETIRE_DELETE_BRANCH_REFUSED = "oats retire no longer deletes branches: --delete-branch is not accepted. Retire without it; the branch is left in the repository. Inspect it there and delete it with Git if it is no longer wanted.";
9
+ /** The spellings the related-work rename (feature instance-related-work) kept as deprecated aliases
10
+ * (feature instance-same-work, the compatibility layer): `oats spawn … --same-work` is `--related-work`,
11
+ * and `oats instance same-work` is `oats instance related-work`. Each use prints its line on stderr, once,
12
+ * before the command runs or is sent to a --server host (sameWorkDeprecation, the dispatch's), and never
13
+ * in a --json answer. spawnInstance's `sameWork` option is the same alias (lib/core.mjs). */
14
+ export const SAME_WORK_ALIASES = Object.freeze({
15
+ flag: "--same-work is renamed: use --related-work",
16
+ verb: "oats instance same-work is renamed: use oats instance related-work",
17
+ });
18
+
19
+ /** spawnInstance's deprecated option, said as a DeprecationWarning (code OATS_SAME_WORK) by lib/core.mjs. */
20
+ export const SAME_WORK_OPTION_RENAMED = "sameWork is renamed: use relatedWork";
21
+
22
+ /** The deprecation line `argv` (the CLI's argv, after `oats`, as typed) earns by an alias of
23
+ * SAME_WORK_ALIASES, or undefined. */
24
+ export function sameWorkDeprecation(argv) {
25
+ if (argv[0] === "instance" && argv[1] === "same-work") return SAME_WORK_ALIASES.verb;
26
+ if (argv[0] === "spawn" && argv.some((a) => a === "--same-work" || a.startsWith("--same-work="))) return SAME_WORK_ALIASES.flag;
27
+ return undefined;
28
+ }
9
29
  export const RETIRE_USAGE = "usage: oats retire <instance> [--plan] [--plan-revision <rev> --idempotency-key <key>] [--home <path>] [--dir <d>] [--server <id>] [--self] [--discard-worktree] [--keep-dir] [--force] [--json]";
10
- export const SPAWN_USAGE = "usage: oats spawn <agent> [--task <text>|--task-file <f>] [--purpose <slug>|--name <slug>|--suggest-name] [--preview] [--base <ref>] [--model <id>|@native-default] [--allow-child-spawns|--no-child-spawns] [--relation child|sibling|parent|unrelated --relative-to <instance> [--relative-root <agents-root>]] [--parent <instance>] [--same-work] [--repo <r>] [--work worktree|checkout|attached|workspace|directory] [--work-dir <owner-work>] [--harness pi|claude|codex] [--backend tmux] [--yolo|--no-yolo] [--background|--no-background] [--model <m>] [--branch <b>] [--no-launch] [--json]";
30
+ export const SPAWN_USAGE = "usage: oats spawn <agent> [--task <text>|--task-file <f>] [--purpose <slug>|--name <slug>|--suggest-name] [--preview] [--base <ref>] [--model <id>|@native-default] [--allow-child-spawns|--no-child-spawns] [--relation child|sibling|parent|unrelated --relative-to <instance> [--relative-root <agents-root>]] [--parent <instance>] [--related-work|--same-work] [--repo <r>] [--work worktree|checkout|attached|workspace|directory] [--work-dir <owner-work>] [--harness pi|claude|codex] [--backend tmux] [--yolo|--no-yolo] [--background|--no-background] [--model <m>] [--branch <b>] [--no-launch] [--json]";
11
31
  export const SYNC_USAGE = "usage: oats sync [--dir <deployment>] [--plan] [--json]";
12
32
  export const APPROVAL_REMOVED = "package approval was removed; declaring a package in packages: is the trust decision";
13
33
  export const TEAMS_USAGE = "usage: oats teams [--json] | oats teams add <label> --team <id> [--description <d>] [--no-default] | oats teams remove <label> | oats teams default <label> [--if-absent | --expect <label>] [--dir <deployment>] [--json]";
@@ -38,6 +58,16 @@ const waiting = (verb) => ({ command: `instance waiting ${verb}`, operands: [],
38
58
  usage: `usage: oats instance waiting ${verb} --producer <id>${verb === "set" ? " --reason permission|question|attention" : ""} [--message=<text>] [--home <abs>] [--dir <d>] [--json]` });
39
59
  const ATTENTION_USAGE = "usage: oats instance attention [--message=<text>] [--clear] [--json]";
40
60
  const attentionHasNo = (flag) => `oats instance attention has no ${flag}: it records the agent's own claim on the instance it runs in ($OATS_INSTANCE_HOME); ${ATTENTION_USAGE}`;
61
+ /** `oats instance board`'s forms (feature instance-board), each its own usage line; BOARD_USAGE all of them. */
62
+ const BOARD_FORMS = Object.freeze({
63
+ set: "oats instance board set <key> --label <text> --value <text> [--unit <text>] [--link <https-url>] [--json]",
64
+ unset: "oats instance board unset <key> [--json]",
65
+ ask: "oats instance board ask <question> --option <text> --option <text> [--option <text>]… [--id <id>] [--context-file <f>] [--json] | oats instance board ask --clear <id> [--json]",
66
+ });
67
+ export const BOARD_USAGE = `usage: ${Object.values(BOARD_FORMS).join(" | ")}`;
68
+ /** `oats instance board` records on the instance it runs in, as `attention` does: these are refused in its words. */
69
+ const boardRefused = (verb) => Object.freeze(Object.fromEntries(["--home", "--dir", "--server"].map((f) => [f, `oats instance board has no ${f}: it records on the board of the instance it runs in ($OATS_INSTANCE_HOME); usage: ${BOARD_FORMS[verb]}`])));
70
+ const board = (verb, operand, values, required = 1) => ({ command: `instance board ${verb}`, operands: [operand], required, values, switches: ["--json"], refused: boardRefused(verb), usage: `usage: ${BOARD_FORMS[verb]}` });
41
71
  const TRIGGER_RUN_SOURCE = Object.freeze(["--run-source", "--json"]);
42
72
  const SESSION_ADDRESS = Object.freeze(["--home", "--instance", "--server"]);
43
73
  /** Every `oats session` form refuses the captured path's selector in these words (bin's sessionCmd says them
@@ -82,7 +112,7 @@ export const COMMAND_FLAGS = Object.freeze([
82
112
  { command: "spawn", operands: ["soul"],
83
113
  values: ["--agents-root", "--backend", "--base", "--branch", "--dir", "--expect-decision", "--harness", "--herdr-socket", "--idempotency-key", "--instance", "--launch-config", "--max-age", "--model", "--name", "--parent", "--provider", "--purpose", "--relation", "--relative-root", "--relative-to", "--repo", "--runtime", "--server", "--task", "--task-file", "--trigger-event", "--wake-cron", "--wake-every", "--wake-file", "--wake-json", "--wake-message", "--wake-message-file", "--wake-tz", "--work", "--work-dir"],
84
114
  arity: { "--provider": 2 },
85
- switches: ["--allow-child-spawns", "--background", "--json", "--no-background", "--no-child-spawns", "--no-launch", "--no-yolo", "--preview", "--same-work", "--suggest-name", "--yolo"],
115
+ switches: ["--allow-child-spawns", "--background", "--json", "--no-background", "--no-child-spawns", "--no-launch", "--no-yolo", "--preview", "--related-work", "--same-work", "--suggest-name", "--yolo"],
86
116
  // Local souls (local-agents/) are gone with the workspace model: a soul is a member
87
117
  // repository's souls/<name>, so spawn never writes one.
88
118
  refused: { "--instructions-file": SPAWN_REMOVED_SOUL("--instructions-file"), "--def-file": SPAWN_REMOVED_SOUL("--def-file"),
@@ -103,11 +133,18 @@ export const COMMAND_FLAGS = Object.freeze([
103
133
  usage: "usage: oats instance color <instance> (<color> | --clear) [--home <abs>] [--dir <d> | --server <id>] [--json]" },
104
134
  onOff("background"),
105
135
  onOff("pin"),
136
+ onOff("related-work"),
137
+ // The verb's deprecated alias (SAME_WORK_ALIASES): the same arguments.
106
138
  onOff("same-work"),
107
139
  waiting("set"),
108
140
  waiting("clear"),
109
141
  { command: "instance attention", operands: [], values: ["--message"], switches: ["--clear", "--json"],
110
142
  refused: Object.fromEntries(["--home", "--dir", "--producer", "--reason"].map((f) => [f, attentionHasNo(f)])), usage: ATTENTION_USAGE },
143
+ board("set", "key", ["--label", "--value", "--unit", "--link"]),
144
+ board("unset", "key", []),
145
+ // `--clear <id>` takes the id as its value, so the question is optional here; the command refuses a form
146
+ // with neither, or with both.
147
+ board("ask", "question", ["--option", "--id", "--context-file", "--clear"], 0),
111
148
  { command: "instance suggest-name", operands: [], values: ["--soul", "--task", "--task-file", "--harness", "--model", "--launch-config", "--dir"], switches: ["--json"],
112
149
  refused: { "--server": "instance suggest-name takes no --server: it runs this machine's harness, for a spawn that may land on another; the host it lands on makes the name unique (or names an unnamed --suggest-name spawn itself)" },
113
150
  usage: "usage: oats instance suggest-name [--soul <soul>] (--task <t> | --task-file <f>) [--harness claude|pi] [--model <m>] [--launch-config <n>] [--dir <d>] [--json]" },
package/lib/core.mjs CHANGED
@@ -48,7 +48,7 @@ import { createHash, randomUUID } from "node:crypto";
48
48
  import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
49
49
  import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
50
50
  import { noteRuntimeName } from "./deprecation.mjs";
51
- import { RETIRE_DELETE_BRANCH_REFUSED } from "./command-flags.mjs";
51
+ import { RETIRE_DELETE_BRANCH_REFUSED, SAME_WORK_OPTION_RENAMED } from "./command-flags.mjs";
52
52
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
53
53
  import { AGENT_PANE_OPTION, inspectSessionTarget, inputSessionTarget, resolveAgentPane } from "./session-input.mjs";
54
54
  import { RETIRE_HOOK_WARNING_KIND, appendEvent, incarnationOf, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
@@ -99,7 +99,8 @@ import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPla
99
99
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
100
100
  import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
101
101
  import { PIN_FILE } from "./instance-pin.mjs";
102
- import { SAME_WORK_FILE, writeSameWork } from "./instance-same-work.mjs";
102
+ import { BOARD_FILE, BOARD_LOCK } from "./instance-board.mjs";
103
+ import { RELATED_WORK_FILE, SAME_WORK_FILE, relatedWorkBinding, writeRelatedWork } from "./instance-related-work.mjs";
103
104
  import { HOST_STOP_REASON, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
104
105
  import { thisBoot } from "./session-seen.mjs";
105
106
  import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
@@ -3683,7 +3684,13 @@ function* spawnBody(root, agent, o = {}) {
3683
3684
  if (relation === "unrelated" && relativeTo) throw new Error(`relation "unrelated" takes no relativeTo`);
3684
3685
  if (relation && relation !== "unrelated" && !relativeTo) throw new Error(`relation "${relation}" needs a relative-to instance`);
3685
3686
  if (typeof o.relativeRoot === "string" && o.relativeRoot.trim() && !relativeTo && !legacyParent) throw new Error(`relativeRoot only qualifies relativeTo/parent`);
3687
+ if (o.relatedWork !== undefined && typeof o.relatedWork !== "boolean") throw oatsError("E_BAD_ARGS", "relatedWork must be true or false");
3688
+ // `sameWork`, the option's old name, is an alias (the related-work compatibility layer): either sets the flag.
3689
+ // Its use is said once per call as Node's DeprecationWarning (stderr, never an answer); the CLI passes
3690
+ // `relatedWork`, its own alias having said so already (lib/command-flags.mjs SAME_WORK_ALIASES).
3686
3691
  if (o.sameWork !== undefined && typeof o.sameWork !== "boolean") throw oatsError("E_BAD_ARGS", "sameWork must be true or false");
3692
+ if (o.sameWork !== undefined) process.emitWarning(SAME_WORK_OPTION_RENAMED, { type: "DeprecationWarning", code: "OATS_SAME_WORK" });
3693
+ const relatedWorkAsked = o.relatedWork === true || o.sameWork === true;
3687
3694
  if (!relation && legacyParent) { relation = "child"; relativeTo = legacyParent; }
3688
3695
  if (relation === "unrelated") { relation = undefined; relativeTo = undefined; }
3689
3696
 
@@ -3814,11 +3821,12 @@ function* spawnBody(root, agent, o = {}) {
3814
3821
  if (anchorMeta?.siblingInstance) siblingInstance = anchorMeta.siblingInstance;
3815
3822
  }
3816
3823
  if (!relation && attachedOwner && attachedOwner !== instance) parentInstance = attachedOwner;
3817
- // Feature instance-same-work: the flag binds the parent the new home records, whichever relation gave
3818
- // it (child, a sibling of a non-root, --relation parent under a parented anchor, attached). None: refused
3819
- // here, before any home, worktree or hook, a preview's included.
3820
- if (o.sameWork === true && !(parentInstance && parentInstance !== instance)) {
3821
- throw oatsError("E_BAD_ARGS", `--same-work needs a parent: ${instance} would record no parent instance${relation ? ` (relation ${relation}${relativeTo ? ` to ${relativeTo}` : ""})` : ""}; spawn it with --parent <instance>, or without --same-work; nothing was spawned`);
3824
+ // Feature instance-related-work: the flag binds the parent the new home records, whichever relation gave
3825
+ // it (child, a sibling of a non-root, --relation parent under a parented anchor, attached), else the
3826
+ // sibling it records (a sibling of a root or of a root's sibling, --relation parent over an anchor with a
3827
+ // sibling link). Neither: refused here, before any home, worktree or hook, a preview's included.
3828
+ if (relatedWorkAsked && !relatedWorkBinding({ parentInstance: parentInstance !== instance ? parentInstance : undefined, siblingInstance: siblingInstance !== instance ? siblingInstance : undefined })) {
3829
+ throw oatsError("E_BAD_ARGS", `--related-work needs a parent or a sibling: ${instance} would record no parent or sibling instance${relation ? ` (relation ${relation}${relativeTo ? ` to ${relativeTo}` : ""})` : ""}; spawn it with --parent <instance> or --relation sibling --relative-to <instance>, or without --related-work; nothing was spawned`);
3822
3830
  }
3823
3831
  // K5 §4 — child-spawn permission is ENFORCED here, by the spawn route. The
3824
3832
  // parent's recorded policy (instance.json policy.childSpawns) says whether
@@ -4939,9 +4947,10 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4939
4947
  Object.assign(meta, workspaceRecord);
4940
4948
  }
4941
4949
  const spawnWarnings = warnings;
4942
- // Feature instance-same-work: bound to the parent the home records, written before the launch so that
4943
- // the instance's first status shows it; the home's removal on a rollback takes it with the rest.
4944
- if (o.sameWork === true && meta.parentInstance) writeSameWork(home, meta.parentInstance);
4950
+ // Feature instance-related-work: bound to the parent the home records, else to its sibling (the one
4951
+ // choice, relatedWorkBinding), written before the launch so that the instance's first status shows it;
4952
+ // the home's removal on a rollback takes it with the rest.
4953
+ if (relatedWorkAsked && relatedWorkBinding(meta)) writeRelatedWork(home, relatedWorkBinding(meta));
4945
4954
 
4946
4955
  spawnTmux = meta.tmux;
4947
4956
  if (work === "directory") assertDirectoryRoots(home, homeReal);
@@ -5476,13 +5485,15 @@ function retireGitProbe(repo, args, { encoding } = {}) {
5476
5485
  * KERNEL_HOME_NAME_PREFIXES in lib/capability-contract.mjs, and the schema). */
5477
5486
  // `.oats-color.json` (feature instance-color) and `.oats-background.json` (feature instance-background) are
5478
5487
  // presentation anyone may change at any time: never work. `.oats-pinned.json` (feature instance-pin) is
5479
- // presentation of the same kind.
5480
- // `.oats-same-work.json` (feature instance-same-work) is kernel presentation of the same kind.
5488
+ // presentation of the same kind. `.oats-board.json` (feature instance-board) is the agent's own display, and
5489
+ // `.oats-board.lock` what a write killed while it held the lock leaves: never work.
5490
+ // `.oats-related-work.json` (feature instance-related-work) is kernel presentation of the same kind, and so is
5491
+ // `.oats-same-work.json`, the file of the flag it replaced: read while the new one is absent, never written.
5481
5492
  // `.oats-start-exited` (lib/session-end.mjs) is the window's record of how the harness ended: every
5482
5493
  // launched home whose harness ever ended holds it.
5483
5494
  // `.oats-start-env.json` and its key (lib/start-env.mjs) are written at every start that renders a
5484
5495
  // recipe, after the spawn's baseline: every launched home holds them.
5485
- const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", ".oats-background.json", PIN_FILE, SAME_WORK_FILE, START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
5496
+ const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", ".oats-background.json", PIN_FILE, BOARD_FILE, BOARD_LOCK, RELATED_WORK_FILE, SAME_WORK_FILE, START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
5486
5497
  // `instance.json.tmp-<pid>` is what a process killed between the two steps of writeJsonAtomic leaves
5487
5498
  // of the record: not a hidden name, so a capability cannot declare it (disposableHomeRootProblem).
5488
5499
  const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, /^instance\.json\.tmp-\d+$/, START_ENV_TMP, LAUNCH_ENV_HANDOFF];
@@ -9559,7 +9570,7 @@ const claimCommand = (action) => action === "resume" ? "oats session start --res
9559
9570
  /** What each verb that meets a held claim says it did not do: the words its refusals end with,
9560
9571
  * before any effect. After a takeover ended a dead holder's step, every verb says the same
9561
9572
  * (lib/errors.mjs nothingAfter). */
9562
- const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", resume: "nothing was started", start: "nothing was started", "worktree add": "no tree was made", "instance color": "the colour was not changed", "instance same-work": "the flag was not changed", "instance background": "the background was not changed", "instance pin": "the pin was not changed" };
9573
+ const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", resume: "nothing was started", start: "nothing was started", "worktree add": "no tree was made", "instance color": "the colour was not changed", "instance related-work": "the flag was not changed", "instance background": "the background was not changed", "instance pin": "the pin was not changed" };
9563
9574
 
9564
9575
  /** The refusals of `arriving` ("retire", "stop", "upgrade", "resume", "start", or "worktree add", which
9565
9576
  * reads the claim and does not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
@@ -0,0 +1,337 @@
1
+ /** The agent's board (feature instance-board, `boardApi: 1`): the facts an agent keeps in view for its
2
+ * person (`oats instance board set|unset`) and the questions it asks them (`oats instance board ask`, closed
3
+ * with `ask --clear`). Agent-reported, display only: the kernel routes no answer and acts on nothing here.
4
+ * The contract is docs/desktop-cli-api.md "The agent's board".
5
+ *
6
+ * ONE HOME FILE, `<home>/.oats-board.json`, kernel-owned (KERNEL_HOME_NAME_PREFIXES, the retire receipts,
7
+ * the manifest schema), written atomically at mode 0600 under a short lock (`.oats-board.lock`), so that
8
+ * parallel writes of one agent never lose one. The file:
9
+ * { boardApi: 1, asked: <n>, facts: { <key>: { label, value, unit, link, at, seq, history: [{ value, at }] } },
10
+ * questions: [{ id, question, options, context, since, session }] }
11
+ * `asked` numbers the default ids (`q<n>`), never reused while the home lives; `seq` keeps the facts in the
12
+ * order first set (a key such as "1" would otherwise lead a JSON object). A reader takes a regular file
13
+ * only, without following a link, up to FILE_MAX bytes; a file that is not a valid board in every part
14
+ * reads as an empty board, never an error; no file reads as null.
15
+ *
16
+ * FACTS persist across sessions until unset or the home is retired. QUESTIONS are per session: each records
17
+ * the session it was asked in (the id of the incarnation's latest kernel session boundary, `launched`,
18
+ * `restarted` or `stopped`: lib/instance-events.mjs liveSession), and is live only while that is still the
19
+ * current session, read with proof: where the log's bounded read cannot show the current session (a tail
20
+ * with no boundary), no question is live. One that is not live is not shown, and a write drops it.
21
+ *
22
+ * THE CLAIM. While a question is live, the home holds the waiting claim of producer `oats.board`, reason
23
+ * `attention` (it holds no scheduled wake), message the oldest live question, bound to the session the write
24
+ * read (setWaiting `session`): a boundary written meanwhile ends it with the question. Every write sets the
25
+ * claim to what the board's questions say after it, so the write that fails to record it is repaired by the
26
+ * next, and a retry of the same command is no change to the board.
27
+ *
28
+ * THE ROW BOUND. The row value (`boardRow`: facts without history, questions without context) is at most
29
+ * ROW_MAX bytes as UTF-8 JSON: a write that would pass it is refused (E_BOARD_FULL), and a file whose row
30
+ * passes it is not a valid board. Every client can rely on the bound per row. Dependency-free. */
31
+ import { lstatSync, rmSync } from "node:fs";
32
+ import { join } from "node:path";
33
+ import { readFileHead } from "./bounded-read.mjs";
34
+ import { withDirLock } from "./dir-lock.mjs";
35
+ import { REFUSED_TEXT } from "./refused-text.mjs";
36
+ import { liveSession, setWaiting } from "./instance-events.mjs";
37
+ import { BOARD_API } from "./kernel-features.mjs";
38
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
39
+
40
+ /** The record's version, the command answer's and the probe's (defined beside the features, which the
41
+ * probe reads without loading this module). */
42
+ export { BOARD_API };
43
+ /** The home file and its lock, kernel-owned. */
44
+ export const BOARD_FILE = ".oats-board.json";
45
+ export const BOARD_LOCK = ".oats-board.lock";
46
+ /** The producer of the board's waiting claim. */
47
+ export const BOARD_PRODUCER = "oats.board";
48
+ /** The bounds (code points, except ROW_MAX and FILE_MAX in bytes, LINK_MAX in ASCII characters). */
49
+ export const BOARD_LIMITS = Object.freeze({ facts: 12, questions: 9, options: { min: 2, max: 4 }, history: 20, key: 16, label: 40, value: 80, unit: 16, option: 60, question: 200, context: 2000, link: 512 });
50
+ export const ROW_MAX = 8192;
51
+ /** A file larger than this is not a board: 12 facts with 20 values each, and 9 contexts, fit well inside it. */
52
+ const FILE_MAX = 256 * 1024;
53
+ /** How long a write waits for another write of the same board. */
54
+ const LOCK_WAIT_MS = 5000;
55
+ /** A fact's key and a question's id. */
56
+ export const BOARD_KEY_RE = /^[a-z0-9][a-z0-9-]{0,15}$/;
57
+
58
+ const boardError = (code, message, details) => Object.assign(new Error(message), { code, ...(details ? { details } : {}) });
59
+ const points = (s) => [...s].length;
60
+ const validTime = (at) => typeof at === "string" && Number.isFinite(Date.parse(at));
61
+ /** One line of 1 to `max` code points, with none of the kernel's refused characters (REFUSED_TEXT). */
62
+ const lineOk = (s, max) => typeof s === "string" && s.length > 0 && points(s) <= max && !REFUSED_TEXT.test(s);
63
+ /** A context: 1 to BOARD_LIMITS.context code points; newlines (LF) allowed, every other refused character not. */
64
+ const contextOk = (s) => typeof s === "string" && s.length > 0 && points(s) <= BOARD_LIMITS.context && s.split("\n").every((l) => !REFUSED_TEXT.test(l));
65
+ /** An absolute `https:` URL of at most BOARD_LIMITS.link printable ASCII characters, with a host. */
66
+ export function linkOk(s) {
67
+ if (typeof s !== "string" || s.length > BOARD_LIMITS.link || !/^https:\/\/[\x21-\x7e]+$/.test(s)) return false;
68
+ try { const u = new URL(s); return u.protocol === "https:" && u.hostname.length > 0; } catch { return false; }
69
+ }
70
+ const TEXT_RULE = "one line with no control character, line separator, bidi control (U+202A-202E, U+2066-2069), U+200B, U+2060, U+FEFF or tag character";
71
+
72
+ // ---------- reading ----------
73
+
74
+ /** A stored fact, or null when any part of it is not one. */
75
+ function readFact(key, f) {
76
+ if (typeof key !== "string" || !BOARD_KEY_RE.test(key) || !f || typeof f !== "object" || Array.isArray(f)) return null;
77
+ const { label, value, unit = null, link = null, at, seq, history } = f;
78
+ if (!lineOk(label, BOARD_LIMITS.label) || !lineOk(value, BOARD_LIMITS.value) || !validTime(at) || !Number.isSafeInteger(seq) || seq < 0) return null;
79
+ if (unit !== null && !lineOk(unit, BOARD_LIMITS.unit)) return null;
80
+ if (link !== null && !linkOk(link)) return null;
81
+ if (!Array.isArray(history) || history.length < 1 || history.length > BOARD_LIMITS.history) return null;
82
+ if (!history.every((h) => h && typeof h === "object" && lineOk(h.value, BOARD_LIMITS.value) && validTime(h.at))) return null;
83
+ return { key, label, value, unit, link, at, seq, history: history.map((h) => ({ value: h.value, at: h.at })) };
84
+ }
85
+ /** A stored question, or null when any part of it is not one. */
86
+ function readQuestion(q) {
87
+ if (!q || typeof q !== "object" || Array.isArray(q)) return null;
88
+ const { id, question, options, context = null, since, session = null } = q;
89
+ if (typeof id !== "string" || !BOARD_KEY_RE.test(id) || !lineOk(question, BOARD_LIMITS.question) || !validTime(since)) return null;
90
+ if (session !== null && !(typeof session === "string" && session.length <= 128)) return null;
91
+ if (!Array.isArray(options) || options.length < BOARD_LIMITS.options.min || options.length > BOARD_LIMITS.options.max || !options.every((o) => lineOk(o, BOARD_LIMITS.option))) return null;
92
+ if (context !== null && !contextOk(context)) return null;
93
+ return { id, question, options: [...options], context, since, session };
94
+ }
95
+ const EMPTY = () => ({ asked: 0, facts: [], questions: [] });
96
+ /** The board document of `home`: `{ asked, facts: [...] in first-set order, questions: [...] in the order
97
+ * asked }`, every question kept (live or not); null for no file (nothing at the name, or a home that can't
98
+ * be read, so nothing shows one); EMPTY for anything that is not a valid
99
+ * board in every part (not a regular file, a link, over FILE_MAX, not JSON, another boardApi, a fact or a
100
+ * question out of its rules, too many, a repeated id, a row over ROW_MAX). Never throws. */
101
+ export function readBoardDocument(home) {
102
+ // No entry that can be seen at the name is no board: absent, or a home whose directory can't be read
103
+ // (mode 000), where nothing shows a file is there.
104
+ try { lstatSync(join(home, BOARD_FILE)); } catch { return null; }
105
+ let bytes, size;
106
+ try { ({ bytes, size } = readFileHead(join(home, BOARD_FILE), FILE_MAX + 1)); }
107
+ catch { return EMPTY(); }
108
+ if (size > FILE_MAX) return EMPTY();
109
+ let doc;
110
+ try { doc = JSON.parse(bytes.toString("utf8")); } catch { return EMPTY(); }
111
+ if (!doc || typeof doc !== "object" || Array.isArray(doc) || doc.boardApi !== BOARD_API) return EMPTY();
112
+ const { asked = 0, facts = {}, questions = [] } = doc;
113
+ if (!Number.isSafeInteger(asked) || asked < 0 || !facts || typeof facts !== "object" || Array.isArray(facts) || !Array.isArray(questions)) return EMPTY();
114
+ const keys = Object.keys(facts);
115
+ if (keys.length > BOARD_LIMITS.facts || questions.length > BOARD_LIMITS.questions) return EMPTY();
116
+ const read = keys.map((k) => readFact(k, facts[k]));
117
+ const asks = questions.map(readQuestion);
118
+ if (read.includes(null) || asks.includes(null) || new Set(asks.map((q) => q.id)).size !== asks.length) return EMPTY();
119
+ const out = { asked, facts: read.sort((x, y) => x.seq - y.seq), questions: asks };
120
+ return rowBytes(out) > ROW_MAX ? EMPTY() : out;
121
+ }
122
+
123
+
124
+ /** The row value of a document (its questions already the live ones): what `oats status --json` and
125
+ * `oats server roster --json` rows carry as `board`. */
126
+ export function boardRow(doc) {
127
+ return {
128
+ facts: doc.facts.map((f) => ({ key: f.key, label: f.label, value: f.value, unit: f.unit, link: f.link, at: f.at })),
129
+ questions: doc.questions.map((q) => ({ id: q.id, question: q.question, options: [...q.options], hasContext: q.context !== null, since: q.since })),
130
+ };
131
+ }
132
+ /** The inspect value (`oats inspect --home <h> --board`): the row's, with each fact's history and each
133
+ * question's context. */
134
+ export function boardDetail(doc) {
135
+ const row = boardRow(doc);
136
+ return {
137
+ facts: row.facts.map((f, i) => ({ ...f, history: doc.facts[i].history.map((h) => ({ ...h })) })),
138
+ questions: row.questions.map((q, i) => ({ ...q, context: doc.questions[i].context })),
139
+ };
140
+ }
141
+ const rowBytes = (doc) => Buffer.byteLength(JSON.stringify(boardRow(doc)), "utf8");
142
+
143
+ /** The live board of a stored document (`stored`: readBoardDocument's): its questions only the ones asked
144
+ * in the current session, and none when that session can't be proved (an unknown incarnation, a log tail
145
+ * with no boundary). `s`: the home's liveSession. null stays null. */
146
+ function liveOf(stored, s) {
147
+ if (stored === null || !stored.questions.length) return stored;
148
+ if (s.incarnation === null || !s.sessionKnown) return { ...stored, questions: [] };
149
+ return { ...stored, questions: stored.questions.filter((q) => q.session === s.session) };
150
+ }
151
+ /** `session`: the home's liveSession when the caller has read it (the status rows), else it is read here,
152
+ * only when the file holds a question. */
153
+ const liveDocument = (home, { session, meta } = {}) => {
154
+ const stored = readBoardDocument(home);
155
+ if (stored === null || !stored.questions.length) return stored;
156
+ return liveOf(stored, session ?? liveSession(home, meta !== undefined ? { meta } : {}));
157
+ };
158
+
159
+ /** `board` on a status row: null for a home with no board file, else the row value of its live board.
160
+ * Never throws: a board that cannot be read is an empty one. */
161
+ export function readBoardRow(home, options) {
162
+ try { const doc = liveDocument(home, options); return doc === null ? null : boardRow(doc); }
163
+ catch { return { facts: [], questions: [] }; }
164
+ }
165
+ /** `instance.board` on `oats inspect --home <h> --board`: as readBoardRow, with history and context. */
166
+ export function readBoardDetail(home) {
167
+ try { const doc = liveDocument(home); return doc === null ? null : boardDetail(doc); }
168
+ catch { return { facts: [], questions: [] }; }
169
+ }
170
+
171
+ /** The READ rule for a `board` another kernel reports (a remote roster row): the row value exactly as this
172
+ * kernel would write it, every fact and question within its rules and the whole within ROW_MAX, or an
173
+ * empty board. null stays null. */
174
+ export function readRemoteBoard(board) {
175
+ if (board === null) return null;
176
+ const empty = { facts: [], questions: [] };
177
+ if (!board || typeof board !== "object" || Array.isArray(board) || !Array.isArray(board.facts) || !Array.isArray(board.questions)) return empty;
178
+ if (board.facts.length > BOARD_LIMITS.facts || board.questions.length > BOARD_LIMITS.questions) return empty;
179
+ const facts = board.facts.map((f, i) => (f && typeof f === "object" ? readFact(f.key, { ...f, seq: i, history: [{ value: f.value, at: f.at }] }) : null));
180
+ const questions = board.questions.map((q) => (q && typeof q === "object" && typeof q.hasContext === "boolean" ? readQuestion({ ...q, context: q.hasContext ? "x" : null, session: null }) : null));
181
+ if (facts.includes(null) || questions.includes(null) || new Set(facts.map((f) => f.key)).size !== facts.length || new Set(questions.map((q) => q.id)).size !== questions.length) return empty;
182
+ const doc = { asked: 0, facts, questions };
183
+ return rowBytes(doc) > ROW_MAX ? empty : boardRow(doc);
184
+ }
185
+
186
+ // ---------- writing ----------
187
+
188
+ /** The checks of one fact's fields, as the CLI gives them → the fields, or E_BAD_ARGS naming the first. */
189
+ function checkFact({ key, label, value, unit, link }) {
190
+ if (typeof key !== "string" || !BOARD_KEY_RE.test(key)) throw boardError("E_BAD_ARGS", `the key must match ${BOARD_KEY_RE.source} (a lowercase letter or digit, then up to 15 lowercase letters, digits or hyphens)`);
191
+ if (label === undefined) throw boardError("E_BAD_ARGS", "--label is required");
192
+ if (value === undefined) throw boardError("E_BAD_ARGS", "--value is required");
193
+ for (const [name, v, max] of [["label", label, BOARD_LIMITS.label], ["value", value, BOARD_LIMITS.value], ["unit", unit, BOARD_LIMITS.unit]]) {
194
+ if (v !== undefined && !lineOk(v, max)) throw boardError("E_BAD_ARGS", `--${name} must be ${TEXT_RULE}, of 1 to ${max} characters`);
195
+ }
196
+ if (link !== undefined && !linkOk(link)) throw boardError("E_BAD_ARGS", `--link must be an absolute https: URL of at most ${BOARD_LIMITS.link} printable ASCII characters`);
197
+ return { key, label, value, unit: unit ?? null, link: link ?? null };
198
+ }
199
+ /** The checks of one question → its fields, or E_BAD_ARGS naming the first. */
200
+ function checkQuestion({ question, options, id, context }) {
201
+ if (question === undefined) throw boardError("E_BAD_ARGS", "the question is required: oats instance board ask <question> --option <text> --option <text>");
202
+ if (!lineOk(question, BOARD_LIMITS.question)) throw boardError("E_BAD_ARGS", `the question must be ${TEXT_RULE}, of 1 to ${BOARD_LIMITS.question} characters`);
203
+ if (!Array.isArray(options) || options.length < BOARD_LIMITS.options.min || options.length > BOARD_LIMITS.options.max) throw boardError("E_BAD_ARGS", `a question takes ${BOARD_LIMITS.options.min} to ${BOARD_LIMITS.options.max} --option (got ${Array.isArray(options) ? options.length : 0})`);
204
+ for (const o of options) if (!lineOk(o, BOARD_LIMITS.option)) throw boardError("E_BAD_ARGS", `each --option must be ${TEXT_RULE}, of 1 to ${BOARD_LIMITS.option} characters`);
205
+ if (id !== undefined && !BOARD_KEY_RE.test(id)) throw boardError("E_BAD_ARGS", `--id must match ${BOARD_KEY_RE.source}`);
206
+ if (context !== undefined && !contextOk(context)) throw boardError("E_BAD_ARGS", `the context must be 1 to ${BOARD_LIMITS.context} characters, with no control character but newline (LF), line separator, bidi control (U+202A-202E, U+2066-2069), U+200B, U+2060, U+FEFF or tag character`);
207
+ return { question, options: [...options], id, context: context ?? null };
208
+ }
209
+
210
+ /** The file's bytes for a document. */
211
+ function serialize(doc) {
212
+ const facts = {};
213
+ for (const f of doc.facts) facts[f.key] = { label: f.label, value: f.value, unit: f.unit, link: f.link, at: f.at, seq: f.seq, history: f.history };
214
+ return JSON.stringify({ boardApi: BOARD_API, asked: doc.asked, facts, questions: doc.questions }) + "\n";
215
+ }
216
+
217
+ /** One read-modify-write of `home`'s board, under its lock. `change(doc, now)` (doc: the live board, an
218
+ * empty one for no file) returns `{ changed, ...answer }` and may change `doc`; a change is checked against
219
+ * the bounds and written, and then the claim is set to what the questions say. → the answer with `board`,
220
+ * the row value after it. The caller holds the right to change the home. */
221
+ function updateBoard(home, change, { now = () => new Date() } = {}) {
222
+ const path = join(home, BOARD_FILE), lock = join(home, BOARD_LOCK);
223
+ return withDirLock(lock, "oats instance board", () => {
224
+ const stored = readBoardDocument(home);
225
+ // The session, read once under the lock: what the questions are judged by, what a new one records, and
226
+ // what the claim is bound to.
227
+ const s = liveSession(home);
228
+ const live = liveOf(stored, s);
229
+ const doc = live === null ? EMPTY() : { ...live, facts: [...live.facts], questions: [...live.questions] };
230
+ const out = change(doc, now().toISOString(), s.sessionKnown ? s.session : undefined);
231
+ // A question a session boundary ended is dropped by any write: a change, or one that only prunes.
232
+ const pruned = stored !== null && stored.questions.length !== doc.questions.length;
233
+ const written = out.changed || pruned;
234
+ if (written) {
235
+ if (doc.facts.length > BOARD_LIMITS.facts) throw boardError("E_BOARD_FULL", `the board holds at most ${BOARD_LIMITS.facts} facts: unset one first (oats instance board unset <key>); nothing was changed`);
236
+ if (doc.questions.length > BOARD_LIMITS.questions) throw boardError("E_BOARD_FULL", `at most ${BOARD_LIMITS.questions} questions are open at once: clear one you have read first (oats instance board ask --clear <id>); nothing was changed`);
237
+ const bytes = rowBytes(doc);
238
+ if (bytes > ROW_MAX) throw boardError("E_BOARD_FULL", `the board would be ${bytes} bytes on a status row, over its ${ROW_MAX}-byte bound: shorten it, or unset a fact or clear a question first; nothing was changed`, { bytes, max: ROW_MAX });
239
+ // What stands at the name, never followed: a directory there is no one's work (the name is kernel-owned),
240
+ // and a rename cannot replace it.
241
+ let standing = null;
242
+ try { standing = lstatSync(path); } catch (e) { if (e?.code !== "ENOENT") throw e; }
243
+ if (standing?.isDirectory()) rmSync(path, { force: true, recursive: true });
244
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, serialize(doc), 0o600);
245
+ }
246
+ // Under the lock, so that two writes set the claim in the order they wrote the board.
247
+ syncClaim(home, doc, s, out);
248
+ const { changed, ...rest } = out;
249
+ return { ...rest, changed, board: stored === null && !written ? null : boardRow(doc) };
250
+ }, { retryMs: LOCK_WAIT_MS, busy: (why) => boardError("E_BOARD_BUSY", `the board of ${home} is being written by another oats process (${why}); retry; if no oats process is writing it, remove ${lock}; nothing was changed`, { lock }) });
251
+ }
252
+
253
+ /** Set the `oats.board` claim to what the live questions say: the oldest one's text while any is open, none
254
+ * otherwise. setWaiting writes only a change. A write it refuses is E_EVENTS_FAILED, after the board was
255
+ * written: the next board command repairs it. */
256
+ function syncClaim(home, doc, s, out) {
257
+ // Only a question of the proved session is live (liveOf), so a claim is set only for one.
258
+ const oldest = s.sessionKnown ? doc.questions.find((q) => q.session === s.session) : undefined;
259
+ try {
260
+ setWaiting(home, oldest ? { producer: BOARD_PRODUCER, waiting: true, reason: "attention", message: oldest.question, session: s.session } : { producer: BOARD_PRODUCER, waiting: false });
261
+ } catch (e) {
262
+ const what = out.id !== undefined ? `question ${out.id}` : `fact ${out.key}`;
263
+ throw boardError(e.code || "E_EVENTS_FAILED", `the board was written (${what}), but its needs-input claim was not: ${e.message}; run the same board command again to repair it (it changes nothing on the board)`, { ...(out.id !== undefined ? { id: out.id } : { key: out.key }) });
264
+ }
265
+ }
266
+
267
+ /** `oats instance board set <key>`: upsert one fact. A set that changes nothing writes nothing; a new value
268
+ * joins the key's history (its last BOARD_LIMITS.history values). → `{ key, changed, board }`. */
269
+ export function setBoardFact(home, fields, options) {
270
+ const fact = checkFact(fields);
271
+ return updateBoard(home, (doc, now) => {
272
+ const i = doc.facts.findIndex((f) => f.key === fact.key);
273
+ const old = i >= 0 ? doc.facts[i] : null;
274
+ if (old && old.label === fact.label && old.value === fact.value && old.unit === fact.unit && old.link === fact.link) return { key: fact.key, changed: false };
275
+ if (!old && doc.facts.length >= BOARD_LIMITS.facts) throw boardError("E_BOARD_FULL", `the board holds at most ${BOARD_LIMITS.facts} facts: unset one first (oats instance board unset <key>); nothing was changed`);
276
+ const history = old ? (old.value === fact.value ? old.history : [...old.history, { value: fact.value, at: now }].slice(-BOARD_LIMITS.history)) : [{ value: fact.value, at: now }];
277
+ const next = { ...fact, at: now, seq: old ? old.seq : Math.max(-1, ...doc.facts.map((f) => f.seq)) + 1, history };
278
+ if (old) doc.facts[i] = next; else doc.facts.push(next);
279
+ return { key: fact.key, changed: true };
280
+ }, options);
281
+ }
282
+
283
+ /** `oats instance board unset <key>`: remove one fact and its history. → `{ key, changed, board }`. */
284
+ export function unsetBoardFact(home, key, options) {
285
+ if (typeof key !== "string" || !BOARD_KEY_RE.test(key)) throw boardError("E_BAD_ARGS", `the key must match ${BOARD_KEY_RE.source}`);
286
+ return updateBoard(home, (doc) => {
287
+ const i = doc.facts.findIndex((f) => f.key === key);
288
+ if (i < 0) return { key, changed: false };
289
+ doc.facts.splice(i, 1);
290
+ return { key, changed: true };
291
+ }, options);
292
+ }
293
+
294
+ /** `oats instance board ask <question>`: open one question. Its id is `--id`, else `q<n>` (n numbered per
295
+ * home, never reused while it lives). The same question asked again under an open id is no change, so a
296
+ * retry is safe; a different one under an open id is refused. → `{ id, changed, board }`. */
297
+ export function askBoardQuestion(home, fields, options) {
298
+ const ask = checkQuestion(fields);
299
+ return updateBoard(home, (doc, now, session) => {
300
+ // No question is asked where the session can't be proved: it could never be live.
301
+ if (session === undefined) throw boardError("E_BOARD_FAILED", `the instance's current session can't be read from its events log (its last 4 MiB hold no session boundary), so a question would never show; use oats instance attention --message instead; nothing was changed`);
302
+ const same = (q) => q.question === ask.question && q.context === ask.context && q.options.length === ask.options.length && q.options.every((o, i) => o === ask.options[i]);
303
+ const open = ask.id !== undefined ? doc.questions.find((q) => q.id === ask.id) : doc.questions.find(same);
304
+ if (open) {
305
+ if (same(open)) return { id: open.id, changed: false };
306
+ throw boardError("E_BAD_ARGS", `question ${ask.id} is open with other text: clear it first (oats instance board ask --clear ${ask.id}), or ask under another --id; nothing was changed`);
307
+ }
308
+ if (doc.questions.length >= BOARD_LIMITS.questions) throw boardError("E_BOARD_FULL", `at most ${BOARD_LIMITS.questions} questions are open at once: clear one you have read first (oats instance board ask --clear <id>); nothing was changed`);
309
+ let id = ask.id;
310
+ if (id === undefined) {
311
+ const taken = new Set(doc.questions.map((q) => q.id));
312
+ let n = doc.asked;
313
+ do { n += 1; id = `q${n}`; } while (taken.has(id));
314
+ // q<n> is a key of at most 16 characters: past q999999999999999 there is no default id.
315
+ if (!BOARD_KEY_RE.test(id)) throw boardError("E_BOARD_FULL", "no default id is left on this board (they reached q999999999999999): ask with --id <id>; nothing was changed");
316
+ doc.asked = n;
317
+ } else {
318
+ // An explicit q<n> moves the count past it, so a default id never repeats it.
319
+ const n = /^q([1-9][0-9]{0,14})$/.exec(id);
320
+ if (n) doc.asked = Math.max(doc.asked, Number(n[1]));
321
+ }
322
+ doc.questions.push({ id, question: ask.question, options: ask.options, context: ask.context, since: now, session });
323
+ return { id, changed: true };
324
+ }, options);
325
+ }
326
+
327
+ /** `oats instance board ask --clear <id>`: close one question; an id that is not open is no change.
328
+ * → `{ id, changed, board }`. */
329
+ export function clearBoardQuestion(home, id, options) {
330
+ if (typeof id !== "string" || !BOARD_KEY_RE.test(id)) throw boardError("E_BAD_ARGS", `--clear takes the id of an open question (${BOARD_KEY_RE.source})`);
331
+ return updateBoard(home, (doc) => {
332
+ const i = doc.questions.findIndex((q) => q.id === id);
333
+ if (i < 0) return { id, changed: false };
334
+ doc.questions.splice(i, 1);
335
+ return { id, changed: true };
336
+ }, options);
337
+ }