@dzhechkov/harness-core 0.3.106 → 0.3.108

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 (40) hide show
  1. package/dist/claim-check-hook-policy.d.ts +8 -4
  2. package/dist/claim-check-hook-policy.d.ts.map +1 -1
  3. package/dist/claim-check-hook-policy.js +8 -24
  4. package/dist/claim-check-hook-policy.js.map +1 -1
  5. package/dist/claim-check.d.ts +31 -0
  6. package/dist/claim-check.d.ts.map +1 -1
  7. package/dist/claim-check.js +172 -14
  8. package/dist/claim-check.js.map +1 -1
  9. package/dist/feature-adr-routing.d.ts +103 -0
  10. package/dist/feature-adr-routing.d.ts.map +1 -1
  11. package/dist/feature-adr-routing.js +220 -0
  12. package/dist/feature-adr-routing.js.map +1 -1
  13. package/dist/index.d.ts +6 -4
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4 -2
  16. package/dist/index.js.map +1 -1
  17. package/dist/publish.d.ts +28 -0
  18. package/dist/publish.d.ts.map +1 -1
  19. package/dist/publish.js +48 -1
  20. package/dist/publish.js.map +1 -1
  21. package/dist/registry.d.ts.map +1 -1
  22. package/dist/registry.js +13 -2
  23. package/dist/registry.js.map +1 -1
  24. package/dist/sign.d.ts +158 -0
  25. package/dist/sign.d.ts.map +1 -0
  26. package/dist/sign.js +325 -0
  27. package/dist/sign.js.map +1 -0
  28. package/dist/skill-schema.d.ts +24 -0
  29. package/dist/skill-schema.d.ts.map +1 -0
  30. package/dist/skill-schema.js +42 -0
  31. package/dist/skill-schema.js.map +1 -0
  32. package/package.json +3 -3
  33. package/src/claim-check-hook-policy.ts +8 -20
  34. package/src/claim-check.ts +186 -14
  35. package/src/feature-adr-routing.ts +271 -0
  36. package/src/index.ts +6 -4
  37. package/src/publish.ts +73 -1
  38. package/src/registry.ts +9 -2
  39. package/src/sign.ts +421 -0
  40. package/src/skill-schema.ts +53 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skill-schema.js","sourceRoot":"","sources":["../src/skill-schema.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AASH;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA+B;IACjE,MAAM,KAAK,GAAG,MAAM,CAAC,UAAiD,CAAC;IACvE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAE3E,MAAM,EAAE,GAAG,KAAK,CAAC,SAAgD,CAAC;IAClE,4FAA4F;IAC5F,iGAAiG;IACjG,oEAAoE;IACpE,IAAI,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAEpG,8FAA8F;IAC9F,iFAAiF;IACjF,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,EAAE,GAAG,EAI7B,CAAC;IAE5B,MAAM,OAAO,GAA4B,EAAE,CAAC;IAC5C,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5D,OAAO,CAAC,OAAO,GAAG,CAAC,CAAC;IACpB,OAAO,CAAC,OAAO,GAAG,CAAC,CAAC;IACpB,IAAI,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,aAAa,CAAC;QAAE,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC;IACxE,qGAAqG;IACrG,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAE1D,KAAK,CAAC,SAAS,GAAG,OAAO,CAAC;IAC1B,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACnC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dzhechkov/harness-core",
3
- "version": "0.3.106",
3
+ "version": "0.3.108",
4
4
  "description": "Shared harness logic - skill loading, additive apply, and the init/sync/verify/doctor operations.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -30,12 +30,12 @@
30
30
  "@dzhechkov/adapter-openclaude": "^0.1.0",
31
31
  "@dzhechkov/adapter-opencode": "^0.2.0",
32
32
  "yaml": "^2.0.0",
33
+ "@dzhechkov/adapter-copilot": "0.1.1",
33
34
  "@dzhechkov/adapter-agents-md": "0.1.1",
34
35
  "@dzhechkov/adapter-cursor": "0.1.1",
35
- "@dzhechkov/adapter-copilot": "0.1.1",
36
+ "@dzhechkov/adapter-windsurf": "0.1.1",
36
37
  "@dzhechkov/adapter-gemini": "0.1.1",
37
38
  "@dzhechkov/core": "0.2.14",
38
- "@dzhechkov/adapter-windsurf": "0.1.1",
39
39
  "@dzhechkov/memory": "0.2.9"
40
40
  },
41
41
  "peerDependenciesMeta": {
@@ -76,27 +76,15 @@ function formatFinding(f: ClaimFinding): string {
76
76
  }
77
77
 
78
78
  /**
79
- * Is the 1-based `line` inside a fenced ``` ``` ``` code block within `text`?
80
- * Counts fence toggles strictly BEFORE the line; an odd count ⇒ the line sits inside a fence.
81
- * Never throws a non-string / out-of-range line returns `false` (treated as not-fenced).
79
+ * Is the 1-based `line` inside a fenced code block within `text`?
80
+ *
81
+ * MOVED to `claim-check.ts` and re-exported here. The engine skips fenced lines and this hook exempts
82
+ * them from its deny path — if the two ever computed "inside a fence" differently, the hook would deny
83
+ * a line the engine had already dismissed, or vice versa. Two implementations WILL drift; one cannot.
84
+ * The engine owns it because the engine is the pure module with no dependents.
82
85
  */
83
- export function isFenced(text: string, line: number): boolean {
84
- if (typeof text !== 'string' || typeof line !== 'number' || !isFinite(line) || line < 1) return false;
85
- const lines = text.split(/\r?\n/);
86
- const upTo = Math.min(line - 1, lines.length);
87
- // CommonMark allows BOTH ``` and ~~~ fences, and a fence is closed only by its OWN marker — a
88
- // ``` inside a ~~~ block is literal content, not a toggle. A naive toggle counter that accepts
89
- // either marker therefore mis-tracks nesting; track the open marker instead.
90
- let open: '`' | '~' | null = null;
91
- for (let i = 0; i < upTo; i++) {
92
- const m = /^\s*(`{3,}|~{3,})/.exec(lines[i] || '');
93
- if (!m) continue;
94
- const marker = m[1]![0] as '`' | '~';
95
- if (open === null) open = marker;
96
- else if (open === marker) open = null;
97
- }
98
- return open !== null;
99
- }
86
+ import { isFenced } from './claim-check.js';
87
+ export { isFenced };
100
88
 
101
89
  /**
102
90
  * Is `excerpt` a NEW claim line (guard d)? True when there is no pre-image (`oldString` absent/empty —
@@ -34,7 +34,9 @@ export interface ClaimCheckResult {
34
34
  /** Phrases that signal a quantitative accuracy claim (safe as substrings). */
35
35
  const METRIC_TERMS = [
36
36
  // Generic accuracy vocabulary kept from ruview.
37
- 'accuracy', 'precision', 'recall',
37
+ // `recall` is NOT here — it is this repo's command name. It re-enters via RECALL_METRIC_RE, which
38
+ // demands a scoring context. `precision` stays: it has no command collision.
39
+ 'accuracy', 'precision',
38
40
  'error rate', 'detection rate', 'true positive',
39
41
  // dz claim vocabulary — a harness monorepo claims coverage, test counts, catalogue sizes,
40
42
  // and performance numbers, not WiFi-sensing PCK/MPJPE.
@@ -42,19 +44,19 @@ const METRIC_TERMS = [
42
44
  'packages', 'presets', 'downloads', 'benchmark', 'speedup', 'latency',
43
45
  ];
44
46
 
45
- // Short/ambiguous metric tokens (ADR-263 F11): 'map' is usually the English
46
- // word or a file extension, 'f1'/'o1' collide with finding/option labels.
47
- // They only count as metric mentions when word-bounded, not a `.map` file
48
- // reference, and the line (after scrubbing) carries a number — "mAP 62.3" is
49
- // a claim, "F-numbers map to findings" is not.
50
- // 'map' additionally must not be a `.map` file suffix or a hyphenated
51
- // compound ("map-free", "map-reduce") — mAP the metric never appears as either.
47
+ // Short/ambiguous metric tokens (ADR-263 F11): 'f1'/'o1' collide with finding/option labels.
48
+ // They only count as metric mentions when word-bounded, and the line (after scrubbing) carries a
49
+ // number "auc 0.9" is a claim, "F-numbers map to findings" is not.
52
50
  // `\d+ tests` is dz's single most-repeated headline claim ("2136 tests") and was slipping through:
53
51
  // the substring term is 'tests passed', so a bare count never fired. Anchor it to a PRECEDING number
54
52
  // rather than adding a bare 'test' term — otherwise every `usage.test.ts:42` path reference would
55
53
  // register as a metric mention.
54
+ // NOTE: 'map' is NOT here. A line-wide "has a number" gate fired on the English word `map` next to any
55
+ // incidental digit — a `FR-2` label, a `v2`, an `item 2` (MEASURED — features/claimcheck-map-fp).
56
+ // mAP the metric is written with its score ADJACENT, so it gets a scoring-context regex (MAP_METRIC_RE),
57
+ // exactly as `recall` does (RECALL_METRIC_RE), instead of the loose line-wide gate.
56
58
  const METRIC_TERMS_SHORT = [
57
- /(?<![.\w])map\b(?!-)/, /\bf1\b/, /\bauc\b/, /\biou\b/,
59
+ /\bf1\b/, /\bauc\b/, /\biou\b/,
58
60
  /\b\d[\d,._]*\s+tests?\b/,
59
61
  ];
60
62
  // Finding/option labels (F1, O2, …) count as labels unless the token sits in a
@@ -88,19 +90,116 @@ function scrubLine(lower: string): string {
88
90
 
89
91
  function mentionsMetricTerm(lower: string, scrubbed: string): boolean {
90
92
  if (METRIC_TERMS.some((t) => lower.includes(t))) return true;
93
+ // `recall` only in a scoring context (see RECALL_METRIC_RE). `precision` on the line is enough:
94
+ // "precision 0.9 / recall 0.8" is the canonical ML pair.
95
+ if (RECALL_METRIC_RE.test(scrubbed)) return true;
96
+ // mAP: a metric only with a score adjacent (see MAP_METRIC_RE). The regex embeds its own number, so
97
+ // it is checked before the loose line-wide HAS_NUMBER gate — the same shape as recall above.
98
+ if (MAP_METRIC_RE.test(scrubbed)) return true;
91
99
  if (!HAS_NUMBER_RE.test(scrubbed)) return false;
92
100
  return METRIC_TERMS_SHORT.some((re) => re.test(scrubbed));
93
101
  }
94
102
 
103
+ /**
104
+ * The PARAGRAPH containing 1-based `line`: the maximal run of contiguous non-blank lines, bounded by
105
+ * a blank line, a heading, or a fence marker. The claim is DETECTED per line; its honesty tag and its
106
+ * reproducer may live anywhere in this run — prose wrapped at 100 columns routinely splits a number
107
+ * from its `MEASURED`, and flagging the author who tagged correctly is how a gate teaches its users to
108
+ * ignore it.
109
+ *
110
+ * LAUNDERING EXPOSURE, stated: one tag covers every claim in its paragraph. It cannot cross a blank
111
+ * line, a heading, or a fence.
112
+ */
113
+ function paragraphAround(lines: readonly string[], i: number): string {
114
+ const bounds = (k: string): boolean => k.trim() === '' || HEADING_RE.test(k) || FENCE_RE.test(k);
115
+ let a = i;
116
+ let b = i;
117
+ while (a > 0 && !bounds(lines[a - 1] ?? '')) a--;
118
+ while (b < lines.length - 1 && !bounds(lines[b + 1] ?? '')) b++;
119
+ return lines.slice(a, b + 1).join('\n');
120
+ }
121
+
95
122
  /** Tags that make a claim honest (case-insensitive). */
96
123
  // `estimated` agrees with the `estimated: true` honest-uncertainty marker `dz usage` already
97
124
  // emits — the two honesty systems must not contradict each other.
98
125
  const HONEST_TAGS = ['measured', 'claimed', 'synthetic', 'unvalidated', 'baseline', 'estimated'];
99
126
 
127
+ /**
128
+ * Is the 1-based `line` inside a fenced code block within `text`?
129
+ *
130
+ * OWNED HERE, re-exported by `claim-check-hook-policy.ts`. The engine skips fenced lines; the hook
131
+ * exempts them from its deny path. Two implementations of "inside a fence" would drift; one cannot.
132
+ *
133
+ * CommonMark allows BOTH ``` and ~~~ fences, and a fence closes only on its OWN marker — a ``` inside
134
+ * a ~~~ block is literal content, not a toggle. A naive toggle counter that accepts either marker
135
+ * mis-tracks nesting, so track the open marker instead. Never throws.
136
+ */
137
+ export function isFenced(text: string, line: number): boolean {
138
+ if (typeof text !== 'string' || typeof line !== 'number' || !isFinite(line) || line < 1) return false;
139
+ const lines = text.split(/\r?\n/);
140
+ const upTo = Math.min(line - 1, lines.length);
141
+ let open: '`' | '~' | null = null;
142
+ for (let i = 0; i < upTo; i++) {
143
+ const m = FENCE_RE.exec(lines[i] || '');
144
+ if (!m) continue;
145
+ const marker = m[1]![0] as '`' | '~';
146
+ if (open === null) open = marker;
147
+ else if (open === marker) open = null;
148
+ }
149
+ return open !== null;
150
+ }
151
+
152
+ const FENCE_RE = /^\s*(`{3,}|~{3,})/;
153
+ const HEADING_RE = /^\s{0,3}#{1,6}\s/;
154
+
155
+ /**
156
+ * `recall` is ruview's completeness metric AND this repo's command name (`dz recall`). Matching it as
157
+ * a bare term produced 31 false positives (MEASURED — reproducer `dz claim-check --json`), every one
158
+ * of them prose about the command. It counts as a metric only in a scoring context: paired with
159
+ * `precision`, or immediately followed by a score (`recall@5`, `recall rate`, `recall of 0.9`,
160
+ * `recall = 0.9`, `recall score`).
161
+ */
162
+ const RECALL_METRIC_RE = /\brecall\s*(?:@\s*\d|rate\b|score\b|of\s+[\d.]|[:=]\s*[\d.])/i;
163
+
164
+ /**
165
+ * mAP (mean Average Precision) is both a metric AND the English word `map`. Matching it via the
166
+ * line-wide "has a number" gate fired on every line where `map` co-occurred with an unrelated digit —
167
+ * a `FR-2` label, a `v2`, an `item 2` (MEASURED — reproducer matrix in features/claimcheck-map-fp).
168
+ * Like `recall`, it counts as a metric only in a SCORING CONTEXT: a score sits ADJACENT to the token.
169
+ *
170
+ * Fires on: `mAP 62.3`, `mAP: 0.62`, `mAP=62`, `mAP@0.5`, `62.3 mAP`, `62% mAP`.
171
+ * Does not fire on: `the map imports` + `FR-2`, `.map` file, `map-reduce`, `a map of 3 zones`.
172
+ *
173
+ * A real mAP score is a DECIMAL or a PERCENT (`0.62`, `62.3`, `62%`) — never a bare integer and never a
174
+ * lone dot. Requiring that (not merely "a digit or dot", which cross-model review showed fires on
175
+ * `map: 3 zones`, `map @ 5 locations`, and even `map: .env`) is what separates the metric from prose:
176
+ * `map 3 items`, `a map of 3 zones`, `top 5 map layers` all stay prose. An optional `@`/`:`/`=` may sit
177
+ * between the token and its score. `(?<![.\w])` excludes `.map`; `(?!-)` excludes `map-reduce`/`map-free`.
178
+ *
179
+ * Known, accepted limitation (cross-model review): exotic notations `mAP50 62.3`, `mAP@[.5:.95]` are NOT
180
+ * matched — under-detection of rare forms, not a false positive. dz's own claims use `mAP 62.3`.
181
+ */
182
+ const MAP_SCORE = String.raw`(?:\d+\.\d+|\.\d+|\d+\s*%)`;
183
+ const MAP_METRIC_RE = new RegExp(
184
+ String.raw`(?<![.\w])map\b(?!-)\s*(?:[@:=]\s*)?${MAP_SCORE}|${MAP_SCORE}\s+(?<![.\w])map\b(?!-)`,
185
+ 'i',
186
+ );
187
+
188
+ /**
189
+ * A shell reproducer is STRUCTURAL, never a word. `(MEASURED — reproducer)` is self-certifying and
190
+ * must not pass; a backticked span whose first token is a command this repo actually measures with is
191
+ * evidence. The allowlist boundary is exactly that: an unknown binary is a claim ABOUT evidence.
192
+ */
193
+ const SHELL_REPRO_RE =
194
+ /`\s*\$?\s*(?:ps|stat|lsof|time|git|npm|npx|node|pnpm|yarn|dz|curl|wc|grep|find|cargo|make|docker|kubectl|awk|sed|du|df|vitest|pytest)\b[^`]*`/i;
195
+
100
196
  /** Reproducer references that count as evidence backing a MEASURED claim. */
101
197
  const REPRODUCER_HINTS = [
102
198
  // Generic evidence hints kept from ruview.
103
- 'baseline', 'reproduce', 'sha256', 'tarball', 'cargo test',
199
+ // 'reproduce' was inherited from ruview and is SELF-CERTIFYING: it makes the bare word "reproducer"
200
+ // count as its own evidence, so `(MEASURED — reproducer)` passed. Removed (D5). Evidence must be a
201
+ // named command or artifact — see SHELL_REPRO_RE for the structural form.
202
+ 'baseline', 'sha256', 'tarball', 'cargo test',
104
203
  // Packaging-claim reproducers (npm reviews): the tarball itself.
105
204
  'npm pack', 'npm view', 'npm i ', 'npm install',
106
205
  // dz reproducers — the actual commands/artifacts that back a dz claim.
@@ -130,14 +229,25 @@ export function claimCheck(text: string): ClaimCheckResult {
130
229
  lines.forEach((raw, i) => {
131
230
  const original = raw.trim();
132
231
  if (!original) return;
232
+ // A fenced block is CODE, not prose. The hook already exempts fenced lines from its deny path
233
+ // (it re-exports `isFenced` from here); the engine flagging them was not a policy, it was a bug —
234
+ // 127 of this repo's 488 findings lived inside fences, and NONE of them was `high`
235
+ // (MEASURED — reproducer `dz claim-check --json`).
236
+ // EXPOSURE, accepted: a claim written inside a fence is now unreachable. That is exactly the right
237
+ // the inline backtick escape already grants; a fence is its block-level form.
238
+ if (isFenced(text, i + 1)) return;
133
239
  // Analyse the URL-stripped line, but report the ORIGINAL so the excerpt stays recognisable.
134
240
  const line = stripUrls(original);
135
241
  if (!line.trim()) return;
136
242
  const lower = line.toLowerCase();
137
243
 
138
- const hasPercent = PERCENT_RE.test(line);
139
- PERCENT_RE.lastIndex = 0; // reset stateful global regex
140
244
  const scrubbed = scrubLine(lower);
245
+ // The percent TRIGGER reads the code-span-scrubbed line. Before this, `hasPercent` was computed on
246
+ // the UN-scrubbed line while metric terms were matched on the scrubbed one, so a backticked `99%`
247
+ // still opened the scan: the backtick escape downgraded a quoted claim from `high` to `medium`
248
+ // instead of silencing it. Documentation that quotes a forbidden claim was punished for doing so.
249
+ const hasPercent = PERCENT_RE.test(scrubbed);
250
+ PERCENT_RE.lastIndex = 0; // reset stateful global regex
141
251
  // DELIBERATE DIVERGENCE from ruview, which matched METRIC_TERMS against the UNSCRUBBED line.
142
252
  // dz's vocabulary contains path-like words ('packages', 'commands', 'skills'), so a code span
143
253
  // such as `packages/x/usage.test.ts:42` registered as a metric mention and produced a false
@@ -147,8 +257,13 @@ export function claimCheck(text: string): ClaimCheckResult {
147
257
  const mentionsMetric = mentionsMetricTerm(scrubbed, scrubbed);
148
258
  if (!hasPercent && !mentionsMetric) return;
149
259
 
150
- const tagged = HONEST_TAGS.some((t) => lower.includes(t));
151
- const hasReproducer = REPRODUCER_HINTS.some((h) => lower.includes(h));
260
+ // The claim is detected on its own line; its honesty tag and reproducer may live anywhere in the
261
+ // same paragraph. Wrapped prose routinely puts `MEASURED` on the next line.
262
+ const para = stripUrls(paragraphAround(lines, i));
263
+ const paraLower = para.toLowerCase();
264
+ const tagged = HONEST_TAGS.some((t) => paraLower.includes(t));
265
+ const hasReproducer =
266
+ REPRODUCER_HINTS.some((h) => paraLower.includes(h)) || SHELL_REPRO_RE.test(para);
152
267
  const perfect = PERFECT_WORD_RE.test(line) || (mentionsMetric && PERFECT_PCT_RE.test(line));
153
268
 
154
269
  if (perfect && !lower.includes('retract')) {
@@ -209,3 +324,60 @@ export function summarize(result: ClaimCheckResult): string {
209
324
  const high = result.findings.filter((f) => f.severity === 'high').length;
210
325
  return `claim-check: ${result.findings.length} finding(s) (${high} high) — accuracy claims need MEASURED/CLAIMED tags + a reproducer.`;
211
326
  }
327
+
328
+ // ── Voluntary text-vet policy (ADR-001, mcp-claim-check-text) ────────────────
329
+ //
330
+ // `claimCheck('')` returns {ok:true} — correct for a file (no claims), wrong for a VOLUNTARY vet: an
331
+ // agent that asks "are my claims OK?" with nothing and hears "yes" is reassured about nothing. This
332
+ // pure policy decides error-vs-run BEFORE the engine is called, so a wrapper (the MCP tool) can fail
333
+ // closed without touching `claimCheck` itself.
334
+
335
+ export type FailOn = 'high' | 'medium' | 'none';
336
+
337
+ export interface ClaimTextDecision {
338
+ readonly kind: 'error' | 'run';
339
+ readonly reason?: string;
340
+ }
341
+
342
+ /** Empty / whitespace-only / non-string ⇒ error. A real paragraph ⇒ run. */
343
+ export function decideClaimCheckText(text: unknown): ClaimTextDecision {
344
+ if (typeof text !== 'string') {
345
+ return { kind: 'error', reason: 'text must be a string, got ' + typeof text };
346
+ }
347
+ // Cross-model review: trim() leaves zero-width and format characters (U+200B ZWSP, U+200D ZWJ,
348
+ // U+FEFF BOM, other Cf), so a string of invisibles would pass as `run` and vet nothing. Strip all
349
+ // whitespace AND Unicode format/control characters before the emptiness test.
350
+ const visible = text.replace(/[\s\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]|\p{Cf}|\p{Cc}/gu, '');
351
+ if (visible.length === 0) {
352
+ return { kind: 'error', reason: 'text is empty or only invisible characters — nothing to vet' };
353
+ }
354
+ return { kind: 'run' };
355
+ }
356
+
357
+ /** Severity counts, so a caller can gate without re-walking the findings. */
358
+ export function severityCounts(result: ClaimCheckResult): { high: number; medium: number } {
359
+ let high = 0;
360
+ let medium = 0;
361
+ for (const f of result.findings) {
362
+ if (f.severity === 'high') high++;
363
+ else if (f.severity === 'medium') medium++;
364
+ }
365
+ return { high, medium };
366
+ }
367
+
368
+ /**
369
+ * Whether a run RESULT trips the caller's threshold. Reporting only — never throws, never converts the
370
+ * fail-closed empty case (which is handled earlier by `decideClaimCheckText`) into a pass.
371
+ * 'high' ⇒ gated iff any high finding
372
+ * 'medium' ⇒ gated iff any high OR medium finding
373
+ * 'none' ⇒ never gated
374
+ */
375
+ export function isGated(result: ClaimCheckResult, failOn: FailOn): boolean {
376
+ const { high, medium } = severityCounts(result);
377
+ if (failOn === 'none') return false;
378
+ if (failOn === 'high') return high > 0;
379
+ if (failOn === 'medium') return high > 0 || medium > 0;
380
+ // Cross-model review: an unknown failOn (only reachable via a direct call, since the Zod enum guards
381
+ // the tool) must not silently behave like 'medium'. Fail SAFE: gate on any finding.
382
+ return high > 0 || medium > 0;
383
+ }
@@ -626,3 +626,274 @@ export function mergeOpts<B extends object, E extends object>(base: B, extra: E)
626
626
  for (const k in extra) out[k] = (extra as Record<string, unknown>)[k];
627
627
  return out as B & E;
628
628
  }
629
+
630
+ // ── CODEX DISPATCH BY DELIVERABLE (ADR-001) ──────────────────────────────────
631
+ //
632
+ // `codex:codex-rescue` is a fire-and-forget Claude WRAPPER: it dispatches to Codex and returns
633
+ // immediately, so its return value is a stub. That is correct for a stage whose deliverable is a
634
+ // FILE written out-of-band (Step 7 code, behind the Step-7.5 landed barrier) and catastrophic for a
635
+ // stage whose deliverable is its RETURN VALUE — a stub reads exactly like a clean review.
636
+ //
637
+ // The workflow script is sandboxed (no `child_process`), so it cannot shell out to `codex exec`
638
+ // itself. An ordinary Claude agent runs the command and returns Codex's stdout verbatim: the agent
639
+ // is the shell.
640
+
641
+ /**
642
+ * Stages whose deliverable is a FILE written out-of-band, and which already verify the write landed
643
+ * before trusting the stub. `code` polls `git status` (Step-7.5). `plan` requires its
644
+ * `06_implementation_plan.md` to appear and otherwise falls back to the Claude planner — it never
645
+ * fabricates. Both are legitimate wrapper users; everything else returns its deliverable.
646
+ */
647
+ const WRAPPER_STAGES: Record<string, number> = { code: 1, plan: 1 };
648
+
649
+ export type CodexDispatch = 'wrapper' | 'exec';
650
+
651
+ /** Dispatch by what the stage's deliverable IS, never by which knob named it. */
652
+ export function codexDispatchMode(stage: string): CodexDispatch {
653
+ return WRAPPER_STAGES[stage] ? 'wrapper' : 'exec';
654
+ }
655
+
656
+ /**
657
+ * A SANITY bound on prompt size, not a stall guard.
658
+ *
659
+ * The earlier 1200-char ceiling was justified by "codex exec stalls on a 55-line payload". Twin
660
+ * experiments refuted that (2026-07-10): 4000 chars of padding answered in 4s, and a 3156-char /
661
+ * 56-line adversarial code review answered in 14s. The stalls are INTERMITTENT latency — the same
662
+ * input hung at 60s and answered at 14s minutes apart. Size is not the variable.
663
+ *
664
+ * So the real guard is the bounded timeout plus the CODEX_UNAVAILABLE sentinel: a slow exec becomes
665
+ * an explicit "unavailable", never a passed review. This constant only stops us from shipping an
666
+ * absurdly large prompt.
667
+ */
668
+ export const CODEX_EXEC_PROMPT_CEILING_CHARS = 24_000;
669
+
670
+ /** The sentinel an exec agent returns when the command failed, timed out, or Codex refused. */
671
+ export const CODEX_UNAVAILABLE = 'CODEX_UNAVAILABLE';
672
+
673
+ export interface CodexExecPlanInput {
674
+ readonly stage: string;
675
+ readonly promptChars: number;
676
+ readonly probedId: string | null;
677
+ }
678
+
679
+ export interface CodexExecPlanResult {
680
+ readonly mode: 'exec' | 'wrapper' | 'claude';
681
+ readonly reason: string;
682
+ }
683
+
684
+ /** Decide, before spending an agent, whether Codex can honestly serve this stage. */
685
+ export function codexExecPlan(input: CodexExecPlanInput): CodexExecPlanResult {
686
+ if (codexDispatchMode(input.stage) === 'wrapper') {
687
+ return { mode: 'wrapper', reason: 'deliverable is a file written out-of-band' };
688
+ }
689
+ if (!input.probedId) {
690
+ return { mode: 'claude', reason: 'no codex model id answered the probe' };
691
+ }
692
+ if (input.promptChars > CODEX_EXEC_PROMPT_CEILING_CHARS) {
693
+ return {
694
+ mode: 'claude',
695
+ reason:
696
+ 'prompt is ' +
697
+ input.promptChars +
698
+ ' chars, over the ' +
699
+ CODEX_EXEC_PROMPT_CEILING_CHARS +
700
+ '-char codex exec ceiling (it would stall)',
701
+ };
702
+ }
703
+ return { mode: 'exec', reason: 'codex exec on ' + input.probedId };
704
+ }
705
+
706
+ /** A model id is user input (`args.codexModel`) and lands in a shell command. Shell-safe ids only. */
707
+ export function isSafeCodexId(id: string): boolean {
708
+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(id);
709
+ }
710
+
711
+ /**
712
+ * A liveness probe. The allowlist says a name is spellable; only this says it answers.
713
+ *
714
+ * Found by cross-model review (codex exec, 2026-07-10): the id was interpolated into a shell command
715
+ * unquoted, so a malformed `args.codexModel` could corrupt or extend the command the agent runs.
716
+ * Reject anything that is not a plain id, and single-quote it anyway.
717
+ */
718
+ export function codexProbeCommand(id: string): string | null {
719
+ if (!isSafeCodexId(id)) return null;
720
+ return "timeout 60 codex exec -m '" + id + "' 'Reply with exactly: OK'";
721
+ }
722
+
723
+ export interface CodexProbeOutput {
724
+ readonly stdout: string;
725
+ readonly exitCode: number;
726
+ }
727
+
728
+ export function interpretCodexProbe(out: CodexProbeOutput): boolean {
729
+ if (out.exitCode !== 0) return false;
730
+ return /\bOK\b/.test(out.stdout);
731
+ }
732
+
733
+ /** First id that actually answers. `null` means: route this stage to Claude. */
734
+ export async function pickAvailableCodexId(
735
+ ids: readonly string[],
736
+ probe: (id: string) => Promise<boolean>,
737
+ ): Promise<string | null> {
738
+ for (const id of ids) {
739
+ if (await probe(id)) return id;
740
+ }
741
+ return null;
742
+ }
743
+
744
+ export interface CodexExecResult {
745
+ readonly ok: boolean;
746
+ readonly text: string;
747
+ readonly reason: string;
748
+ }
749
+
750
+ /**
751
+ * Risk R2, the most dangerous line in this change: an EMPTY reply must never read as "no findings".
752
+ * A genuine clean review has to say something. Empty, whitespace, or the sentinel ⇒ not ok ⇒ the
753
+ * caller falls back to a Claude reviewer.
754
+ */
755
+ /**
756
+ * Extract an A–D grade. Cross-model review flagged that "Looks good" would otherwise pass as a
757
+ * review; a verdict must NAME its grade. No grade ⇒ no verdict ⇒ the caller falls back to Claude.
758
+ */
759
+ export function parseCodexGrade(text: string): string | null {
760
+ const m = /\bgrade\s*[:=]?\s*([A-D])\b/i.exec(text);
761
+ const g = m && m[1] ? m[1] : null;
762
+ return g ? g.toUpperCase() : null;
763
+ }
764
+
765
+ export function parseCodexExecResult(text: string | null | undefined): CodexExecResult {
766
+ const t = typeof text === 'string' ? text.trim() : '';
767
+ if (t.length === 0) return { ok: false, text: '', reason: 'codex exec returned no text' };
768
+ if (t.indexOf(CODEX_UNAVAILABLE) !== -1) {
769
+ return { ok: false, text: t, reason: 'codex exec reported it could not run' };
770
+ }
771
+ return { ok: true, text: t, reason: 'codex answered' };
772
+ }
773
+
774
+ /** CX-3: a workflow that names an agent type the harness does not have must fall back, not die. */
775
+ export function isAgentTypeMissingError(err: unknown): boolean {
776
+ const msg = err instanceof Error ? err.message : String(err ?? '');
777
+ return /agent type .*not found|unknown agent type|no such agent/i.test(msg);
778
+ }
779
+
780
+ /**
781
+ * Run a Codex-routed agent so that a missing agent type demotes to `null` (→ the caller's Claude
782
+ * fallback) instead of throwing and killing the whole run. Any other error still propagates: we do
783
+ * not want to swallow real bugs behind a fallback.
784
+ */
785
+ export async function safeCodexAgent<T>(
786
+ agentFn: (prompt: string, opts: object) => Promise<T>,
787
+ prompt: string,
788
+ opts: object,
789
+ log: (msg: string) => void,
790
+ ): Promise<T | null> {
791
+ try {
792
+ return await agentFn(prompt, opts);
793
+ } catch (err) {
794
+ if (isAgentTypeMissingError(err)) {
795
+ log('codex: agent type unavailable — falling back to Claude (' + String(err) + ')');
796
+ return null;
797
+ }
798
+ throw err;
799
+ }
800
+ }
801
+
802
+ // ── ABSOLUTE ARTIFACT ROOT (ADR-001, absolute-artifact-paths) ────────────────
803
+ //
804
+ // `FDIR` (and `BRAIN`, which derives from the same value) used to be relative, because
805
+ // `args.repo` defaults to `'.'`. A relative path means different things to different agents: once a
806
+ // coder `cd`s elsewhere, a later agent resolves `./features/<slug>/03_adr` against another cwd, finds
807
+ // nothing, and reports a confident FALSE BLOCKER while the artifacts sit at the workflow root.
808
+ //
809
+ // The workflow script is sandboxed — no filesystem, no Node API — so it cannot call `process.cwd()`.
810
+ // The absolute root arrives either as an absolute `args.repo`, or from an agent that runs `pwd`.
811
+ // The resolver below takes `cwd` as a PARAMETER so it is testable without ambient state.
812
+
813
+ /** True for a POSIX absolute path. */
814
+ export function isAbsolutePosix(p: string): boolean {
815
+ return typeof p === 'string' && p.charAt(0) === '/';
816
+ }
817
+
818
+ /**
819
+ * Collapse `a//b`, `a/./b` and a trailing slash. Deliberately does NOT resolve `..` — a workflow root
820
+ * containing `..` is a caller error we would rather surface than silently normalise away.
821
+ */
822
+ export function normalizeRepoPath(p: string): string {
823
+ const collapsed = p.replace(/\/{2,}/g, '/').replace(/\/\.(?=\/|$)/g, '');
824
+ const trimmed = collapsed.replace(/\/+$/, '');
825
+ return trimmed === '' ? '/' : trimmed;
826
+ }
827
+
828
+ /**
829
+ * Resolve the artifact root to an absolute path.
830
+ *
831
+ * `raw` is `args.repo` (may be `'.'`, `'./x'`, `'x/'`, or already absolute).
832
+ * `cwd` is the absolute working directory, obtained ONCE from a `pwd` agent — never ambient.
833
+ * An already absolute `raw` ignores `cwd` entirely (zero agents on that path).
834
+ */
835
+ export function absolutizeRepo(raw: string, cwd: string): string {
836
+ const r = typeof raw === 'string' && raw.length > 0 ? raw : '.';
837
+ if (isAbsolutePosix(r)) return normalizeRepoPath(r);
838
+ const base = normalizeRepoPath(cwd);
839
+ const rel = r.replace(/^\.\/+/, '').replace(/^\.$/, '');
840
+ return rel === '' ? base : normalizeRepoPath(base + '/' + rel);
841
+ }
842
+
843
+ /** The instruction appended to prompts that embed an artifact path (FR-3). */
844
+ export const ABSOLUTE_PATH_NOTE =
845
+ ' All artifact paths in this prompt are ABSOLUTE. Read and write them exactly as given; do not cd' +
846
+ ' first and do not re-relativize them.';
847
+
848
+ /**
849
+ * Pick the absolute path out of possibly chatty `pwd` output.
850
+ *
851
+ * Cross-model review (codex exec, 2026-07-10) found `.split('\n').pop()` selects the LAST line — so a
852
+ * `pwd` agent that appends "Done" would degrade the run despite having printed a valid path. Take the
853
+ * last line that actually looks like an absolute path.
854
+ */
855
+ export function pickAbsolutePathLine(text: string | null | undefined): string | null {
856
+ if (typeof text !== 'string') return null;
857
+ const abs = text
858
+ .split('\n')
859
+ .map((l) => l.trim())
860
+ .filter((l) => isAbsolutePosix(l));
861
+ return abs.length ? (abs[abs.length - 1] as string) : null;
862
+ }
863
+
864
+ /** `args.repo` may be anything the caller passed. A non-string must not throw on `.replace`. */
865
+ export function coerceRepoArg(raw: unknown): string {
866
+ return typeof raw === 'string' && raw.length > 0 ? raw.replace(/\/+$/, '') : '.';
867
+ }
868
+
869
+
870
+ /**
871
+ * Round-2 cross-model review (codex exec, 2026-07-10) — three path-safety defects, all real:
872
+ * 1. `..` segments survived normalisation, so `args.repo='../evil'` produced an absolute-but-unstable
873
+ * root. Under the fail-fast stance this is a refusal, not a normalisation.
874
+ * 2. A newline in `args.repo` could split an embedded path across lines in a prompt.
875
+ * 3. `SLUG` was concatenated raw: `'../../outside'` escapes the `features/` directory entirely.
876
+ */
877
+ const UNSAFE_PATH_CHARS = /[\u0000-\u001f\u007f]/;
878
+ const DOT_DOT_SEGMENT = /(^|\/)\.\.(\/|$)/;
879
+
880
+ export function hasUnsafePathChars(p: string): boolean {
881
+ return UNSAFE_PATH_CHARS.test(String(p));
882
+ }
883
+
884
+ export function hasDotDotSegment(p: string): boolean {
885
+ return DOT_DOT_SEGMENT.test(String(p));
886
+ }
887
+
888
+ /** The slug names a directory under `features/`. Kebab-case, Latin, max 40 chars — the documented rule. */
889
+ export function isSafeSlug(slug: string): boolean {
890
+ return typeof slug === 'string' && /^[a-z0-9][a-z0-9-]{0,39}$/.test(slug);
891
+ }
892
+
893
+ /** Returns an error message, or `null` when the root is safe to embed in a prompt. */
894
+ export function checkArtifactRoot(root: string): string | null {
895
+ if (!isAbsolutePosix(root)) return 'artifact root is not absolute: ' + JSON.stringify(root);
896
+ if (hasUnsafePathChars(root)) return 'artifact root contains control characters';
897
+ if (hasDotDotSegment(root)) return 'artifact root contains a ".." segment: ' + root;
898
+ return null;
899
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,8 @@ export type { BundleOptions, BundleResult, BundledSkill } from './bundle.js';
17
17
  export * from './targets.js';
18
18
  export * from './operations.js';
19
19
  export * from './workflows.js';
20
+ export * from './sign.js';
21
+ export * from './skill-schema.js';
20
22
  export { createSkill } from './create-skill.js';
21
23
  export type { CreateSkillOptions, CreateSkillResult } from './create-skill.js';
22
24
  export { checkUpstream, checkAllUpstream, discoverSourcePackages, loadSourcesManifest } from './sync-upstream.js';
@@ -119,8 +121,8 @@ export type { PluginManifest } from './plugin.js';
119
121
  export type { SetupOptions, SetupResult, SetupStep } from './setup.js';
120
122
  export type { PretrainResult, DetectedTech } from './pretrain.js';
121
123
  export type { RecommendationReport, SkillRecommendation } from './recommend.js';
122
- export { claimCheck, summarize } from './claim-check.js';
123
- export type { ClaimFinding, ClaimCheckResult } from './claim-check.js';
124
+ export { claimCheck, summarize, decideClaimCheckText, severityCounts, isGated } from './claim-check.js';
125
+ export type { ClaimFinding, ClaimCheckResult, ClaimTextDecision, FailOn } from './claim-check.js';
124
126
  export { hookDecision, isFenced, isNewLine, ESCAPE_TEACHING } from './claim-check-hook-policy.js';
125
127
  export type { HookDecision, HookDecisionOpts } from './claim-check-hook-policy.js';
126
128
  export { step8ClaimGate } from './feature-adr-claim-gate.js';
@@ -159,12 +161,12 @@ export type {
159
161
  RecallUsagePatternRow,
160
162
  RecallUsageReport,
161
163
  } from './recall-usage.js';
162
- export { discoverPackages, publishPackages, bumpPatch, compareVersions, findUnpackagedSkills, orderByDependencies, syncReadmeVersion } from './publish.js';
164
+ export { decideProvenance, environmentCanMintProvenance, publishArgv, discoverPackages, publishPackages, bumpPatch, compareVersions, findUnpackagedSkills, orderByDependencies, syncReadmeVersion } from './publish.js';
163
165
  export { fetchAllDownloads } from './downloads.js';
164
166
  export type { PackageDownloads, DownloadsReport } from './downloads.js';
165
167
  export { discoverInstalled, checkUpgrades } from './upgrade.js';
166
168
  export type { InstalledSkill, UpgradeCheck, UpgradeReport } from './upgrade.js';
167
- export type { PublishResult, PublishReport } from './publish.js';
169
+ export type { PublishResult, PublishReport, ProvenanceMode, ProvenanceDecision } from './publish.js';
168
170
  export { computeRiskScore } from './risk-scoring.js';
169
171
  export type { RiskScore, RiskThresholds } from './risk-scoring.js';
170
172
  export {