sil-openclaw 0.3.8 → 0.4.0

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,129 +1,96 @@
1
1
  /**
2
- * sil shopper behaviour-artefact store — the single multi-domain shopper layout.
2
+ * sil shopper behaviour-artefact store — frontmatter-as-truth, no manifest.
3
3
  *
4
- * The agent-creation engine (the bundled `sil-shopping/SKILL.md` procedure driving
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
- *
10
- * What the plugin DOES own is the shopper's *behaviour* layer, materialized into
11
- * its own disclosed `filesystemScope` — `$SIL_DATA_DIR` (the same directory
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:
4
+ * There is ONE persistent shopper (a SINGLETON). Its artefacts live under a fixed,
5
+ * compile-time-constant sub-tree of the plugin's disclosed `filesystemScope`
6
+ * (`$SIL_DATA_DIR`, the same home `lib/credentials.ts` uses for tokens/identity):
17
7
  *
18
8
  * $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.
9
+ * ├─ user_spec.md the person — FRONTMATTER carries the shopper `name`;
10
+ * │ its presence IS "a shopper exists". Written by setup.
30
11
  * └─ 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.
36
- *
37
- * The persona is NOT a sil artefact: the shopper's identity/voice/standing rules
38
- * are the host workspace `SOUL.md`, written directly via the host CLI by the
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.
12
+ * ├─ method.md frontmatter { domain, name, updated_at } + body
13
+ * ├─ prds/
14
+ * │ └─ <product>-<intent>.md frontmatter { key, product, intent, title,
15
+ * │ domain, created_at, updated_at } + body
16
+ * └─ assets/
17
+ * └─ <content-hash>.<ext> image bytes, owner-only, linked by path
41
18
  *
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.
49
- *
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.
19
+ * There is NO `profile.json` manifest: the **frontmatter IS the source of truth**,
20
+ * discovered by scanning the filesystem, so there is no second index layer to keep
21
+ * in sync. Crash-safety is free from atomic rename (tmp → rename → chmod 0600, dir
22
+ * 0700): a file is whole or absent. A file with malformed/absent frontmatter is
23
+ * SKIPPED and surfaced as `unreadable` (fail-closed read), never half-read and never
24
+ * silently dropped. `slug` and `prdKey` are the only caller-supplied path segments;
25
+ * both carry the lower-kebab / non-`main` guard BEFORE any join. The persona is NOT a
26
+ * sil artefact — it is the host workspace SOUL.md, written by the host CLI.
64
27
  */
65
- import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
28
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from "node:fs";
66
29
  import { dirname, join } from "node:path";
67
- import { randomBytes } from "node:crypto";
30
+ import { createHash, randomBytes } from "node:crypto";
68
31
  import { DIR_MODE, ensureDataDir, getDataDir } from "./credentials.js";
69
- /** Owner-only file mode — the artefacts are user-scoped, like tokens. The dir
70
- * mode (`DIR_MODE`, `0o700`) is owned by `credentials.ts` (the data-dir owner)
71
- * and imported, so the data-home permission lives in exactly one place. */
32
+ /** Owner-only file mode — artefacts are user-scoped, like tokens. The dir mode
33
+ * (`DIR_MODE`, `0o700`) is owned by `credentials.ts` and imported, so the data-home
34
+ * permission lives in exactly one place. */
72
35
  const FILE_MODE = 0o600;
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). */
36
+ /** Fixed, compile-time-constant sub-tree under `$SIL_DATA_DIR` that holds the ONE
37
+ * shopper's behaviour artefacts. A SINGLETON, so this is a constant — NOT caller
38
+ * input — which makes the shopper path segment un-spoofable. */
77
39
  const SHOPPER_SUBDIR = "shopper";
78
- /** The sub-tree under the shopper dir that holds the per-domain packs. */
79
40
  const DOMAINS_SUBDIR = "domains";
80
- /** Artefact filenames (stable — the sil skill resolves them from profile.json,
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. */
41
+ const PRDS_SUBDIR = "prds";
42
+ const ASSETS_SUBDIR = "assets";
83
43
  const USER_SPEC_FILE = "user_spec.md";
84
- const DOMAIN_SPEC_FILE = "domain_spec.md";
85
- const INTENT_SPEC_FILE = "intent_spec.md";
86
- const PLAYBOOK_FILE = "playbook.md";
87
- const PROFILE_FILE = "profile.json";
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`). */
44
+ const METHOD_FILE = "method.md";
45
+ /** A domain slug / PRD key must be lower-kebab and never `main` (host-reserved). Both
46
+ * are joined as filesystem path segments, so they carry this guard before any join. */
47
+ const SEGMENT_RE = /^[a-z0-9][a-z0-9-]*$/;
48
+ /** The stable marker the shop loop's reject-at-pick rule greps for an inviolable
49
+ * constraint (e.g. `- [hard] never leather`). */
90
50
  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.) */
94
- const AGENT_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
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);
51
+ /** attach-asset limits: ~8 MB decoded, image MIME allowlist → file extension. */
52
+ const MAX_ASSET_BYTES = 8 * 1024 * 1024;
53
+ const MIME_EXT = {
54
+ "image/jpeg": "jpg",
55
+ "image/png": "png",
56
+ "image/webp": "webp",
57
+ "image/gif": "gif",
58
+ };
59
+ function invalid(field, message) {
60
+ return { ok: false, kind: "invalid_request", field, message };
104
61
  }
105
- /** Resolve a per-domain pack directory under the singleton shopper dir.
106
- *
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);
62
+ function notFound(message) {
63
+ return { ok: false, kind: "not_found", message };
64
+ }
65
+ function unreadable(path) {
66
+ return {
67
+ ok: false,
68
+ kind: "unreadable",
69
+ message: path + ": the artefact is present but corrupt (malformed or absent frontmatter)"
70
+ + " — inspect / repair, do NOT overwrite (it may still be recoverable).",
71
+ };
72
+ }
73
+ function persistenceFailed(path, err) {
74
+ return {
75
+ ok: false,
76
+ kind: "persistence_failed",
77
+ error: path + ": " + errCause(err),
78
+ message: "The shopper behaviour artefacts could NOT be written to the sil data directory,"
79
+ + " so the change did not stick. Fix the data directory (it must be writable —"
80
+ + " check permissions / free space / that $SIL_DATA_DIR is a directory), then"
81
+ + " try again.",
82
+ recovery: "fix_data_dir",
83
+ };
114
84
  }
115
- /** True when `s` is a present, non-blank string. */
116
85
  function nonBlank(s) {
117
86
  return typeof s === "string" && s.trim().length > 0;
118
87
  }
119
- function invalid(field, message) {
120
- return { ok: false, kind: "invalid_request", field, message };
88
+ function errCause(err) {
89
+ return err instanceof Error ? err.message : String(err);
121
90
  }
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. */
91
+ /** Validate a caller-supplied path segment the SAME way at every call site: present +
92
+ * non-blank, never `main`, lower-kebab — applied BEFORE any join/read/delete so a
93
+ * traversal, an absolute path, a bare dot, or `main` never becomes a path segment. */
127
94
  function rejectBadSegment(value, field) {
128
95
  if (!nonBlank(value)) {
129
96
  return invalid(field, field + " is required and must be non-empty.");
@@ -131,544 +98,574 @@ function rejectBadSegment(value, field) {
131
98
  if (value === "main") {
132
99
  return invalid(field, '"main" is host-reserved and cannot be a ' + field + ".");
133
100
  }
134
- if (!AGENT_ID_RE.test(value)) {
101
+ if (!SEGMENT_RE.test(value)) {
135
102
  return invalid(field, field + " must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(value));
136
103
  }
137
104
  return null;
138
105
  }
106
+ // ===========================================================================
107
+ // Path resolvers — the shopper segment is a constant; only slug/prd are input.
108
+ // ===========================================================================
109
+ /** The SINGLETON shopper artefact directory under the plugin's data dir. Never
110
+ * hardcoded — `getDataDir()` honors `$SIL_DATA_DIR`/`$XDG_DATA_HOME`. The shopper
111
+ * segment is the constant `SHOPPER_SUBDIR`, so there is no traversal vector here. */
112
+ export function getShopperArtefactDir() {
113
+ return join(getDataDir(), SHOPPER_SUBDIR);
114
+ }
115
+ /** A per-domain directory under the singleton shopper dir. SAFETY: `slug` is a
116
+ * caller-supplied path segment — every caller MUST `rejectBadSegment` it BEFORE this
117
+ * join. */
118
+ export function getDomainArtefactDir(slug) {
119
+ return join(getShopperArtefactDir(), DOMAINS_SUBDIR, slug);
120
+ }
121
+ /** One-line scalar for a coordinate value: newlines folded to spaces, trimmed. */
122
+ function scalar(value) {
123
+ return String(value).replace(/\r?\n/g, " ").trim();
124
+ }
125
+ function serializeArtefact(fields, body) {
126
+ const fm = Object.entries(fields)
127
+ .map(([k, v]) => k + ": " + scalar(v))
128
+ .join("\n");
129
+ const b = body.endsWith("\n") ? body : body + "\n";
130
+ return "---\n" + fm + "\n---\n" + b;
131
+ }
132
+ /** Parse `--- key: value … ---` frontmatter + body. Returns null (⇒ `unreadable`) on
133
+ * a missing open fence, a missing close fence, or an empty frontmatter block — a
134
+ * fail-closed read, never a silent coercion. */
135
+ function parseArtefact(raw) {
136
+ if (!raw.startsWith("---"))
137
+ return null;
138
+ const close = raw.slice(3).match(/\n---[ \t]*\r?\n/);
139
+ if (!close || close.index === undefined)
140
+ return null;
141
+ const fmRaw = raw.slice(3, 3 + close.index);
142
+ const body = raw.slice(3 + close.index + close[0].length);
143
+ const fields = {};
144
+ for (const line of fmRaw.split(/\r?\n/)) {
145
+ const m = /^([A-Za-z0-9_]+):\s*(.*)$/.exec(line);
146
+ if (m && m[2] !== "")
147
+ fields[m[1]] = m[2].trim();
148
+ }
149
+ if (Object.keys(fields).length === 0)
150
+ return null;
151
+ return { fields, body };
152
+ }
153
+ /** Read + parse one artefact file, or null if absent/unreadable/malformed. */
154
+ function readArtefactFile(path) {
155
+ if (!existsSync(path))
156
+ return null;
157
+ let raw;
158
+ try {
159
+ raw = readFileSync(path, "utf8");
160
+ }
161
+ catch {
162
+ return null;
163
+ }
164
+ return parseArtefact(raw);
165
+ }
166
+ /** Atomic single-file write: tmp sibling → write → rename over target → chmod. A
167
+ * reader sees the old file or the new one, never a half-written one (mirrors
168
+ * `credentials.ts`). Ensures the containing dir (0700) first. */
169
+ function atomicWrite(path, contents) {
170
+ mkdirSync(dirname(path), { recursive: true, mode: DIR_MODE });
171
+ const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
172
+ writeFileSync(tmp, contents, { mode: FILE_MODE });
173
+ renameSync(tmp, path);
174
+ chmodSync(path, FILE_MODE);
175
+ }
176
+ /** Write binary bytes atomically, owner-only. */
177
+ function atomicWriteBytes(path, bytes) {
178
+ mkdirSync(dirname(path), { recursive: true, mode: DIR_MODE });
179
+ const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
180
+ writeFileSync(tmp, bytes, { mode: FILE_MODE });
181
+ renameSync(tmp, path);
182
+ chmodSync(path, FILE_MODE);
183
+ }
139
184
  /**
140
- * Materialize the shopper / a domain pack.
141
- *
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.
185
+ * Materialize the ONE shopper — write `user_spec.md` whose FRONTMATTER carries the
186
+ * shopper `name` and whose body is the shared user spec. SETUP-ONLY: it mints no
187
+ * method/PRD (that is `sil_learn create`) and writes no manifest. Validate-first: a
188
+ * blank `name`/`userSpec` returns `invalid_request` and writes nothing.
152
189
  */
153
190
  export function materializeProfile(spec) {
154
- // --- validate-first (nothing is written until every field is good) ---
155
- if (!nonBlank(spec.name)) {
191
+ if (!nonBlank(spec.name))
156
192
  return invalid("name", "name is required and must be non-empty.");
157
- }
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.
160
193
  if (!nonBlank(spec.userSpec)) {
161
194
  return invalid("userSpec", "userSpec is required and must be non-empty.");
162
195
  }
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
- }
182
- }
183
196
  const dir = getShopperArtefactDir();
184
197
  const userSpecPath = join(dir, USER_SPEC_FILE);
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
- }
217
- const manifest = {
218
- name: spec.name,
219
- userSpecPath,
220
- createdAt,
221
- domains,
222
- };
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.
227
- const dirPreexisted = existsSync(dir);
228
198
  try {
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.
231
199
  ensureDataDir();
232
200
  mkdirSync(dir, { recursive: true, mode: DIR_MODE });
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
- }
243
- atomicWrite(userSpecPath, spec.userSpec);
244
- atomicWrite(profilePath, JSON.stringify(manifest, null, 2) + "\n");
201
+ atomicWrite(userSpecPath, serializeArtefact({ name: spec.name }, spec.userSpec));
245
202
  }
246
203
  catch (err) {
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.
263
- try {
264
- rmSync(dir, { recursive: true, force: true });
265
- }
266
- catch {
267
- // best-effort
268
- }
269
- }
270
- const cause = err instanceof Error ? err.message : String(err);
204
+ return persistenceFailed(dir, err);
205
+ }
206
+ return { ok: true, dir, userSpecPath };
207
+ }
208
+ export function readShopperIdentity() {
209
+ const userSpecPath = join(getShopperArtefactDir(), USER_SPEC_FILE);
210
+ if (!existsSync(userSpecPath))
211
+ return { ok: true, unreadable: [] };
212
+ const parsed = readArtefactFile(userSpecPath);
213
+ if (parsed === null) {
271
214
  return {
272
- ok: false,
273
- kind: "persistence_failed",
274
- error: dir + ": " + cause,
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.",
215
+ ok: true,
216
+ unreadable: [{ id: USER_SPEC_FILE, error: "user_spec.md has malformed or absent frontmatter" }],
279
217
  };
280
218
  }
281
- if (domain !== undefined && entry !== undefined) {
282
- return { ok: true, dir, userSpecPath, profilePath, domain: entry };
219
+ const name = parsed.fields["name"];
220
+ if (!nonBlank(name)) {
221
+ return {
222
+ ok: true,
223
+ unreadable: [{ id: USER_SPEC_FILE, error: "user_spec.md frontmatter carries no name" }],
224
+ };
283
225
  }
284
- return { ok: true, dir, userSpecPath, profilePath };
285
- }
286
- /** Atomic single-file write: tmp sibling → write → rename over target → chmod.
287
- * Mirrors the token/identity write in `credentials.ts` so a half-written
288
- * artefact never appears (a reader sees the old file or the new one). */
289
- function atomicWrite(path, contents) {
290
- const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
291
- writeFileSync(tmp, contents, { mode: FILE_MODE });
292
- renameSync(tmp, path);
293
- chmodSync(path, FILE_MODE);
226
+ return { ok: true, name, unreadable: [] };
294
227
  }
295
- function notFoundRemember(message) {
296
- return { ok: false, kind: "not_found", message };
228
+ /** Resolve the target artefact file, guarding the selectors first. Returns an
229
+ * `InvalidRequest` when a required selector is missing/bad. */
230
+ function resolveTarget(spec) {
231
+ if (spec.target === "user_spec") {
232
+ return { path: join(getShopperArtefactDir(), USER_SPEC_FILE), label: "user_spec" };
233
+ }
234
+ const badDomain = rejectBadSegment(spec.domain, "domain");
235
+ if (badDomain)
236
+ return badDomain;
237
+ const slug = spec.domain;
238
+ if (spec.target === "method") {
239
+ return { path: join(getDomainArtefactDir(slug), METHOD_FILE), label: "method", domain: slug };
240
+ }
241
+ // prd
242
+ const badPrd = rejectBadSegment(spec.prd, "prd");
243
+ if (badPrd)
244
+ return badPrd;
245
+ const prd = spec.prd;
246
+ return {
247
+ path: join(getDomainArtefactDir(slug), PRDS_SUBDIR, prd + ".md"),
248
+ label: "prd",
249
+ domain: slug,
250
+ prd,
251
+ };
297
252
  }
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.");
253
+ export function learnArtefact(spec) {
254
+ // `hard` is valid ONLY on append to user_spec / prd. Every other combination —
255
+ // all four non-append kinds on any target, and append to method — is rejected
256
+ // LOUDLY, never silently dropped: a buyer who passes `hard:true` expecting to
257
+ // promote a constraint must learn at once when the promotion does not land.
258
+ // Hoisted ABOVE the kind switch so a hard misuse wins error-precedence over the
259
+ // per-kind field checks (this subsumes the old method-only append guard).
260
+ if (spec.hard === true && !(spec.kind === "append" && spec.target !== "method")) {
261
+ return invalid("hard", "hard is valid only on append to user_spec or prd — a method carries no hard"
262
+ + " constraints, and create/amend/retract/attach-asset take no hard flag.");
263
+ }
264
+ switch (spec.kind) {
265
+ case "create":
266
+ return learnCreate(spec);
267
+ case "append":
268
+ return learnAppend(spec);
269
+ case "amend":
270
+ case "retract":
271
+ return learnAmendRetract(spec);
272
+ case "attach-asset":
273
+ return learnAttachAsset(spec);
274
+ default:
275
+ return invalid("kind", "kind must be one of create|append|amend|retract|attach-asset.");
335
276
  }
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\".");
277
+ }
278
+ /** `create` mints a whole method or PRD body atomically — the file IS the
279
+ * registration (no manifest). NOT valid for user_spec (that is materialize). */
280
+ function learnCreate(spec) {
281
+ if (spec.target === "user_spec") {
282
+ return invalid("target", "create is not valid for user_spec — the shopper's shared spec is written by"
283
+ + " sil_profile_materialize (setup), then refined with append/amend/retract.");
284
+ }
285
+ if (!nonBlank(spec.body))
286
+ return invalid("body", "body is required and must be non-empty.");
287
+ const badDomain = rejectBadSegment(spec.domain, "domain");
288
+ if (badDomain)
289
+ return badDomain;
290
+ const slug = spec.domain;
291
+ const now = new Date().toISOString();
292
+ if (spec.target === "method") {
293
+ if (!nonBlank(spec.name))
294
+ return invalid("name", "name is required for a method.");
295
+ const path = join(getDomainArtefactDir(slug), METHOD_FILE);
296
+ const fields = { domain: slug, name: spec.name, updated_at: now };
297
+ try {
298
+ atomicWrite(path, serializeArtefact(fields, spec.body));
299
+ }
300
+ catch (err) {
301
+ return persistenceFailed(path, err);
302
+ }
303
+ return { ok: true, kind: "create", target: "method", domain: slug, path };
304
+ }
305
+ // prd
306
+ const badPrd = rejectBadSegment(spec.prd, "prd");
307
+ if (badPrd)
308
+ return badPrd;
309
+ const prd = spec.prd;
310
+ for (const f of ["product", "intent", "title"]) {
311
+ if (!nonBlank(spec[f]))
312
+ return invalid(f, f + " is required for a prd.");
313
+ }
314
+ const path = join(getDomainArtefactDir(slug), PRDS_SUBDIR, prd + ".md");
315
+ // Preserve created_at on a re-mint; advance updated_at.
316
+ const prior = readArtefactFile(path);
317
+ const createdAt = prior?.fields["created_at"] ?? now;
318
+ const fields = {
319
+ key: prd,
320
+ product: spec.product,
321
+ intent: spec.intent,
322
+ title: spec.title,
323
+ domain: slug,
324
+ created_at: createdAt,
325
+ updated_at: now,
326
+ };
327
+ try {
328
+ atomicWrite(path, serializeArtefact(fields, spec.body));
339
329
  }
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.");
330
+ catch (err) {
331
+ return persistenceFailed(path, err);
342
332
  }
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;
333
+ return { ok: true, kind: "create", target: "prd", domain: slug, prd, path };
334
+ }
335
+ /** append — add `- <text>` (or `- [hard] <text>`) under `## <section>` when given
336
+ * (fail-closed if that heading is absent), else at EOF. The target must already
337
+ * exist → not_found (never resurrects a seed-less doc). `hard` is guarded up-front
338
+ * in `learnArtefact` (append to method / any non-append kind is rejected there). */
339
+ function learnAppend(spec) {
340
+ if (!nonBlank(spec.text))
341
+ return invalid("text", "text is required and must be non-empty.");
342
+ const target = resolveTarget(spec);
343
+ if ("ok" in target)
344
+ return target;
345
+ const existing = readArtefactFile(target.path);
346
+ if (existing === null) {
347
+ return notFound("The target " + target.label + " does not exist — create it first (append never"
348
+ + " resurrects a seed-less doc).");
349
+ }
350
+ const mark = spec.hard === true ? HARD_MARKER + " " : "";
351
+ const bullet = "- " + mark + spec.text.trim();
352
+ let body;
353
+ if (nonBlank(spec.section)) {
354
+ const inserted = insertUnderSection(existing.body, spec.section, bullet);
355
+ if (inserted === null) {
356
+ const sections = listSections(existing.body);
357
+ return invalid("section", 'no "## ' + spec.section + '" heading in the ' + target.label + "; existing sections: "
358
+ + (sections.length > 0 ? sections.join(", ") : "(none)"));
359
+ }
360
+ body = inserted;
349
361
  }
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.");
362
+ else {
363
+ body = existing.body.replace(/\n*$/, "\n") + bullet + "\n";
354
364
  }
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;
365
+ return writeArtefactBody(target, existing.fields, body, "append");
366
+ }
367
+ /** amend/retract — exact single-occurrence bullet match on `from`; 0 → not_found,
368
+ * 2+ → invalid_request(ambiguous_match). A `[hard]` marker is preserved on amend. */
369
+ function learnAmendRetract(spec) {
370
+ if (!nonBlank(spec.from))
371
+ return invalid("from", "from is required and must be non-empty.");
372
+ if (spec.kind === "amend" && !nonBlank(spec.to)) {
373
+ return invalid("to", "to is required for amend.");
374
+ }
375
+ const target = resolveTarget(spec);
376
+ if ("ok" in target)
377
+ return target;
378
+ const existing = readArtefactFile(target.path);
379
+ if (existing === null) {
380
+ return notFound("The target " + target.label + " does not exist — nothing to change.");
381
+ }
382
+ const from = spec.from.trim();
383
+ const lines = existing.body.split("\n");
384
+ const matches = [];
385
+ const scoped = nonBlank(spec.section)
386
+ ? sectionLineRange(lines, spec.section)
387
+ : { start: 0, end: lines.length };
388
+ for (let i = scoped.start; i < scoped.end; i++) {
389
+ const parsed = parseBullet(lines[i]);
390
+ if (parsed && parsed.text.trim() === from)
391
+ matches.push(i);
392
+ }
393
+ if (matches.length === 0) {
394
+ return notFound('No bullet matching "' + from + '" in the ' + target.label + ".");
395
+ }
396
+ if (matches.length > 1) {
397
+ return invalid("ambiguous_match", "the text matches " + matches.length + " bullets — refine `from` (or scope with"
398
+ + " `section`) so it matches exactly one; refusing an ambiguous multi-write.");
399
+ }
400
+ const idx = matches[0];
401
+ if (spec.kind === "retract") {
402
+ lines.splice(idx, 1);
360
403
  }
361
404
  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.");
405
+ const parsed = parseBullet(lines[idx]);
406
+ const mark = parsed.hard ? HARD_MARKER + " " : "";
407
+ lines[idx] = parsed.indent + "- " + mark + spec.to.trim();
387
408
  }
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();
409
+ return writeArtefactBody(target, existing.fields, lines.join("\n"), spec.kind);
410
+ }
411
+ /** attach-asset — persist image bytes into `domains/<slug>/assets/<hash>.<ext>`
412
+ * (owner-only, content-hash = free dedup), then link them into the target by a
413
+ * RELATIVE markdown path. Per-domain only (user_spec is rejected). */
414
+ function learnAttachAsset(spec) {
415
+ if (spec.target === "user_spec") {
416
+ return invalid("target", "assets are per-domain — attach to a method or prd, not user_spec.");
417
+ }
418
+ if (!nonBlank(spec.bytes))
419
+ return invalid("bytes", "bytes (base64) is required.");
420
+ const ext = MIME_EXT[spec.mime ?? ""];
421
+ if (ext === undefined) {
422
+ return invalid("mime", "mime must be one of image/jpeg, image/png, image/webp, image/gif.");
423
+ }
424
+ const buf = Buffer.from(spec.bytes, "base64");
425
+ if (buf.length === 0)
426
+ return invalid("bytes", "bytes did not decode to a non-empty image.");
427
+ if (buf.length > MAX_ASSET_BYTES) {
428
+ return invalid("bytes", "image exceeds the " + MAX_ASSET_BYTES + "-byte cap.");
429
+ }
430
+ const target = resolveTarget(spec);
431
+ if ("ok" in target)
432
+ return target;
433
+ const existing = readArtefactFile(target.path);
434
+ if (existing === null) {
435
+ return notFound("The target " + target.label + " does not exist — create it before attaching an asset.");
436
+ }
437
+ const slug = target.domain;
438
+ const hash = createHash("sha256").update(buf).digest("hex").slice(0, 16);
439
+ const filename = hash + "." + ext;
440
+ const assetRel = ASSETS_SUBDIR + "/" + filename;
441
+ const assetAbs = join(getDomainArtefactDir(slug), ASSETS_SUBDIR, filename);
442
+ // Bytes FIRST (content-hashed → a mid-failure leaves only a benign, dedup-safe
443
+ // orphan), then the path-link into the target.
392
444
  try {
393
- appendFileSync(target, line, { flag: "a", mode: FILE_MODE });
445
+ atomicWriteBytes(assetAbs, buf);
394
446
  }
395
447
  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
- }
448
+ return persistenceFailed(assetAbs, err);
449
+ }
450
+ // Idempotent link on the asset PATH (not the caption): if `assets/<hash>.<ext>` is
451
+ // already referenced in the target, skip the body write — no second link line, no
452
+ // updated_at churn. The bytes were re-written above (identical-hash overwrite, a
453
+ // benign no-op), so a re-attach under any caption is a body no-op that still
454
+ // reports ok + assetPath.
455
+ const res = existing.body.includes("](" + assetRel + ")")
456
+ ? okAttach(target)
457
+ : writeArtefactBody(target, existing.fields, existing.body.replace(/\n*$/, "\n")
458
+ + "![" + (nonBlank(spec.caption) ? spec.caption.trim() : "") + "](" + assetRel + ")\n", "attach-asset");
459
+ if (!res.ok)
460
+ return res;
461
+ return { ...res, assetPath: assetRel };
462
+ }
463
+ /** The success envelope for an attach-asset that wrote no body (idempotent re-link)
464
+ * — mirrors `writeArtefactBody`'s ok shape without the re-serialize / timestamp bump. */
465
+ function okAttach(target) {
407
466
  return {
408
467
  ok: true,
409
- kind: spec.kind,
410
- target,
411
- ...(resolvedDomain !== undefined ? { domain: resolvedDomain } : {}),
468
+ kind: "attach-asset",
469
+ target: target.label,
470
+ ...(target.domain !== undefined ? { domain: target.domain } : {}),
471
+ ...(target.prd !== undefined ? { prd: target.prd } : {}),
472
+ path: target.path,
412
473
  };
413
474
  }
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. */
419
- function readManifestFile(profilePath) {
420
- const raw = readFileSync(profilePath, "utf8");
421
- const parsed = JSON.parse(raw);
422
- if (typeof parsed !== "object" ||
423
- parsed === null ||
424
- typeof parsed.name !== "string" ||
425
- typeof parsed.userSpecPath !== "string" ||
426
- typeof parsed.createdAt !== "string" ||
427
- typeof parsed.domains !== "object" ||
428
- parsed.domains === null ||
429
- Array.isArray(parsed.domains)) {
430
- throw new Error("profile.json is missing required manifest fields");
431
- }
432
- return parsed;
433
- }
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;
475
+ /** Re-serialize a method/PRD with a bumped `updated_at`; user_spec carries no
476
+ * timestamp. Atomic. */
477
+ function writeArtefactBody(target, fields, body, kind) {
478
+ const nextFields = { ...fields };
479
+ if (target.label !== "user_spec")
480
+ nextFields["updated_at"] = new Date().toISOString();
439
481
  try {
440
- return readManifestFile(profilePath);
482
+ atomicWrite(target.path, serializeArtefact(nextFields, body));
441
483
  }
442
- catch {
443
- return null;
484
+ catch (err) {
485
+ return persistenceFailed(target.path, err);
444
486
  }
487
+ return {
488
+ ok: true,
489
+ kind,
490
+ target: target.label,
491
+ ...(target.domain !== undefined ? { domain: target.domain } : {}),
492
+ ...(target.prd !== undefined ? { prd: target.prd } : {}),
493
+ path: target.path,
494
+ };
445
495
  }
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));
496
+ /** Parse a markdown bullet line (`- text` / `- [hard] text`), or null. */
497
+ function parseBullet(line) {
498
+ const m = /^(\s*)-\s+(\[hard\]\s+)?(.*)$/.exec(line);
499
+ if (!m)
500
+ return null;
501
+ return { indent: m[1], hard: m[2] !== undefined, text: m[3] };
452
502
  }
453
- /** Compare two ISO 8601 createdAt strings, oldest first. */
454
- function createdAtAsc(a, b) {
455
- const ta = Date.parse(a);
456
- const tb = Date.parse(b);
457
- if (Number.isNaN(ta) || Number.isNaN(tb)) {
458
- return a < b ? -1 : a > b ? 1 : 0;
459
- }
460
- return ta - tb;
503
+ /** All `## <section>` heading texts present in a body (for a fail-closed message). */
504
+ function listSections(body) {
505
+ return body
506
+ .split("\n")
507
+ .map((l) => /^##\s+(.*)$/.exec(l))
508
+ .filter((m) => m !== null)
509
+ .map((m) => m[1].trim());
461
510
  }
462
- /**
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`.
472
- *
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.
479
- */
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();
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);
511
+ /** The [start,end) line range of a `## <section>` body (heading exclusive, up to the
512
+ * next `## ` heading or EOF). `start === -1` when the heading is absent. */
513
+ function sectionLineRange(lines, section) {
514
+ const target = section.trim();
515
+ let start = -1;
516
+ for (let i = 0; i < lines.length; i++) {
517
+ const m = /^##\s+(.*)$/.exec(lines[i]);
518
+ if (m && m[1].trim() === target) {
519
+ start = i + 1;
520
+ break;
498
521
  }
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
- };
522
+ }
523
+ if (start === -1)
524
+ return { start: 0, end: 0 };
525
+ let end = lines.length;
526
+ for (let i = start; i < lines.length; i++) {
527
+ if (/^##\s+/.test(lines[i])) {
528
+ end = i;
529
+ break;
508
530
  }
509
- let userSpec;
510
- try {
511
- userSpec = readFileSync(manifest.userSpecPath, "utf8");
531
+ }
532
+ return { start, end };
533
+ }
534
+ /** Insert `bullet` at the end of `## <section>` (before the next heading, after the
535
+ * section's last non-blank line), or null when the heading is absent. */
536
+ function insertUnderSection(body, section, bullet) {
537
+ if (!listSections(body).includes(section.trim()))
538
+ return null;
539
+ const lines = body.split("\n");
540
+ const range = sectionLineRange(lines, section);
541
+ let at = range.end;
542
+ while (at > range.start && lines[at - 1].trim() === "")
543
+ at--;
544
+ lines.splice(at, 0, bullet);
545
+ return lines.join("\n");
546
+ }
547
+ export function searchProfileFrontmatter(query = {}) {
548
+ const domainsRoot = join(getShopperArtefactDir(), DOMAINS_SUBDIR);
549
+ const domains = [];
550
+ const prds = [];
551
+ const unreadable = [];
552
+ let slugs = [];
553
+ if (existsSync(domainsRoot)) {
554
+ slugs = readdirSync(domainsRoot, { withFileTypes: true })
555
+ .filter((d) => d.isDirectory())
556
+ .map((d) => d.name)
557
+ .sort();
558
+ }
559
+ for (const slug of slugs) {
560
+ const methodPath = join(domainsRoot, slug, METHOD_FILE);
561
+ if (!existsSync(methodPath))
562
+ continue; // a dir with no method is not a domain yet
563
+ const method = readArtefactFile(methodPath);
564
+ if (method === null) {
565
+ unreadable.push({ id: slug, error: "method.md has malformed or absent frontmatter" });
566
+ continue;
512
567
  }
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
- };
568
+ domains.push({ slug, name: method.fields["name"] ?? slug });
569
+ const prdsDir = join(domainsRoot, slug, PRDS_SUBDIR);
570
+ if (!existsSync(prdsDir))
571
+ continue;
572
+ const prdFiles = readdirSync(prdsDir)
573
+ .filter((f) => f.endsWith(".md"))
574
+ .sort();
575
+ for (const file of prdFiles) {
576
+ const prdPath = join(prdsDir, file);
577
+ const prd = readArtefactFile(prdPath);
578
+ if (prd === null) {
579
+ unreadable.push({
580
+ id: slug + "/" + PRDS_SUBDIR + "/" + file,
581
+ error: "prd has malformed frontmatter",
582
+ });
583
+ continue;
584
+ }
585
+ prds.push({
586
+ domain: slug,
587
+ key: prd.fields["key"] ?? file.replace(/\.md$/, ""),
588
+ product: prd.fields["product"] ?? "",
589
+ intent: prd.fields["intent"] ?? "",
590
+ title: prd.fields["title"] ?? "",
591
+ path: prdPath,
592
+ updated_at: prd.fields["updated_at"] ?? "",
593
+ });
523
594
  }
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 ---
535
- if (!existsSync(profilePath)) {
536
- return notFoundRead();
537
- }
538
- let manifest;
539
- try {
540
- manifest = readManifestFile(profilePath);
541
- }
542
- catch {
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
- }
560
- let domainSpec;
561
- let intentSpec;
562
- let playbook;
563
- try {
564
- domainSpec = readFileSync(entry.domainSpecPath, "utf8");
565
- intentSpec = readFileSync(entry.intentSpecPath, "utf8");
566
- playbook = readFileSync(entry.playbookPath, "utf8");
567
595
  }
568
- catch {
569
- return notFoundRead();
570
- }
571
- return {
572
- ok: true,
573
- name: manifest.name,
574
- userSpec,
575
- domains: toDomainSummaries(manifest),
576
- unreadable: [],
577
- profilePath,
578
- createdAt: entry.createdAt,
579
- slug: entry.slug,
580
- domainSpec,
581
- intentSpec,
582
- playbook,
583
- updatedAt: entry.updatedAt,
584
- };
596
+ const q = nonBlank(query.query) ? query.query.toLowerCase() : undefined;
597
+ const filteredDomains = domains.filter((d) => (!nonBlank(query.domain) || d.slug === query.domain)
598
+ && (q === undefined || (d.slug + " " + d.name).toLowerCase().includes(q)));
599
+ const filteredPrds = prds.filter((p) => (!nonBlank(query.domain) || p.domain === query.domain)
600
+ && (!nonBlank(query.product) || p.product === query.product)
601
+ && (!nonBlank(query.intent) || p.intent === query.intent)
602
+ && (q === undefined
603
+ || (p.key + " " + p.product + " " + p.intent + " " + p.title).toLowerCase().includes(q)));
604
+ return { ok: true, domains: filteredDomains, prds: filteredPrds, unreadable };
585
605
  }
586
- function notFoundRead() {
587
- return {
588
- ok: false,
589
- kind: "not_found",
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).",
592
- };
606
+ export function readArtefactBody(domainSlug, prd) {
607
+ const badSlug = rejectBadSegment(domainSlug, "domainSlug");
608
+ if (badSlug)
609
+ return badSlug;
610
+ if (nonBlank(prd)) {
611
+ const badPrd = rejectBadSegment(prd, "prd");
612
+ if (badPrd)
613
+ return badPrd;
614
+ const path = join(getDomainArtefactDir(domainSlug), PRDS_SUBDIR, prd + ".md");
615
+ // Split absent from corrupt: an absent file is not_found, a present-but-unparseable
616
+ // one is unreadable (never conflated — the agent must not re-mint over a corrupt PRD).
617
+ if (!existsSync(path))
618
+ return notFound('No PRD "' + prd + '" in domain "' + domainSlug + '".');
619
+ const parsed = readArtefactFile(path);
620
+ if (parsed === null)
621
+ return unreadable(path);
622
+ return { ok: true, target: "prd", domain: domainSlug, prd, fields: parsed.fields, body: parsed.body, path };
623
+ }
624
+ const path = join(getDomainArtefactDir(domainSlug), METHOD_FILE);
625
+ if (!existsSync(path)) {
626
+ return notFound('No method for domain "' + domainSlug + '" — mint it with sil_learn create.');
627
+ }
628
+ const parsed = readArtefactFile(path);
629
+ if (parsed === null)
630
+ return unreadable(path);
631
+ return { ok: true, target: "method", domain: domainSlug, fields: parsed.fields, body: parsed.body, path };
593
632
  }
594
- /**
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`).
598
- *
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.
608
- *
609
- * A genuine delete/rewrite failure → `persistence_failed` with `<dir>: <cause>`.
610
- * Never throws across the boundary.
611
- */
612
- export function removeAgentArtefacts(domainSlug) {
633
+ export function removeArtefact(domainSlug, prd) {
613
634
  const badSlug = rejectBadSegment(domainSlug, "domainSlug");
614
635
  if (badSlug)
615
636
  return badSlug;
616
637
  const shopperDir = getShopperArtefactDir();
617
638
  const domainsRoot = join(shopperDir, DOMAINS_SUBDIR);
618
- const leaf = getDomainArtefactDir(domainSlug);
639
+ const domainLeaf = getDomainArtefactDir(domainSlug);
619
640
  // 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)) {
630
- return {
631
- ok: false,
632
- kind: "not_found",
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.",
636
- };
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.
640
- try {
641
- rmSync(leaf, { recursive: true, force: true });
642
- }
643
- catch (err) {
644
- return persistenceFailedRemove(leaf, err);
641
+ // domains root — never the root itself (deleting it wipes every sibling).
642
+ if (dirname(domainLeaf) !== domainsRoot || domainLeaf === domainsRoot) {
643
+ return invalid("domainSlug", "domainSlug resolves outside the domains subtree — refusing to delete: " + JSON.stringify(domainSlug));
644
+ }
645
+ if (nonBlank(prd)) {
646
+ const badPrd = rejectBadSegment(prd, "prd");
647
+ if (badPrd)
648
+ return badPrd;
649
+ const prdPath = join(domainLeaf, PRDS_SUBDIR, prd + ".md");
650
+ if (!existsSync(prdPath)) {
651
+ return notFound('No PRD "' + prd + '" in domain "' + domainSlug + '" to remove (already gone).');
652
+ }
653
+ try {
654
+ rmSync(prdPath, { force: true });
655
+ }
656
+ catch (err) {
657
+ return persistenceFailed(prdPath, err);
658
+ }
659
+ return { ok: true, domainSlug, prd };
645
660
  }
646
- const nextDomains = {};
647
- for (const [slug, entry] of Object.entries(manifest.domains)) {
648
- if (slug !== domainSlug)
649
- nextDomains[slug] = entry;
661
+ if (!existsSync(domainLeaf)) {
662
+ return notFound('No domain "' + domainSlug + '" on the shopper to remove (already gone). A re-run is safe.');
650
663
  }
651
- const updated = { ...manifest, domains: nextDomains };
652
664
  try {
653
- atomicWrite(profilePath, JSON.stringify(updated, null, 2) + "\n");
665
+ rmSync(domainLeaf, { recursive: true, force: true });
654
666
  }
655
667
  catch (err) {
656
- return persistenceFailedRemove(profilePath, err);
668
+ return persistenceFailed(domainLeaf, err);
657
669
  }
658
670
  return { ok: true, domainSlug };
659
671
  }
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
- };
670
- }
671
- /** Extract a human-readable cause from an unknown thrown value (never PII). */
672
- function errCause(err) {
673
- return err instanceof Error ? err.message : String(err);
674
- }