sil-openclaw 0.4.1 → 0.4.3

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.
@@ -45,9 +45,6 @@ const METHOD_FILE = "method.md";
45
45
  /** A domain slug / PRD key must be lower-kebab and never `main` (host-reserved). Both
46
46
  * are joined as filesystem path segments, so they carry this guard before any join. */
47
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`). */
50
- const HARD_MARKER = "[hard]";
51
48
  /** attach-asset limits: ~8 MB decoded, image MIME allowlist → file extension. */
52
49
  const MAX_ASSET_BYTES = 8 * 1024 * 1024;
53
50
  const MIME_EXT = {
@@ -126,7 +123,10 @@ function serializeArtefact(fields, body) {
126
123
  const fm = Object.entries(fields)
127
124
  .map(([k, v]) => k + ": " + scalar(v))
128
125
  .join("\n");
129
- const b = body.endsWith("\n") ? body : body + "\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
130
  return "---\n" + fm + "\n---\n" + b;
131
131
  }
132
132
  /** Parse `--- key: value … ---` frontmatter + body. Returns null (⇒ `unreadable`) on
@@ -150,6 +150,15 @@ function parseArtefact(raw) {
150
150
  return null;
151
151
  return { fields, body };
152
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
+ }
153
162
  /** Read + parse one artefact file, or null if absent/unreadable/malformed. */
154
163
  function readArtefactFile(path) {
155
164
  if (!existsSync(path))
@@ -251,36 +260,25 @@ function resolveTarget(spec) {
251
260
  };
252
261
  }
253
262
  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
263
  switch (spec.kind) {
265
264
  case "create":
266
265
  return learnCreate(spec);
267
- case "append":
268
- return learnAppend(spec);
269
- case "amend":
270
- case "retract":
271
- return learnAmendRetract(spec);
266
+ case "write":
267
+ return learnWrite(spec);
272
268
  case "attach-asset":
273
269
  return learnAttachAsset(spec);
274
270
  default:
275
- return invalid("kind", "kind must be one of create|append|amend|retract|attach-asset.");
271
+ return invalid("kind", "kind must be one of create|write|attach-asset.");
276
272
  }
277
273
  }
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). */
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`). */
280
278
  function learnCreate(spec) {
281
279
  if (spec.target === "user_spec") {
282
280
  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.");
281
+ + " sil_profile_materialize (setup), then refined with kind:write.");
284
282
  }
285
283
  if (!nonBlank(spec.body))
286
284
  return invalid("body", "body is required and must be non-empty.");
@@ -293,6 +291,10 @@ function learnCreate(spec) {
293
291
  if (!nonBlank(spec.name))
294
292
  return invalid("name", "name is required for a method.");
295
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
+ }
296
298
  const fields = { domain: slug, name: spec.name, updated_at: now };
297
299
  try {
298
300
  atomicWrite(path, serializeArtefact(fields, spec.body));
@@ -312,16 +314,17 @@ function learnCreate(spec) {
312
314
  return invalid(f, f + " is required for a prd.");
313
315
  }
314
316
  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;
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
+ }
318
321
  const fields = {
319
322
  key: prd,
320
323
  product: spec.product,
321
324
  intent: spec.intent,
322
325
  title: spec.title,
323
326
  domain: slug,
324
- created_at: createdAt,
327
+ created_at: now,
325
328
  updated_at: now,
326
329
  };
327
330
  try {
@@ -332,81 +335,26 @@ function learnCreate(spec) {
332
335
  }
333
336
  return { ok: true, kind: "create", target: "prd", domain: slug, prd, path };
334
337
  }
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.");
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.");
342
347
  const target = resolveTarget(spec);
343
348
  if ("ok" in target)
344
349
  return target;
345
350
  const existing = readArtefactFile(target.path);
346
351
  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;
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).");
361
356
  }
362
- else {
363
- body = existing.body.replace(/\n*$/, "\n") + bullet + "\n";
364
- }
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);
403
- }
404
- else {
405
- const parsed = parseBullet(lines[idx]);
406
- const mark = parsed.hard ? HARD_MARKER + " " : "";
407
- lines[idx] = parsed.indent + "- " + mark + spec.to.trim();
408
- }
409
- return writeArtefactBody(target, existing.fields, lines.join("\n"), spec.kind);
357
+ return writeArtefactBody(target, existing.fields, spec.body, "write");
410
358
  }
411
359
  /** attach-asset — persist image bytes into `domains/<slug>/assets/<hash>.<ext>`
412
360
  * (owner-only, content-hash = free dedup), then link them into the target by a
@@ -493,57 +441,6 @@ function writeArtefactBody(target, fields, body, kind) {
493
441
  path: target.path,
494
442
  };
495
443
  }
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] };
502
- }
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());
510
- }
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;
521
- }
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;
530
- }
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
444
  export function searchProfileFrontmatter(query = {}) {
548
445
  const domainsRoot = join(getShopperArtefactDir(), DOMAINS_SUBDIR);
549
446
  const domains = [];
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Plugin-version currency — read what is installed, ask ClawHub what is
3
+ * published, and say so. Nothing else.
4
+ *
5
+ * The doctor NEVER acts on the version it reports: it installs nothing, writes
6
+ * no host config, spawns no process, and prompts nobody. It also cannot — a
7
+ * plugin can't hot-swap its own running code. It names OpenClaw's own update
8
+ * path and stops.
9
+ *
10
+ * The ClawHub GET is the doctor's ONLY outbound request: unauthenticated,
11
+ * bounded by an explicit timeout + abort, carrying no token, no PII, and no
12
+ * store contents. It FAILS SOFT TO SILENCE — a probe that is unreachable, slow,
13
+ * non-200, or unparseable yields `null`, which yields no finding at all. Never
14
+ * "you are current" (a false green on a real update), never "you are behind" (a
15
+ * false alarm from a failed read). Unknown is not a state we invent a value for.
16
+ *
17
+ * This module is `lib/` because the self-upgrade card adds
18
+ * `buildGatewayCompatFinding()` here, reusing `compareSemver` — a genuinely
19
+ * different datum (running host vs our declared compat range; local, no probe).
20
+ */
21
+ import { readFileSync } from "node:fs";
22
+ import { dirname, join } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ /**
25
+ * The published-version authority. A doctor running inside OpenClaw is a
26
+ * ClawHub install, so ClawHub — not npm — is the authority that matches how the
27
+ * user would actually update, which is the whole point of the advisory. We
28
+ * publish the same tarball to both, under this name on ClawHub (`sil` is
29
+ * unclaimable). Declared in `openclaw.plugin.json#networkEndpoints`.
30
+ */
31
+ const CLAWHUB_ORIGIN = "https://clawhub.ai";
32
+ const CLAWHUB_PACKAGE_NAME = "@4gpts/sil";
33
+ const CLAWHUB_PACKAGE_URL = `${CLAWHUB_ORIGIN}/api/v1/packages/${encodeURIComponent(CLAWHUB_PACKAGE_NAME)}`;
34
+ /** A blackholed registry must never stall a diagnosis — the doctor is needed
35
+ * most when things are broken, and "broken" often includes the network. */
36
+ const PROBE_TIMEOUT_MS = 3_000;
37
+ /** Semver core + optional prerelease/build. We only ever compare strings we or
38
+ * the registry published, so this is a shape guard, not a validator. */
39
+ const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
40
+ /** The packaged `package.json`, resolved relative to this module — two levels up
41
+ * from both `src/lib/` and `dist/lib/`. `package.json#version` is the single
42
+ * source of truth (`sync-version.mjs` mirrors it into the manifest), so a
43
+ * hardcoded constant would silently drift the moment `pnpm version` runs. */
44
+ const PACKAGE_JSON_PATH = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
45
+ /**
46
+ * The installed version, read locally on every run.
47
+ *
48
+ * Throws when the packaged `package.json` is missing or carries no version: that
49
+ * is a broken build, not a runtime state to model — which is why the report's
50
+ * `installedVersion` is `string`, never `string | null`.
51
+ */
52
+ export function readInstalledVersion() {
53
+ const parsed = JSON.parse(readFileSync(PACKAGE_JSON_PATH, "utf8"));
54
+ const version = parsed.version;
55
+ if (typeof version !== "string" || version.length === 0) {
56
+ throw new Error(`${PACKAGE_JSON_PATH}: package.json carries no version string`);
57
+ }
58
+ return version;
59
+ }
60
+ function parseSemver(version) {
61
+ const m = SEMVER_RE.exec(version.trim());
62
+ if (m === null)
63
+ return null;
64
+ return {
65
+ core: [Number(m[1]), Number(m[2]), Number(m[3])],
66
+ prerelease: m[4] === undefined ? [] : m[4].split("."),
67
+ };
68
+ }
69
+ /** Compare two dot-separated prerelease identifiers per semver §11: numeric
70
+ * identifiers rank below alphanumeric ones and compare numerically; a shorter
71
+ * prerelease ranks below an otherwise-equal longer one. */
72
+ function comparePrerelease(a, b) {
73
+ // Absent prerelease outranks any present one (1.0.0 > 1.0.0-rc.1).
74
+ if (a.length === 0 && b.length === 0)
75
+ return 0;
76
+ if (a.length === 0)
77
+ return 1;
78
+ if (b.length === 0)
79
+ return -1;
80
+ for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
81
+ const x = a[i];
82
+ const y = b[i];
83
+ if (x === undefined)
84
+ return -1;
85
+ if (y === undefined)
86
+ return 1;
87
+ const xNum = /^\d+$/.test(x);
88
+ const yNum = /^\d+$/.test(y);
89
+ if (xNum && yNum) {
90
+ const d = Number(x) - Number(y);
91
+ if (d !== 0)
92
+ return d < 0 ? -1 : 1;
93
+ }
94
+ else if (xNum !== yNum) {
95
+ return xNum ? -1 : 1;
96
+ }
97
+ else if (x !== y) {
98
+ return x < y ? -1 : 1;
99
+ }
100
+ }
101
+ return 0;
102
+ }
103
+ /**
104
+ * Semver PRECEDENCE, not string compare: `"0.4.10" < "0.4.9"` lexicographically
105
+ * is a real trap this repo hits at 0.4.10, and it would silently SUPPRESS the
106
+ * advisory — fail-quiet, the worst direction. Build metadata is ignored (§10).
107
+ *
108
+ * Returns <0 / 0 / >0. An unparseable version sorts as equal, so a garbage
109
+ * "latest" fails soft to silence rather than into the report.
110
+ */
111
+ export function compareSemver(a, b) {
112
+ const pa = parseSemver(a);
113
+ const pb = parseSemver(b);
114
+ if (pa === null || pb === null)
115
+ return 0;
116
+ for (let i = 0; i < 3; i += 1) {
117
+ const d = pa.core[i] - pb.core[i];
118
+ if (d !== 0)
119
+ return d < 0 ? -1 : 1;
120
+ }
121
+ return comparePrerelease(pa.prerelease, pb.prerelease);
122
+ }
123
+ /**
124
+ * The latest published version, or `null` on ANY failure (unreachable, aborted
125
+ * past the timeout, non-200, unparseable, absurd body).
126
+ *
127
+ * A bare public GET for a version string: no `Authorization`, no token, no PII,
128
+ * no store contents. `redirect: "error"` keeps it pinned to the ONE declared
129
+ * host — a probe that follows a redirect off ClawHub is out of contract.
130
+ */
131
+ export async function probeLatestVersion(fetchImpl = fetch, timeoutMs = PROBE_TIMEOUT_MS) {
132
+ const controller = new AbortController();
133
+ let timer;
134
+ // The deadline RESOLVES the race — it does not merely abort the signal.
135
+ // Aborting alone would leave the bound in the transport's hands: a channel
136
+ // that blackholes the connection and ignores the signal would hang the whole
137
+ // diagnosis forever, and the doctor is needed most when the network is sick.
138
+ // We still abort, so a well-behaved fetch releases its socket promptly.
139
+ const deadline = new Promise((resolve) => {
140
+ timer = setTimeout(() => {
141
+ controller.abort();
142
+ resolve(null);
143
+ }, timeoutMs);
144
+ });
145
+ const request = (async () => {
146
+ const res = await fetchImpl(CLAWHUB_PACKAGE_URL, {
147
+ signal: controller.signal,
148
+ headers: { accept: "application/json" },
149
+ redirect: "error",
150
+ });
151
+ if (!res.ok)
152
+ return null;
153
+ const body = await res.json();
154
+ const pkg = body?.package;
155
+ // `latestVersion ?? tags.latest` — the resolution ClawHub's own CLI does.
156
+ // A real body carries both in agreement; only the tag is a real shape too.
157
+ const latest = pkg?.latestVersion ?? pkg?.tags?.latest;
158
+ // The registry's string is used for ONE comparison and ONE report string —
159
+ // never a path, never a URL to follow, never eval'd, never written to disk.
160
+ return typeof latest === "string" && SEMVER_RE.test(latest.trim())
161
+ ? latest.trim()
162
+ : null;
163
+ })().catch(() => null); // Any failure is silence — and never an unhandled
164
+ // rejection when the deadline already won the race.
165
+ try {
166
+ return await Promise.race([request, deadline]);
167
+ }
168
+ finally {
169
+ clearTimeout(timer);
170
+ }
171
+ }
172
+ /**
173
+ * The drift-only advisory: a finding IFF installed < latest.
174
+ *
175
+ * Three states emit nothing — up to date, installed NEWER than published (a
176
+ * local/dev build; never advise a downgrade), and `latest === null` (probe
177
+ * failed/offline). Silence honestly means "no update indicated". The installed
178
+ * version still reports as `DoctorReport.installedVersion` — that fact is local
179
+ * and was never in doubt.
180
+ *
181
+ * `info` severity: being a release behind is not a degradation — the installed
182
+ * plugin works exactly as well the minute after a newer one publishes as the
183
+ * minute before. Anything higher turns every install permanently yellow the
184
+ * moment we publish, and the `healthy` roll-up stops meaning anything.
185
+ */
186
+ /**
187
+ * A single `>=X.Y.Z` floor — the ONLY range shape we parse.
188
+ *
189
+ * Every range we declare is exactly this (`package.json#openclaw.compat`), which
190
+ * is the whole licence for a ~20-line tuple compare instead of a `semver`
191
+ * dependency. The licence holds only because anything else FAILS CLOSED: a
192
+ * caret/tilde/OR/range-pair parsed "approximately" is how a working host gets
193
+ * told to update. No prerelease floor, no wildcards, no compound ranges — if we
194
+ * ever declare one for real, this parser grows to meet it FIRST.
195
+ */
196
+ const GATEWAY_RANGE_RE = /^>=(\d+\.\d+\.\d+)$/;
197
+ /**
198
+ * Our declared minimum gateway version, or `null` when it is absent or not a
199
+ * bare `>=X.Y.Z`.
200
+ *
201
+ * Read from `package.json#openclaw.compat` (not the manifest): compat lives ONLY
202
+ * there, and `package.json` is the source of truth `sync-version.mjs` mirrors
203
+ * outward. Unlike `readInstalledVersion()` this never throws — an unreadable
204
+ * floor is inconclusive, and a compat check that threw would be a worse failure
205
+ * than the one it diagnoses.
206
+ */
207
+ function readDeclaredGatewayRange() {
208
+ try {
209
+ const parsed = JSON.parse(readFileSync(PACKAGE_JSON_PATH, "utf8"));
210
+ const range = parsed.openclaw?.compat?.minGatewayVersion;
211
+ return typeof range === "string" ? range : null;
212
+ }
213
+ catch {
214
+ return null;
215
+ }
216
+ }
217
+ /**
218
+ * The host-compat advisory: a finding IFF the RUNNING gateway is below our
219
+ * declared floor. Local, synchronous, no probe — the question is "is my host new
220
+ * enough for me?", not "am I current?", so nothing here touches the network and
221
+ * it still fires with the network down.
222
+ *
223
+ * FAILS CLOSED TO INCONCLUSIVE — `null` (no finding) whenever we cannot be sure:
224
+ * an unreadable host version (`readHostVersion` → null), a host that is not
225
+ * semver, or a range we do not fully understand. Never a fabricated verdict in
226
+ * either direction: "your host is too old" is not something a user can un-learn,
227
+ * and a silent "you're fine" dressed up as a real check is worse.
228
+ *
229
+ * `warn`, not `info`: unlike a version-behind, this install may genuinely not
230
+ * run — that IS a degradation. Not `critical`: by the doctor's ladder that means
231
+ * the core path is broken, and a plugin that broken could not run a tool to say
232
+ * so.
233
+ */
234
+ export function buildGatewayCompatFinding(hostVersion, requiredRange = readDeclaredGatewayRange()) {
235
+ if (hostVersion === null || requiredRange === null)
236
+ return null;
237
+ const required = GATEWAY_RANGE_RE.exec(requiredRange.trim())?.[1];
238
+ if (required === undefined)
239
+ return null;
240
+ // Parse-check the host explicitly rather than leaning on compareSemver's
241
+ // unparseable-sorts-equal rule: silence must be a decision here, not a
242
+ // by-product of a comparator contract that exists for a different caller.
243
+ if (!SEMVER_RE.test(hostVersion.trim()))
244
+ return null;
245
+ if (compareSemver(hostVersion.trim(), required) >= 0)
246
+ return null;
247
+ return {
248
+ id: "version.gateway_compat",
249
+ severity: "warn",
250
+ status: "advisory",
251
+ detected: `This OpenClaw host is older than sil requires: sil needs ${required} or`
252
+ + ` newer, and the running host is ${hostVersion.trim()}. Some sil tools`
253
+ + " may not work correctly on this host.",
254
+ suggestedAction: `Update OpenClaw itself to ${required} or newer using OpenClaw's own`
255
+ + " update path, then reload. sil never updates the host and ships no"
256
+ + " installer.",
257
+ appliedAction: null,
258
+ };
259
+ }
260
+ export function buildVersionBehindFinding(installed, latest) {
261
+ if (latest === null)
262
+ return null;
263
+ if (compareSemver(installed, latest) >= 0)
264
+ return null;
265
+ return {
266
+ id: "version.plugin_behind",
267
+ severity: "info",
268
+ status: "advisory",
269
+ detected: `A newer sil plugin is published: installed ${installed}, latest ${latest}.`,
270
+ suggestedAction: "Update via OpenClaw's own plugin update path (for example"
271
+ + ` \`openclaw plugins update ${CLAWHUB_PACKAGE_NAME}\`), then reload the`
272
+ + " plugin. sil never updates itself.",
273
+ appliedAction: null,
274
+ };
275
+ }
@@ -59,6 +59,7 @@
59
59
  import { Type } from "typebox";
60
60
  import { getApiUrl } from "../lib/config.js";
61
61
  import { clearTokens, readTokens } from "../lib/credentials.js";
62
+ import { wiringAdvisories } from "../lib/host-wiring.js";
62
63
  import { lookupCatalog, refreshAndRetryOnce, searchCatalog, specsCatalog, } from "../lib/sil-client.js";
63
64
  import { jsonResult } from "../lib/tool-result.js";
64
65
  /**
@@ -380,7 +381,7 @@ function registerSearch(api) {
380
381
  function mapSearchOutcome(api, outcome) {
381
382
  switch (outcome.kind) {
382
383
  case "ok":
383
- return searchResult(outcome);
384
+ return searchResult(api, outcome);
384
385
  case "forbidden":
385
386
  // A 403 surfaces the SAME forbidden envelope `sil_whoami` emits — never the
386
387
  // false-transient `retryable`. On `user_not_provisioned` (and ONLY that exact
@@ -535,7 +536,7 @@ function registerProductGet(api) {
535
536
  function mapLookupOutcome(api, outcome) {
536
537
  switch (outcome.kind) {
537
538
  case "ok":
538
- return lookupResult(outcome);
539
+ return lookupResult(api, outcome);
539
540
  case "forbidden":
540
541
  // Symmetric with sil_search (one vocabulary, AC2/AC7/AC10): a 403 is the shared
541
542
  // forbidden envelope, and `user_not_provisioned` — and ONLY that exact reason —
@@ -678,7 +679,7 @@ function registerSpecs(api) {
678
679
  function mapSpecsOutcome(api, outcome) {
679
680
  switch (outcome.kind) {
680
681
  case "ok":
681
- return specsResult(outcome);
682
+ return specsResult(api, outcome);
682
683
  case "forbidden":
683
684
  // Symmetric with sil_search/sil_product_get (one vocabulary): a 403 is the
684
685
  // shared forbidden envelope, and `user_not_provisioned` — and ONLY that exact
@@ -715,9 +716,9 @@ function readIds(params) {
715
716
  * optional `not_found`); spread its payload (minus the `kind` discriminant) onto
716
717
  * the agent-facing `{ status: "ok", ... }` envelope. A `not_found` list is
717
718
  * partial-success DATA, NOT an error and NOT a recovery hint. */
718
- function lookupResult(outcome) {
719
+ function lookupResult(api, outcome) {
719
720
  const { kind: _kind, ...payload } = outcome;
720
- return jsonResult({ status: "ok", ...payload });
721
+ return jsonResult({ status: "ok", ...payload, ...wiringAdvisories(api) });
721
722
  }
722
723
  /** Client-side validation: the request named no usable id. Distinct from a sil-api
723
724
  * 400 (which carries the server's structured error) — this never hit the network.
@@ -1034,9 +1035,9 @@ function hasUsableInput(params) {
1034
1035
  * An empty `products` list is a valid, successful empty match. The `ok` outcome
1035
1036
  * already carries `products` (+ optional `cursor`); spread its payload (minus the
1036
1037
  * `kind` discriminant) onto the agent-facing `{ status: "ok", ... }` envelope. */
1037
- function searchResult(outcome) {
1038
+ function searchResult(api, outcome) {
1038
1039
  const { kind: _kind, ...payload } = outcome;
1039
- return jsonResult({ status: "ok", ...payload });
1040
+ return jsonResult({ status: "ok", ...payload, ...wiringAdvisories(api) });
1040
1041
  }
1041
1042
  /** Not registered: a distinct, actionable outcome naming the recovery tool. No
1042
1043
  * products field so the agent can't mistake it for an empty match. The `tool`
@@ -1094,9 +1095,9 @@ function invalidSpec(field) {
1094
1095
  /** Success: the resolved canonicalizations — no token, no Bearer header. The `ok`
1095
1096
  * outcome carries `resolved` directly; spread its payload (minus the `kind`
1096
1097
  * discriminant) onto the agent-facing `{ status: "ok", resolved }` envelope. */
1097
- function specsResult(outcome) {
1098
+ function specsResult(api, outcome) {
1098
1099
  const { kind: _kind, ...payload } = outcome;
1099
- return jsonResult({ status: "ok", ...payload });
1100
+ return jsonResult({ status: "ok", ...payload, ...wiringAdvisories(api) });
1100
1101
  }
1101
1102
  /** Client-side validation: no usable canonicalization input (a blank `query` or an
1102
1103
  * empty/all-dropped `specs`). Distinct from a sil-api 400 — this never hit the