sil-openclaw 0.4.6 → 0.5.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +33 -45
  3. package/dist/gateway/search-results.js +11 -7
  4. package/dist/index.js +24 -24
  5. package/dist/lib/allowlist-script.js +13 -0
  6. package/dist/lib/artifacts.js +30 -0
  7. package/dist/lib/credentials.js +2 -3
  8. package/dist/lib/host-wiring.js +44 -15
  9. package/dist/lib/pkce.js +3 -3
  10. package/dist/lib/search-results-log.js +23 -0
  11. package/dist/lib/search-results-store.js +4 -4
  12. package/dist/lib/shopping-call.js +143 -0
  13. package/dist/lib/sil-client.js +185 -1046
  14. package/dist/lib/tool-result.js +10 -3
  15. package/dist/tools/catalog.js +311 -1197
  16. package/dist/tools/doctor.js +25 -63
  17. package/dist/tools/identity.js +110 -245
  18. package/openclaw.plugin.json +14 -11
  19. package/package.json +7 -6
  20. package/schema/PROVENANCE.md +15 -0
  21. package/schema/shopping-brief-create-request.schema.json +98 -0
  22. package/schema/shopping-brief-create-response.schema.json +24 -0
  23. package/schema/shopping-brief-edit-request.schema.json +125 -0
  24. package/schema/shopping-brief-edit-response.schema.json +24 -0
  25. package/schema/shopping-brief-read-request.schema.json +15 -0
  26. package/schema/shopping-brief-read-response.schema.json +235 -0
  27. package/schema/shopping-domain-create-request.schema.json +160 -0
  28. package/schema/shopping-domain-create-response.schema.json +60 -0
  29. package/schema/shopping-domain-get-request.schema.json +18 -0
  30. package/schema/shopping-domain-get-response.schema.json +307 -0
  31. package/schema/shopping-domain-search-request.schema.json +18 -0
  32. package/schema/shopping-domain-search-response.schema.json +92 -0
  33. package/schema/shopping-offers-request.schema.json +31 -0
  34. package/schema/shopping-offers-response.schema.json +172 -0
  35. package/schema/shopping-product-get-request.schema.json +24 -0
  36. package/schema/shopping-product-get-response.schema.json +121 -0
  37. package/schema/shopping-profile-edit-request.schema.json +97 -0
  38. package/schema/shopping-profile-edit-response.schema.json +17 -0
  39. package/schema/shopping-search-request.schema.json +106 -0
  40. package/schema/shopping-search-response.schema.json +182 -0
  41. package/schema/shopping-seller-get-request.schema.json +24 -0
  42. package/schema/shopping-seller-get-response.schema.json +342 -0
  43. package/scripts/allowlist-openclaw.mjs +4 -5
  44. package/sil-shopping/SKILL.md +196 -97
  45. package/sil-shopping/references/mint.md +190 -0
  46. package/dist/lib/bind-channel.js +0 -10
  47. package/dist/lib/creation-entrypoint.js +0 -111
  48. package/dist/lib/derive-agent-id.js +0 -36
  49. package/dist/lib/profile-store.js +0 -568
  50. package/dist/tools/profile.js +0 -300
  51. package/scripts/create-shopper.mjs +0 -677
  52. package/sil-shopping/examples/multi_domain_shopper_walkthrough.md +0 -65
  53. package/sil-shopping/references/agent_creation_engine.md +0 -223
  54. package/sil-shopping/references/fill_and_feedback.md +0 -102
  55. package/sil-shopping/references/method_and_prds.md +0 -143
  56. package/sil-shopping/references/setup_onboarding.md +0 -64
  57. package/sil-shopping/references/shop_loop.md +0 -118
@@ -1,568 +0,0 @@
1
- /**
2
- * sil shopper behaviour-artefact store — frontmatter-as-truth, no manifest.
3
- *
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):
7
- *
8
- * $SIL_DATA_DIR/shopper/
9
- * ├─ user_spec.md the person — FRONTMATTER carries the shopper `name`;
10
- * │ its presence IS "a shopper exists". Written by setup.
11
- * └─ domains/<slug>/
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
18
- *
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.
27
- */
28
- import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from "node:fs";
29
- import { dirname, join } from "node:path";
30
- import { createHash, randomBytes } from "node:crypto";
31
- import { DIR_MODE, ensureDataDir, getDataDir } from "./credentials.js";
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. */
35
- const FILE_MODE = 0o600;
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. */
39
- const SHOPPER_SUBDIR = "shopper";
40
- const DOMAINS_SUBDIR = "domains";
41
- const PRDS_SUBDIR = "prds";
42
- const ASSETS_SUBDIR = "assets";
43
- const USER_SPEC_FILE = "user_spec.md";
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
- /** attach-asset limits: ~8 MB decoded, image MIME allowlist → file extension. */
49
- const MAX_ASSET_BYTES = 8 * 1024 * 1024;
50
- const MIME_EXT = {
51
- "image/jpeg": "jpg",
52
- "image/png": "png",
53
- "image/webp": "webp",
54
- "image/gif": "gif",
55
- };
56
- function invalid(field, message) {
57
- return { ok: false, kind: "invalid_request", field, message };
58
- }
59
- function notFound(message) {
60
- return { ok: false, kind: "not_found", message };
61
- }
62
- function unreadable(path) {
63
- return {
64
- ok: false,
65
- kind: "unreadable",
66
- message: path + ": the artefact is present but corrupt (malformed or absent frontmatter)"
67
- + " — inspect / repair, do NOT overwrite (it may still be recoverable).",
68
- };
69
- }
70
- function persistenceFailed(path, err) {
71
- return {
72
- ok: false,
73
- kind: "persistence_failed",
74
- error: path + ": " + errCause(err),
75
- message: "The shopper behaviour artefacts could NOT be written to the sil data directory,"
76
- + " so the change did not stick. Fix the data directory (it must be writable —"
77
- + " check permissions / free space / that $SIL_DATA_DIR is a directory), then"
78
- + " try again.",
79
- recovery: "fix_data_dir",
80
- };
81
- }
82
- function nonBlank(s) {
83
- return typeof s === "string" && s.trim().length > 0;
84
- }
85
- function errCause(err) {
86
- return err instanceof Error ? err.message : String(err);
87
- }
88
- /** Validate a caller-supplied path segment the SAME way at every call site: present +
89
- * non-blank, never `main`, lower-kebab — applied BEFORE any join/read/delete so a
90
- * traversal, an absolute path, a bare dot, or `main` never becomes a path segment. */
91
- function rejectBadSegment(value, field) {
92
- if (!nonBlank(value)) {
93
- return invalid(field, field + " is required and must be non-empty.");
94
- }
95
- if (value === "main") {
96
- return invalid(field, '"main" is host-reserved and cannot be a ' + field + ".");
97
- }
98
- if (!SEGMENT_RE.test(value)) {
99
- return invalid(field, field + " must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(value));
100
- }
101
- return null;
102
- }
103
- // ===========================================================================
104
- // Path resolvers — the shopper segment is a constant; only slug/prd are input.
105
- // ===========================================================================
106
- /** The SINGLETON shopper artefact directory under the plugin's data dir. Never
107
- * hardcoded — `getDataDir()` honors `$SIL_DATA_DIR`/`$XDG_DATA_HOME`. The shopper
108
- * segment is the constant `SHOPPER_SUBDIR`, so there is no traversal vector here. */
109
- export function getShopperArtefactDir() {
110
- return join(getDataDir(), SHOPPER_SUBDIR);
111
- }
112
- /** A per-domain directory under the singleton shopper dir. SAFETY: `slug` is a
113
- * caller-supplied path segment — every caller MUST `rejectBadSegment` it BEFORE this
114
- * join. */
115
- export function getDomainArtefactDir(slug) {
116
- return join(getShopperArtefactDir(), DOMAINS_SUBDIR, slug);
117
- }
118
- /** One-line scalar for a coordinate value: newlines folded to spaces, trimmed. */
119
- function scalar(value) {
120
- return String(value).replace(/\r?\n/g, " ").trim();
121
- }
122
- function serializeArtefact(fields, body) {
123
- const fm = Object.entries(fields)
124
- .map(([k, v]) => k + ": " + scalar(v))
125
- .join("\n");
126
- // The store owns frontmatter — strip any block a model prepended to the body so the
127
- // artefact never stacks two (self-heals a previously double-wrapped file on re-write).
128
- const clean = stripLeadingFrontmatter(body);
129
- const b = clean.endsWith("\n") ? clean : clean + "\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
- /** Strip a leading `--- … ---` frontmatter block a model may have prepended to a body,
154
- * reusing `parseArtefact` so ONLY a fence whose content is real frontmatter (≥1
155
- * `key: value`) is removed — a body opening with a bare `---` thematic break parses to
156
- * null and is returned untouched. The store owns frontmatter (frontmatter-as-truth), so a
157
- * model-authored block must never survive into the serialized body and stack a second. */
158
- function stripLeadingFrontmatter(body) {
159
- const parsed = parseArtefact(body);
160
- return parsed === null ? body : parsed.body;
161
- }
162
- /** Read + parse one artefact file, or null if absent/unreadable/malformed. */
163
- function readArtefactFile(path) {
164
- if (!existsSync(path))
165
- return null;
166
- let raw;
167
- try {
168
- raw = readFileSync(path, "utf8");
169
- }
170
- catch {
171
- return null;
172
- }
173
- return parseArtefact(raw);
174
- }
175
- /** Atomic single-file write: tmp sibling → write → rename over target → chmod. A
176
- * reader sees the old file or the new one, never a half-written one (mirrors
177
- * `credentials.ts`). Ensures the containing dir (0700) first. */
178
- function atomicWrite(path, contents) {
179
- mkdirSync(dirname(path), { recursive: true, mode: DIR_MODE });
180
- const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
181
- writeFileSync(tmp, contents, { mode: FILE_MODE });
182
- renameSync(tmp, path);
183
- chmodSync(path, FILE_MODE);
184
- }
185
- /** Write binary bytes atomically, owner-only. */
186
- function atomicWriteBytes(path, bytes) {
187
- mkdirSync(dirname(path), { recursive: true, mode: DIR_MODE });
188
- const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
189
- writeFileSync(tmp, bytes, { mode: FILE_MODE });
190
- renameSync(tmp, path);
191
- chmodSync(path, FILE_MODE);
192
- }
193
- /**
194
- * Materialize the ONE shopper — write `user_spec.md` whose FRONTMATTER carries the
195
- * shopper `name` and whose body is the shared user spec. SETUP-ONLY: it mints no
196
- * method/PRD (that is `sil_learn create`) and writes no manifest. Validate-first: a
197
- * blank `name`/`userSpec` returns `invalid_request` and writes nothing.
198
- */
199
- export function materializeProfile(spec) {
200
- if (!nonBlank(spec.name))
201
- return invalid("name", "name is required and must be non-empty.");
202
- if (!nonBlank(spec.userSpec)) {
203
- return invalid("userSpec", "userSpec is required and must be non-empty.");
204
- }
205
- const dir = getShopperArtefactDir();
206
- const userSpecPath = join(dir, USER_SPEC_FILE);
207
- try {
208
- ensureDataDir();
209
- mkdirSync(dir, { recursive: true, mode: DIR_MODE });
210
- atomicWrite(userSpecPath, serializeArtefact({ name: spec.name }, spec.userSpec));
211
- }
212
- catch (err) {
213
- return persistenceFailed(dir, err);
214
- }
215
- return { ok: true, dir, userSpecPath };
216
- }
217
- export function readShopperIdentity() {
218
- const userSpecPath = join(getShopperArtefactDir(), USER_SPEC_FILE);
219
- if (!existsSync(userSpecPath))
220
- return { ok: true, unreadable: [] };
221
- const parsed = readArtefactFile(userSpecPath);
222
- if (parsed === null) {
223
- return {
224
- ok: true,
225
- unreadable: [{ id: USER_SPEC_FILE, error: "user_spec.md has malformed or absent frontmatter" }],
226
- };
227
- }
228
- const name = parsed.fields["name"];
229
- if (!nonBlank(name)) {
230
- return {
231
- ok: true,
232
- unreadable: [{ id: USER_SPEC_FILE, error: "user_spec.md frontmatter carries no name" }],
233
- };
234
- }
235
- return { ok: true, name, unreadable: [] };
236
- }
237
- /** Resolve the target artefact file, guarding the selectors first. Returns an
238
- * `InvalidRequest` when a required selector is missing/bad. */
239
- function resolveTarget(spec) {
240
- if (spec.target === "user_spec") {
241
- return { path: join(getShopperArtefactDir(), USER_SPEC_FILE), label: "user_spec" };
242
- }
243
- const badDomain = rejectBadSegment(spec.domain, "domain");
244
- if (badDomain)
245
- return badDomain;
246
- const slug = spec.domain;
247
- if (spec.target === "method") {
248
- return { path: join(getDomainArtefactDir(slug), METHOD_FILE), label: "method", domain: slug };
249
- }
250
- // prd
251
- const badPrd = rejectBadSegment(spec.prd, "prd");
252
- if (badPrd)
253
- return badPrd;
254
- const prd = spec.prd;
255
- return {
256
- path: join(getDomainArtefactDir(slug), PRDS_SUBDIR, prd + ".md"),
257
- label: "prd",
258
- domain: slug,
259
- prd,
260
- };
261
- }
262
- export function learnArtefact(spec) {
263
- switch (spec.kind) {
264
- case "create":
265
- return learnCreate(spec);
266
- case "write":
267
- return learnWrite(spec);
268
- case "attach-asset":
269
- return learnAttachAsset(spec);
270
- default:
271
- return invalid("kind", "kind must be one of create|write|attach-asset.");
272
- }
273
- }
274
- /** `create` mints a NEW method or PRD body atomically — the file IS the registration
275
- * (no manifest). Refuses if one already exists at these coordinates (→ use `write` to
276
- * replace it), so a mint never silently clobbers. NOT valid for user_spec (that is
277
- * materialize; refine it with `write`). */
278
- function learnCreate(spec) {
279
- if (spec.target === "user_spec") {
280
- return invalid("target", "create is not valid for user_spec — the shopper's shared spec is written by"
281
- + " sil_profile_materialize (setup), then refined with kind:write.");
282
- }
283
- if (!nonBlank(spec.body))
284
- return invalid("body", "body is required and must be non-empty.");
285
- const badDomain = rejectBadSegment(spec.domain, "domain");
286
- if (badDomain)
287
- return badDomain;
288
- const slug = spec.domain;
289
- const now = new Date().toISOString();
290
- if (spec.target === "method") {
291
- if (!nonBlank(spec.name))
292
- return invalid("name", "name is required for a method.");
293
- const path = join(getDomainArtefactDir(slug), METHOD_FILE);
294
- if (existsSync(path)) {
295
- return invalid("kind", 'a method already exists for domain "' + slug + '" — use kind:write to replace its'
296
- + " body (create only mints a new one, it never overwrites).");
297
- }
298
- const fields = { domain: slug, name: spec.name, updated_at: now };
299
- try {
300
- atomicWrite(path, serializeArtefact(fields, spec.body));
301
- }
302
- catch (err) {
303
- return persistenceFailed(path, err);
304
- }
305
- return { ok: true, kind: "create", target: "method", domain: slug, path };
306
- }
307
- // prd
308
- const badPrd = rejectBadSegment(spec.prd, "prd");
309
- if (badPrd)
310
- return badPrd;
311
- const prd = spec.prd;
312
- for (const f of ["product", "intent", "title"]) {
313
- if (!nonBlank(spec[f]))
314
- return invalid(f, f + " is required for a prd.");
315
- }
316
- const path = join(getDomainArtefactDir(slug), PRDS_SUBDIR, prd + ".md");
317
- if (existsSync(path)) {
318
- return invalid("kind", 'a PRD "' + prd + '" already exists in domain "' + slug + '" — use kind:write to'
319
- + " replace its body (create only mints a new one, it never overwrites).");
320
- }
321
- const fields = {
322
- key: prd,
323
- product: spec.product,
324
- intent: spec.intent,
325
- title: spec.title,
326
- domain: slug,
327
- created_at: now,
328
- updated_at: now,
329
- };
330
- try {
331
- atomicWrite(path, serializeArtefact(fields, spec.body));
332
- }
333
- catch (err) {
334
- return persistenceFailed(path, err);
335
- }
336
- return { ok: true, kind: "create", target: "prd", domain: slug, prd, path };
337
- }
338
- /** `write` replaces the WHOLE body of an EXISTING method / PRD / user_spec with a
339
- * reconciled version — the model reads current (`sil_profile_get`), reconciles in
340
- * context, and writes the whole doc back. Frontmatter coordinates + `created_at` are
341
- * preserved and `updated_at` bumps (user_spec carries no timestamp). Fail-closed on a
342
- * missing doc (`not_found` — write never mints, that is create) and on a present-but-
343
- * corrupt one (`unreadable` — inspect / repair, never clobber a recoverable artefact). */
344
- function learnWrite(spec) {
345
- if (!nonBlank(spec.body))
346
- return invalid("body", "body is required and must be non-empty.");
347
- const target = resolveTarget(spec);
348
- if ("ok" in target)
349
- return target;
350
- const existing = readArtefactFile(target.path);
351
- if (existing === null) {
352
- if (existsSync(target.path))
353
- return unreadable(target.path);
354
- return notFound("The target " + target.label + " does not exist — mint it with kind:create first"
355
- + " (write replaces an existing doc, it never mints).");
356
- }
357
- return writeArtefactBody(target, existing.fields, spec.body, "write");
358
- }
359
- /** attach-asset — persist image bytes into `domains/<slug>/assets/<hash>.<ext>`
360
- * (owner-only, content-hash = free dedup), then link them into the target by a
361
- * RELATIVE markdown path. Per-domain only (user_spec is rejected). */
362
- function learnAttachAsset(spec) {
363
- if (spec.target === "user_spec") {
364
- return invalid("target", "assets are per-domain — attach to a method or prd, not user_spec.");
365
- }
366
- if (!nonBlank(spec.bytes))
367
- return invalid("bytes", "bytes (base64) is required.");
368
- const ext = MIME_EXT[spec.mime ?? ""];
369
- if (ext === undefined) {
370
- return invalid("mime", "mime must be one of image/jpeg, image/png, image/webp, image/gif.");
371
- }
372
- const buf = Buffer.from(spec.bytes, "base64");
373
- if (buf.length === 0)
374
- return invalid("bytes", "bytes did not decode to a non-empty image.");
375
- if (buf.length > MAX_ASSET_BYTES) {
376
- return invalid("bytes", "image exceeds the " + MAX_ASSET_BYTES + "-byte cap.");
377
- }
378
- const target = resolveTarget(spec);
379
- if ("ok" in target)
380
- return target;
381
- const existing = readArtefactFile(target.path);
382
- if (existing === null) {
383
- return notFound("The target " + target.label + " does not exist — create it before attaching an asset.");
384
- }
385
- const slug = target.domain;
386
- const hash = createHash("sha256").update(buf).digest("hex").slice(0, 16);
387
- const filename = hash + "." + ext;
388
- const assetRel = ASSETS_SUBDIR + "/" + filename;
389
- const assetAbs = join(getDomainArtefactDir(slug), ASSETS_SUBDIR, filename);
390
- // Bytes FIRST (content-hashed → a mid-failure leaves only a benign, dedup-safe
391
- // orphan), then the path-link into the target.
392
- try {
393
- atomicWriteBytes(assetAbs, buf);
394
- }
395
- catch (err) {
396
- return persistenceFailed(assetAbs, err);
397
- }
398
- // Idempotent link on the asset PATH (not the caption): if `assets/<hash>.<ext>` is
399
- // already referenced in the target, skip the body write — no second link line, no
400
- // updated_at churn. The bytes were re-written above (identical-hash overwrite, a
401
- // benign no-op), so a re-attach under any caption is a body no-op that still
402
- // reports ok + assetPath.
403
- const res = existing.body.includes("](" + assetRel + ")")
404
- ? okAttach(target)
405
- : writeArtefactBody(target, existing.fields, existing.body.replace(/\n*$/, "\n")
406
- + "![" + (nonBlank(spec.caption) ? spec.caption.trim() : "") + "](" + assetRel + ")\n", "attach-asset");
407
- if (!res.ok)
408
- return res;
409
- return { ...res, assetPath: assetRel };
410
- }
411
- /** The success envelope for an attach-asset that wrote no body (idempotent re-link)
412
- * — mirrors `writeArtefactBody`'s ok shape without the re-serialize / timestamp bump. */
413
- function okAttach(target) {
414
- return {
415
- ok: true,
416
- kind: "attach-asset",
417
- target: target.label,
418
- ...(target.domain !== undefined ? { domain: target.domain } : {}),
419
- ...(target.prd !== undefined ? { prd: target.prd } : {}),
420
- path: target.path,
421
- };
422
- }
423
- /** Re-serialize a method/PRD with a bumped `updated_at`; user_spec carries no
424
- * timestamp. Atomic. */
425
- function writeArtefactBody(target, fields, body, kind) {
426
- const nextFields = { ...fields };
427
- if (target.label !== "user_spec")
428
- nextFields["updated_at"] = new Date().toISOString();
429
- try {
430
- atomicWrite(target.path, serializeArtefact(nextFields, body));
431
- }
432
- catch (err) {
433
- return persistenceFailed(target.path, err);
434
- }
435
- return {
436
- ok: true,
437
- kind,
438
- target: target.label,
439
- ...(target.domain !== undefined ? { domain: target.domain } : {}),
440
- ...(target.prd !== undefined ? { prd: target.prd } : {}),
441
- path: target.path,
442
- };
443
- }
444
- export function searchProfileFrontmatter(query = {}) {
445
- const domainsRoot = join(getShopperArtefactDir(), DOMAINS_SUBDIR);
446
- const domains = [];
447
- const prds = [];
448
- const unreadable = [];
449
- let slugs = [];
450
- if (existsSync(domainsRoot)) {
451
- slugs = readdirSync(domainsRoot, { withFileTypes: true })
452
- .filter((d) => d.isDirectory())
453
- .map((d) => d.name)
454
- .sort();
455
- }
456
- for (const slug of slugs) {
457
- const methodPath = join(domainsRoot, slug, METHOD_FILE);
458
- if (!existsSync(methodPath))
459
- continue; // a dir with no method is not a domain yet
460
- const method = readArtefactFile(methodPath);
461
- if (method === null) {
462
- unreadable.push({ id: slug, error: "method.md has malformed or absent frontmatter" });
463
- continue;
464
- }
465
- domains.push({ slug, name: method.fields["name"] ?? slug });
466
- const prdsDir = join(domainsRoot, slug, PRDS_SUBDIR);
467
- if (!existsSync(prdsDir))
468
- continue;
469
- const prdFiles = readdirSync(prdsDir)
470
- .filter((f) => f.endsWith(".md"))
471
- .sort();
472
- for (const file of prdFiles) {
473
- const prdPath = join(prdsDir, file);
474
- const prd = readArtefactFile(prdPath);
475
- if (prd === null) {
476
- unreadable.push({
477
- id: slug + "/" + PRDS_SUBDIR + "/" + file,
478
- error: "prd has malformed frontmatter",
479
- });
480
- continue;
481
- }
482
- prds.push({
483
- domain: slug,
484
- key: prd.fields["key"] ?? file.replace(/\.md$/, ""),
485
- product: prd.fields["product"] ?? "",
486
- intent: prd.fields["intent"] ?? "",
487
- title: prd.fields["title"] ?? "",
488
- path: prdPath,
489
- updated_at: prd.fields["updated_at"] ?? "",
490
- });
491
- }
492
- }
493
- const q = nonBlank(query.query) ? query.query.toLowerCase() : undefined;
494
- const filteredDomains = domains.filter((d) => (!nonBlank(query.domain) || d.slug === query.domain)
495
- && (q === undefined || (d.slug + " " + d.name).toLowerCase().includes(q)));
496
- const filteredPrds = prds.filter((p) => (!nonBlank(query.domain) || p.domain === query.domain)
497
- && (!nonBlank(query.product) || p.product === query.product)
498
- && (!nonBlank(query.intent) || p.intent === query.intent)
499
- && (q === undefined
500
- || (p.key + " " + p.product + " " + p.intent + " " + p.title).toLowerCase().includes(q)));
501
- return { ok: true, domains: filteredDomains, prds: filteredPrds, unreadable };
502
- }
503
- export function readArtefactBody(domainSlug, prd) {
504
- const badSlug = rejectBadSegment(domainSlug, "domainSlug");
505
- if (badSlug)
506
- return badSlug;
507
- if (nonBlank(prd)) {
508
- const badPrd = rejectBadSegment(prd, "prd");
509
- if (badPrd)
510
- return badPrd;
511
- const path = join(getDomainArtefactDir(domainSlug), PRDS_SUBDIR, prd + ".md");
512
- // Split absent from corrupt: an absent file is not_found, a present-but-unparseable
513
- // one is unreadable (never conflated — the agent must not re-mint over a corrupt PRD).
514
- if (!existsSync(path))
515
- return notFound('No PRD "' + prd + '" in domain "' + domainSlug + '".');
516
- const parsed = readArtefactFile(path);
517
- if (parsed === null)
518
- return unreadable(path);
519
- return { ok: true, target: "prd", domain: domainSlug, prd, fields: parsed.fields, body: parsed.body, path };
520
- }
521
- const path = join(getDomainArtefactDir(domainSlug), METHOD_FILE);
522
- if (!existsSync(path)) {
523
- return notFound('No method for domain "' + domainSlug + '" — mint it with sil_learn create.');
524
- }
525
- const parsed = readArtefactFile(path);
526
- if (parsed === null)
527
- return unreadable(path);
528
- return { ok: true, target: "method", domain: domainSlug, fields: parsed.fields, body: parsed.body, path };
529
- }
530
- export function removeArtefact(domainSlug, prd) {
531
- const badSlug = rejectBadSegment(domainSlug, "domainSlug");
532
- if (badSlug)
533
- return badSlug;
534
- const shopperDir = getShopperArtefactDir();
535
- const domainsRoot = join(shopperDir, DOMAINS_SUBDIR);
536
- const domainLeaf = getDomainArtefactDir(domainSlug);
537
- // Defence in depth beyond the slug gate: the leaf must be a STRICT child of the
538
- // domains root — never the root itself (deleting it wipes every sibling).
539
- if (dirname(domainLeaf) !== domainsRoot || domainLeaf === domainsRoot) {
540
- return invalid("domainSlug", "domainSlug resolves outside the domains subtree — refusing to delete: " + JSON.stringify(domainSlug));
541
- }
542
- if (nonBlank(prd)) {
543
- const badPrd = rejectBadSegment(prd, "prd");
544
- if (badPrd)
545
- return badPrd;
546
- const prdPath = join(domainLeaf, PRDS_SUBDIR, prd + ".md");
547
- if (!existsSync(prdPath)) {
548
- return notFound('No PRD "' + prd + '" in domain "' + domainSlug + '" to remove (already gone).');
549
- }
550
- try {
551
- rmSync(prdPath, { force: true });
552
- }
553
- catch (err) {
554
- return persistenceFailed(prdPath, err);
555
- }
556
- return { ok: true, domainSlug, prd };
557
- }
558
- if (!existsSync(domainLeaf)) {
559
- return notFound('No domain "' + domainSlug + '" on the shopper to remove (already gone). A re-run is safe.');
560
- }
561
- try {
562
- rmSync(domainLeaf, { recursive: true, force: true });
563
- }
564
- catch (err) {
565
- return persistenceFailed(domainLeaf, err);
566
- }
567
- return { ok: true, domainSlug };
568
- }