@awebai/oats 0.69.22 → 0.69.24
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.
- package/bin/oats.mjs +185 -38
- package/docs/capabilities.md +365 -7
- package/docs/capability-manifest.schema.json +37 -1
- package/docs/configuration.md +27 -7
- package/docs/container.md +206 -228
- package/docs/design/2026-11-19-sandboxes.md +1352 -0
- package/docs/design/2026-11-20-provider-home-lifecycle.md +320 -0
- package/docs/design/README.md +7 -0
- package/docs/desktop-cli-api.md +673 -81
- package/docs/desktop.md +241 -65
- package/docs/execution-targets.md +186 -3
- package/docs/first-team.md +11 -0
- package/docs/implementation.md +6 -2
- package/docs/integrations.md +3 -3
- package/docs/knowledge-capability-authoring.md +10 -7
- package/docs/knowledge-reference/acceptance.md +21 -19
- package/docs/knowledge-reference/adoption.md +18 -4
- package/docs/knowledge-reference/model.md +11 -9
- package/docs/knowledge-reference/package-craft.md +2 -2
- package/docs/knowledge-reference/proposal.md +127 -0
- package/docs/knowledge-reference/provider-mapping.md +10 -10
- package/docs/knowledge-reference/reader-capture.md +26 -22
- package/docs/knowledge-theory.md +1 -1
- package/docs/knowledge.md +25 -16
- package/docs/official-catalog.md +4 -4
- package/docs/packages.md +13 -13
- package/docs/release-notes/v0.69.23.md +231 -0
- package/docs/release-notes/v0.69.24.md +264 -0
- package/docs/servers.md +10 -6
- package/docs/souls-and-instances.md +96 -22
- package/docs/tui.md +25 -4
- package/docs/upgrading.md +19 -5
- package/docs/workspaces.md +14 -6
- package/lib/argv.mjs +6 -2
- package/lib/capability-contract.mjs +2 -2
- package/lib/capability-show.mjs +11 -1
- package/lib/command-flags.mjs +40 -3
- package/lib/compile-cache.mjs +1 -1
- package/lib/core.mjs +1201 -195
- package/lib/errors.mjs +4 -1
- package/lib/hook-env.mjs +106 -0
- package/lib/host-run.mjs +11 -3
- package/lib/instance-board.mjs +337 -0
- package/lib/instance-events.mjs +48 -10
- package/lib/instance-inspect.mjs +44 -0
- package/lib/instance-lifecycle.mjs +34 -18
- package/lib/instance-listing.mjs +113 -16
- package/lib/instance-related-work.mjs +143 -0
- package/lib/kernel-features.mjs +13 -1
- package/lib/node-version.mjs +9 -0
- package/lib/provider-call-child.mjs +60 -0
- package/lib/provider-resume.mjs +83 -0
- package/lib/provider-test-seams.mjs +20 -0
- package/lib/read-call.mjs +2 -0
- package/lib/reserved-launch-env.mjs +8 -1
- package/lib/retire-admission.mjs +5 -1
- package/lib/schedule.mjs +14 -4
- package/lib/servers.mjs +151 -17
- package/lib/session-inspect.mjs +104 -13
- package/lib/session-providers.mjs +528 -0
- package/lib/session-resume.mjs +68 -15
- package/lib/stable-node.mjs +3 -0
- package/lib/triggers.mjs +3 -1
- package/package-catalog.json +3 -3
- package/package.json +2 -1
- package/packages/client/capability-list.mjs +21 -0
- package/packages/client/cli-adapter.mjs +19 -4
- package/packages/client/cli-locator.mjs +5 -1
- package/packages/client/deployment-data.mjs +27 -3
- package/packages/client/deployment-panel.mjs +27 -4
- package/packages/client/home-board.mjs +33 -19
- package/packages/client/inspect-boundary.mjs +18 -8
- package/packages/client/instance-acts.mjs +30 -3
- package/packages/client/instance-board.mjs +206 -0
- package/packages/client/instance-presentation.mjs +55 -0
- package/packages/client/instance-tree.mjs +34 -4
- package/packages/client/keymap.mjs +5 -0
- package/packages/client/liveness.mjs +15 -4
- package/packages/client/mail-contract.mjs +130 -0
- package/packages/client/own-codes.mjs +5 -1
- package/packages/client/panel-views.mjs +7 -7
- package/packages/client/related-work.mjs +84 -0
- package/packages/client/remote-roster.mjs +9 -3
- package/packages/client/session-backends.mjs +31 -0
- package/packages/client/session-start.mjs +18 -6
- package/packages/client/spawn-apply-cli.mjs +5 -3
- package/packages/client/spawn-apply-contract.mjs +25 -2
- package/packages/client/spawn-apply.mjs +5 -1
- package/packages/client/spawn-messages.mjs +3 -0
- package/packages/client/terminal-contract.mjs +4 -0
- package/packages/client/waiting-on-you.mjs +12 -2
- package/packages/client/workspace-cli.mjs +13 -2
- package/packages/tui/lib/model.mjs +14 -3
- package/packages/tui/lib/store.mjs +12 -3
- package/skills/oats-getting-started/SKILL.md +11 -8
- package/docs/knowledge-reference/harvester.md +0 -109
- package/lib/instance-same-work.mjs +0 -67
- package/packages/client/same-work.mjs +0 -49
package/lib/errors.mjs
CHANGED
|
@@ -78,11 +78,14 @@ const SPAWN_REFUSAL_DETAILS = Object.freeze({
|
|
|
78
78
|
});
|
|
79
79
|
const spawnFailedDetails = (e) => (e?.details?.unconfirmed === true ? e.details : undefined);
|
|
80
80
|
/** The `details` of the answer to an error `e` of `oats spawn` (bin/oats.mjs spawnFail): the table's
|
|
81
|
-
* for a code it holds, a launch refusal's own (`E_LAUNCH_…`),
|
|
81
|
+
* for a code it holds, a launch refusal's own (`E_LAUNCH_…`), a session backend's (`E_BACKEND_…`), else
|
|
82
|
+
* spawnFailedDetails. */
|
|
82
83
|
export function spawnRefusalDetails(e) {
|
|
83
84
|
const code = kernelCode(e, null);
|
|
84
85
|
if (code && Object.hasOwn(SPAWN_REFUSAL_DETAILS, code)) return SPAWN_REFUSAL_DETAILS[code](e);
|
|
85
86
|
if (code?.startsWith("E_LAUNCH_")) return e.details;
|
|
87
|
+
// A session backend's refusal (lib/session-providers.mjs): the backend, and what it names.
|
|
88
|
+
if (code?.startsWith("E_BACKEND_")) return e.details;
|
|
86
89
|
return spawnFailedDetails(e);
|
|
87
90
|
}
|
|
88
91
|
/** `e` as a kernel error. One whose code an answer carries (isAnswerCode) is returned as it is. Any other is wrapped:
|
package/lib/hook-env.mjs
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/** The environment a capability's code runs with in an instance home (docs/capabilities.md, Commands
|
|
2
|
+
* and hooks): one builder for every lifecycle hook and for a session provider's commands
|
|
3
|
+
* (lib/session-providers.mjs), with the soul, team and kernel facts it is built from. A leaf: the
|
|
4
|
+
* hot reads (lib/hot-reads.mjs: `session inspect`, `status`) call a session provider without
|
|
5
|
+
* loading core.mjs, which imports these and re-exports what it exported. */
|
|
6
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
7
|
+
import { isAbsolute, join } from "node:path";
|
|
8
|
+
import { kernelNode } from "./stable-node.mjs";
|
|
9
|
+
import { teamsEnv } from "./teams.mjs";
|
|
10
|
+
import { PKG_ROOT } from "./version.mjs";
|
|
11
|
+
|
|
12
|
+
/** The canonical path of this kernel's CLI: what the home's shim points at, and OATS_CLI_BIN. */
|
|
13
|
+
export function kernelBin() { return realpathSync(join(PKG_ROOT, "bin", "oats.mjs")); }
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A soul's STABLE identity for capability hooks (OATS_SOUL_ID): what a provider
|
|
17
|
+
* may key durable state on. Workspace soul: `<repo key>#<soul name>` — it does not
|
|
18
|
+
* change when the member commits (the per-commit soul directory does) or when the
|
|
19
|
+
* copy moves. Classic soul: the realpath of agents/<name>/soul, i.e. today's value,
|
|
20
|
+
* so 0.24 deployments are unchanged. Order: an explicit `soulId` (a prepared spawn),
|
|
21
|
+
* the home's recorded `instance.json.workspace.soul` (retire/launch of a workspace
|
|
22
|
+
* home), else the path.
|
|
23
|
+
*/
|
|
24
|
+
export function stableSoulId({ soulId, home, soulDir, agentName } = {}) {
|
|
25
|
+
if (typeof soulId === "string" && soulId) return soulId;
|
|
26
|
+
if (home) {
|
|
27
|
+
try {
|
|
28
|
+
const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
|
|
29
|
+
const s = meta?.workspace?.soul;
|
|
30
|
+
if (typeof s?.id === "string" && s.id) return s.id;
|
|
31
|
+
if (typeof s?.repoKey === "string" && s.repoKey) return `${s.repoKey}#${meta.agent ?? agentName ?? ""}`;
|
|
32
|
+
} catch { /* not a workspace home */ }
|
|
33
|
+
}
|
|
34
|
+
if (soulDir) { try { return realpathSync(soulDir); } catch { return soulDir; } }
|
|
35
|
+
return "";
|
|
36
|
+
}
|
|
37
|
+
/** The soul directory an instance incarnates, as spawn recorded it (instance.json
|
|
38
|
+
* `soulDir`): a workspace soul's per-commit copy (agents/<soul>/souls/<commit12>) or
|
|
39
|
+
* the read-only soul inside a capability package. It is what every classic
|
|
40
|
+
* lifecycle hook and dispatched command sees as OATS_SOUL (captured hooks set
|
|
41
|
+
* none); instance homes carry no soul link. */
|
|
42
|
+
export function instanceSoulDir(home, meta = undefined) {
|
|
43
|
+
if (meta === undefined && home) { try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); } catch { meta = null; } }
|
|
44
|
+
return typeof meta?.soulDir === "string" && isAbsolute(meta.soulDir) ? meta.soulDir : undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The team and workspace facts a lifecycle hook, command or provider check receives (workspace
|
|
48
|
+
* model only, lead decision c3-7): OATS_TEAM_SCOPE is the deployment directory; OATS_WORKSPACE_NAME /
|
|
49
|
+
* _KEY the workspace's name and canonical key; OATS_TEAM_NAME (the 0.25 `team:` block's name) is always
|
|
50
|
+
* empty, so an ambient value never reaches a hook.
|
|
51
|
+
*
|
|
52
|
+
* Team model v2 (docs/desktop-cli-api.md, The provider environment): `resolved.teams` are the soul's
|
|
53
|
+
* TeamRows here and `resolved.defaultTeam` its DefaultTeam; teamsEnv sets OATS_DEFAULT_TEAM(_ID,_FROM),
|
|
54
|
+
* OATS_TEAMS (mapped rows only) and OATS_TEAMS_SOURCE (`live`: the workspace + oats-local.yaml read now,
|
|
55
|
+
* or a fresh resolution; `recorded`: the spawn-time record). A provider LEAVES a joined team only on a
|
|
56
|
+
* `live` list. Teams not known (`resolved.teams` not an array): every team name unset. */
|
|
57
|
+
export function teamEnv(resolved) {
|
|
58
|
+
const ws = resolved?.workspace && typeof resolved.workspace === "object" ? resolved.workspace : {};
|
|
59
|
+
const known = Array.isArray(resolved?.teams);
|
|
60
|
+
return {
|
|
61
|
+
OATS_TEAM_NAME: "", OATS_TEAM_SCOPE: typeof ws.deployment === "string" ? ws.deployment : "",
|
|
62
|
+
...teamsEnv(known ? { teams: resolved.teams, defaultTeam: resolved.defaultTeam ?? null, source: resolved.teamsSource } : null),
|
|
63
|
+
OATS_WORKSPACE_NAME: typeof ws.name === "string" ? ws.name : "", OATS_WORKSPACE_KEY: typeof ws.key === "string" ? ws.key : "",
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export function withoutAmbientHookFacts(env) {
|
|
67
|
+
const { OATS_LAUNCH_PREVIEW: _ambient, OATS_HARNESS_EXECUTABLE: _inherited, OATS_SPAWNER_HOME: _spawner, ...rest } = env;
|
|
68
|
+
return rest;
|
|
69
|
+
}
|
|
70
|
+
/** The environment one capability's lifecycle hook runs with: the invoker's own
|
|
71
|
+
* (inherited, as for every hook; the kernel adds no credentials), plus the
|
|
72
|
+
* standard OATS_* variables (docs/capabilities.md, Commands and hooks) and the
|
|
73
|
+
* caller's `extraEnv`. One builder for every event, so the `worktree` runner
|
|
74
|
+
* (lib/worktree-hooks.mjs) hands its hooks exactly what every other hook gets. */
|
|
75
|
+
export function lifecycleHookEnv(event, cap, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta = {}, extraEnv = {} }) {
|
|
76
|
+
return {
|
|
77
|
+
// OATS_LAUNCH_PREVIEW is the kernel's to give (prepareLaunchHooks), never
|
|
78
|
+
// inherited: a real start's hook must not read an ambient one as a preview.
|
|
79
|
+
// Nor are OATS_HARNESS_EXECUTABLE and OATS_SPAWNER_HOME (spawn's
|
|
80
|
+
// callerSpawner): a hook started from inside an instance must not read its caller's.
|
|
81
|
+
...withoutAmbientHookFacts(process.env),
|
|
82
|
+
// OATS_INSTANCE_HOME is the runtime-neutral contract name for the
|
|
83
|
+
// instance home (absolute). OATS_HOME predates it and stays as a
|
|
84
|
+
// compatibility alias: shipped capability hooks read it
|
|
85
|
+
// (the official oats.aweb and oats.okf packages) and are versioned
|
|
86
|
+
// independently of this kernel. Neither is OATS_HOME_DIR, which is
|
|
87
|
+
// the package STORE root — do not conflate them.
|
|
88
|
+
OATS_EVENT: event, OATS_INSTANCE: instance, OATS_INSTANCE_HOME: home, OATS_HOME: home, OATS_AGENT: agentName,
|
|
89
|
+
OATS_CAPABILITY: cap.id, OATS_LAYER: cap.layer || "", OATS_ROOT: rootDir || "",
|
|
90
|
+
OATS_SOUL: soulDir || "", OATS_SOUL_ID: stableSoulId({ soulId, home, soulDir, agentName }), OATS_CONTEXT: contextDir, OATS_WORKSPACE: workspaceDir || "", OATS_LEVEL: cap.level || "",
|
|
91
|
+
...teamEnv(resolved),
|
|
92
|
+
...extraEnv,
|
|
93
|
+
// Hooks also run through direct core callers (not only bin/oats).
|
|
94
|
+
// Author this from the running kernel, never PATH, ambient env or
|
|
95
|
+
// a caller's extraEnv: those may point at a different executable.
|
|
96
|
+
OATS_CLI_BIN: kernelBin(),
|
|
97
|
+
// The node a capability writes into anything that outlives its hook (lib/stable-node.mjs).
|
|
98
|
+
OATS_NODE_BIN: kernelNode().node,
|
|
99
|
+
OATS_SETTINGS: JSON.stringify(cap.settings || {}),
|
|
100
|
+
// Where each leaf of OATS_SETTINGS came from (JSON pointer → { kind, at }; kind is
|
|
101
|
+
// manifest-default | workspace | soul | host | spawn | anchor), so a provider can tell a
|
|
102
|
+
// soul-set value from a host-set one. {} when the home recorded none (spawned before 0.29).
|
|
103
|
+
OATS_SETTINGS_ORIGINS: JSON.stringify(cap.settingsOrigins || {}),
|
|
104
|
+
OATS_META: JSON.stringify(priorMeta[cap.id] || {}),
|
|
105
|
+
};
|
|
106
|
+
}
|
package/lib/host-run.mjs
CHANGED
|
@@ -107,7 +107,8 @@ function sweepSaid(rows) {
|
|
|
107
107
|
* On the signal, in this order: no minute is armed any more; a tick or a sweep that runs is
|
|
108
108
|
* given 10 s to finish, then new admissions are fenced and owned children are cancelled
|
|
109
109
|
* within a further 5 s (a tick's wake job may start a home, so owned work ends before any
|
|
110
|
-
* home is stopped); one bounded listing; then every running home
|
|
110
|
+
* home is stopped); one bounded listing; then every running home, and every home on a session provider that OATS has
|
|
111
|
+
* not stopped (its session idle or in error included), is stopped, side by side, each by a child of its
|
|
111
112
|
* own (lib/host-stop-child.mjs: the stop `oats session restart` and a retire use, its record
|
|
112
113
|
* written first and asking for a resume, the harness given `stopGraceMs` and never escalated).
|
|
113
114
|
* The next start's sweep resumes those homes.
|
|
@@ -176,7 +177,10 @@ export async function hostRun({
|
|
|
176
177
|
// minute missed while this process did not run is never armed again.
|
|
177
178
|
const ticks = { run: 0, skipped: 0, failed: 0, noScope: 0 };
|
|
178
179
|
let ticking = null, sweeping = null, ticked;
|
|
179
|
-
|
|
180
|
+
// The shutdown's listing asks no session provider: it must answer within its few seconds while
|
|
181
|
+
// the host, and a provider's own server with it, go down. It needs no provider's answer: the
|
|
182
|
+
// stop covers every provider home OATS has not stopped, whatever its session reads.
|
|
183
|
+
const list = (options) => execute(["session", "resume", "--plan", "--without-provider-inspect", "--json"], options);
|
|
180
184
|
const arm = () => { disarm = timer(minute, MINUTE - (now() % MINUTE)); };
|
|
181
185
|
const minute = () => {
|
|
182
186
|
if (signal) return;
|
|
@@ -213,7 +217,11 @@ export async function hostRun({
|
|
|
213
217
|
await Promise.all([ticking, sweeping]);
|
|
214
218
|
const last = await list({ timeoutMs: 3000 });
|
|
215
219
|
if (last?.ok !== true) say(`listing failed ${failed(last)}: no instance is stopped`);
|
|
216
|
-
|
|
220
|
+
// Every running home, and every home on a session provider the listing answered (its row carries
|
|
221
|
+
// `backend`), idle or in error included: a provider restarts such a session on its next input,
|
|
222
|
+
// so the stop is what keeps input refused while the host goes down. A provider home OATS
|
|
223
|
+
// already stopped is idle for the stop, which changes nothing of it.
|
|
224
|
+
const homes = last?.ok === true ? (last.result?.rows ?? []).filter((row) => (row.outcome === OUTCOME.ALREADY_RUNNING || typeof row.backend === "string") && typeof row.home === "string").map((row) => row.home) : [];
|
|
217
225
|
if (homes.length) say(`stopping ${plural(homes.length, "running instance")}, each given ${stopGraceMs / 1000} s`);
|
|
218
226
|
// Side by side: each stop waits for its own harness, and the host's patience is one span for all.
|
|
219
227
|
const stopped = await Promise.all(homes.map(async (home) => {
|
|
@@ -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
|
+
}
|