sil-openclaw 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,478 @@
1
+ /**
2
+ * sil shopping-expert behaviour-artefact store.
3
+ *
4
+ * The agent-creation engine (the bundled `skill/SKILL.md` procedure driving
5
+ * the OpenClaw host CLI) registers the *wiring* of a new sil-wired agent into
6
+ * the host's own config — the `agents.list[]` entry, the enabled `sil` plugin,
7
+ * the attached `sil` skill. That host-config write is the host agent driving
8
+ * its own `openclaw …` CLI; the plugin never touches `~/.openclaw`.
9
+ *
10
+ * What the plugin DOES own is the agent's *behaviour* layer, materialized into
11
+ * its own disclosed `filesystemScope` — `$SIL_DATA_DIR` (the same directory
12
+ * `lib/credentials.ts` uses for tokens/identity). The created expert runs
13
+ * entirely on Spec-Driven Shopping (SDS): the engine writes the SDS behaviour
14
+ * artefacts there, read by the sil skill at runtime:
15
+ *
16
+ * $SIL_DATA_DIR/agents/<agentId>/
17
+ * ├─ domain_spec.md the SDS DOMAIN SPEC — deep researched niche expertise:
18
+ * │ how to buy well, the full mechanics (gearing theory,
19
+ * │ frame geometry, the complete bike-fit process…).
20
+ * │ REQUIRED at creation; web-refreshed every query.
21
+ * ├─ intent_spec.md the SDS INTENT SPEC — the agent-specific decomposition
22
+ * │ DIMENSIONS (a PRD-style template) a query must resolve,
23
+ * │ derived from domain_spec. REQUIRED at creation. The
24
+ * │ per-query intent (dimensions filled in) is EPHEMERAL —
25
+ * │ never persisted.
26
+ * ├─ user_spec.md the SDS USER SPEC — the user's domain-relevant facts +
27
+ * │ hard constraints. REQUIRED at creation (seeded partial
28
+ * │ by the ≤10-question setup), AUGMENTED every query.
29
+ * ├─ playbook.md the SDS PLAYBOOK — the user's buying TASTE (price
30
+ * │ sensitivity, brand, preferences). REQUIRED at creation
31
+ * │ (seeded partial), AUGMENTED every query.
32
+ * └─ profile.json the strictly-typed manifest the sil skill resolves the
33
+ * artefacts from (no filesystem guessing)
34
+ *
35
+ * The persona is NOT a sil artefact: the agent's identity/voice/standing rules
36
+ * are the host workspace `SOUL.md`, written directly via the host CLI by the
37
+ * engine — there is no `persona.md` in this store and no copy step. This store
38
+ * holds only the four SDS BEHAVIOUR artefacts.
39
+ *
40
+ * All FOUR slots are REQUIRED at creation (`domainSpec` + `intentSpec` +
41
+ * `userSpec` + `playbook`) — SDS is the operating model, not an optional layer,
42
+ * so a created expert without all four is a defect (Founder review round 2: all
43
+ * four sil docs are present, non-blank, from creation). They are seeded *partial*
44
+ * (the ≤10-question setup + a quick initial research pass), then lazily
45
+ * AUGMENTED / reinforced on EVERY query — domain_spec web-refreshed, intent_spec
46
+ * dimensions sharpened, user_spec facts and playbook taste reinforced. We keep
47
+ * learning. All four are refine-mutable in place. The per-query intent is NOT a
48
+ * slot here: only the intent_spec *dimension schema* is persisted; the filled
49
+ * dimensions for one request are ephemeral, derived in the conversation.
50
+ *
51
+ * Store boundary: host config + `SOUL.md` (identity/wiring) = host; the four SDS
52
+ * behaviour artefacts = `$SIL_DATA_DIR` via this plugin tool. Identity/tokens
53
+ * already live in `$SIL_DATA_DIR` but stay logically separate (no identity
54
+ * coupling — creating an expert reads/writes no token).
55
+ *
56
+ * Writes are atomic and all-or-nothing (Product invariant 7): a bad spec
57
+ * writes NOTHING (validate first), and a mid-write failure leaves no partial
58
+ * artefact directory behind. The atomic write mirrors `credentials.ts` —
59
+ * tmp file → write → rename over target → chmod 0600, dir 0700.
60
+ */
61
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from "node:fs";
62
+ import { dirname, join } from "node:path";
63
+ import { randomBytes } from "node:crypto";
64
+ import { getDataDir } from "./credentials.js";
65
+ /** Owner-only file/dir modes — the artefacts are user-scoped, like tokens. */
66
+ const FILE_MODE = 0o600;
67
+ const DIR_MODE = 0o700;
68
+ /** The sub-tree under `$SIL_DATA_DIR` that holds per-agent behaviour artefacts. */
69
+ const AGENTS_SUBDIR = "agents";
70
+ /** Artefact filenames (stable — the sil skill resolves them from profile.json,
71
+ * but the names are also documented so a human can find them). The three SDS
72
+ * *specs* carry the `_spec.md` suffix; `playbook.md` (taste) does not. */
73
+ const DOMAIN_SPEC_FILE = "domain_spec.md";
74
+ const INTENT_SPEC_FILE = "intent_spec.md";
75
+ const USER_SPEC_FILE = "user_spec.md";
76
+ const PLAYBOOK_FILE = "playbook.md";
77
+ const PROFILE_FILE = "profile.json";
78
+ /** A host-agent id must be lower-kebab and is never `main` (host-reserved). */
79
+ const AGENT_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
80
+ /** Resolve the per-agent artefact directory under the plugin's data dir. Never
81
+ * hardcoded — `getDataDir()` honors `$SIL_DATA_DIR`/`$XDG_DATA_HOME`.
82
+ *
83
+ * SAFETY: this resolver does NOT guard `agentId` — it joins it as a path segment
84
+ * verbatim. The path-traversal guard lives at the only caller, `materializeProfile`,
85
+ * which validates `agentId` against `AGENT_ID_RE` (lower-kebab, not `main`) BEFORE
86
+ * the join, so `../escape`, `a/../b`, `.`, etc. never reach here. The guard is
87
+ * placed at the caller (not here) because validation must precede ALL writes for
88
+ * the validate-first / write-nothing-on-bad-input invariant to hold; a guard
89
+ * duplicated here would be redundant for that path. A FUTURE DIRECT CALLER of this
90
+ * exported resolver would bypass the guard — re-run `AGENT_ID_RE` (or route through
91
+ * `materializeProfile`) before trusting the returned path with any filesystem op. */
92
+ export function getAgentArtefactDir(agentId) {
93
+ return join(getDataDir(), AGENTS_SUBDIR, agentId);
94
+ }
95
+ /** True when `s` is a present, non-blank string. */
96
+ function nonBlank(s) {
97
+ return typeof s === "string" && s.trim().length > 0;
98
+ }
99
+ function invalid(field, message) {
100
+ return { ok: false, kind: "invalid_request", field, message };
101
+ }
102
+ /**
103
+ * Materialize the behaviour artefacts for a created sil-wired agent.
104
+ *
105
+ * Validate-first: any invalid field returns `invalid_request` and writes
106
+ * NOTHING. On a write failure, the partial directory is removed and
107
+ * `persistence_failed` is returned with `<dir>: <cause>` — no partial artefact
108
+ * set ever survives (Product invariant 7, atomic outcome).
109
+ */
110
+ export function materializeProfile(spec) {
111
+ // --- validate-first (nothing is written until every field is good) ---
112
+ if (!nonBlank(spec.agentId)) {
113
+ return invalid("agentId", "agentId is required and must be non-empty.");
114
+ }
115
+ if (spec.agentId === "main") {
116
+ return invalid("agentId", '"main" is host-reserved and cannot be a sil expert id.');
117
+ }
118
+ if (!AGENT_ID_RE.test(spec.agentId)) {
119
+ return invalid("agentId", "agentId must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(spec.agentId));
120
+ }
121
+ if (!nonBlank(spec.name)) {
122
+ return invalid("name", "name is required and must be non-empty.");
123
+ }
124
+ // All FOUR SDS specs are REQUIRED at creation — SDS is the operating model,
125
+ // not an optional layer. A created expert always carries all four (Founder
126
+ // review round 2): they are seeded *partial* at creation, then augmented every
127
+ // query. A present-but-blank or omitted spec is rejected (validate-first; write
128
+ // nothing).
129
+ if (!nonBlank(spec.domainSpec)) {
130
+ return invalid("domainSpec", "domainSpec is required and must be non-empty.");
131
+ }
132
+ if (!nonBlank(spec.intentSpec)) {
133
+ return invalid("intentSpec", "intentSpec is required and must be non-empty.");
134
+ }
135
+ if (!nonBlank(spec.userSpec)) {
136
+ return invalid("userSpec", "userSpec is required and must be non-empty.");
137
+ }
138
+ if (!nonBlank(spec.playbook)) {
139
+ return invalid("playbook", "playbook is required and must be non-empty.");
140
+ }
141
+ const dir = getAgentArtefactDir(spec.agentId);
142
+ const domainSpecPath = join(dir, DOMAIN_SPEC_FILE);
143
+ const intentSpecPath = join(dir, INTENT_SPEC_FILE);
144
+ const userSpecPath = join(dir, USER_SPEC_FILE);
145
+ const playbookPath = join(dir, PLAYBOOK_FILE);
146
+ const profilePath = join(dir, PROFILE_FILE);
147
+ const manifest = {
148
+ agentId: spec.agentId,
149
+ name: spec.name,
150
+ domainSpecPath,
151
+ intentSpecPath,
152
+ userSpecPath,
153
+ playbookPath,
154
+ createdAt: new Date().toISOString(),
155
+ };
156
+ // Whether the artefact directory already existed before this call. If it did,
157
+ // it is not ours to delete on failure (it may hold a prior expert's artefacts,
158
+ // or — if the path is occupied by a non-directory — a user's file). We only
159
+ // remove what THIS call created (Product invariant 7: nothing partial, without
160
+ // destroying anything pre-existing).
161
+ const dirPreexisted = existsSync(dir);
162
+ try {
163
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE });
164
+ atomicWrite(domainSpecPath, spec.domainSpec);
165
+ atomicWrite(intentSpecPath, spec.intentSpec);
166
+ atomicWrite(userSpecPath, spec.userSpec);
167
+ atomicWrite(playbookPath, spec.playbook);
168
+ atomicWrite(profilePath, JSON.stringify(manifest, null, 2) + "\n");
169
+ }
170
+ catch (err) {
171
+ // Leave nothing partial behind — but only tear down the dir if WE created it.
172
+ if (!dirPreexisted) {
173
+ try {
174
+ rmSync(dir, { recursive: true, force: true });
175
+ }
176
+ catch {
177
+ // Cleanup is best-effort; the original cause is what the caller needs.
178
+ }
179
+ }
180
+ const cause = err instanceof Error ? err.message : String(err);
181
+ return {
182
+ ok: false,
183
+ kind: "persistence_failed",
184
+ error: dir + ": " + cause,
185
+ message: "The shopping-expert behaviour artefacts could NOT be written to the sil"
186
+ + " data directory, so the profile did not stick. Fix the data directory"
187
+ + " (it must be writable — check permissions / free space / that"
188
+ + " $SIL_DATA_DIR is a directory), then create the expert again.",
189
+ };
190
+ }
191
+ return {
192
+ ok: true,
193
+ agentId: spec.agentId,
194
+ dir,
195
+ domainSpecPath,
196
+ intentSpecPath,
197
+ userSpecPath,
198
+ playbookPath,
199
+ profilePath,
200
+ };
201
+ }
202
+ /** Atomic single-file write: tmp sibling → write → rename over target → chmod.
203
+ * Mirrors the token/identity write in `credentials.ts` so a half-written
204
+ * artefact never appears (a reader sees the old file or the new one). */
205
+ function atomicWrite(path, contents) {
206
+ const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
207
+ writeFileSync(tmp, contents, { mode: FILE_MODE });
208
+ renameSync(tmp, path);
209
+ chmodSync(path, FILE_MODE);
210
+ }
211
+ // ===========================================================================
212
+ // Local expert lifecycle — list / view / remove the artefact half.
213
+ //
214
+ // The manifest (`profile.json`) is the source of truth for "is this a sil
215
+ // expert": a directory under `agents/<id>/` with a readable profile.json IS an
216
+ // expert; a bare host `agents.list[]` entry without one is not ours to manage.
217
+ // The host-config (wiring) half of list/remove is the host agent driving its
218
+ // own `openclaw …` CLI — these primitives only ever touch `$SIL_DATA_DIR`.
219
+ //
220
+ // Each primitive returns a discriminated result and NEVER throws across the
221
+ // boundary (mirroring MaterializeResult), so one corrupt manifest or a single
222
+ // failed delete degrades only its own outcome — never the whole operation.
223
+ // ===========================================================================
224
+ /** Resolve the agents subtree root under the plugin's data dir — the parent of
225
+ * every per-agent artefact directory. The deleter asserts a target is strictly
226
+ * a child of this (and never this itself), so a delete can never reach the
227
+ * parent and wipe sibling experts. */
228
+ function getAgentsRoot() {
229
+ return join(getDataDir(), AGENTS_SUBDIR);
230
+ }
231
+ /** Re-run the writer's exact `agentId` gate at a DIRECT caller of
232
+ * `getAgentArtefactDir`. Returns `null` when valid; an `invalid_request`
233
+ * variant naming the field otherwise. The gate is identical to
234
+ * `materializeProfile`'s validate-first block (`AGENT_ID_RE` + non-`main`),
235
+ * applied BEFORE any `join`/`read`/`rm` so a `../`, `/`, `.`, or `main` never
236
+ * becomes a filesystem path segment. `getAgentArtefactDir`'s SAFETY note
237
+ * mandates exactly this for every direct caller — list does not (it never
238
+ * trusts a caller-supplied id; it reads only ids it discovered on disk), but
239
+ * read and remove DO take a caller id and so call this first. */
240
+ function rejectBadAgentId(agentId) {
241
+ if (!nonBlank(agentId)) {
242
+ return invalidAgentId("agentId is required and must be non-empty.");
243
+ }
244
+ if (agentId === "main") {
245
+ return invalidAgentId('"main" is host-reserved and is not a sil expert id.');
246
+ }
247
+ if (!AGENT_ID_RE.test(agentId)) {
248
+ return invalidAgentId("agentId must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(agentId));
249
+ }
250
+ return null;
251
+ }
252
+ function invalidAgentId(message) {
253
+ return { ok: false, kind: "invalid_request", field: "agentId", message };
254
+ }
255
+ /** Read + parse one `agents/<id>/profile.json` into a typed manifest, or throw
256
+ * a descriptive error the caller maps to an `unreadable`/`not_found` outcome.
257
+ * A manifest whose JSON parses but is missing the required string fields is
258
+ * treated as corrupt (an interrupted or hand-edited write) — not silently
259
+ * coerced. */
260
+ function readManifestFile(profilePath) {
261
+ const raw = readFileSync(profilePath, "utf8");
262
+ const parsed = JSON.parse(raw);
263
+ if (typeof parsed !== "object" ||
264
+ parsed === null ||
265
+ typeof parsed.agentId !== "string" ||
266
+ typeof parsed.name !== "string" ||
267
+ typeof parsed.domainSpecPath !== "string" ||
268
+ typeof parsed.intentSpecPath !== "string" ||
269
+ typeof parsed.userSpecPath !== "string" ||
270
+ typeof parsed.playbookPath !== "string" ||
271
+ typeof parsed.createdAt !== "string") {
272
+ throw new Error("profile.json is missing required manifest fields");
273
+ }
274
+ return parsed;
275
+ }
276
+ /**
277
+ * Enumerate the materialized experts under each `$SIL_DATA_DIR/agents/<id>/`.
278
+ *
279
+ * The manifest is the source of truth — each `agents/<id>/profile.json` is read
280
+ * and parsed (no dirname guessing). Experts are returned `createdAt` DESC (the
281
+ * just-made expert first, the one the user most likely wants to act on). An
282
+ * absent/empty store yields a normal empty listing. One unreadable or corrupt
283
+ * manifest lands in `unreadable[]` and never aborts the listing — the healthy
284
+ * experts still list. Reads only; never writes, never reads a token.
285
+ */
286
+ export function listAgentProfiles() {
287
+ const root = getAgentsRoot();
288
+ if (!existsSync(root)) {
289
+ return { ok: true, experts: [], unreadable: [] };
290
+ }
291
+ const experts = [];
292
+ const unreadable = [];
293
+ let entries;
294
+ try {
295
+ entries = readdirSync(root, { withFileTypes: true });
296
+ }
297
+ catch (err) {
298
+ // The agents root exists but cannot be enumerated (e.g. EACCES). Surface it
299
+ // as a single degraded entry rather than throwing across the boundary.
300
+ unreadable.push({
301
+ agentId: AGENTS_SUBDIR,
302
+ error: errCause(err),
303
+ });
304
+ return { ok: true, experts, unreadable };
305
+ }
306
+ for (const entry of entries) {
307
+ if (!entry.isDirectory())
308
+ continue;
309
+ const agentId = entry.name;
310
+ const profilePath = join(root, agentId, PROFILE_FILE);
311
+ if (!existsSync(profilePath)) {
312
+ // A directory under agents/ with no manifest is not a (loadable) sil
313
+ // expert — report it degraded so the user sees the residue (e.g. a
314
+ // remove that cleared the manifest but left a stray file).
315
+ unreadable.push({ agentId, error: "no profile.json manifest" });
316
+ continue;
317
+ }
318
+ try {
319
+ const manifest = readManifestFile(profilePath);
320
+ experts.push({
321
+ agentId: manifest.agentId,
322
+ name: manifest.name,
323
+ createdAt: manifest.createdAt,
324
+ });
325
+ }
326
+ catch (err) {
327
+ unreadable.push({ agentId, error: errCause(err) });
328
+ }
329
+ }
330
+ // Most-recently-created first (Product Flow 1). createdAt is ISO 8601, so a
331
+ // lexical compare is also chronological; fall back to it when Date.parse is
332
+ // NaN (a corrupt-but-parseable date) so the sort is total and stable-ish.
333
+ experts.sort((a, b) => createdAtDesc(a.createdAt, b.createdAt));
334
+ return { ok: true, experts, unreadable };
335
+ }
336
+ /** Compare two ISO 8601 createdAt strings, most-recent first. */
337
+ function createdAtDesc(a, b) {
338
+ const ta = Date.parse(a);
339
+ const tb = Date.parse(b);
340
+ if (Number.isNaN(ta) || Number.isNaN(tb)) {
341
+ // Lexical fallback keeps the sort total when a timestamp is unparseable.
342
+ return a < b ? 1 : a > b ? -1 : 0;
343
+ }
344
+ return tb - ta;
345
+ }
346
+ /**
347
+ * Read one expert's full detail — the manifest PLUS the SDS artefact bodies from
348
+ * the files it points at — so the skill can render a complete view.
349
+ *
350
+ * Re-runs the writer's `agentId` gate BEFORE any `join`/read (a traversal-shaped
351
+ * id → `invalid_request`, reading nothing). An unknown id, an absent/unreadable
352
+ * manifest, or an absent body of ANY of the four REQUIRED SDS specs
353
+ * (`domain_spec.md` / `intent_spec.md` / `user_spec.md` / `playbook.md`) →
354
+ * `not_found` (Founder review round 2: all four always exist; a degraded expert
355
+ * is, from the user's view, not viewable). There is no degrade-to-undefined path
356
+ * any more — a referenced-but-missing body of any of the four fails the read
357
+ * closed. Never throws across the boundary; reads only.
358
+ */
359
+ export function readAgentProfile(agentId) {
360
+ const bad = rejectBadAgentId(agentId);
361
+ if (bad)
362
+ return bad;
363
+ const dir = getAgentArtefactDir(agentId);
364
+ const profilePath = join(dir, PROFILE_FILE);
365
+ if (!existsSync(profilePath)) {
366
+ return notFoundRead(agentId);
367
+ }
368
+ let manifest;
369
+ try {
370
+ manifest = readManifestFile(profilePath);
371
+ }
372
+ catch {
373
+ // A corrupt/half-written manifest is, to the viewer, an expert that cannot
374
+ // be loaded — surface not_found (the skill lists the healthy ones), never a
375
+ // raw parse error across the boundary.
376
+ return notFoundRead(agentId);
377
+ }
378
+ // All FOUR SDS spec bodies are REQUIRED for a created expert — they gate the
379
+ // read fail-closed (the role the persona body played pre-SDS). A manifest that
380
+ // points at a domain_spec.md / intent_spec.md / user_spec.md / playbook.md whose
381
+ // body is gone (a partial write, a hand-deleted file) is, to the viewer, an
382
+ // expert that cannot be loaded. This is the per-file-atomic, NOT-cross-file-
383
+ // transactional safety boundary: a partial write degrades to a fail-closed
384
+ // not_found, never a coherent-but-incomplete expert (Founder review round 2:
385
+ // all four are present from creation, so none degrades to absence).
386
+ let domainSpec;
387
+ let intentSpec;
388
+ let userSpec;
389
+ let playbook;
390
+ try {
391
+ domainSpec = readFileSync(manifest.domainSpecPath, "utf8");
392
+ intentSpec = readFileSync(manifest.intentSpecPath, "utf8");
393
+ userSpec = readFileSync(manifest.userSpecPath, "utf8");
394
+ playbook = readFileSync(manifest.playbookPath, "utf8");
395
+ }
396
+ catch {
397
+ return notFoundRead(agentId);
398
+ }
399
+ return {
400
+ ok: true,
401
+ agentId: manifest.agentId,
402
+ name: manifest.name,
403
+ domainSpec,
404
+ intentSpec,
405
+ userSpec,
406
+ playbook,
407
+ profilePath,
408
+ createdAt: manifest.createdAt,
409
+ };
410
+ }
411
+ function notFoundRead(agentId) {
412
+ return {
413
+ ok: false,
414
+ kind: "not_found",
415
+ agentId,
416
+ message: 'No sil expert "' + agentId + '" — list your experts to see which exist.',
417
+ };
418
+ }
419
+ /**
420
+ * Remove one expert's behaviour-artefact directory — the sil-side half of a
421
+ * clean removal (the host-wiring half is the skill's `openclaw` CLI step; the
422
+ * plugin cannot write `~/.openclaw`).
423
+ *
424
+ * Fail-closed and scoped to exactly the named expert:
425
+ * - re-runs the writer's `agentId` gate ITSELF (never trusts the caller) — a
426
+ * bad/`main`/traversal-shaped id → `invalid_request`, deletes NOTHING;
427
+ * - asserts the resolved target is strictly UNDER `getDataDir()/agents/` and
428
+ * is NOT the `agents/` parent, so a delete can never escape the subtree or
429
+ * wipe sibling experts;
430
+ * - `rmSync(dir, { recursive, force })` the single leaf dir.
431
+ *
432
+ * Absent target → `not_found` (idempotent — a re-run after a partial host-CLI
433
+ * failure is safe). A genuine `rmSync` failure (e.g. EACCES) →
434
+ * `persistence_failed` with `<dir>: <cause>`. Never throws across the boundary.
435
+ */
436
+ export function removeAgentArtefacts(agentId) {
437
+ const bad = rejectBadAgentId(agentId);
438
+ if (bad)
439
+ return bad;
440
+ const dir = getAgentArtefactDir(agentId);
441
+ // Defence in depth beyond the id gate: assert the resolved path is strictly a
442
+ // child of the agents root and never the root itself. A `rmSync` of the
443
+ // parent would wipe every sibling expert — refuse it even if some future
444
+ // change to the gate let a separator-bearing id through.
445
+ const root = getAgentsRoot();
446
+ if (dirname(dir) !== root || dir === root) {
447
+ return invalidAgentId("agentId resolves outside the agents subtree — refusing to delete: " +
448
+ JSON.stringify(agentId));
449
+ }
450
+ if (!existsSync(dir)) {
451
+ return {
452
+ ok: false,
453
+ kind: "not_found",
454
+ agentId,
455
+ message: 'No sil expert "' + agentId + '" to remove (already gone) — list your'
456
+ + " experts to see which exist. A re-run is safe (idempotent).",
457
+ };
458
+ }
459
+ try {
460
+ rmSync(dir, { recursive: true, force: true });
461
+ }
462
+ catch (err) {
463
+ return {
464
+ ok: false,
465
+ kind: "persistence_failed",
466
+ error: dir + ": " + errCause(err),
467
+ message: "The expert's behaviour artefacts could NOT be removed from the sil data"
468
+ + " directory. Fix the data directory (it must be writable — check"
469
+ + " permissions), then remove the expert again.",
470
+ recovery: "fix_data_dir",
471
+ };
472
+ }
473
+ return { ok: true, agentId };
474
+ }
475
+ /** Extract a human-readable cause from an unknown thrown value (never PII). */
476
+ function errCause(err) {
477
+ return err instanceof Error ? err.message : String(err);
478
+ }