@tpsdev-ai/flair 0.54.1 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +73 -2
  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 +80 -8
  10. package/dist/commands/upgrade.js +41 -5
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/engine-version.js +12 -4
  13. package/dist/fabric-upgrade.js +30 -15
  14. package/dist/hook-install.js +170 -16
  15. package/dist/lib/doctor-run.js +49 -3
  16. package/dist/lib/embed-gpu-doctor.js +30 -0
  17. package/dist/lib/federation-pair-access.js +118 -0
  18. package/dist/lib/harper-port-value.js +43 -0
  19. package/dist/lib/http-bind.js +227 -0
  20. package/dist/lib/init-admin-pass.js +316 -0
  21. package/dist/lib/launchd-management.js +16 -0
  22. package/dist/lib/launchd-repair.js +122 -1
  23. package/dist/lib/npm-registry.js +578 -0
  24. package/dist/lib/owned-pins.js +54 -1
  25. package/dist/lib/process-start-time.js +82 -0
  26. package/dist/lib/scratch-owner.js +124 -10
  27. package/dist/lib/stale-client-pin.js +26 -0
  28. package/dist/rem/runner.js +10 -1
  29. package/dist/resources/AdminInstance.js +8 -2
  30. package/dist/resources/Memory.js +36 -1
  31. package/dist/resources/MemoryBootstrap.js +23 -32
  32. package/dist/resources/MemoryFeed.js +4 -1
  33. package/dist/resources/MemoryReflect.js +121 -93
  34. package/dist/resources/SkillScan.js +13 -11
  35. package/dist/resources/Soul.js +15 -1
  36. package/dist/resources/XAA.js +16 -1
  37. package/dist/resources/a2a-url.js +5 -2
  38. package/dist/resources/client-version-gate.js +144 -0
  39. package/dist/resources/embed-gpu.js +241 -0
  40. package/dist/resources/embeddings-boot.js +34 -42
  41. package/dist/resources/federation-peer-liveness.js +7 -1
  42. package/dist/resources/health.js +12 -3
  43. package/dist/resources/mcp-tools.js +8 -3
  44. package/dist/resources/memory-reflect-lib.js +66 -0
  45. package/dist/resources/memory-reflect-models.js +9 -0
  46. package/dist/resources/migrations/embedding-stamp.js +32 -4
  47. package/dist/resources/oauth-discovery.js +3 -1
  48. package/dist/resources/record-type-kit.js +59 -0
  49. package/dist/resources/scan/skill-markdown.js +166 -0
  50. package/dist/resources/scan/skill-scanner.js +89 -68
  51. package/dist/resources/skill-provenance.js +273 -0
  52. package/dist/resources/skill-write.js +26 -7
  53. package/{node_modules/@tpsdev-ai/flair-tool-descriptors/dist → dist/resources/tool-descriptors}/index.js +4 -0
  54. package/dist/src/lib/harper-port-value.js +43 -0
  55. package/dist/version-check.js +29 -8
  56. package/docs/api-reference.md +35 -2
  57. package/docs/deployment.md +1 -1
  58. package/docs/federation.md +18 -7
  59. package/docs/mcp-clients.md +19 -6
  60. package/docs/releasing.md +96 -24
  61. package/docs/rem.md +1 -1
  62. package/docs/secrets-and-keys.md +1 -0
  63. package/docs/standalone-local.md +1 -1
  64. package/docs/troubleshooting.md +17 -0
  65. package/package.json +4 -9
  66. package/node_modules/@tpsdev-ai/flair-tool-descriptors/LICENSE +0 -19
  67. package/node_modules/@tpsdev-ai/flair-tool-descriptors/README.md +0 -22
  68. package/node_modules/@tpsdev-ai/flair-tool-descriptors/dist/index.d.ts +0 -70
  69. package/node_modules/@tpsdev-ai/flair-tool-descriptors/package.json +0 -46
@@ -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
+ }
@@ -0,0 +1,273 @@
1
+ /**
2
+ * skill-provenance.ts — durable source + stated conflict outcome (flair#1433).
3
+ *
4
+ * Two defects, two functions, no Harper imports:
5
+ *
6
+ * 1. Registration: a skill-assignment (Soul key `skill-assignment`) whose
7
+ * `metadata.source` is a filesystem path under a temp directory is not
8
+ * provenance. `registerSkillAssignment` / `refuseSkillAssignmentWrite`
9
+ * fail and name the path. Scratch/inspect paths (`/tmp/...-inspect/...`)
10
+ * are the known-answer case from the 2026-08-26 flint bootstrap payload.
11
+ *
12
+ * 2. Load: `SKILL_CONFLICT` must decide something. Skills are identified by
13
+ * `value` (name). Priority is stated precedence (critical > high >
14
+ * standard > low). A unique highest priority loads; an equal-priority
15
+ * tie refuses the whole name-set. Map iteration order never picks a
16
+ * winner. The payload line states the decision and why.
17
+ *
18
+ * Trust/signature is out of scope (epic #1434, later). This module does not
19
+ * invent a signing model.
20
+ *
21
+ * A normally-installed, non-conflicting skill with a durable (or absent)
22
+ * source still loads silently — no marker.
23
+ */
24
+ import { tmpdir } from "node:os";
25
+ import { isAbsolute, resolve, sep } from "node:path";
26
+ import { fileURLToPath } from "node:url";
27
+ export const SKILL_ASSIGNMENT_KEY = "skill-assignment";
28
+ export const PRIORITY_RANK = {
29
+ critical: 0,
30
+ high: 1,
31
+ standard: 2,
32
+ low: 3,
33
+ };
34
+ export function parseSkillMetadata(metadata) {
35
+ if (metadata && typeof metadata === "object" && !Array.isArray(metadata)) {
36
+ return metadata;
37
+ }
38
+ if (typeof metadata === "string" && metadata.length > 0) {
39
+ try {
40
+ const parsed = JSON.parse(metadata);
41
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
42
+ return parsed;
43
+ }
44
+ }
45
+ catch {
46
+ /* opaque / corrupt blob — no source */
47
+ }
48
+ }
49
+ return {};
50
+ }
51
+ export function skillSourceOf(record) {
52
+ const src = parseSkillMetadata(record.metadata).source;
53
+ return typeof src === "string" && src.trim().length > 0 ? src.trim() : undefined;
54
+ }
55
+ const SCHEME = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;
56
+ function isWindowsDrivePath(source) {
57
+ return /^[a-zA-Z]:[\\/]/.test(source);
58
+ }
59
+ /**
60
+ * If `source` names a filesystem path (absolute, relative, or `file:` URL),
61
+ * return that path. Scheme-bearing identifiers (`npm:`, `https:`, …) are
62
+ * not filesystem paths. A bare name is not a path.
63
+ */
64
+ export function filesystemPathFromSkillSource(source) {
65
+ const trimmed = source.trim();
66
+ if (!trimmed)
67
+ return null;
68
+ if (trimmed.startsWith("file:")) {
69
+ try {
70
+ return fileURLToPath(trimmed);
71
+ }
72
+ catch {
73
+ const rest = trimmed.replace(/^file:\/\//, "").replace(/^file:/, "");
74
+ return rest.length > 0 ? rest : null;
75
+ }
76
+ }
77
+ if (SCHEME.test(trimmed) && !isWindowsDrivePath(trimmed))
78
+ return null;
79
+ if (isAbsolute(trimmed) || trimmed.startsWith(".") || /[\\/]/.test(trimmed)) {
80
+ return trimmed;
81
+ }
82
+ return null;
83
+ }
84
+ function tempRoots() {
85
+ const roots = new Set();
86
+ const add = (p) => {
87
+ if (!p || typeof p !== "string" || p.length === 0)
88
+ return;
89
+ try {
90
+ roots.add(resolve(p));
91
+ }
92
+ catch {
93
+ /* ignore unresolvable */
94
+ }
95
+ };
96
+ add(tmpdir());
97
+ add("/tmp");
98
+ add("/private/tmp");
99
+ add("/var/tmp");
100
+ add(process.env.TMPDIR);
101
+ add(process.env.TMP);
102
+ add(process.env.TEMP);
103
+ return [...roots];
104
+ }
105
+ export function isNonDurableFilesystemPath(fsPath) {
106
+ let resolved;
107
+ try {
108
+ resolved = resolve(fsPath);
109
+ }
110
+ catch {
111
+ return true;
112
+ }
113
+ for (const root of tempRoots()) {
114
+ if (resolved === root || resolved.startsWith(root + sep))
115
+ return true;
116
+ }
117
+ return false;
118
+ }
119
+ export function isDurableSkillSource(source) {
120
+ const fsPath = filesystemPathFromSkillSource(source);
121
+ if (fsPath == null)
122
+ return true;
123
+ return !isNonDurableFilesystemPath(fsPath);
124
+ }
125
+ export function registerSkillAssignment(input) {
126
+ const key = typeof input.key === "string" ? input.key : SKILL_ASSIGNMENT_KEY;
127
+ if (key !== SKILL_ASSIGNMENT_KEY)
128
+ return { ok: true };
129
+ const source = skillSourceOf(input);
130
+ if (!source)
131
+ return { ok: true };
132
+ if (isDurableSkillSource(source))
133
+ return { ok: true };
134
+ return {
135
+ ok: false,
136
+ error: "skill_source_not_durable",
137
+ path: source,
138
+ message: `skill source is not durable: ${source}`,
139
+ };
140
+ }
141
+ export function refuseNonDurableSourceResponse(source) {
142
+ if (!source)
143
+ return null;
144
+ if (isDurableSkillSource(source))
145
+ return null;
146
+ return new Response(JSON.stringify({
147
+ error: "skill_source_not_durable",
148
+ path: source,
149
+ message: `skill source is not durable: ${source}`,
150
+ }), { status: 400, headers: { "content-type": "application/json" } });
151
+ }
152
+ function assignmentKey(content, existing) {
153
+ const key = content?.key ?? existing?.key;
154
+ return typeof key === "string" ? key : undefined;
155
+ }
156
+ /** Soul post/put/patch gate. `existing` supplies omitted fields on PATCH. */
157
+ export function refuseSkillAssignmentWrite(content, existing) {
158
+ if (assignmentKey(content, existing) !== SKILL_ASSIGNMENT_KEY)
159
+ return null;
160
+ const metadata = content?.metadata !== undefined ? content.metadata : existing?.metadata;
161
+ const result = registerSkillAssignment({
162
+ key: SKILL_ASSIGNMENT_KEY,
163
+ value: content?.value ?? existing?.value,
164
+ priority: content?.priority ?? existing?.priority,
165
+ metadata,
166
+ });
167
+ if (result.ok)
168
+ return null;
169
+ return new Response(JSON.stringify({
170
+ error: result.error,
171
+ path: result.path,
172
+ message: result.message,
173
+ }), { status: 400, headers: { "content-type": "application/json" } });
174
+ }
175
+ function normalizePriority(p) {
176
+ if (typeof p === "string" && Object.hasOwn(PRIORITY_RANK, p))
177
+ return p;
178
+ return "standard";
179
+ }
180
+ function priorityRank(p) {
181
+ return PRIORITY_RANK[p] ?? PRIORITY_RANK.standard;
182
+ }
183
+ function formatBase(name, priority, source) {
184
+ const src = source ? `, source: ${source}` : "";
185
+ return `- ${name} (${priority} priority${src})`;
186
+ }
187
+ function compareOutcomes(a, b) {
188
+ const byName = a.name.localeCompare(b.name);
189
+ if (byName !== 0)
190
+ return byName;
191
+ const bySource = (a.source ?? "").localeCompare(b.source ?? "");
192
+ if (bySource !== 0)
193
+ return bySource;
194
+ const byPri = priorityRank(a.priority) - priorityRank(b.priority);
195
+ if (byPri !== 0)
196
+ return byPri;
197
+ return a.reason.localeCompare(b.reason);
198
+ }
199
+ function outcomeOf(name, priority, source, decision, reason, loaded) {
200
+ let line = formatBase(name, priority, source);
201
+ if (decision === "superseded") {
202
+ line += ` [SKILL_CONFLICT superseded: ${reason}]`;
203
+ }
204
+ else if (decision === "refused") {
205
+ line += reason.startsWith("non-durable source")
206
+ ? ` [refused: ${reason}]`
207
+ : ` [SKILL_CONFLICT refused: ${reason}]`;
208
+ }
209
+ return { name, priority, source, decision, reason, loaded, line };
210
+ }
211
+ /**
212
+ * Stated, deterministic Active Skills outcome.
213
+ *
214
+ * Identity is `value` (name). Two different names at the same priority are
215
+ * not a conflict — they are two skills. Two records of the same name:
216
+ * unique highest priority wins (stated); an equal-priority tie refuses
217
+ * every member of that name-set. Non-durable sources are refused at load
218
+ * as well as at registration so a scratch path already on disk cannot
219
+ * keep applying.
220
+ *
221
+ * Output order is name → source → priority → reason, so a restart with
222
+ * the same records produces the same lines regardless of input order.
223
+ */
224
+ export function resolveActiveSkills(assignments) {
225
+ const prepared = [];
226
+ const outcomes = [];
227
+ for (const raw of assignments) {
228
+ const name = typeof raw.value === "string" ? raw.value : "";
229
+ if (name.length === 0)
230
+ continue;
231
+ const priority = normalizePriority(raw.priority);
232
+ const source = skillSourceOf(raw);
233
+ if (source && !isDurableSkillSource(source)) {
234
+ outcomes.push(outcomeOf(name, priority, source, "refused", `non-durable source ${source}`, false));
235
+ continue;
236
+ }
237
+ prepared.push({ name, priority, source });
238
+ }
239
+ const byName = new Map();
240
+ for (const row of prepared) {
241
+ const list = byName.get(row.name);
242
+ if (list)
243
+ list.push(row);
244
+ else
245
+ byName.set(row.name, [row]);
246
+ }
247
+ for (const group of byName.values()) {
248
+ if (group.length === 1) {
249
+ const only = group[0];
250
+ outcomes.push(outcomeOf(only.name, only.priority, only.source, "loaded", "sole", true));
251
+ continue;
252
+ }
253
+ const best = Math.min(...group.map((g) => priorityRank(g.priority)));
254
+ const top = group.filter((g) => priorityRank(g.priority) === best);
255
+ if (top.length === 1) {
256
+ const winner = top[0];
257
+ outcomes.push(outcomeOf(winner.name, winner.priority, winner.source, "loaded", `unique_priority ${winner.priority}`, true));
258
+ for (const loser of group) {
259
+ if (loser === winner)
260
+ continue;
261
+ outcomes.push(outcomeOf(loser.name, loser.priority, loser.source, "superseded", `${winner.priority} priority is stated precedence over ${loser.priority}`, false));
262
+ }
263
+ continue;
264
+ }
265
+ const sources = [...new Set(top.map((t) => t.source ?? "(none)"))].sort((a, b) => a.localeCompare(b));
266
+ const reason = `equal-priority tie at ${top[0].priority}; load refused (sources: ${sources.join(", ")})`;
267
+ for (const member of group) {
268
+ outcomes.push(outcomeOf(member.name, member.priority, member.source, "refused", reason, false));
269
+ }
270
+ }
271
+ outcomes.sort(compareOutcomes);
272
+ return { lines: outcomes.map((o) => o.line), outcomes };
273
+ }