sil-openclaw 0.3.5 → 0.3.6

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.
@@ -1,70 +1,68 @@
1
1
  /**
2
- * sil shopping-expert behaviour-artefact store.
2
+ * sil shopper behaviour-artefact store — the single multi-domain shopper layout.
3
3
  *
4
4
  * The agent-creation engine (the bundled `sil-shopping/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`.
5
+ * the OpenClaw host CLI) registers the *wiring* of the one sil shopper into the
6
+ * host's own config — the `agents.list[]` entry, the enabled `sil` plugin, the
7
+ * attached `sil` skill. That host-config write is the host agent driving its own
8
+ * `openclaw …` CLI; the plugin never touches `~/.openclaw`.
9
9
  *
10
- * What the plugin DOES own is the agent's *behaviour* layer, materialized into
10
+ * What the plugin DOES own is the shopper's *behaviour* layer, materialized into
11
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:
12
+ * `lib/credentials.ts` uses for tokens/identity). There is ONE persistent shopper
13
+ * (a SINGLETON), so its artefacts live under a fixed, compile-time-constant
14
+ * sub-directory — NOT a caller-supplied key. The store keeps a SHARED user spec
15
+ * (the one person) plus a per-domain pack that is minted LAZILY on the first shop
16
+ * in a niche:
15
17
  *
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)
18
+ * $SIL_DATA_DIR/shopper/
19
+ * ├─ user_spec.md SHARED — the one person: addresses, sizes,
20
+ * │ allergy/ethics HARD constraints, budget
21
+ * │ psychology. Read by EVERY domain's shop loop, so a
22
+ * │ fact captured while shopping niche A is reused in
23
+ * │ niche B without being re-asked. Overwritten
24
+ * │ (full-body) on every materialize call.
25
+ * ├─ profile.json the strictly-typed manifest the sil skill resolves
26
+ * │ artefacts from — name + userSpecPath + a
27
+ * │ slug-keyed `domains` MAP (the source of truth; no
28
+ * │ filesystem guessing). `domains: {}` is the HEALTHY
29
+ * │ state of a freshly-created shopper.
30
+ * └─ domains/<slug>/
31
+ * ├─ domain_spec.md per-domain: deep researched niche expertise.
32
+ * ├─ intent_spec.md per-domain: the decomposition DIMENSIONS a query
33
+ * │ must resolve (the dimension SCHEMA only — the
34
+ * │ per-query intent is ephemeral, never persisted).
35
+ * └─ playbook.md per-domain: the user's buying TASTE for THIS niche.
34
36
  *
35
- * The persona is NOT a sil artefact: the agent's identity/voice/standing rules
37
+ * The persona is NOT a sil artefact: the shopper's identity/voice/standing rules
36
38
  * 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
+ * engine — there is no `persona.md` here and no copy step. This store holds only
40
+ * the SHARED user spec and the per-domain SDS packs.
39
41
  *
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.
42
+ * `sil_profile_materialize` stays ONE tool with an OPTIONAL `domain` pack:
43
+ * - no `domain` ⇒ CREATE the shopper: write the shared `user_spec.md` + a
44
+ * `profile.json` with `domains: {}`. NO `domains/` dir is created yet.
45
+ * - with `domain` ⇒ lazily MINT/refresh that niche: write
46
+ * `domains/<slug>/{domain_spec,intent_spec,playbook}.md`, overwrite the shared
47
+ * `user_spec.md`, and upsert `domains[slug]` — one atomic call. Persisting a
48
+ * cross-niche fact surfaced in the same query is therefore native.
50
49
  *
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
- * Write safety (Product invariant 7): a bad spec writes NOTHING (validate
57
- * first). Each artefact is written atomically — tmp file → write → rename over
58
- * target → chmod 0600, dir 0700 (mirroring `credentials.ts`) — so a reader never
59
- * sees a half-written file. On a mid-write failure the guarantee depends on
60
- * whether the expert is new: a FRESH create (the dir did not pre-exist) is torn
61
- * down, leaving no partial directory behind (all-or-nothing); a RE-MATERIALIZE
62
- * over an existing expert is per-file atomic and dir-preserving — it is NOT a
63
- * cross-file transaction, so on failure the prior expert is left intact and is
64
- * never served half-refined (a referenced-but-missing body fails the read closed
65
- * — see `readAgentProfile`). The catch block below encodes exactly this split.
50
+ * Write safety: a bad spec writes NOTHING (validate-first). Each artefact is
51
+ * written atomically — tmp file → write → rename over target → chmod 0600, dir
52
+ * 0700 (mirroring `credentials.ts`) — so a reader never sees a half-written file.
53
+ * Write order on a mint is `domains/<slug>/* → shared user_spec → profile.json
54
+ * LAST`, so a crash never leaves a registered-but-absent pack: the worst outcome
55
+ * is an ORPHANED, unreferenced `domains/<slug>/` leaf, which readers gate out via
56
+ * the manifest (fail-closed). On a mid-write failure the teardown is keyed on
57
+ * MANIFEST MEMBERSHIP, NOT filesystem pre-existence: a failed FIRST mint of a NEW
58
+ * domain (slug ∉ the existing `domains` map) tears down ONLY that fresh leaf — the
59
+ * shopper dir, the shared user_spec, and sibling domains survive; a failed re-mint
60
+ * of an EXISTING domain is dir-preserving (the prior pack is left intact and is
61
+ * never served half-refined — a referenced-but-missing body fails the read closed,
62
+ * see `readAgentProfile`). A leaf we did not create (the path was already occupied)
63
+ * is never torn down.
66
64
  */
67
- import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from "node:fs";
65
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
68
66
  import { dirname, join } from "node:path";
69
67
  import { randomBytes } from "node:crypto";
70
68
  import { DIR_MODE, ensureDataDir, getDataDir } from "./credentials.js";
@@ -72,33 +70,47 @@ import { DIR_MODE, ensureDataDir, getDataDir } from "./credentials.js";
72
70
  * mode (`DIR_MODE`, `0o700`) is owned by `credentials.ts` (the data-dir owner)
73
71
  * and imported, so the data-home permission lives in exactly one place. */
74
72
  const FILE_MODE = 0o600;
75
- /** The sub-tree under `$SIL_DATA_DIR` that holds per-agent behaviour artefacts. */
76
- const AGENTS_SUBDIR = "agents";
73
+ /** The fixed, compile-time-constant sub-tree under `$SIL_DATA_DIR` that holds the
74
+ * ONE shopper's behaviour artefacts. The product is a SINGLETON, so this is a
75
+ * constant — NOT caller input — which makes the shopper path segment un-spoofable
76
+ * (no caller-controlled `agentId` traversal vector). */
77
+ const SHOPPER_SUBDIR = "shopper";
78
+ /** The sub-tree under the shopper dir that holds the per-domain packs. */
79
+ const DOMAINS_SUBDIR = "domains";
77
80
  /** Artefact filenames (stable — the sil skill resolves them from profile.json,
78
- * but the names are also documented so a human can find them). The three SDS
79
- * *specs* carry the `_spec.md` suffix; `playbook.md` (taste) does not. */
81
+ * but the names are also documented so a human can find them). The shared user
82
+ * spec sits at the shopper level; the three SDS pack files sit under each domain. */
83
+ const USER_SPEC_FILE = "user_spec.md";
80
84
  const DOMAIN_SPEC_FILE = "domain_spec.md";
81
85
  const INTENT_SPEC_FILE = "intent_spec.md";
82
- const USER_SPEC_FILE = "user_spec.md";
83
86
  const PLAYBOOK_FILE = "playbook.md";
84
87
  const PROFILE_FILE = "profile.json";
85
- /** A host-agent id must be lower-kebab and is never `main` (host-reserved). */
88
+ /** The stable, case-insensitive marker the shop loop's reject-at-pick rule greps
89
+ * to find an appended hard constraint (e.g. `- [hard] never leather`). */
90
+ const HARD_MARKER = "[hard]";
91
+ /** A domain slug must be lower-kebab and is never `main` (host-reserved). It is
92
+ * joined as a filesystem path segment, so it carries this guard. (The shopper dir
93
+ * segment is the un-spoofable constant `SHOPPER_SUBDIR` — it needs no guard.) */
86
94
  const AGENT_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
87
- /** Resolve the per-agent artefact directory under the plugin's data dir. Never
88
- * hardcoded — `getDataDir()` honors `$SIL_DATA_DIR`/`$XDG_DATA_HOME`.
95
+ /** Resolve the SINGLETON shopper artefact directory under the plugin's data dir.
96
+ * Never hardcoded — `getDataDir()` honors `$SIL_DATA_DIR`/`$XDG_DATA_HOME`.
97
+ *
98
+ * SAFETY: the shopper segment is the compile-time constant `SHOPPER_SUBDIR`, NOT
99
+ * caller input, so there is no path-traversal vector here (nothing to spoof). The
100
+ * only caller-supplied segment in the store is the domain `slug` — see
101
+ * `getDomainArtefactDir`, which every caller guards before the join. */
102
+ export function getShopperArtefactDir() {
103
+ return join(getDataDir(), SHOPPER_SUBDIR);
104
+ }
105
+ /** Resolve a per-domain pack directory under the singleton shopper dir.
89
106
  *
90
- * SAFETY: this resolver does NOT guard `agentId` — it joins it as a path segment
91
- * verbatim. The path-traversal guard lives at the only caller, `materializeProfile`,
92
- * which validates `agentId` against `AGENT_ID_RE` (lower-kebab, not `main`) BEFORE
93
- * the join, so a traversal-shaped id (a parent-directory hop, a nested back-step,
94
- * a bare dot) never reaches here. The guard is
95
- * placed at the caller (not here) because validation must precede ALL writes for
96
- * the validate-first / write-nothing-on-bad-input invariant to hold; a guard
97
- * duplicated here would be redundant for that path. A FUTURE DIRECT CALLER of this
98
- * exported resolver would bypass the guard — re-run `AGENT_ID_RE` (or route through
99
- * `materializeProfile`) before trusting the returned path with any filesystem op. */
100
- export function getAgentArtefactDir(agentId) {
101
- return join(getDataDir(), AGENTS_SUBDIR, agentId);
107
+ * SAFETY: `slug` is the ONLY caller-supplied path segment in the store. It is
108
+ * joined verbatim here, so every caller MUST validate it with `rejectBadSegment`
109
+ * (`AGENT_ID_RE` + non-`main`) BEFORE the join. A FUTURE DIRECT CALLER would bypass
110
+ * that guard — re-validate `slug` before trusting the returned path with any
111
+ * filesystem op. */
112
+ export function getDomainArtefactDir(slug) {
113
+ return join(getShopperArtefactDir(), DOMAINS_SUBDIR, slug);
102
114
  }
103
115
  /** True when `s` is a present, non-blank string. */
104
116
  function nonBlank(s) {
@@ -107,87 +119,152 @@ function nonBlank(s) {
107
119
  function invalid(field, message) {
108
120
  return { ok: false, kind: "invalid_request", field, message };
109
121
  }
122
+ /** Validate the domain-slug path-segment field the SAME way at every caller:
123
+ * present + non-blank, never `main`, lower-kebab. Returns `null` when valid, an
124
+ * `invalid_request` naming the field otherwise — applied BEFORE any
125
+ * join/read/delete so a parent-directory traversal, an absolute path, a bare dot,
126
+ * or `main` never becomes a filesystem path segment. */
127
+ function rejectBadSegment(value, field) {
128
+ if (!nonBlank(value)) {
129
+ return invalid(field, field + " is required and must be non-empty.");
130
+ }
131
+ if (value === "main") {
132
+ return invalid(field, '"main" is host-reserved and cannot be a ' + field + ".");
133
+ }
134
+ if (!AGENT_ID_RE.test(value)) {
135
+ return invalid(field, field + " must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(value));
136
+ }
137
+ return null;
138
+ }
110
139
  /**
111
- * Materialize the behaviour artefacts for a created sil-wired agent.
140
+ * Materialize the shopper / a domain pack.
112
141
  *
113
- * Validate-first: any invalid field returns `invalid_request` and writes
114
- * NOTHING. On a write failure, the partial directory is removed and
115
- * `persistence_failed` is returned with `<dir>: <cause>` — no partial artefact
116
- * set ever survives (Product invariant 7, atomic outcome).
142
+ * Validate-first (deterministic field order: `name` → `userSpec` →, when `domain`
143
+ * is present, `domain.slug` → `domain.name` → `domain.domainSpec` →
144
+ * `domain.intentSpec` → `domain.playbook`): any invalid field returns
145
+ * `invalid_request` naming it and writes NOTHING.
146
+ *
147
+ * - no `domain` ⇒ write the shared `user_spec.md` + `profile.json` (`domains: {}`);
148
+ * no `domains/` dir.
149
+ * - with `domain` ⇒ write `domains/<slug>/*` → overwrite the shared `user_spec.md`
150
+ * → write `profile.json` LAST (upsert `domains[slug]`; preserve `createdAt` on a
151
+ * re-mint, advance `updatedAt`). `domain` is echoed in the ok result.
117
152
  */
118
153
  export function materializeProfile(spec) {
119
154
  // --- validate-first (nothing is written until every field is good) ---
120
- if (!nonBlank(spec.agentId)) {
121
- return invalid("agentId", "agentId is required and must be non-empty.");
122
- }
123
- if (spec.agentId === "main") {
124
- return invalid("agentId", '"main" is host-reserved and cannot be a sil expert id.');
125
- }
126
- if (!AGENT_ID_RE.test(spec.agentId)) {
127
- return invalid("agentId", "agentId must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(spec.agentId));
128
- }
129
155
  if (!nonBlank(spec.name)) {
130
156
  return invalid("name", "name is required and must be non-empty.");
131
157
  }
132
- // All FOUR SDS specs are REQUIRED at creation — SDS is the operating model,
133
- // not an optional layer. A created expert always carries all four (Founder
134
- // review round 2): they are seeded *partial* at creation, then augmented every
135
- // query. A present-but-blank or omitted spec is rejected (validate-first; write
136
- // nothing).
137
- if (!nonBlank(spec.domainSpec)) {
138
- return invalid("domainSpec", "domainSpec is required and must be non-empty.");
139
- }
140
- if (!nonBlank(spec.intentSpec)) {
141
- return invalid("intentSpec", "intentSpec is required and must be non-empty.");
142
- }
158
+ // The SHARED user spec is REQUIRED non-blank on EVERY call — create AND mint —
159
+ // so a mint can never blank out the one person's standing facts/constraints.
143
160
  if (!nonBlank(spec.userSpec)) {
144
161
  return invalid("userSpec", "userSpec is required and must be non-empty.");
145
162
  }
146
- if (!nonBlank(spec.playbook)) {
147
- return invalid("playbook", "playbook is required and must be non-empty.");
163
+ const domain = spec.domain;
164
+ if (domain !== undefined) {
165
+ // The slug is the caller-supplied filesystem path segment — guard it BEFORE any
166
+ // join. All five pack fields are REQUIRED non-blank.
167
+ const badSlug = rejectBadSegment(domain.slug, "domain.slug");
168
+ if (badSlug)
169
+ return badSlug;
170
+ if (!nonBlank(domain.name)) {
171
+ return invalid("domain.name", "domain.name is required and must be non-empty.");
172
+ }
173
+ if (!nonBlank(domain.domainSpec)) {
174
+ return invalid("domain.domainSpec", "domain.domainSpec is required and must be non-empty.");
175
+ }
176
+ if (!nonBlank(domain.intentSpec)) {
177
+ return invalid("domain.intentSpec", "domain.intentSpec is required and must be non-empty.");
178
+ }
179
+ if (!nonBlank(domain.playbook)) {
180
+ return invalid("domain.playbook", "domain.playbook is required and must be non-empty.");
181
+ }
148
182
  }
149
- const dir = getAgentArtefactDir(spec.agentId);
150
- const domainSpecPath = join(dir, DOMAIN_SPEC_FILE);
151
- const intentSpecPath = join(dir, INTENT_SPEC_FILE);
183
+ const dir = getShopperArtefactDir();
152
184
  const userSpecPath = join(dir, USER_SPEC_FILE);
153
- const playbookPath = join(dir, PLAYBOOK_FILE);
154
185
  const profilePath = join(dir, PROFILE_FILE);
186
+ // The manifest is the source of truth: read what is already on disk so a mint is
187
+ // an UPSERT (the createdAt of the shopper and of any existing domain is
188
+ // preserved) rather than a clobber. A corrupt/absent manifest is treated as a
189
+ // fresh shopper — re-materialize heals it.
190
+ const existing = tryReadManifest(profilePath);
191
+ const createdAt = existing?.createdAt ?? new Date().toISOString();
192
+ const domains = existing ? { ...existing.domains } : {};
193
+ // Per-mint state, resolved BEFORE the write so the catch block knows whether the
194
+ // failed leaf is ours to tear down (manifest membership) and whether the path
195
+ // pre-existed (never delete a path we did not create).
196
+ let leaf = "";
197
+ let entry;
198
+ let domainIsNew = false;
199
+ let leafPreexisted = false;
200
+ if (domain !== undefined) {
201
+ leaf = getDomainArtefactDir(domain.slug);
202
+ const prior = domains[domain.slug];
203
+ domainIsNew = prior === undefined;
204
+ leafPreexisted = existsSync(leaf);
205
+ const now = new Date().toISOString();
206
+ entry = {
207
+ slug: domain.slug,
208
+ name: domain.name,
209
+ domainSpecPath: join(leaf, DOMAIN_SPEC_FILE),
210
+ intentSpecPath: join(leaf, INTENT_SPEC_FILE),
211
+ playbookPath: join(leaf, PLAYBOOK_FILE),
212
+ createdAt: prior?.createdAt ?? now,
213
+ updatedAt: now,
214
+ };
215
+ domains[domain.slug] = entry;
216
+ }
155
217
  const manifest = {
156
- agentId: spec.agentId,
157
218
  name: spec.name,
158
- domainSpecPath,
159
- intentSpecPath,
160
219
  userSpecPath,
161
- playbookPath,
162
- createdAt: new Date().toISOString(),
220
+ createdAt,
221
+ domains,
163
222
  };
164
- // Whether the artefact directory already existed before this call. If it did,
165
- // it is not ours to delete on failure (it may hold a prior expert's artefacts,
166
- // or — if the path is occupied by a non-directory — a user's file). We only
167
- // remove what THIS call created (Product invariant 7: nothing partial, without
168
- // destroying anything pre-existing).
223
+ // Whether the shopper dir already existed. A fresh CREATE that fails is torn down
224
+ // whole (all-or-nothing); a MINT never tears down the shopper dir (it holds the
225
+ // shared user_spec + sibling domains) — only the fresh leaf, and only if it is
226
+ // ours.
169
227
  const dirPreexisted = existsSync(dir);
170
228
  try {
171
- // Ensure the data home (`$SIL_DATA_DIR`, 0700) exists first — its creation
172
- // and mode are owned by credentials.ts (the data-dir owner), and this also
173
- // re-heals it if it was deleted mid-session. Then create the per-agent leaf
174
- // (`agents/<id>`), which is profile-store's own concern.
229
+ // Ensure the data home (`$SIL_DATA_DIR`, 0700) exists first — its creation and
230
+ // mode are owned by credentials.ts — then the shopper leaf.
175
231
  ensureDataDir();
176
232
  mkdirSync(dir, { recursive: true, mode: DIR_MODE });
177
- atomicWrite(domainSpecPath, spec.domainSpec);
178
- atomicWrite(intentSpecPath, spec.intentSpec);
233
+ if (domain !== undefined && entry !== undefined) {
234
+ // Write order: the domain pack FIRST, the shared user_spec, the manifest
235
+ // LAST — so a crash before the manifest write leaves only an orphaned,
236
+ // unreferenced leaf (invisible to readers), never a registered-but-absent
237
+ // pack.
238
+ mkdirSync(leaf, { recursive: true, mode: DIR_MODE });
239
+ atomicWrite(entry.domainSpecPath, domain.domainSpec);
240
+ atomicWrite(entry.intentSpecPath, domain.intentSpec);
241
+ atomicWrite(entry.playbookPath, domain.playbook);
242
+ }
179
243
  atomicWrite(userSpecPath, spec.userSpec);
180
- atomicWrite(playbookPath, spec.playbook);
181
244
  atomicWrite(profilePath, JSON.stringify(manifest, null, 2) + "\n");
182
245
  }
183
246
  catch (err) {
184
- // Leave nothing partial behind — but only tear down the dir if WE created it.
185
- if (!dirPreexisted) {
247
+ if (domain !== undefined) {
248
+ // MINT teardown — keyed on manifest membership, NOT filesystem pre-existence:
249
+ // tear down ONLY a fresh leaf this call created for a NEW domain. A re-mint of
250
+ // an EXISTING domain is dir-preserving (the prior pack survives), and a leaf
251
+ // path already occupied (the test's blocking file) is never our leaf to remove.
252
+ if (domainIsNew && !leafPreexisted) {
253
+ try {
254
+ rmSync(leaf, { recursive: true, force: true });
255
+ }
256
+ catch {
257
+ // Cleanup is best-effort; the original cause is what the caller needs.
258
+ }
259
+ }
260
+ }
261
+ else if (!dirPreexisted) {
262
+ // Fresh CREATE — leave nothing partial behind, but only if WE created the dir.
186
263
  try {
187
264
  rmSync(dir, { recursive: true, force: true });
188
265
  }
189
266
  catch {
190
- // Cleanup is best-effort; the original cause is what the caller needs.
267
+ // best-effort
191
268
  }
192
269
  }
193
270
  const cause = err instanceof Error ? err.message : String(err);
@@ -195,22 +272,16 @@ export function materializeProfile(spec) {
195
272
  ok: false,
196
273
  kind: "persistence_failed",
197
274
  error: dir + ": " + cause,
198
- message: "The shopping-expert behaviour artefacts could NOT be written to the sil"
199
- + " data directory, so the profile did not stick. Fix the data directory"
200
- + " (it must be writable — check permissions / free space / that"
201
- + " $SIL_DATA_DIR is a directory), then create the expert again.",
275
+ message: "The shopper behaviour artefacts could NOT be written to the sil data"
276
+ + " directory, so the change did not stick. Fix the data directory (it must"
277
+ + " be writable — check permissions / free space / that $SIL_DATA_DIR is a"
278
+ + " directory), then try again.",
202
279
  };
203
280
  }
204
- return {
205
- ok: true,
206
- agentId: spec.agentId,
207
- dir,
208
- domainSpecPath,
209
- intentSpecPath,
210
- userSpecPath,
211
- playbookPath,
212
- profilePath,
213
- };
281
+ if (domain !== undefined && entry !== undefined) {
282
+ return { ok: true, dir, userSpecPath, profilePath, domain: entry };
283
+ }
284
+ return { ok: true, dir, userSpecPath, profilePath };
214
285
  }
215
286
  /** Atomic single-file write: tmp sibling → write → rename over target → chmod.
216
287
  * Mirrors the token/identity write in `credentials.ts` so a half-written
@@ -221,269 +292,381 @@ function atomicWrite(path, contents) {
221
292
  renameSync(tmp, path);
222
293
  chmodSync(path, FILE_MODE);
223
294
  }
224
- // ===========================================================================
225
- // Local expert lifecycle — list / view / remove the artefact half.
226
- //
227
- // The manifest (`profile.json`) is the source of truth for "is this a sil
228
- // expert": a directory under `agents/<id>/` with a readable profile.json IS an
229
- // expert; a bare host `agents.list[]` entry without one is not ours to manage.
230
- // The host-config (wiring) half of list/remove is the host agent driving its
231
- // own `openclaw …` CLI — these primitives only ever touch `$SIL_DATA_DIR`.
232
- //
233
- // Each primitive returns a discriminated result and NEVER throws across the
234
- // boundary (mirroring MaterializeResult), so one corrupt manifest or a single
235
- // failed delete degrades only its own outcome — never the whole operation.
236
- // ===========================================================================
237
- /** Resolve the agents subtree root under the plugin's data dir — the parent of
238
- * every per-agent artefact directory. The deleter asserts a target is strictly
239
- * a child of this (and never this itself), so a delete can never reach the
240
- * parent and wipe sibling experts. */
241
- function getAgentsRoot() {
242
- return join(getDataDir(), AGENTS_SUBDIR);
295
+ function notFoundRemember(message) {
296
+ return { ok: false, kind: "not_found", message };
243
297
  }
244
- /** Re-run the writer's exact `agentId` gate at a DIRECT caller of
245
- * `getAgentArtefactDir`. Returns `null` when valid; an `invalid_request`
246
- * variant naming the field otherwise. The gate is identical to
247
- * `materializeProfile`'s validate-first block (`AGENT_ID_RE` + non-`main`),
248
- * applied BEFORE any path join, read, or delete so a parent-directory traversal,
249
- * an absolute path, a bare dot, or `main` never becomes a filesystem path segment. `getAgentArtefactDir`'s SAFETY note
250
- * mandates exactly this for every direct caller — list does not (it never
251
- * trusts a caller-supplied id; it reads only ids it discovered on disk), but
252
- * read and remove DO take a caller id and so call this first. */
253
- function rejectBadAgentId(agentId) {
254
- if (!nonBlank(agentId)) {
255
- return invalidAgentId("agentId is required and must be non-empty.");
256
- }
257
- if (agentId === "main") {
258
- return invalidAgentId('"main" is host-reserved and is not a sil expert id.');
259
- }
260
- if (!AGENT_ID_RE.test(agentId)) {
261
- return invalidAgentId("agentId must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(agentId));
298
+ /**
299
+ * Append ONE typed learning to the shopper's behaviour artefacts — the cheap
300
+ * per-query persist path (the card's reason to exist). Unlike `materializeProfile`
301
+ * (whole-doc overwrite), this NEVER reads or re-serializes the body: a `kind:"fact"`
302
+ * lands at the EOF of the shared `user_spec.md`, a `kind:"taste"` at the EOF of the
303
+ * active domain's `playbook.md`.
304
+ *
305
+ * Validate-first (deterministic field order: `text` → the routing category errors →
306
+ * a taste's explicit `domain` shape): any bad field returns `invalid_request`
307
+ * naming it and writes NOTHING.
308
+ * - `kind:"fact"` carrying a `domain` → `invalid_request(domain)` (a fact is
309
+ * shopper-level).
310
+ * - `kind:"taste"` carrying `hard:true` → `invalid_request(hard)` (taste is soft).
311
+ *
312
+ * Active-domain resolution (taste only): explicit `domain` slug → else the single
313
+ * registered domain → 0 domains → `not_found` → 2+ domains → `invalid_request(domain)`
314
+ * (ambiguous — never a silent write to the wrong niche).
315
+ *
316
+ * Fail-closed existence gate — append NEVER creates a file: an unknown shopper (no
317
+ * manifest), a missing `user_spec.md` body, an unregistered domain, or a registered
318
+ * domain whose `playbook.md` body is gone → `not_found` (no lone-bullet seed-less
319
+ * doc is ever born via append).
320
+ *
321
+ * The write is `appendFileSync(target, "\n- …", { flag: "a", mode: FILE_MODE })` —
322
+ * O_APPEND lands the entry at EOF atomically per write (POSIX), so concurrent
323
+ * appenders never lose an entry. The entry is `"\n"`-prefixed (O_APPEND does not
324
+ * read the prior terminator) and is ONE short learning, well under PIPE_BUF (~4 KB),
325
+ * so the per-write atomicity holds. A hard fact carries the `[hard]` marker so the
326
+ * shop loop's reject-at-pick rule can grep it. No manifest rewrite — the entry is
327
+ * already visible to `readAgentProfile` via `userSpecPath` / `playbookPath`. The
328
+ * `mode` option only applies on file creation, and the gate guarantees the target
329
+ * already exists, so the file's `0600` mode (set at materialize) is preserved.
330
+ */
331
+ export function appendProfileEntry(spec) {
332
+ // --- validate-first (nothing is written until every field is good) ---
333
+ if (!nonBlank(spec.text)) {
334
+ return invalid("text", "text is required and must be non-empty.");
262
335
  }
263
- return null;
264
- }
265
- function invalidAgentId(message) {
266
- return { ok: false, kind: "invalid_request", field: "agentId", message };
336
+ // Routing category errors — fail fast, write nothing.
337
+ if (spec.kind === "fact" && spec.domain !== undefined) {
338
+ return invalid("domain", "a fact is shopper-level (it carries across every niche) — drop `domain`, or use kind:\"taste\".");
339
+ }
340
+ if (spec.kind === "taste" && spec.hard === true) {
341
+ return invalid("hard", "taste is always soft/bendable — a hard taste is a contradiction; mark `hard` on FACTS only.");
342
+ }
343
+ // A taste's explicit domain slug is the caller-supplied filesystem path segment —
344
+ // guard its SHAPE (field `domain`) BEFORE any resolve/read.
345
+ if (spec.kind === "taste" && spec.domain !== undefined) {
346
+ const badSlug = rejectBadSegment(spec.domain, "domain");
347
+ if (badSlug)
348
+ return badSlug;
349
+ }
350
+ const profilePath = join(getShopperArtefactDir(), PROFILE_FILE);
351
+ const manifest = tryReadManifest(profilePath);
352
+ if (manifest === null) {
353
+ return notFoundRemember("No sil shopper to remember for — create it first with sil_profile_materialize.");
354
+ }
355
+ // Resolve the target body file (and, for a taste, the active domain).
356
+ let target;
357
+ let resolvedDomain;
358
+ if (spec.kind === "fact") {
359
+ target = manifest.userSpecPath;
360
+ }
361
+ else {
362
+ const slugs = Object.keys(manifest.domains);
363
+ let slug;
364
+ if (spec.domain !== undefined) {
365
+ slug = spec.domain;
366
+ }
367
+ else if (slugs.length === 1) {
368
+ slug = slugs[0];
369
+ }
370
+ else if (slugs.length === 0) {
371
+ return notFoundRemember("The shopper has no domains yet — mint the niche first via sil_profile_materialize.");
372
+ }
373
+ else {
374
+ return invalid("domain", "The shopper has " + slugs.length + " domains (" + slugs.join(", ")
375
+ + ") — name the `domain` to remember a taste in (omitting it is ambiguous).");
376
+ }
377
+ const entry = manifest.domains[slug];
378
+ if (entry === undefined) {
379
+ return notFoundRemember('No domain "' + slug + '" on the shopper — mint it first via sil_profile_materialize.');
380
+ }
381
+ target = entry.playbookPath;
382
+ resolvedDomain = slug;
383
+ }
384
+ // Fail-closed existence gate — append NEVER resurrects a seed-less doc.
385
+ if (!existsSync(target)) {
386
+ return notFoundRemember("The target artefact is missing — re-materialize the shopper/domain before remembering.");
387
+ }
388
+ // O_APPEND write — one short entry at EOF, "\n"-prefixed. A hard fact is marked
389
+ // unambiguously so the reject-at-pick rule can grep it.
390
+ const mark = spec.kind === "fact" && spec.hard === true ? HARD_MARKER + " " : "";
391
+ const line = "\n- " + mark + spec.text.trim();
392
+ try {
393
+ appendFileSync(target, line, { flag: "a", mode: FILE_MODE });
394
+ }
395
+ catch (err) {
396
+ return {
397
+ ok: false,
398
+ kind: "persistence_failed",
399
+ error: target + ": " + errCause(err),
400
+ message: "The remembered entry could NOT be appended to the sil data directory, so it"
401
+ + " did not stick. Fix the data directory (it must be writable — check"
402
+ + " permissions / free space / that the target is a file, not a directory),"
403
+ + " then try again.",
404
+ recovery: "fix_data_dir",
405
+ };
406
+ }
407
+ return {
408
+ ok: true,
409
+ kind: spec.kind,
410
+ target,
411
+ ...(resolvedDomain !== undefined ? { domain: resolvedDomain } : {}),
412
+ };
267
413
  }
268
- /** Read + parse one `agents/<id>/profile.json` into a typed manifest, or throw
269
- * a descriptive error the caller maps to an `unreadable`/`not_found` outcome.
270
- * A manifest whose JSON parses but is missing the required string fields is
271
- * treated as corrupt (an interrupted or hand-edited write) — not silently
272
- * coerced. */
414
+ /** Read + parse the singleton `shopper/profile.json` into a typed manifest, or
415
+ * throw a descriptive error the caller maps to an `unreadable`/`not_found` outcome.
416
+ * A manifest whose JSON parses but is missing the required fields (name +
417
+ * userSpecPath + createdAt + a `domains` object) is treated as corrupt — not
418
+ * silently coerced. */
273
419
  function readManifestFile(profilePath) {
274
420
  const raw = readFileSync(profilePath, "utf8");
275
421
  const parsed = JSON.parse(raw);
276
422
  if (typeof parsed !== "object" ||
277
423
  parsed === null ||
278
- typeof parsed.agentId !== "string" ||
279
424
  typeof parsed.name !== "string" ||
280
- typeof parsed.domainSpecPath !== "string" ||
281
- typeof parsed.intentSpecPath !== "string" ||
282
425
  typeof parsed.userSpecPath !== "string" ||
283
- typeof parsed.playbookPath !== "string" ||
284
- typeof parsed.createdAt !== "string") {
426
+ typeof parsed.createdAt !== "string" ||
427
+ typeof parsed.domains !== "object" ||
428
+ parsed.domains === null ||
429
+ Array.isArray(parsed.domains)) {
285
430
  throw new Error("profile.json is missing required manifest fields");
286
431
  }
287
432
  return parsed;
288
433
  }
289
- /**
290
- * Enumerate the materialized experts under each `$SIL_DATA_DIR/agents/<id>/`.
291
- *
292
- * The manifest is the source of truth — each `agents/<id>/profile.json` is read
293
- * and parsed (no dirname guessing). Experts are returned `createdAt` DESC (the
294
- * just-made expert first, the one the user most likely wants to act on). An
295
- * absent/empty store yields a normal empty listing. One unreadable or corrupt
296
- * manifest lands in `unreadable[]` and never aborts the listing — the healthy
297
- * experts still list. Reads only; never writes, never reads a token.
298
- */
299
- export function listAgentProfiles() {
300
- const root = getAgentsRoot();
301
- if (!existsSync(root)) {
302
- return { ok: true, experts: [], unreadable: [] };
303
- }
304
- const experts = [];
305
- const unreadable = [];
306
- let entries;
434
+ /** Read the manifest if it exists and parses; `null` otherwise. Used by the
435
+ * upsert/de-register paths that must merge with whatever is already on disk. */
436
+ function tryReadManifest(profilePath) {
437
+ if (!existsSync(profilePath))
438
+ return null;
307
439
  try {
308
- entries = readdirSync(root, { withFileTypes: true });
440
+ return readManifestFile(profilePath);
309
441
  }
310
- catch (err) {
311
- // The agents root exists but cannot be enumerated (e.g. EACCES). Surface it
312
- // as a single degraded entry rather than throwing across the boundary.
313
- unreadable.push({
314
- agentId: AGENTS_SUBDIR,
315
- error: errCause(err),
316
- });
317
- return { ok: true, experts, unreadable };
318
- }
319
- for (const entry of entries) {
320
- if (!entry.isDirectory())
321
- continue;
322
- const agentId = entry.name;
323
- const profilePath = join(root, agentId, PROFILE_FILE);
324
- if (!existsSync(profilePath)) {
325
- // A directory under agents/ with no manifest is not a (loadable) sil
326
- // expert — report it degraded so the user sees the residue (e.g. a
327
- // remove that cleared the manifest but left a stray file).
328
- unreadable.push({ agentId, error: "no profile.json manifest" });
329
- continue;
330
- }
331
- try {
332
- const manifest = readManifestFile(profilePath);
333
- experts.push({
334
- agentId: manifest.agentId,
335
- name: manifest.name,
336
- createdAt: manifest.createdAt,
337
- });
338
- }
339
- catch (err) {
340
- unreadable.push({ agentId, error: errCause(err) });
341
- }
442
+ catch {
443
+ return null;
342
444
  }
343
- // Most-recently-created first (Product Flow 1). createdAt is ISO 8601, so a
344
- // lexical compare is also chronological; fall back to it when Date.parse is
345
- // NaN (a corrupt-but-parseable date) so the sort is total and stable-ish.
346
- experts.sort((a, b) => createdAtDesc(a.createdAt, b.createdAt));
347
- return { ok: true, experts, unreadable };
348
445
  }
349
- /** Compare two ISO 8601 createdAt strings, most-recent first. */
350
- function createdAtDesc(a, b) {
446
+ /** Project a manifest's `domains` map to the cheap summary index, ordered by
447
+ * first-mint time (then slug) so the index is deterministic. */
448
+ function toDomainSummaries(manifest) {
449
+ return Object.values(manifest.domains)
450
+ .map((d) => ({ slug: d.slug, name: d.name, createdAt: d.createdAt, updatedAt: d.updatedAt }))
451
+ .sort((a, b) => createdAtAsc(a.createdAt, b.createdAt) || (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
452
+ }
453
+ /** Compare two ISO 8601 createdAt strings, oldest first. */
454
+ function createdAtAsc(a, b) {
351
455
  const ta = Date.parse(a);
352
456
  const tb = Date.parse(b);
353
457
  if (Number.isNaN(ta) || Number.isNaN(tb)) {
354
- // Lexical fallback keeps the sort total when a timestamp is unparseable.
355
- return a < b ? 1 : a > b ? -1 : 0;
458
+ return a < b ? -1 : a > b ? 1 : 0;
356
459
  }
357
- return tb - ta;
460
+ return ta - tb;
358
461
  }
359
462
  /**
360
- * Read one expert's full detail — the manifest PLUS the SDS artefact bodies from
361
- * the files it points at — so the skill can render a complete view.
463
+ * Read the shopper overview (Zoom A, no args) OR one domain's full pack (slug).
464
+ *
465
+ * Zoom A (no slug) is the folded listing — it ABSORBS the old standalone listing
466
+ * surface: an empty store, or a freshly-created shopper with `domains: {}`, reads `ok`
467
+ * (empty-is-healthy) with an empty `domains` index and `unreadable: []` — NEVER
468
+ * `not_found` (the create-collision check + the "you haven't set up a shopper yet"
469
+ * framing + the shop-time existence check all depend on it). A corrupt manifest, or
470
+ * a degraded shopper directory, is surfaced inline in `unreadable[]` and never
471
+ * aborts the read nor downgrades to `not_found`.
362
472
  *
363
- * Re-runs the writer's `agentId` gate BEFORE any `join`/read (a traversal-shaped
364
- * id → `invalid_request`, reading nothing). An unknown id, an absent/unreadable
365
- * manifest, or an absent body of ANY of the four REQUIRED SDS specs
366
- * (`domain_spec.md` / `intent_spec.md` / `user_spec.md` / `playbook.md`) →
367
- * `not_found` (Founder review round 2: all four always exist; a degraded expert
368
- * is, from the user's view, not viewable). There is no degrade-to-undefined path
369
- * any more — a referenced-but-missing body of any of the four fails the read
370
- * closed. Never throws across the boundary; reads only.
473
+ * Per-domain (slug given) guards the `domainSlug` BEFORE any `join`/read (a
474
+ * traversal-shaped slug → `invalid_request(field=domainSlug)`). Fail-closed: an
475
+ * absent/corrupt manifest, a missing SHARED user-spec body, a slug NOT in the
476
+ * `domains` map (manifest-gated — an orphaned leaf is invisible), or any of the 3
477
+ * referenced domain bodies missing → `not_found` (never a half pack). Never throws;
478
+ * reads only.
371
479
  */
372
- export function readAgentProfile(agentId) {
373
- const bad = rejectBadAgentId(agentId);
374
- if (bad)
375
- return bad;
376
- const dir = getAgentArtefactDir(agentId);
480
+ export function readAgentProfile(domainSlug) {
481
+ const wantsDomain = nonBlank(domainSlug);
482
+ if (wantsDomain) {
483
+ const badSlug = rejectBadSegment(domainSlug, "domainSlug");
484
+ if (badSlug)
485
+ return badSlug;
486
+ }
487
+ const dir = getShopperArtefactDir();
377
488
  const profilePath = join(dir, PROFILE_FILE);
489
+ if (!wantsDomain) {
490
+ // --- Zoom A: the no-args overview (folded listing, empty-is-healthy) ---
491
+ if (!existsSync(profilePath)) {
492
+ // Empty store — a normal, healthy empty outcome.
493
+ return { ok: true, userSpec: "", domains: [], unreadable: [], profilePath };
494
+ }
495
+ let manifest;
496
+ try {
497
+ manifest = readManifestFile(profilePath);
498
+ }
499
+ catch (err) {
500
+ // Corrupt manifest — degraded, surfaced inline, never not_found / never throws.
501
+ return {
502
+ ok: true,
503
+ userSpec: "",
504
+ domains: [],
505
+ unreadable: [{ id: SHOPPER_SUBDIR, error: errCause(err) }],
506
+ profilePath,
507
+ };
508
+ }
509
+ let userSpec;
510
+ try {
511
+ userSpec = readFileSync(manifest.userSpecPath, "utf8");
512
+ }
513
+ catch (err) {
514
+ // The shared user-spec body is gone — the shopper cannot fully load; surface
515
+ // the breakage as degraded rather than hiding it or aborting the read.
516
+ return {
517
+ ok: true,
518
+ userSpec: "",
519
+ domains: [],
520
+ unreadable: [{ id: SHOPPER_SUBDIR, error: errCause(err) }],
521
+ profilePath,
522
+ };
523
+ }
524
+ return {
525
+ ok: true,
526
+ name: manifest.name,
527
+ userSpec,
528
+ domains: toDomainSummaries(manifest),
529
+ unreadable: [],
530
+ profilePath,
531
+ createdAt: manifest.createdAt,
532
+ };
533
+ }
534
+ // --- Per-domain read (slug given) — fail-closed ---
378
535
  if (!existsSync(profilePath)) {
379
- return notFoundRead(agentId);
536
+ return notFoundRead();
380
537
  }
381
538
  let manifest;
382
539
  try {
383
540
  manifest = readManifestFile(profilePath);
384
541
  }
385
542
  catch {
386
- // A corrupt/half-written manifest is, to the viewer, an expert that cannot
387
- // be loaded — surface not_found (the skill lists the healthy ones), never a
388
- // raw parse error across the boundary.
389
- return notFoundRead(agentId);
390
- }
391
- // All FOUR SDS spec bodies are REQUIRED for a created expert — they gate the
392
- // read fail-closed (the role the persona body played pre-SDS). A manifest that
393
- // points at a domain_spec.md / intent_spec.md / user_spec.md / playbook.md whose
394
- // body is gone (a partial write, a hand-deleted file) is, to the viewer, an
395
- // expert that cannot be loaded. This is the per-file-atomic, NOT-cross-file-
396
- // transactional safety boundary: a partial write degrades to a fail-closed
397
- // not_found, never a coherent-but-incomplete expert (Founder review round 2:
398
- // all four are present from creation, so none degrades to absence).
543
+ return notFoundRead();
544
+ }
545
+ // The SHARED user-spec body gates the read fail-closed — a manifest pointing at a
546
+ // user_spec.md whose body is gone is, to the viewer, a shopper that cannot load.
547
+ let userSpec;
548
+ try {
549
+ userSpec = readFileSync(manifest.userSpecPath, "utf8");
550
+ }
551
+ catch {
552
+ return notFoundRead();
553
+ }
554
+ // Manifest-gated — a slug not in the map (incl. an orphaned on-disk leaf) is
555
+ // not_found, never a filesystem guess.
556
+ const entry = manifest.domains[domainSlug];
557
+ if (entry === undefined) {
558
+ return notFoundRead();
559
+ }
399
560
  let domainSpec;
400
561
  let intentSpec;
401
- let userSpec;
402
562
  let playbook;
403
563
  try {
404
- domainSpec = readFileSync(manifest.domainSpecPath, "utf8");
405
- intentSpec = readFileSync(manifest.intentSpecPath, "utf8");
406
- userSpec = readFileSync(manifest.userSpecPath, "utf8");
407
- playbook = readFileSync(manifest.playbookPath, "utf8");
564
+ domainSpec = readFileSync(entry.domainSpecPath, "utf8");
565
+ intentSpec = readFileSync(entry.intentSpecPath, "utf8");
566
+ playbook = readFileSync(entry.playbookPath, "utf8");
408
567
  }
409
568
  catch {
410
- return notFoundRead(agentId);
569
+ return notFoundRead();
411
570
  }
412
571
  return {
413
572
  ok: true,
414
- agentId: manifest.agentId,
415
573
  name: manifest.name,
574
+ userSpec,
575
+ domains: toDomainSummaries(manifest),
576
+ unreadable: [],
577
+ profilePath,
578
+ createdAt: entry.createdAt,
579
+ slug: entry.slug,
416
580
  domainSpec,
417
581
  intentSpec,
418
- userSpec,
419
582
  playbook,
420
- profilePath,
421
- createdAt: manifest.createdAt,
583
+ updatedAt: entry.updatedAt,
422
584
  };
423
585
  }
424
- function notFoundRead(agentId) {
586
+ function notFoundRead() {
425
587
  return {
426
588
  ok: false,
427
589
  kind: "not_found",
428
- agentId,
429
- message: 'No sil expert "' + agentId + '" — list your experts to see which exist.',
590
+ message: "No such domain on the sil shopper — call sil_profile_get with no domainSlug to see"
591
+ + " what the shopper has (its shared user spec + the domains it has learned).",
430
592
  };
431
593
  }
432
594
  /**
433
- * Remove one expert's behaviour-artefact directory — the sil-side half of a
434
- * clean removal (the host-wiring half is the skill's `openclaw` CLI step; the
435
- * plugin cannot write `~/.openclaw`).
595
+ * Remove exactly ONE of the shopper's domain packs — the sil-side half of a clean
596
+ * domain removal (the host-wiring half, if any, is the skill's `openclaw` CLI
597
+ * step; the plugin cannot write `~/.openclaw`).
436
598
  *
437
- * Fail-closed and scoped to exactly the named expert:
438
- * - re-runs the writer's `agentId` gate ITSELF (never trusts the caller) — a
439
- * bad/`main`/traversal-shaped id → `invalid_request`, deletes NOTHING;
440
- * - asserts the resolved target is strictly UNDER `getDataDir()/agents/` and
441
- * is NOT the `agents/` parent, so a delete can never escape the subtree or
442
- * wipe sibling experts;
443
- * - recursively delete the single validated leaf dir.
599
+ * Fail-closed and scoped to one domain leaf:
600
+ * - re-runs the `domainSlug` gate (never trusts the caller) — a bad/`main`/
601
+ * traversal/missing slug → `invalid_request` (`field:"domainSlug"`), deletes
602
+ * NOTHING (no omit-deletes-everything trap);
603
+ * - asserts the resolved leaf is strictly UNDER `<shopperDir>/domains/` and is NOT
604
+ * that parent, so a delete can never escape the subtree or wipe a sibling;
605
+ * - manifest-gated: an unregistered slug → `not_found` (idempotent);
606
+ * - removes the single leaf, THEN rewrites `profile.json` to de-register
607
+ * `domains[slug]` — the shopper and the SHARED user_spec survive.
444
608
  *
445
- * Absent target → `not_found` (idempotent — a re-run after a partial host-CLI
446
- * failure is safe). A genuine delete failure (e.g. EACCES) →
447
- * `persistence_failed` with `<dir>: <cause>`. Never throws across the boundary.
609
+ * A genuine delete/rewrite failure → `persistence_failed` with `<dir>: <cause>`.
610
+ * Never throws across the boundary.
448
611
  */
449
- export function removeAgentArtefacts(agentId) {
450
- const bad = rejectBadAgentId(agentId);
451
- if (bad)
452
- return bad;
453
- const dir = getAgentArtefactDir(agentId);
454
- // Defence in depth beyond the id gate: assert the resolved path is strictly a
455
- // child of the agents root and never the root itself. Deleting the parent
456
- // directory would wipe every sibling expert — refuse it even if some future
457
- // change to the gate let a separator-bearing id through.
458
- const root = getAgentsRoot();
459
- if (dirname(dir) !== root || dir === root) {
460
- return invalidAgentId("agentId resolves outside the agents subtree — refusing to delete: " +
461
- JSON.stringify(agentId));
462
- }
463
- if (!existsSync(dir)) {
612
+ export function removeAgentArtefacts(domainSlug) {
613
+ const badSlug = rejectBadSegment(domainSlug, "domainSlug");
614
+ if (badSlug)
615
+ return badSlug;
616
+ const shopperDir = getShopperArtefactDir();
617
+ const domainsRoot = join(shopperDir, DOMAINS_SUBDIR);
618
+ const leaf = getDomainArtefactDir(domainSlug);
619
+ // Defence in depth beyond the slug gate: the leaf must be a STRICT child of the
620
+ // domains root and never the root itself — deleting the parent would wipe every
621
+ // sibling domain.
622
+ if (dirname(leaf) !== domainsRoot || leaf === domainsRoot) {
623
+ return invalid("domainSlug", "domainSlug resolves outside the domains subtree — refusing to delete: " +
624
+ JSON.stringify(domainSlug));
625
+ }
626
+ const profilePath = join(shopperDir, PROFILE_FILE);
627
+ const manifest = tryReadManifest(profilePath);
628
+ // Manifest-gated: an unregistered (or absent) domain is already gone.
629
+ if (manifest === null || !(domainSlug in manifest.domains)) {
464
630
  return {
465
631
  ok: false,
466
632
  kind: "not_found",
467
- agentId,
468
- message: 'No sil expert "' + agentId + '" to remove (already gone) — list your'
469
- + " experts to see which exist. A re-run is safe (idempotent).",
633
+ message: 'No domain "' + domainSlug + '" on the sil shopper to remove (already gone) —'
634
+ + " call sil_profile_get with no domainSlug to see which domains exist. A"
635
+ + " re-run is safe.",
470
636
  };
471
637
  }
638
+ // Remove the leaf FIRST; only de-register once the bytes are actually gone, so a
639
+ // failed delete never leaves the map pointing at a still-present pack.
472
640
  try {
473
- rmSync(dir, { recursive: true, force: true });
641
+ rmSync(leaf, { recursive: true, force: true });
474
642
  }
475
643
  catch (err) {
476
- return {
477
- ok: false,
478
- kind: "persistence_failed",
479
- error: dir + ": " + errCause(err),
480
- message: "The expert's behaviour artefacts could NOT be removed from the sil data"
481
- + " directory. Fix the data directory (it must be writable — check"
482
- + " permissions), then remove the expert again.",
483
- recovery: "fix_data_dir",
484
- };
644
+ return persistenceFailedRemove(leaf, err);
485
645
  }
486
- return { ok: true, agentId };
646
+ const nextDomains = {};
647
+ for (const [slug, entry] of Object.entries(manifest.domains)) {
648
+ if (slug !== domainSlug)
649
+ nextDomains[slug] = entry;
650
+ }
651
+ const updated = { ...manifest, domains: nextDomains };
652
+ try {
653
+ atomicWrite(profilePath, JSON.stringify(updated, null, 2) + "\n");
654
+ }
655
+ catch (err) {
656
+ return persistenceFailedRemove(profilePath, err);
657
+ }
658
+ return { ok: true, domainSlug };
659
+ }
660
+ function persistenceFailedRemove(path, err) {
661
+ return {
662
+ ok: false,
663
+ kind: "persistence_failed",
664
+ error: path + ": " + errCause(err),
665
+ message: "The domain's behaviour artefacts could NOT be removed from the sil data"
666
+ + " directory. Fix the data directory (it must be writable — check"
667
+ + " permissions), then remove the domain again.",
668
+ recovery: "fix_data_dir",
669
+ };
487
670
  }
488
671
  /** Extract a human-readable cause from an unknown thrown value (never PII). */
489
672
  function errCause(err) {