sil-openclaw 0.3.9 → 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,442 +1,306 @@
1
1
  /**
2
- * sil shopper profile tools — the single multi-domain shopper seam.
2
+ * sil shopper profile tools — the frontmatter-as-truth artefact seam.
3
3
  *
4
- * `sil_profile_materialize` is the plugin's half of the agent-creation engine and
5
- * the lazy domain-mint path: it writes the SHARED user spec and, when a `domain`
6
- * pack is supplied, that niche's SDS artefacts
7
- * (`domains/<slug>/{domain_spec,intent_spec,playbook}.md`) into the plugin's own
8
- * data directory (`$SIL_DATA_DIR`, the disclosed `filesystemScope`). It stays ONE
9
- * tool with an OPTIONAL `domain`: no `domain` ⇒ create the one shopper; with
10
- * `domain` ⇒ lazily mint/refresh a niche AND persist any cross-niche fact captured
11
- * into the shared user spec — one atomic call. The persona is NOT written here —
12
- * the shopper's identity/voice is the host workspace `SOUL.md`. The wiring half
13
- * (the host `agents.list[]` entry, the enabled `sil` plugin, the attached skill,
14
- * the `SOUL.md`) is the host agent driving its own `openclaw …` CLI; the plugin
15
- * never writes `~/.openclaw` (`security.noChildProcess: true`).
4
+ * FIVE local verbs over the singleton shopper store ($SIL_DATA_DIR/shopper), each
5
+ * making NO network call and reading no token:
16
6
  *
17
- * The product is a SINGLETON shopper, so the store is scoped to a fixed,
18
- * compile-time-constant path — there is no caller-supplied `agentId` on ANY of the
19
- * four profile tools. Domain classification / routing at shop time stays
20
- * SKILL-REASONING — there is no routing tool. The surface is exactly four profile
21
- * tools; the skill reads `profile.json.domains` (via `sil_profile_get`) to pick or
22
- * lazily mint a niche.
7
+ * - `sil_profile_materialize { name, userSpec }` — SETUP-ONLY: write user_spec.md
8
+ * (its frontmatter carries the shopper name). Does NOT mint methods/PRDs.
9
+ * - `sil_learn { target, domain?, prd?, kind, … }` — the single target+change verb
10
+ * for the whole method/PRD lifecycle: create mints a whole doc; append/amend/
11
+ * retract refine in place; attach-asset persists image bytes by path.
12
+ * - `sil_profile_search { domain?, product?, intent?, query? }` — query artefact
13
+ * FRONTMATTER (coordinates only, no bodies); the discovery / reuse-before-mint
14
+ * primitive. Malformed frontmatter surfaces in `unreadable`, never dropped.
15
+ * - `sil_profile_get { domainSlug, prd? }` — the rich read (one whole body).
16
+ * - `sil_profile_remove { domainSlug, prd? }` — remove a whole domain, or one PRD.
23
17
  *
24
- * This follows `identity.ts` (the reference group): a `registerXTools(api)`
25
- * function, a `Type.Object` schema the host validates inputs against, the
26
- * `jsonResult` success/structured-error envelope, and ALL I/O inside `execute()`
27
- * (register() opens nothing).
18
+ * This follows `identity.ts` (the reference group): a `registerXTools(api)` function,
19
+ * a `Type.Object` schema the host validates inputs against, the `jsonResult`
20
+ * success/structured-error envelope, and ALL I/O inside `execute()` (register() opens
21
+ * nothing). The persona is NOT written here — it is the host workspace SOUL.md.
28
22
  */
29
23
  import { Type } from "typebox";
30
- import { appendProfileEntry, materializeProfile, readAgentProfile, removeAgentArtefacts, } from "../lib/profile-store.js";
24
+ import { learnArtefact, materializeProfile, readArtefactBody, removeArtefact, searchProfileFrontmatter, } from "../lib/profile-store.js";
31
25
  import { jsonResult } from "../lib/tool-result.js";
32
- /** Narrow a host-validated param to a string, defaulting to "" so the store does
33
- * the real, structured-error validation (validate-first / write-nothing). */
26
+ /** Narrow a host-validated param to a string, defaulting to "" so the store does the
27
+ * real, structured-error validation (validate-first / write-nothing). */
34
28
  function asString(value) {
35
29
  return typeof value === "string" ? value : "";
36
30
  }
31
+ /** Narrow an optional string param — `undefined` unless a non-empty string is given,
32
+ * so a selector is never carried as a spurious empty value. */
33
+ function optString(value) {
34
+ return typeof value === "string" && value.length > 0 ? value : undefined;
35
+ }
37
36
  export function registerProfileTools(api) {
38
37
  registerMaterialize(api);
38
+ registerLearn(api);
39
+ registerSearch(api);
39
40
  registerGet(api);
40
41
  registerRemove(api);
41
- registerRemember(api);
42
42
  }
43
43
  function registerMaterialize(api) {
44
44
  api.registerTool({
45
45
  name: "sil_profile_materialize",
46
- label: "Materialize the sil shopper / mint a domain pack",
47
- description: "Write the one sil shopper's behaviour artefacts into the sil data directory."
48
- + " ONE tool, two modes. WITHOUT a `domain`: create the shopper — write the"
49
- + " SHARED user spec (the one person's standing facts + hard constraints that"
50
- + " carry across every niche) and a manifest with an empty domains map. WITH a"
51
- + " `domain`: lazily mint or refresh that niche on first shop — write its domain"
52
- + " spec (deep researched niche expertise), intent spec (the decomposition"
53
- + " dimensions a query must resolve) and playbook (the niche buying taste) under"
54
- + " domains/<slug>/, AND overwrite the shared user spec (so a cross-niche fact"
55
- + " surfaced in the same query is persisted) — all in one atomic call that"
56
- + " upserts domains[slug]. `userSpec` is REQUIRED on every call (pass the full"
57
- + " updated body — it overwrites atomically). The persona is NOT written here —"
58
- + " it is the host workspace SOUL.md. Re-run with the SAME domain.slug to refresh"
59
- + " a niche in place. Does NOT touch the host OpenClaw config. Writes are atomic:"
60
- + " an invalid spec writes nothing, and a write failure leaves nothing partial (a"
61
- + " failed new-domain mint tears down only that fresh leaf; the shopper and"
62
- + " siblings survive).",
46
+ label: "Set up the sil shopper",
47
+ description: "SETUP-ONLY: create the one sil shopper by writing its shared user spec into the"
48
+ + " sil data directory. Writes user_spec.md — the person's standing facts + hard"
49
+ + " constraints (addresses, sizes, allergy/ethics rules, budget psychology) that"
50
+ + " carry across EVERY niche — with the shopper `name` in the file's own"
51
+ + " frontmatter (there is NO manifest; the frontmatter IS the source of truth)."
52
+ + " It does NOT mint any domain method or PRD — that is sil_learn create. `name`"
53
+ + " and `userSpec` are both REQUIRED. Run this ONCE at setup: post-setup user-spec"
54
+ + " refinement is sil_learn (append/amend), NEVER a re-materialize (a re-run"
55
+ + " overwrites the whole body, discarding what sil_learn added). Makes no network"
56
+ + " call and reads no token. The"
57
+ + " persona is NOT written here — it is the host workspace SOUL.md. A blank"
58
+ + " name/userSpec returns invalid_request and writes nothing; a write failure"
59
+ + " returns persistence_failed.",
63
60
  parameters: Type.Object({
64
61
  name: Type.String({
65
- description: "The human-readable shopper name (recorded in the manifest).",
62
+ description: "The human-readable shopper name (recorded in user_spec.md frontmatter).",
66
63
  }),
67
64
  userSpec: Type.String({
68
- description: "The SHARED user spec — the one person's domain-relevant facts + hard"
69
- + " constraints (addresses, sizes, allergy/ethics rules they never break,"
70
- + " budget psychology) that carry across EVERY niche. REQUIRED, non-empty on"
71
- + " every call. Materialized as user_spec.md and read by every domain's shop"
72
- + " loop, so a fact captured while shopping one niche is reused in another"
73
- + " without being re-asked. On any augment, pass the full updated body — it"
74
- + " overwrites atomically.",
65
+ description: "The shared user spec — the one person's cross-domain facts + hard"
66
+ + " constraints. REQUIRED, non-empty. Read by every domain's shop loop, so a"
67
+ + " fact captured in one niche is reused in another without re-asking.",
75
68
  }),
76
- domain: Type.Optional(Type.Object({
77
- slug: Type.String({
78
- description: "The domain slug, lower-kebab; not \"main\". Keys domains/<slug>/."
79
- + " Reuse the slug of an existing matching niche before minting a new"
80
- + " one (the skill dedups; the store enforces only shape).",
81
- }),
82
- name: Type.String({
83
- description: "The human-readable domain name (e.g. \"Road cycling\").",
84
- }),
85
- domainSpec: Type.String({
86
- description: "The SDS domain spec — deep researched niche expertise: how to buy"
87
- + " well in the niche and its full mechanics. REQUIRED, non-empty."
88
- + " Materialized as domains/<slug>/domain_spec.md; web-refreshed every"
89
- + " query.",
90
- }),
91
- intentSpec: Type.String({
92
- description: "The SDS intent spec — the decomposition DIMENSIONS a shopping query"
93
- + " in this niche must resolve (use-case, budget, compatibility…),"
94
- + " derived from the domain spec. REQUIRED, non-empty. The dimension"
95
- + " SCHEMA only — the per-query intent is ephemeral. Materialized as"
96
- + " domains/<slug>/intent_spec.md.",
97
- }),
98
- playbook: Type.String({
99
- description: "The SDS playbook — the user's buying TASTE for THIS niche (price"
100
- + " band, brand leanings, niche-mechanical preferences). REQUIRED,"
101
- + " non-empty. Materialized as domains/<slug>/playbook.md. On a"
102
- + " per-query augment, pass the full updated body.",
103
- }),
104
- }, {
105
- description: "OPTIONAL per-domain pack. Omit to create/refresh the shopper only;"
106
- + " include to lazily mint or refresh a niche.",
107
- })),
108
69
  }),
109
70
  async execute(_callId, params) {
110
- // The host validates `params` against the schema above before we run, but
111
- // narrow at the read site (the SDK types params as Record<string,unknown>)
112
- // and let the store do the real, structured-error validation.
113
- const rawDomain = params["domain"];
114
- let domain;
115
- if (typeof rawDomain === "object" && rawDomain !== null) {
116
- const d = rawDomain;
117
- domain = {
118
- slug: asString(d["slug"]),
119
- name: asString(d["name"]),
120
- domainSpec: asString(d["domainSpec"]),
121
- intentSpec: asString(d["intentSpec"]),
122
- playbook: asString(d["playbook"]),
123
- };
124
- }
125
- const spec = {
71
+ const result = materializeProfile({
126
72
  name: asString(params["name"]),
127
73
  userSpec: asString(params["userSpec"]),
128
- ...(domain ? { domain } : {}),
129
- };
130
- const result = materializeProfile(spec);
74
+ });
131
75
  if (result.ok) {
132
- api.logger.info("sil_profile_materialized", {
133
- domain_slug: result.domain?.slug,
134
- });
135
- const payload = {
136
- status: "ok",
137
- dir: result.dir,
138
- userSpecPath: result.userSpecPath,
139
- profilePath: result.profilePath,
140
- };
141
- if (result.domain)
142
- payload["domain"] = result.domain;
143
- return jsonResult(payload);
76
+ api.logger.info("sil_profile_materialized", {});
77
+ return jsonResult({ status: "ok", dir: result.dir, userSpecPath: result.userSpecPath });
144
78
  }
145
- if (result.kind === "invalid_request") {
146
- api.logger.warn("sil_profile_invalid_request", { field: result.field });
147
- return jsonResult({
148
- status: "invalid_request",
149
- field: result.field,
150
- message: result.message,
151
- });
152
- }
153
- // persistence_failed — the path + cause are in `error` (never a token/PII).
154
- api.logger.error("sil_profile_persistence_failed", { error: result.error });
155
- return jsonResult({
156
- status: "persistence_failed",
157
- error: result.error,
158
- message: result.message,
159
- recovery: "fix_data_dir",
160
- });
79
+ return mapFailure(api, "sil_profile_materialize", result);
161
80
  },
162
81
  });
163
82
  }
164
- /**
165
- * `sil_profile_get` — view the shopper at TWO zoom levels (read-only, no `agentId`).
166
- *
167
- * WITHOUT a `domainSlug` (Zoom A — absorbs the old standalone listing surface): the
168
- * shopper overview — its name, the SHARED user spec, the domain index (each niche's
169
- * slug/name/timestamps, no bodies) and the `unreadable[]` degraded-directory array.
170
- * An EMPTY store, or a freshly-created shopper with no domains, is `ok` (empty-is-
171
- * healthy) — never `not_found`. WITH a `domainSlug` (Zoom C): that one domain's
172
- * three bodies (domain spec, intent spec, playbook) PLUS the shared user spec. An
173
- * unminted/unloadable domain → `not_found` (recovery: the no-args `sil_profile_get`);
174
- * a malformed/traversal slug → `invalid_request`. Reads no token and writes nothing.
175
- */
176
- function registerGet(api) {
83
+ function registerLearn(api) {
177
84
  api.registerTool({
178
- name: "sil_profile_get",
179
- label: "View the sil shopper overview or one domain",
180
- description: "Show the sil shopper's detail — read-only. WITHOUT a `domainSlug`: the shopper"
181
- + " overview — its name, the SHARED user spec (the one person's facts + hard"
182
- + " constraints), the domain index (each niche's slug/name/timestamps, no"
183
- + " per-domain bodies) and any degraded directories in `unreadable`. This is the"
184
- + " way to see what the shopper knows / which domains it has learned. An empty"
185
- + " store, or a freshly-created shopper with no domains, returns ok (healthy,"
186
- + " empty domain index) — never not_found. WITH a `domainSlug`: that one"
187
- + " domain's pack — its domain spec, intent spec and playbook (buying taste)"
188
- + " PLUS the shared user spec. The persona is not here — it is the host"
189
- + " workspace SOUL.md. An unminted/unloadable domain returns `not_found` (omit"
190
- + " the domainSlug to see what exists). A malformed/traversal slug returns"
191
- + " `invalid_request`. Reads no token and writes nothing.",
85
+ name: "sil_learn",
86
+ label: "Teach the sil shopper (create or refine a method / PRD)",
87
+ description: "The single target+change verb that owns the whole method/PRD lifecycle for the"
88
+ + " sil shopper — create a whole doc, or refine one in place. `target` selects"
89
+ + " WHERE the change lands: `user_spec` (the shared person spec, no selector),"
90
+ + " `method` (needs `domain`), or `prd` (needs `domain` + `prd`, the"
91
+ + " <product>-<intent> key). `kind` selects the change: `create` mints a whole"
92
+ + " method (domain, name, body) or PRD (domain, prd, product, intent, title,"
93
+ + " body) — NOT valid for user_spec; `append` adds one `- text` bullet under a"
94
+ + " named `## section` (fail-closed if that heading is absent) else at EOF;"
95
+ + " `amend` replaces the single bullet matching `from` with `to` (an ambiguous"
96
+ + " 2+ match is refused); `retract` removes the single bullet matching `from`;"
97
+ + " `attach-asset` persists image `bytes` (base64 + `mime`) into the domain's"
98
+ + " assets and links them by relative path. `hard` marks an inviolable"
99
+ + " constraint — valid only on append to user_spec or prd. append/amend/retract/"
100
+ + " attach-asset require the target to already exist (else not_found). Makes no"
101
+ + " network call and reads no token; writes are atomic + owner-only. A bad field"
102
+ + " returns invalid_request and writes nothing.",
192
103
  parameters: Type.Object({
193
- domainSlug: Type.Optional(Type.String({
194
- description: "OPTIONAL. A domain slug to view that niche's pack; omit for the shopper"
195
- + " overview (name + shared user spec + domain index).",
196
- })),
104
+ target: Type.Union([Type.Literal("user_spec"), Type.Literal("method"), Type.Literal("prd")], { description: "WHERE the change lands: user_spec | method | prd." }),
105
+ kind: Type.Union([
106
+ Type.Literal("create"),
107
+ Type.Literal("append"),
108
+ Type.Literal("amend"),
109
+ Type.Literal("retract"),
110
+ Type.Literal("attach-asset"),
111
+ ], { description: "The change: create | append | amend | retract | attach-asset." }),
112
+ domain: Type.Optional(Type.String({ description: "The domain slug (lower-kebab, not \"main\") — required for method/prd." })),
113
+ prd: Type.Optional(Type.String({ description: "The PRD key <product>-<intent> (lower-kebab) — required for a prd target." })),
114
+ name: Type.Optional(Type.String({ description: "create method: the human-readable domain name." })),
115
+ body: Type.Optional(Type.String({ description: "create: the whole markdown body to mint." })),
116
+ product: Type.Optional(Type.String({ description: "create prd: the product type." })),
117
+ intent: Type.Optional(Type.String({ description: "create prd: the use-context (general when context-free)." })),
118
+ title: Type.Optional(Type.String({ description: "create prd: the human-readable job title." })),
119
+ text: Type.Optional(Type.String({ description: "append: the one bullet to add." })),
120
+ from: Type.Optional(Type.String({ description: "amend/retract: the exact bullet text to match (single occurrence)." })),
121
+ to: Type.Optional(Type.String({ description: "amend: the replacement bullet text." })),
122
+ section: Type.Optional(Type.String({ description: "append/amend/retract: the `## section` to scope to." })),
123
+ hard: Type.Optional(Type.Boolean({ description: "append to user_spec/prd only: mark an inviolable constraint the shop loop rejects against." })),
124
+ bytes: Type.Optional(Type.String({ description: "attach-asset: the image bytes, base64-encoded." })),
125
+ mime: Type.Optional(Type.String({ description: "attach-asset: image/jpeg | image/png | image/webp | image/gif." })),
126
+ caption: Type.Optional(Type.String({ description: "attach-asset: an optional caption for the markdown link." })),
197
127
  }),
198
128
  async execute(_callId, params) {
199
- const rawSlug = params["domainSlug"];
200
- const domainSlug = typeof rawSlug === "string" ? rawSlug : undefined;
201
- const result = readAgentProfile(domainSlug);
129
+ const spec = {
130
+ target: params["target"] ?? "method",
131
+ kind: params["kind"] ?? "append",
132
+ domain: optString(params["domain"]),
133
+ prd: optString(params["prd"]),
134
+ name: optString(params["name"]),
135
+ body: optString(params["body"]),
136
+ product: optString(params["product"]),
137
+ intent: optString(params["intent"]),
138
+ title: optString(params["title"]),
139
+ text: optString(params["text"]),
140
+ from: optString(params["from"]),
141
+ to: optString(params["to"]),
142
+ section: optString(params["section"]),
143
+ hard: params["hard"] === true ? true : undefined,
144
+ bytes: optString(params["bytes"]),
145
+ mime: optString(params["mime"]),
146
+ caption: optString(params["caption"]),
147
+ };
148
+ const result = learnArtefact(spec);
202
149
  if (result.ok) {
203
- if (result.slug !== undefined) {
204
- // Per-domain read (Zoom C) — the niche's three bodies + the shared user spec.
205
- api.logger.info("sil_profile_viewed", { domain_slug: result.slug });
206
- return jsonResult({
207
- status: "ok",
208
- name: result.name,
209
- slug: result.slug,
210
- userSpec: result.userSpec,
211
- domainSpec: result.domainSpec,
212
- intentSpec: result.intentSpec,
213
- playbook: result.playbook,
214
- profilePath: result.profilePath,
215
- createdAt: result.createdAt,
216
- updatedAt: result.updatedAt,
217
- });
218
- }
219
- // Zoom A overview — the domain index + unreadable[]; the shared user spec +
220
- // identity only when a shopper actually exists (an empty store is healthy
221
- // and carries no shopper content).
222
- api.logger.info("sil_profile_viewed", {
223
- shopper_present: result.name !== undefined,
224
- domain_count: result.domains.length,
225
- unreadable_count: result.unreadable.length,
150
+ // Non-PII markers only — no artefact body/text is ever logged.
151
+ api.logger.info("sil_learned", {
152
+ kind: result.kind,
153
+ target: result.target,
154
+ domain_slug: result.domain,
155
+ prd: result.prd,
226
156
  });
227
- const payload = {
228
- status: "ok",
229
- domains: result.domains,
230
- unreadable: result.unreadable,
231
- };
232
- if (result.name !== undefined) {
233
- payload["name"] = result.name;
234
- payload["userSpec"] = result.userSpec;
235
- payload["profilePath"] = result.profilePath;
236
- payload["createdAt"] = result.createdAt;
237
- }
238
- return jsonResult(payload);
239
- }
240
- if (result.kind === "invalid_request") {
241
- api.logger.warn("sil_profile_get_invalid_request", { field: result.field });
242
157
  return jsonResult({
243
- status: "invalid_request",
244
- field: result.field,
245
- message: result.message,
158
+ status: "ok",
159
+ kind: result.kind,
160
+ target: result.target,
161
+ ...(result.domain !== undefined ? { domain: result.domain } : {}),
162
+ ...(result.prd !== undefined ? { prd: result.prd } : {}),
163
+ path: result.path,
164
+ ...(result.assetPath !== undefined ? { assetPath: result.assetPath } : {}),
246
165
  });
247
166
  }
248
- // not_found — a normal outcome; steer the agent to the no-args read (the
249
- // overview), never to a now-removed standalone listing tool.
250
- api.logger.info("sil_profile_get_not_found", {});
167
+ return mapFailure(api, "sil_learn", result);
168
+ },
169
+ });
170
+ }
171
+ function registerSearch(api) {
172
+ api.registerTool({
173
+ name: "sil_profile_search",
174
+ label: "Search what the sil shopper knows (domains + PRDs)",
175
+ description: "Query the sil shopper's artefact FRONTMATTER — the discovery / reuse-before-mint"
176
+ + " primitive. Returns COORDINATES only (no document bodies): the domains the"
177
+ + " shopper has learned ({slug, name}) and its PRDs ({domain, key, product,"
178
+ + " intent, title, …}). All filters are optional — pass none for the full"
179
+ + " overview, or narrow by `domain` / `product` / `intent` / a free-text"
180
+ + " `query`. This is a filesystem SCAN, not an index read; a domain or PRD whose"
181
+ + " frontmatter is malformed is SKIPPED and surfaced in `unreadable` (never"
182
+ + " silently dropped, never half-read) while healthy siblings still list. An"
183
+ + " empty store returns ok with empty domains/prds (healthy). Makes no network"
184
+ + " call and reads no token.",
185
+ parameters: Type.Object({
186
+ domain: Type.Optional(Type.String({ description: "Filter to one domain slug." })),
187
+ product: Type.Optional(Type.String({ description: "Filter PRDs by product type." })),
188
+ intent: Type.Optional(Type.String({ description: "Filter PRDs by intent (use-context)." })),
189
+ query: Type.Optional(Type.String({ description: "Free-text substring match over the coordinates." })),
190
+ }),
191
+ async execute(_callId, params) {
192
+ const result = searchProfileFrontmatter({
193
+ domain: optString(params["domain"]),
194
+ product: optString(params["product"]),
195
+ intent: optString(params["intent"]),
196
+ query: optString(params["query"]),
197
+ });
198
+ api.logger.info("sil_profile_searched", {
199
+ domain_count: result.domains.length,
200
+ prd_count: result.prds.length,
201
+ unreadable_count: result.unreadable.length,
202
+ });
251
203
  return jsonResult({
252
- status: "not_found",
253
- message: result.message,
254
- recovery: "sil_profile_get",
204
+ status: "ok",
205
+ domains: result.domains,
206
+ prds: result.prds,
207
+ unreadable: result.unreadable,
255
208
  });
256
209
  },
257
210
  });
258
211
  }
259
- /**
260
- * `sil_profile_remove` — remove ONE of the shopper's domain packs (artefact half).
261
- *
262
- * `domainSlug` is REQUIRED — there is no omit-deletes-everything trap; removing the
263
- * whole shopper is a host concern, not this tool. Removes exactly the one
264
- * `domains/<slug>/` leaf and de-registers it from the manifest; the shopper and the
265
- * SHARED user spec survive. Re-runs the gate itself, deletes NOTHING on a bad/
266
- * missing slug. Absent (unregistered) slug → `not_found` (idempotent). A genuine
267
- * `rmSync`/rewrite failure → `persistence_failed`. Reads no token.
268
- */
269
- function registerRemove(api) {
212
+ function registerGet(api) {
270
213
  api.registerTool({
271
- name: "sil_profile_remove",
272
- label: "Remove one of the sil shopper's domains",
273
- description: "Remove ONE of the sil shopper's domain packs from the sil data directory"
274
- + " (its domains/<slug>/ directory) — the SIL-SIDE artefact half only. Pass"
275
- + " `domainSlug`; it is REQUIRED — this never deletes the whole shopper"
276
- + " (decommissioning the shopper is a host concern). Scoped to exactly that one"
277
- + " domain: the shopper, the SHARED user spec, and every sibling domain survive."
278
- + " A malformed/traversal/\"main\" or missing slug returns `invalid_request` and"
279
- + " deletes nothing; an unregistered slug returns `not_found` (idempotent — safe"
280
- + " to re-run after a partial failure); a genuine filesystem failure returns"
281
- + " `persistence_failed`. Confirm with the user before removing — it is"
282
- + " destructive and irreversible.",
214
+ name: "sil_profile_get",
215
+ label: "Read one sil shopper document (method or PRD)",
216
+ description: "Read ONE full body from the sil shopper's store — the rich read. With a"
217
+ + " `domainSlug` only, returns that domain's method body (its buying guide +"
218
+ + " taste + search vocabulary); with `domainSlug` + `prd`, returns that PRD's"
219
+ + " body (its requirements + filled preferences). Use sil_profile_search first"
220
+ + " to discover which domains/PRDs exist (coordinates), then this to read one in"
221
+ + " full. A missing method/PRD returns not_found; a present-but-corrupt body"
222
+ + " (malformed/absent frontmatter) returns unreadable (inspect / repair — do NOT"
223
+ + " overwrite it, it may be recoverable), distinct from not_found; a malformed/"
224
+ + "traversal/\"main\" slug returns invalid_request. Makes no network call and reads"
225
+ + " no token.",
283
226
  parameters: Type.Object({
284
227
  domainSlug: Type.String({
285
- description: "The domain slug to remove (lower-kebab; not \"main\"). REQUIRED —"
286
- + " exactly one domain pack is affected; the shopper itself is not.",
228
+ description: "The domain slug to read (lower-kebab, not \"main\"). REQUIRED.",
287
229
  }),
230
+ prd: Type.Optional(Type.String({ description: "OPTIONAL. A PRD key to read that PRD's body instead of the method." })),
288
231
  }),
289
232
  async execute(_callId, params) {
290
- const domainSlug = asString(params["domainSlug"]);
291
- const result = removeAgentArtefacts(domainSlug);
233
+ const result = readArtefactBody(asString(params["domainSlug"]), optString(params["prd"]));
292
234
  if (result.ok) {
293
- api.logger.info("sil_profile_removed", { domain_slug: result.domainSlug });
294
- return jsonResult({
295
- status: "removed",
296
- domainSlug: result.domainSlug,
297
- });
298
- }
299
- if (result.kind === "invalid_request") {
300
- api.logger.warn("sil_profile_remove_invalid_request", { field: result.field });
235
+ api.logger.info("sil_profile_read", { target: result.target, domain_slug: result.domain, prd: result.prd });
301
236
  return jsonResult({
302
- status: "invalid_request",
303
- field: result.field,
304
- message: result.message,
305
- });
306
- }
307
- if (result.kind === "not_found") {
308
- api.logger.info("sil_profile_remove_not_found", {});
309
- return jsonResult({
310
- status: "not_found",
311
- message: result.message,
312
- recovery: "sil_profile_get",
237
+ status: "ok",
238
+ target: result.target,
239
+ domain: result.domain,
240
+ ...(result.prd !== undefined ? { prd: result.prd } : {}),
241
+ fields: result.fields,
242
+ body: result.body,
243
+ path: result.path,
313
244
  });
314
245
  }
315
- // persistence_failed — the path + cause are in `error` (never a token/PII).
316
- api.logger.error("sil_profile_remove_persistence_failed", { error: result.error });
317
- return jsonResult({
318
- status: "persistence_failed",
319
- error: result.error,
320
- message: result.message,
321
- recovery: result.recovery,
322
- });
246
+ return mapFailure(api, "sil_profile_get", result);
323
247
  },
324
248
  });
325
249
  }
326
- /**
327
- * `sil_remember` — the lightweight per-query APPEND memory verb.
328
- *
329
- * Appends ONE typed learning without re-emitting the whole document — the cheap
330
- * path the model actually takes under load (vs. the heavy whole-doc
331
- * `sil_profile_materialize` round-trip). `kind:"fact"` (something true about the
332
- * person) lands in the shared `user_spec.md` and carries across every niche;
333
- * `kind:"taste"` (how they like to buy in this niche) lands in the active domain's
334
- * `playbook.md`. `hard:true` marks an inviolable user-spec constraint (FACT only);
335
- * `domain` selects the niche for a TASTE (omitted ⇒ the single registered domain).
336
- *
337
- * Thin over `appendProfileEntry`: narrow the host-validated params, call the store,
338
- * map the discriminated result to the canonical envelope. The remembered `text` is
339
- * user content — it is NEVER written to a log payload (only non-PII markers are).
340
- */
341
- function registerRemember(api) {
250
+ function registerRemove(api) {
342
251
  api.registerTool({
343
- name: "sil_remember",
344
- label: "Remember one fact or taste for the sil shopper",
345
- description: "Append ONE typed learning to the sil shopper's behaviour artefacts — the"
346
- + " CHEAP per-query persistence path (no whole-doc round-trip). Use this every"
347
- + " query to capture something the interaction surfaced, in the open (never"
348
- + " silently). `kind:\"fact\"` records something true about the PERSON (a"
349
- + " measurement, a size, an address, an allergy/ethics rule) — it appends to the"
350
- + " shared user spec and carries across EVERY niche; set `hard:true` to mark an"
351
- + " INVIOLABLE constraint (a reject-at-pick rule, FACTS only). `kind:\"taste\"`"
352
- + " records how the person likes to BUY in a niche (price band, brand leaning) —"
353
- + " it appends to that niche's buying-taste playbook; pass `domain` to select the"
354
- + " niche (omit it only when the shopper has exactly one). ONE discrete learning"
355
- + " per call — two facts and a taste are three calls. Append-only and accretive:"
356
- + " it never rewrites or de-duplicates the doc — a contradiction or a full"
357
- + " refine/overwrite stays the whole-doc sil_profile_materialize path. Makes NO"
358
- + " network call and reads no token; writes one short line via O_APPEND. A blank"
359
- + " text, a fact carrying a domain, a taste carrying hard:true, or a"
360
- + " malformed/traversal/\"main\" taste domain returns invalid_request and writes"
361
- + " nothing; an unknown shopper / unminted domain / missing body returns"
362
- + " not_found (mint it first); a genuine write failure returns"
363
- + " persistence_failed.",
252
+ name: "sil_profile_remove",
253
+ label: "Remove a sil shopper domain, or one of its PRDs",
254
+ description: "Remove artefacts from the sil shopper's store — the SIL-SIDE half only. With a"
255
+ + " `domainSlug` only, removes the WHOLE domain subtree (method + all PRDs +"
256
+ + " assets); with `domainSlug` + `prd`, removes just that ONE PRD (the method and"
257
+ + " sibling PRDs survive). Scoped and fail-closed: a malformed/traversal/\"main\""
258
+ + " slug returns invalid_request and deletes nothing; an unregistered domain/PRD"
259
+ + " returns not_found (idempotent — safe to re-run); a genuine filesystem failure"
260
+ + " returns persistence_failed. Never removes the shopper itself (that is a host"
261
+ + " concern). Confirm with the user before removing — it is destructive. Makes no"
262
+ + " network call and reads no token.",
364
263
  parameters: Type.Object({
365
- kind: Type.Union([Type.Literal("fact"), Type.Literal("taste")], {
366
- description: "\"fact\" → the shared user spec (true about the person; carries across"
367
- + " niches). \"taste\" → the active domain's buying-taste playbook (how they"
368
- + " buy in THIS niche).",
369
- }),
370
- text: Type.String({
371
- description: "The ONE short learning to record (a single discrete fact or taste). Keep it"
372
- + " to one entry — it is appended verbatim as a markdown bullet.",
264
+ domainSlug: Type.String({
265
+ description: "The domain slug to remove from (lower-kebab, not \"main\"). REQUIRED.",
373
266
  }),
374
- domain: Type.Optional(Type.String({
375
- description: "TASTE only — the domain slug (lower-kebab; not \"main\") to append the"
376
- + " taste to. Omit ONLY when the shopper has exactly one domain (it"
377
- + " resolves automatically); with 2+ domains, omitting it is ambiguous and"
378
- + " returns invalid_request. Ignored / a category error on a fact.",
379
- })),
380
- hard: Type.Optional(Type.Boolean({
381
- description: "FACT only — true marks an INVIOLABLE user-spec constraint (an allergy, an"
382
- + " ethics rule, an age gate) the shop loop rejects candidates against."
383
- + " Taste is always soft, so hard:true on a taste is a contradiction"
384
- + " (invalid_request).",
385
- })),
267
+ prd: Type.Optional(Type.String({ description: "OPTIONAL. A PRD key to remove just that PRD instead of the whole domain." })),
386
268
  }),
387
269
  async execute(_callId, params) {
388
- // Host-validated against the schema above; narrow at the read site (the SDK
389
- // types params as Record<string,unknown>) and let the store do the real,
390
- // structured-error validation. Only carry domain/hard when meaningfully set
391
- // so a fact never carries a spurious `domain: undefined`.
392
- const kind = params["kind"] === "taste" ? "taste" : "fact";
393
- const rawDomain = params["domain"];
394
- const domain = typeof rawDomain === "string" ? rawDomain : undefined;
395
- const hard = params["hard"] === true ? true : undefined;
396
- const spec = {
397
- kind,
398
- text: asString(params["text"]),
399
- ...(domain !== undefined ? { domain } : {}),
400
- ...(hard !== undefined ? { hard } : {}),
401
- };
402
- const result = appendProfileEntry(spec);
270
+ const result = removeArtefact(asString(params["domainSlug"]), optString(params["prd"]));
403
271
  if (result.ok) {
404
- // Non-PII marker only — the remembered `text` is user content and is never
405
- // logged.
406
- api.logger.info("sil_remembered", {
407
- kind: result.kind,
408
- domain_slug: result.domain,
409
- });
410
- return jsonResult({
411
- status: "ok",
412
- kind: result.kind,
413
- ...(result.domain !== undefined ? { domain: result.domain } : {}),
414
- });
415
- }
416
- if (result.kind === "invalid_request") {
417
- api.logger.warn("sil_remember_invalid_request", { field: result.field });
272
+ api.logger.info("sil_profile_removed", { domain_slug: result.domainSlug, prd: result.prd });
418
273
  return jsonResult({
419
- status: "invalid_request",
420
- field: result.field,
421
- message: result.message,
422
- });
423
- }
424
- if (result.kind === "not_found") {
425
- api.logger.info("sil_remember_not_found", {});
426
- return jsonResult({
427
- status: "not_found",
428
- message: result.message,
429
- recovery: "sil_profile_materialize",
274
+ status: "removed",
275
+ domainSlug: result.domainSlug,
276
+ ...(result.prd !== undefined ? { prd: result.prd } : {}),
430
277
  });
431
278
  }
432
- // persistence_failed — the path + cause are in `error` (never a token/PII).
433
- api.logger.error("sil_remember_persistence_failed", { error: result.error });
434
- return jsonResult({
435
- status: "persistence_failed",
436
- error: result.error,
437
- message: result.message,
438
- recovery: result.recovery,
439
- });
279
+ return mapFailure(api, "sil_profile_remove", result);
440
280
  },
441
281
  });
442
282
  }
283
+ /** Map a store failure variant to the canonical structured envelope + a non-PII log. */
284
+ function mapFailure(api, tool, result) {
285
+ if (result.kind === "invalid_request") {
286
+ api.logger.warn(tool + "_invalid_request", { field: result.field });
287
+ return jsonResult({ status: "invalid_request", field: result.field, message: result.message });
288
+ }
289
+ if (result.kind === "not_found") {
290
+ api.logger.info(tool + "_not_found", {});
291
+ return jsonResult({ status: "not_found", message: result.message });
292
+ }
293
+ if (result.kind === "unreadable") {
294
+ // A present-but-corrupt artefact — steer the agent to inspect/repair, NEVER re-mint
295
+ // over it (silent data loss on a recoverable artefact). Distinct from not_found.
296
+ api.logger.warn(tool + "_unreadable", {});
297
+ return jsonResult({ status: "unreadable", message: result.message, recovery: "inspect_artefact" });
298
+ }
299
+ api.logger.error(tool + "_persistence_failed", { error: result.error });
300
+ return jsonResult({
301
+ status: "persistence_failed",
302
+ error: result.error,
303
+ message: result.message,
304
+ recovery: result.recovery,
305
+ });
306
+ }