@tpsdev-ai/flair 0.54.2 → 0.55.1

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 (60) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +86 -1
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +62 -7
  10. package/dist/commands/upgrade.js +6 -0
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/hook-install.js +170 -16
  13. package/dist/lib/doctor-run.js +49 -3
  14. package/dist/lib/embed-gpu-doctor.js +63 -0
  15. package/dist/lib/federation-pair-access.js +118 -0
  16. package/dist/lib/harper-port-value.js +43 -0
  17. package/dist/lib/http-bind.js +227 -0
  18. package/dist/lib/init-admin-pass.js +316 -0
  19. package/dist/lib/launchd-management.js +16 -0
  20. package/dist/lib/launchd-repair.js +122 -1
  21. package/dist/lib/owned-pins.js +54 -1
  22. package/dist/lib/process-start-time.js +82 -0
  23. package/dist/lib/scratch-owner.js +124 -10
  24. package/dist/lib/stale-client-pin.js +26 -0
  25. package/dist/lib/upgrade-plain-tree.js +293 -48
  26. package/dist/rem/runner.js +10 -1
  27. package/dist/resources/AdminInstance.js +8 -2
  28. package/dist/resources/Memory.js +36 -1
  29. package/dist/resources/MemoryBootstrap.js +23 -32
  30. package/dist/resources/MemoryFeed.js +4 -1
  31. package/dist/resources/MemoryReflect.js +121 -93
  32. package/dist/resources/SkillScan.js +13 -11
  33. package/dist/resources/Soul.js +15 -1
  34. package/dist/resources/XAA.js +16 -1
  35. package/dist/resources/a2a-url.js +5 -2
  36. package/dist/resources/client-version-gate.js +144 -0
  37. package/dist/resources/embed-gpu.js +241 -0
  38. package/dist/resources/embeddings-boot.js +34 -42
  39. package/dist/resources/federation-peer-liveness.js +7 -1
  40. package/dist/resources/health.js +12 -3
  41. package/dist/resources/memory-reflect-lib.js +66 -0
  42. package/dist/resources/memory-reflect-models.js +9 -0
  43. package/dist/resources/migrations/embedding-stamp.js +32 -4
  44. package/dist/resources/oauth-discovery.js +3 -1
  45. package/dist/resources/record-type-kit.js +59 -0
  46. package/dist/resources/scan/skill-markdown.js +166 -0
  47. package/dist/resources/scan/skill-scanner.js +89 -68
  48. package/dist/resources/skill-provenance.js +273 -0
  49. package/dist/resources/skill-write.js +26 -7
  50. package/dist/src/lib/harper-port-value.js +43 -0
  51. package/docs/api-reference.md +35 -2
  52. package/docs/deployment.md +39 -6
  53. package/docs/federation.md +18 -7
  54. package/docs/mcp-clients.md +19 -6
  55. package/docs/releasing.md +79 -13
  56. package/docs/rem.md +1 -1
  57. package/docs/secrets-and-keys.md +1 -0
  58. package/docs/standalone-local.md +8 -5
  59. package/docs/troubleshooting.md +17 -0
  60. package/package.json +1 -1
@@ -135,6 +135,8 @@
135
135
  */
136
136
  import { databases } from "harper";
137
137
  import { getModelId } from "../embeddings-provider.js";
138
+ import { harperPortValue } from "../../src/lib/harper-port-value.js";
139
+ import { DEFAULT_HTTP_PORT } from "../a2a-url.js";
138
140
  import { currentSpaceRawForms, isCurrentSpaceStamp } from "../embedding-space-guard.js";
139
141
  import { EMBEDDING_STAMP_ID } from "./stamp-outstanding.js";
140
142
  export { EMBEDDING_STAMP_ID };
@@ -149,10 +151,36 @@ function resolveAdminAuthHeader() {
149
151
  return null;
150
152
  return "Basic " + Buffer.from(`admin:${pass}`).toString("base64");
151
153
  }
152
- /** Same HTTP_PORT env resolution src/cli.ts sets on every Harper spawn (see that file's grep for HTTP_PORT). */
153
- function resolveSelfBaseUrl() {
154
- const port = process.env.HTTP_PORT ?? "9926";
155
- return `http://127.0.0.1:${port}`;
154
+ /**
155
+ * Base URL for the loopback self-call that regenerates an embedding.
156
+ *
157
+ * ALWAYS loopback. This is the destination of a credentialed self-call —
158
+ * `regenViaHttpPut` sends `Authorization: Basic` carrying the admin password to
159
+ * it — so it must never leave the box. `FLAIR_PUBLIC_URL` names a remote /
160
+ * reverse-proxied origin and is deliberately ignored here, matching
161
+ * `a2a-url.localBaseUrl` ("never the public/proxy URL"): two self-call
162
+ * resolvers, both pinned to loopback. The public-facing resolvers (e.g.
163
+ * oauth-discovery, AdminInstance, XAA; also a2a-url.resolvePublicBaseUrl and
164
+ * the MCP issuer resolvers) honour `FLAIR_PUBLIC_URL` precisely because their
165
+ * output is meant to be reachable off-box; this one's output is not. That list
166
+ * is illustrative, not exhaustive — the deciding question is whether the URL
167
+ * leaves the box, not a roster of call sites.
168
+ *
169
+ * Pinned by the "loopback self-call target" suite in
170
+ * test/unit/host-qualified-port-consumers.test.ts, which asserts this returns
171
+ * loopback even when `FLAIR_PUBLIC_URL` is set (and not merely that it parses).
172
+ *
173
+ * `HTTP_PORT` is parsed through `harperPortValue` so a host-qualified value
174
+ * (`127.0.0.1:19926`) yields a valid URL rather than a doubled host. Absent
175
+ * (or out-of-range) falls back to `DEFAULT_HTTP_PORT` (19926) — NOT the legacy
176
+ * early-install 9926 this used to reach for. 9926 is Harper's OWN default bind,
177
+ * which is what the one boot shape that reaches this fallback actually uses: a
178
+ * bare `harper run .` that flair did not spawn. On a pre-March data dir that
179
+ * 9926 coincidentally matched the real bind; post-March 19926 does. Both are
180
+ * guesses — `HTTP_PORT` is the only channel carrying the truth.
181
+ */
182
+ export function resolveSelfBaseUrl(env = process.env) {
183
+ return `http://127.0.0.1:${harperPortValue(env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
156
184
  }
157
185
  /**
158
186
  * Triggers Memory.put()'s regen branch via a genuine loopback HTTP PUT —
@@ -28,6 +28,8 @@
28
28
  */
29
29
  import { mcpOAuthEnabled } from "./mcp-oauth-flag.js";
30
30
  import { dcrEnabled } from "./dcr-gate.js";
31
+ import { harperPortValue } from "../src/lib/harper-port-value.js";
32
+ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
31
33
  /** RFC 9728 §3.1 — Protected Resource Metadata well-known path. */
32
34
  export const PRM_PATH = "/.well-known/oauth-protected-resource";
33
35
  /** RFC 8414 §3 — Authorization Server Metadata well-known path. */
@@ -39,7 +41,7 @@ export const AS_METADATA_PATH = "/.well-known/oauth-authorization-server";
39
41
  * existed — moved, not changed. See the header note on flair#1005.
40
42
  */
41
43
  export function oauthPublicBaseUrl() {
42
- return process.env.FLAIR_PUBLIC_URL || `http://127.0.0.1:${process.env.HTTP_PORT || 19926}`;
44
+ return process.env.FLAIR_PUBLIC_URL || `http://127.0.0.1:${harperPortValue(process.env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
43
45
  }
44
46
  /**
45
47
  * The RFC 8707 resource identifier of flair's MCP surface: `<base>/mcp`.
@@ -292,6 +292,65 @@ export function makeScopedSearch(readScope) {
292
292
  export function stampAttribution(auth, content, field, mode, forbiddenMessage) {
293
293
  if (auth.kind !== "agent")
294
294
  return {}; // internal → always passthrough
295
+ // KNOWN, DATED ASYMMETRY (2026-09-18, tracked as flair#1741 — do not
296
+ // "fix" here; that change wants its own design pass):
297
+ //
298
+ // An admin AGENT KEY (a TPS-Ed25519 signature whose principal is in the
299
+ // admin set) is treated as an OPERATOR on this branch: every kit table's
300
+ // write path honors a body-supplied owner field from it (or defaults it
301
+ // under "stamp-default") rather than stamping the caller's own identity.
302
+ // agent-auth.ts resolves such a key and credentialed Basic super_user
303
+ // ALIKE to `isAdmin: true`, but from different evidence — the key's
304
+ // boolean is the middleware-computed `tpsAgentIsAdmin` annotation, the
305
+ // Basic one a `user.role.permission.super_user` role claim — and the
306
+ // verdict cannot tell which evidence produced it. That predates #1537's
307
+ // source-class model, which adopted the OPPOSITE rule for Soul — "Role
308
+ // is not source: an admin agent key or delegated OAuth identity is still
309
+ // a runtime credential. Only verified Basic admin auth enters the
310
+ // operator path" (resources/soul-write-policy.ts) — and this branch has
311
+ // NOT been re-adjudicated against it. Both controls were deliberate;
312
+ // nobody propagated the newer rule backward. That is policy drift, not
313
+ // code drift.
314
+ //
315
+ // WRITE reach, so this is taken seriously and not read as a Soul-only
316
+ // concern: this branch sits BEFORE the mode switch, so it covers EVERY
317
+ // kit call site in EVERY mode — Memory, MemoryFeed, Credential, OrgEvent,
318
+ // Relationship, WorkspaceState, Asset and MemoryCandidate. Soul is
319
+ // protected only because its source gate (authorizeSoulWrite) lives
320
+ // OUTSIDE the kit and re-reads the raw Authorization header before
321
+ // stampAttribution is ever reached.
322
+ //
323
+ // READ reach — the SAME `isAdmin` boolean is also the READ authorization
324
+ // in this kit, so the exposure is unfiltered reads of owner-scoped data,
325
+ // not just forged provenance on writes: resolveAuthGate returns
326
+ // { kind: "unfiltered" } for admin (the verdict that also dispatches the
327
+ // Asset/MemoryCandidate/OrgEvent delete() paths), makeByIdReadGate
328
+ // returns superGet(target) with no ownership check, Credential.search()/
329
+ // get() branch on the same verdict out-of-kit (Credential.ts), and
330
+ // Message.ts hand-rolls the identical branch inline. With an admin agent
331
+ // key, that reads: MemoryCandidate rows whose contract is "a candidate
332
+ // must not be org-readable before a human/agent reviewer explicitly
333
+ // promotes or rejects it" (record-types.ts); other principals' Credential
334
+ // rows — get() strips tokenHash but returns the metadata, and search()'s
335
+ // admin branch strips NOTHING (the strip lives only in get()); and every
336
+ // Message in the table. Provenance integrity AND confidentiality, one
337
+ // root cause: the verdict conflates a runtime credential with the
338
+ // operator. Same fix — #1741's credential class.
339
+ //
340
+ // PINNING: the behaviour is pinned, but only as behaviour, and every pin
341
+ // passes `isAdmin` as a bare boolean (`agentCtx("agent-admin", true)`)
342
+ // because the code cannot express the credential distinction. Writes —
343
+ // record-type-kit.test.ts's "admin → always passthrough" (validate-
344
+ // truthy and validate-strict), "admin + field absent → default-if-absent
345
+ // (||=)" (stamp-default) and "admin → passthrough, NO default-if-absent"
346
+ // (stamp-strict). Reads — the same file's "admin agent → unfiltered via
347
+ // superGet, no ownership check" and "admin agent → unfiltered", plus
348
+ // memory-candidate-read-gate.test.ts's "admin agent → returns any id
349
+ // unchanged, no ownership check" and "an admin agent sees every
350
+ // candidate, unfiltered". Soul's out-of-kit gate — the TPS-Ed25519-
351
+ // adminAgent-toNull line in soul-adk-refusal.test.ts. Until #1741 lands,
352
+ // "an admin agent key cannot read X" is UNTESTABLE — the read path's
353
+ // credential-class property is pinned by nothing today.
295
354
  if (auth.isAdmin) {
296
355
  if (mode === "stamp-default")
297
356
  content[field] ||= auth.agentId;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Classify SKILL.md into scan regions before SkillScan runs.
3
+ *
4
+ * Well-formed markdown inline code and fenced blocks are documentation —
5
+ * they are how a document *names* a command, not a substitution a loader
6
+ * would execute. Frontmatter, prose, and unclosed/unmatched leftovers are
7
+ * the executable surfaces (fail-closed when the parse is unsure).
8
+ *
9
+ * Pure module: no Harper runtime deps. Used by skill-scanner.ts and unit
10
+ * tests.
11
+ */
12
+ const FENCE_RE = /^[ \t]*(`{3,}|~{3,})([\w.-]*)[ \t]*$/;
13
+ export function isDocsSpan(kind) {
14
+ return kind === "inline_code" || kind === "fenced_code";
15
+ }
16
+ export function isExecutableSpan(kind) {
17
+ return kind === "frontmatter" || kind === "prose" || kind === "unclosed";
18
+ }
19
+ export function isFenceMarkerLine(text) {
20
+ return FENCE_RE.test(text);
21
+ }
22
+ /**
23
+ * Split SKILL.md into classified spans. A line may produce several spans
24
+ * (prose around inline code). Unclosed fences and unmatched backtick runs
25
+ * are `unclosed` so the scanner can stay fail-closed.
26
+ */
27
+ /**
28
+ * YAML frontmatter is a `---` … `---` pair. It is usually the first line,
29
+ * but `skillScanGate` prepends `trigger` + a blank line, so the pair sits
30
+ * after leading prose. Treat that pair as frontmatter too — otherwise
31
+ * `$(...)` wrapped in inline code inside YAML is parsed as docs and the
32
+ * write gate can allow a payload the raw SKILL.md still scores high.
33
+ *
34
+ * A pair after a blank line with no closer is a thematic break, not
35
+ * frontmatter. Mis-identifying a hr pair as frontmatter is fail-closed
36
+ * (those lines are scanned as executable).
37
+ */
38
+ function findFrontmatterRange(lines) {
39
+ const starts = [];
40
+ if (lines[0] === "---")
41
+ starts.push(0);
42
+ for (let i = 1; i < lines.length; i++) {
43
+ if (lines[i] === "---" && lines[i - 1] === "") {
44
+ starts.push(i);
45
+ break;
46
+ }
47
+ }
48
+ for (const start of starts) {
49
+ for (let j = start + 1; j < lines.length; j++) {
50
+ if (lines[j] === "---")
51
+ return { start, end: j };
52
+ }
53
+ }
54
+ return null;
55
+ }
56
+ export function classifySkillMarkdown(content) {
57
+ const lines = content.split("\n");
58
+ const spans = [];
59
+ let i = 0;
60
+ const fm = findFrontmatterRange(lines);
61
+ if (fm) {
62
+ for (let j = 0; j < fm.start; j++) {
63
+ spans.push(...splitProseLine(lines[j] ?? "", j + 1));
64
+ }
65
+ for (let j = fm.start; j <= fm.end; j++) {
66
+ spans.push({ kind: "frontmatter", line: j + 1, text: lines[j] ?? "" });
67
+ }
68
+ i = fm.end + 1;
69
+ }
70
+ let fence = null;
71
+ for (; i < lines.length; i++) {
72
+ const line = lines[i] ?? "";
73
+ const m = line.match(FENCE_RE);
74
+ if (m) {
75
+ const marker = m[1] ?? "";
76
+ const lang = (m[2] || "").toLowerCase();
77
+ const char = marker[0] ?? "`";
78
+ if (!fence) {
79
+ fence = {
80
+ char,
81
+ len: marker.length,
82
+ lang,
83
+ buf: [{ kind: "fenced_code", line: i + 1, text: line, lang }],
84
+ };
85
+ continue;
86
+ }
87
+ // CommonMark: a closing fence is the same char, at least as long, and
88
+ // has no info string.
89
+ if (char === fence.char && marker.length >= fence.len && !lang) {
90
+ spans.push(...fence.buf, {
91
+ kind: "fenced_code",
92
+ line: i + 1,
93
+ text: line,
94
+ lang: fence.lang,
95
+ });
96
+ fence = null;
97
+ continue;
98
+ }
99
+ }
100
+ if (fence) {
101
+ fence.buf.push({
102
+ kind: "fenced_code",
103
+ line: i + 1,
104
+ text: line,
105
+ lang: fence.lang,
106
+ });
107
+ continue;
108
+ }
109
+ spans.push(...splitProseLine(line, i + 1));
110
+ }
111
+ if (fence) {
112
+ // Unclosed fence: fail-closed — treat marker + body as executable.
113
+ for (const s of fence.buf)
114
+ s.kind = "unclosed";
115
+ spans.push(...fence.buf);
116
+ }
117
+ return spans;
118
+ }
119
+ function splitProseLine(line, lineNo) {
120
+ const out = [];
121
+ let i = 0;
122
+ while (i < line.length) {
123
+ if (line[i] === "`") {
124
+ let n = 0;
125
+ while (i + n < line.length && line[i + n] === "`")
126
+ n++;
127
+ const close = findClosingBackticks(line, i + n, n);
128
+ if (close === -1) {
129
+ out.push({ kind: "unclosed", line: lineNo, text: line.slice(i) });
130
+ return out;
131
+ }
132
+ out.push({
133
+ kind: "inline_code",
134
+ line: lineNo,
135
+ text: line.slice(i, close + n),
136
+ });
137
+ i = close + n;
138
+ }
139
+ else {
140
+ const next = line.indexOf("`", i);
141
+ const end = next === -1 ? line.length : next;
142
+ out.push({ kind: "prose", line: lineNo, text: line.slice(i, end) });
143
+ i = end;
144
+ }
145
+ }
146
+ if (out.length === 0)
147
+ out.push({ kind: "prose", line: lineNo, text: line });
148
+ return out;
149
+ }
150
+ function findClosingBackticks(line, from, n) {
151
+ let i = from;
152
+ while (i < line.length) {
153
+ if (line[i] === "`") {
154
+ let m = 0;
155
+ while (i + m < line.length && line[i + m] === "`")
156
+ m++;
157
+ if (m === n)
158
+ return i;
159
+ i += m;
160
+ }
161
+ else {
162
+ i++;
163
+ }
164
+ }
165
+ return -1;
166
+ }
@@ -6,9 +6,21 @@
6
6
  * separate module lets the tests run without instantiating the Harper
7
7
  * runtime.
8
8
  *
9
- * See SkillScan.ts for the design rationale on markdown awareness and the
10
- * language-agnostic vs shell-only pattern split.
9
+ * Markdown is classified first (`./skill-markdown.ts`). Well-formed inline
10
+ * code and fenced blocks are documentation for `shell_backtick` — naming
11
+ * a command is not a substitution. The scanner still runs the non-backtick
12
+ * detectors (exec/fetch/writeFile/encoding) on inline and fenced interiors,
13
+ * because wrapping `exec(...)` in one backtick does not stop it being a
14
+ * payload. Prose, YAML frontmatter, and unclosed leftovers are fully
15
+ * scanned. Unicode/homoglyphs always run on the raw line.
16
+ *
17
+ * `shell_backtick` means a substitution the loader would see (`$(...)` in
18
+ * an executable surface, an unmatched backtick run, or any backtick in
19
+ * YAML frontmatter — YAML backticks are legacy shell substitution, not
20
+ * markdown docs). It does not mean "this line contains a markdown code
21
+ * span."
11
22
  */
23
+ import { classifySkillMarkdown, isExecutableSpan, isFenceMarkerLine, } from "./skill-markdown.js";
12
24
  const SHELL_PATTERNS = [
13
25
  { regex: /\bexec\s*\(/, type: "shell_command" },
14
26
  { regex: /\bspawn\s*\(/, type: "shell_command" },
@@ -44,62 +56,32 @@ const UNICODE_PATTERNS = [
44
56
  { regex: /[​-‏⁠]/, type: "zero_width_char" },
45
57
  { regex: /[А-я]/, type: "cyrillic_homoglyph" },
46
58
  ];
47
- const LANG_AGNOSTIC_PATTERNS = [
59
+ /** Network, fs, env, and encoding. Unicode always scans the raw line. */
60
+ const CONTENT_HAZARD_PATTERNS = [
48
61
  ...NETWORK_PATTERNS,
49
62
  ...FS_PATTERNS,
50
63
  ...ENV_PATTERNS,
51
64
  ...ENCODING_PATTERNS,
52
- ...UNICODE_PATTERNS,
53
65
  ];
54
66
  const SHELL_FENCE_LANGS = new Set(["", "sh", "bash", "shell", "zsh"]);
55
- const MARKDOWN_IDENTIFIER_RE = /^[\w@./-]+$/;
56
- const SHELL_BACKTICK_INDICATORS = [
57
- /\s/,
58
- /[|;&]/,
59
- /\$\(/,
60
- /\$\{/,
61
- /^\$\w/,
62
- />/,
63
- /<\(/,
64
- ];
65
- function lineHasShellishBacktick(line) {
66
- const matches = line.match(/`([^`\n]+)`/g);
67
- if (!matches)
68
- return false;
69
- for (const raw of matches) {
70
- const inner = raw.slice(1, -1);
71
- if (MARKDOWN_IDENTIFIER_RE.test(inner))
72
- continue;
73
- for (const indicator of SHELL_BACKTICK_INDICATORS) {
74
- if (indicator.test(inner))
75
- return true;
76
- }
77
- }
78
- return false;
79
- }
80
- function assessRisk(violations) {
67
+ export function assessRisk(violations) {
81
68
  if (violations.length === 0)
82
69
  return "low";
83
70
  const types = new Set(violations.map((v) => v.type));
84
- // Programmatic shell call patterns: exec/spawn/system/child_process. These
85
- // are definite payloads when they appear in a skill.
86
71
  const hasShellCommand = types.has("shell_command");
87
- // Backticked shell-ish content in markdown prose. Could be `npm run deploy`
88
- // in documentation (medium), or could combine with other smells (high).
72
+ // shell_backtick is a substitution on an executable surface, not a
73
+ // markdown code span. Alone it is still reviewable; with other smells
74
+ // it is a payload.
89
75
  const hasShellBacktick = types.has("shell_backtick");
90
76
  const hasFs = types.has("fs_write") || types.has("fs_redirect");
91
77
  const hasEncoding = types.has("base64_decode") || types.has("hex_decode");
92
78
  const hasZeroWidth = types.has("zero_width_char");
93
79
  const hasHomoglyph = types.has("cyrillic_homoglyph");
94
- // Critical: any shell combined with encoded payloads, OR obfuscation chars.
95
80
  if (((hasShellCommand || hasShellBacktick) && hasEncoding) ||
96
81
  hasZeroWidth ||
97
82
  hasHomoglyph) {
98
83
  return "critical";
99
84
  }
100
- // High: programmatic shell, fs writes, or shell-backtick + other smells
101
- // (env access, network call). A skill that quotes a command AND reads env
102
- // AND fetches a URL is doing something, not just documenting.
103
85
  const hasOtherSmells = types.has("env_access") ||
104
86
  types.has("env_variable") ||
105
87
  types.has("network_call") ||
@@ -107,60 +89,99 @@ function assessRisk(violations) {
107
89
  if (hasShellCommand || hasFs || (hasShellBacktick && hasOtherSmells)) {
108
90
  return "high";
109
91
  }
110
- // Medium: shell_backtick alone (doc reference), or network/encoding
111
- // without shell. Reviewable but not blocked.
112
92
  if (hasShellBacktick || hasOtherSmells || hasEncoding) {
113
93
  return "medium";
114
94
  }
115
95
  return "low";
116
96
  }
117
- function detectFenceTransition(line, state) {
118
- const m = line.match(/^[ \t]*```([\w.-]*)\s*$/);
119
- if (!m)
120
- return false;
121
- if (state.inFence) {
122
- state.inFence = false;
123
- state.lang = "";
124
- }
125
- else {
126
- state.inFence = true;
127
- state.lang = (m[1] || "").toLowerCase();
128
- }
129
- return true;
97
+ function executableText(spans) {
98
+ return spans.filter((s) => isExecutableSpan(s.kind)).map((s) => s.text).join("");
99
+ }
100
+ function hasCommandSubstitution(text) {
101
+ return /\$\(/.test(text);
130
102
  }
131
103
  export function scanSkillContent(content) {
132
104
  const lines = content.split("\n");
105
+ const spans = classifySkillMarkdown(content);
133
106
  const violations = [];
134
- const fence = { inFence: false, lang: "" };
135
- const recordIfMatch = (lineIndex, line, patterns) => {
107
+ const recordIfMatch = (lineIndex, text, patterns) => {
108
+ const original = (lines[lineIndex] ?? "").trim().slice(0, 200);
136
109
  for (const pattern of patterns) {
137
- if (pattern.regex.test(line)) {
110
+ if (pattern.regex.test(text)) {
138
111
  violations.push({
139
112
  type: pattern.type,
140
113
  line: lineIndex + 1,
141
- content: line.trim().slice(0, 200),
114
+ content: original || text.trim().slice(0, 200),
142
115
  });
143
116
  }
144
117
  }
145
118
  };
119
+ // Obfuscation is never "documentation format" — scan the raw line.
146
120
  for (let i = 0; i < lines.length; i++) {
147
- const line = lines[i] ?? "";
148
- if (detectFenceTransition(line, fence))
121
+ recordIfMatch(i, lines[i] ?? "", UNICODE_PATTERNS);
122
+ }
123
+ const byLine = new Map();
124
+ for (const span of spans) {
125
+ const list = byLine.get(span.line) ?? [];
126
+ list.push(span);
127
+ byLine.set(span.line, list);
128
+ }
129
+ for (const [lineNo, lineSpans] of byLine) {
130
+ const lineIndex = lineNo - 1;
131
+ const allFence = lineSpans.every((s) => s.kind === "fenced_code");
132
+ const rawLine = lineSpans[0]?.text ?? "";
133
+ if (allFence && isFenceMarkerLine(rawLine))
134
+ continue;
135
+ if (allFence) {
136
+ const lang = lineSpans[0]?.lang ?? "";
137
+ const text = lineSpans.map((s) => s.text).join("");
138
+ if (SHELL_FENCE_LANGS.has(lang)) {
139
+ recordIfMatch(lineIndex, text, SHELL_PATTERNS);
140
+ }
141
+ recordIfMatch(lineIndex, text, CONTENT_HAZARD_PATTERNS);
149
142
  continue;
150
- const insideShellFence = fence.inFence && SHELL_FENCE_LANGS.has(fence.lang);
151
- const insideNonShellFence = fence.inFence && !insideShellFence;
152
- if (!fence.inFence && lineHasShellishBacktick(line)) {
143
+ }
144
+ const exec = executableText(lineSpans);
145
+ const inline = lineSpans
146
+ .filter((s) => s.kind === "inline_code")
147
+ .map((s) => s.text)
148
+ .join("");
149
+ const hasUnclosed = lineSpans.some((s) => s.kind === "unclosed");
150
+ const execSpans = lineSpans.filter((s) => isExecutableSpan(s.kind));
151
+ // Frontmatter is an executable surface. A backtick pair there is YAML
152
+ // legacy shell substitution, not markdown documentation (Kern: the
153
+ // $()-less `curl … | sh` / `rm -rf /` variants must not walk past the
154
+ // gate when the $() form is already pinned as a refusal).
155
+ const frontmatterBacktick = execSpans.length > 0 &&
156
+ execSpans.every((s) => s.kind === "frontmatter") &&
157
+ exec.includes("`");
158
+ // shell_backtick is format-vs-hazard on prose: only unclosed runs and
159
+ // $(...). A named command in a well-formed markdown span is docs.
160
+ if (hasUnclosed || hasCommandSubstitution(exec) || frontmatterBacktick) {
153
161
  violations.push({
154
162
  type: "shell_backtick",
155
- line: i + 1,
156
- content: line.trim().slice(0, 200),
163
+ line: lineNo,
164
+ content: (lines[lineIndex] ?? "").trim().slice(0, 200),
157
165
  });
158
166
  }
159
- if (!insideNonShellFence) {
160
- recordIfMatch(i, line, SHELL_PATTERNS);
161
- }
162
- recordIfMatch(i, line, LANG_AGNOSTIC_PATTERNS);
167
+ recordIfMatch(lineIndex, exec, SHELL_PATTERNS);
168
+ recordIfMatch(lineIndex, exec, CONTENT_HAZARD_PATTERNS);
169
+ // Inline interiors get the same non-backtick detectors as fenced
170
+ // interiors. One backtick around exec() is not a documentation exemption.
171
+ recordIfMatch(lineIndex, inline, SHELL_PATTERNS);
172
+ recordIfMatch(lineIndex, inline, CONTENT_HAZARD_PATTERNS);
163
173
  }
164
174
  const riskLevel = assessRisk(violations);
165
175
  return { safe: violations.length === 0, violations, riskLevel };
166
176
  }
177
+ /**
178
+ * Merge independently-scanned parts (trigger, content) and re-apply the
179
+ * combinatorial risk rules. Parsing separately stops a crafted prefix
180
+ * from stealing frontmatter; assessing the union keeps
181
+ * `shell_backtick` + URL / encoding across fields at high/critical.
182
+ */
183
+ export function combineScanResults(scans) {
184
+ const violations = scans.flatMap((s) => s.violations);
185
+ const riskLevel = assessRisk(violations);
186
+ return { safe: violations.length === 0, violations, riskLevel };
187
+ }