@staix/agent-research 0.2.1 → 0.3.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 (72) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +255 -24
  3. package/package.json +2 -2
  4. package/src/cli.ts +117 -10
  5. package/src/commands-table.ts +39 -8
  6. package/src/commands.ts +192 -32
  7. package/src/exp/attempts.ts +500 -65
  8. package/src/exp/executor.ts +235 -12
  9. package/src/exp/final.ts +1 -1
  10. package/src/exp/logs.ts +25 -12
  11. package/src/exp/metrics.ts +6 -5
  12. package/src/exp/pipeline.ts +92 -0
  13. package/src/exp/protocol.ts +85 -18
  14. package/src/exp/retention-script.ts +649 -0
  15. package/src/exp/retention.ts +70 -0
  16. package/src/exp/reuse-admission.ts +63 -0
  17. package/src/exp/reuse-contract.ts +48 -0
  18. package/src/exp/reuse-runtime.ts +87 -0
  19. package/src/exp/reuse.ts +87 -0
  20. package/src/exp/selection.ts +1 -1
  21. package/src/exp/snapshot.ts +3 -3
  22. package/src/exp/stages.ts +117 -0
  23. package/src/harness/experience-source.ts +34 -0
  24. package/src/harness/experience.ts +206 -0
  25. package/src/harness/hub-guidance.ts +140 -0
  26. package/src/harness/hub-reference.ts +18 -0
  27. package/src/harness/lesson-candidates.ts +162 -0
  28. package/src/harness/limits.ts +2 -0
  29. package/src/harness/privacy.ts +4 -0
  30. package/src/harness/receipts.ts +84 -0
  31. package/src/harness/rounds.ts +198 -0
  32. package/src/harness/transitions.ts +152 -0
  33. package/src/lit/candidates.ts +13 -5
  34. package/src/lit/cards.ts +55 -4
  35. package/src/lit/flow.ts +82 -0
  36. package/src/lit/queries.ts +62 -0
  37. package/src/manifest.ts +13 -6
  38. package/src/mcp-tools.ts +123 -25
  39. package/src/mcp.ts +4 -0
  40. package/src/memory/amem-show.ts +135 -0
  41. package/src/memory/amem.ts +3 -0
  42. package/src/memory/archive.ts +17 -8
  43. package/src/memory/evidence-local.ts +77 -0
  44. package/src/memory/evidence.ts +39 -0
  45. package/src/memory/lessons.ts +4 -2
  46. package/src/memory/skill-check.ts +56 -0
  47. package/src/memory/skill-format.ts +77 -0
  48. package/src/memory/skills.ts +72 -26
  49. package/src/memory/source-budget.ts +11 -0
  50. package/src/memory/vault-cards.ts +226 -0
  51. package/src/paper/build.ts +16 -7
  52. package/src/paper/check.ts +37 -10
  53. package/src/paper/headings.ts +39 -0
  54. package/src/paper/hygiene.ts +153 -0
  55. package/src/paper/placeholders.ts +16 -1
  56. package/src/paper/plan.ts +170 -0
  57. package/src/paper/point-evidence.ts +63 -0
  58. package/src/paper/points.ts +83 -0
  59. package/src/paper/review.ts +102 -9
  60. package/src/paper/scopes.ts +51 -0
  61. package/src/plan/definition.ts +5 -1
  62. package/src/plan/hub.ts +6 -0
  63. package/src/plan/state.ts +5 -0
  64. package/src/playbook.ts +35 -20
  65. package/src/privacy.ts +9 -0
  66. package/src/provenance.ts +679 -0
  67. package/src/scope.ts +24 -3
  68. package/src/study-export.ts +55 -27
  69. package/src/study.ts +54 -14
  70. package/src/ui/panel.css +4 -0
  71. package/src/ui/panel.js +263 -6
  72. package/src/ui/plugin.ts +68 -10
@@ -0,0 +1,135 @@
1
+ import type {SourceBudget} from "./source-budget.ts";
2
+ import {spawn} from "node:child_process";
3
+ import {once} from "node:events";
4
+ import {isAbsolute} from "node:path";
5
+ import {PROCESS_CONTEXT_ENV_KEYS, type ProcessRunner, type ProcessRequest, type ProcessResult} from "../exp/executor.ts";
6
+ import {plain, sha256} from "../study.ts";
7
+ import {canonical} from "../plan/state.ts";
8
+
9
+ export const AMEM_SHOW_MS = 25_000, AMEM_SHOW_BYTES = 262_144;
10
+ export interface ScreenedAmemInspection {
11
+ state: "available" | "changed" | "unavailable" | "unsupported";
12
+ digest: string | null;
13
+ observedAt: string;
14
+ sourceVersion?: string;
15
+ kind?: "decision" | "finding" | "contract" | "fail" | "other";
16
+ }
17
+ const ENV = ["PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "LANG", "LC_ALL", "LC_CTYPE", ...PROCESS_CONTEXT_ENV_KEYS];
18
+ /** Unlike spawnRunner, this transport passes exactly the screened environment and retains no diagnostics. */
19
+ interface ScreenedProcessResult extends ProcessResult {screenedOutputBytes: number}
20
+ const exactRunner = (request: ProcessRequest): Promise<ScreenedProcessResult> => new Promise((accept, reject) => {
21
+ const child = spawn(request.command, request.args, {cwd: request.cwd, env: request.env ?? {}, detached: true, stdio: ["pipe", "pipe", "pipe"]});
22
+ let bytes = 0, truncated = false, closed = false;
23
+ const kill = () => {
24
+ if (closed) return;
25
+ if (child.pid !== undefined) {try {process.kill(-child.pid, "SIGKILL"); return;} catch { /* fall back only to this owned child */ }}
26
+ child.kill("SIGKILL");
27
+ };
28
+ request.signal?.addEventListener("abort", kill, {once: true});
29
+ if (request.signal?.aborted) kill();
30
+ child.stdin.on("error", () => {});
31
+ const count = (chunk: Buffer) => {bytes += chunk.length; if (bytes > (request.maxOutputBytes ?? AMEM_SHOW_BYTES)) {truncated = true; kill(); return false;} return true;};
32
+ child.stdout.on("data", (chunk: Buffer) => {
33
+ if (!count(chunk)) return;
34
+ try {void Promise.resolve(request.stdoutSink?.(chunk)).catch(kill);} catch {kill();}
35
+ });
36
+ child.stderr.on("data", (chunk: Buffer) => {count(chunk);});
37
+ child.on("exit", kill);
38
+ child.on("error", reject);
39
+ child.on("close", code => {closed = true; request.signal?.removeEventListener("abort", kill); accept({screenedOutputBytes: bytes, exitCode: code ?? 1, stdout: "", stderr: "", ...(truncated ? {truncated: true} : {})});});
40
+ void (async () => {
41
+ try {
42
+ if (request.stdin && Symbol.asyncIterator in request.stdin) for await (const chunk of request.stdin) {if (!child.stdin.write(chunk)) await once(child.stdin, "drain");}
43
+ else if (request.stdin) child.stdin.write(request.stdin);
44
+ child.stdin.end();
45
+ } catch {kill();}
46
+ })();
47
+ });
48
+ function queue() {
49
+ const chunks: Uint8Array[] = []; let closed = false, wake: (() => void) | undefined;
50
+ return {
51
+ push(value: unknown) {chunks.push(Buffer.from(JSON.stringify(value) + "\n")); wake?.(); wake = undefined;},
52
+ close() {closed = true; wake?.(); wake = undefined;},
53
+ async *stream() {for (;;) {if (chunks.length) yield chunks.shift()!; else if (closed) return; else await new Promise<void>(resolve => {wake = resolve;});}},
54
+ };
55
+ }
56
+ export function supportsScreenedAmem(value: unknown): value is string {
57
+ if (typeof value !== "string" || value.length > 128) return false;
58
+ const match = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(value);
59
+ if (!match) return false;
60
+ const [major, minor, patch] = match.slice(1, 4).map(Number);
61
+ return [major, minor, patch].every(Number.isSafeInteger) && (major! > 0 || minor! > 22 || minor === 22 && (patch! > 1 || patch === 1 && !match[4]));
62
+ }
63
+ function showAdvertised(value: unknown): boolean {
64
+ if (!plain(value) || !Array.isArray(value.tools) || value.tools.length > 256 || value.nextCursor != null) return false;
65
+ const matches = value.tools.filter(tool => plain(tool) && tool.name === "amem_show");
66
+ if (matches.length !== 1) return false;
67
+ const schema = matches[0]!.inputSchema;
68
+ if (!plain(schema) || schema.type !== "object" || !plain(schema.properties) || Object.keys(schema.properties).length !== 1 || !plain(schema.properties.id) || schema.properties.id.type !== "string" || !Array.isArray(schema.required) || schema.required.length !== 1 || schema.required[0] !== "id" || schema.additionalProperties !== false) return false;
69
+ const id = schema.properties.id;
70
+ return (id.minLength === undefined || Number.isSafeInteger(id.minLength) && Number(id.minLength) >= 0 && Number(id.minLength) <= 32) && (id.maxLength === undefined || Number.isSafeInteger(id.maxLength) && Number(id.maxLength) >= 32);
71
+ }
72
+ /** Source contract: agent-mem 0.22.1 src/mcp.ts:14 and src/mcp-memory.ts:55,103ff,244ff: startup-scoped, screened curated amem_show. */
73
+ export async function readScreenedAmem(cwd: string, id: string, options: {runner?: ProcessRunner; env?: NodeJS.ProcessEnv; now?: () => number; timeoutMs?: number; maxOutputBytes?: number; budget?: SourceBudget; onText?: (text: string) => void} = {}): Promise<ScreenedAmemInspection> {
74
+ const now = options.now ?? Date.now;
75
+ const observedAt = () => {const value = now(); return Number.isFinite(value) && Math.abs(value) <= 8.64e15 ? new Date(value).toISOString() : new Date().toISOString();};
76
+ let version: string | undefined, responseObservedAt: string | undefined;
77
+ const result = (state: ScreenedAmemInspection["state"], digest: string | null = null): ScreenedAmemInspection => ({state, digest, observedAt: responseObservedAt ?? observedAt(), ...(version ? {sourceVersion: version} : {})});
78
+ const timeoutMs = Math.min(options.timeoutMs ?? AMEM_SHOW_MS, options.budget?.remainingMs() ?? AMEM_SHOW_MS), maxOutputBytes = Math.min(options.maxOutputBytes ?? AMEM_SHOW_BYTES, options.budget?.remainingBytes ?? AMEM_SHOW_BYTES);
79
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > AMEM_SHOW_MS || !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0 || maxOutputBytes > AMEM_SHOW_BYTES) return result("unavailable");
80
+ if (id.length !== 32 || !/^[a-f0-9]{32}$/.test(id) || !isAbsolute(cwd)) return result("unsupported");
81
+ const started = now(), input = queue(), stop = new AbortController(), pending = new Map<number, {resolve: (value: unknown) => void; reject: () => void}>();
82
+ let bytes = 0, buffer = "", broken = false, ended = false, accounted = false;
83
+ const refuse = () => {broken = true; for (const item of pending.values()) item.reject(); pending.clear(); stop.abort(); input.close();};
84
+ let deadline!: () => void;
85
+ const expired = new Promise<never>((_resolve, reject) => {deadline = () => {refuse(); reject(new Error("amem unavailable"));};});
86
+ void expired.catch(() => {});
87
+ const timer = setTimeout(deadline, timeoutMs), decoder = new TextDecoder("utf-8", {fatal: true});
88
+ const env = options.env ?? process.env, context = Object.fromEntries(ENV.flatMap(key => env[key] === undefined ? [] : [[key, env[key]!]]));
89
+ const child = Promise.resolve().then(() => (options.runner ?? exactRunner)({command: "amem", args: ["mcp"], cwd, env: context, stdin: input.stream(), signal: stop.signal, timeoutMs, maxOutputBytes,
90
+ stdoutSink(chunk) {
91
+ try {
92
+ bytes += chunk.byteLength; if (bytes > maxOutputBytes) throw new Error();
93
+ buffer += decoder.decode(chunk, {stream: true});
94
+ for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {
95
+ const line = buffer.slice(0, end); buffer = buffer.slice(end + 1); if (!line.trim()) continue;
96
+ const message: unknown = JSON.parse(line);
97
+ if (!plain(message) || message.jsonrpc !== "2.0") throw new Error();
98
+ if (!Object.hasOwn(message, "id") && typeof message.method === "string") continue;
99
+ const waiter = pending.get(message.id as number); if (!waiter || message.error !== undefined || !Object.hasOwn(message, "result")) throw new Error();
100
+ if (message.id === 3) responseObservedAt = observedAt();
101
+ pending.delete(message.id as number); waiter.resolve(message.result);
102
+ }
103
+ } catch {refuse();}
104
+ },
105
+ })).then(value => {
106
+ ended = true;
107
+ const observedBytes = options.runner === undefined && "screenedOutputBytes" in value ? Number(value.screenedOutputBytes) : bytes + Buffer.byteLength(value.stdout) + Buffer.byteLength(value.stderr);
108
+ accounted = true;
109
+ const withinBudget = options.budget?.consume(observedBytes) ?? true;
110
+ if (!withinBudget || observedBytes > maxOutputBytes || value.exitCode !== 0 || value.timedOut || value.truncated || bytes + Buffer.byteLength(value.stdout) + Buffer.byteLength(value.stderr) > maxOutputBytes || buffer.length || decoder.decode().length || pending.size) {refuse(); throw new Error("amem unavailable");}
111
+ }, () => {ended = true; refuse(); throw new Error("amem unavailable");});
112
+ void child.catch(() => {});
113
+ const call = async (requestId: number, method: string, params: unknown) => {
114
+ if (broken || ended || now() - started >= timeoutMs) throw new Error("amem unavailable");
115
+ const response = new Promise<unknown>((resolve, reject) => pending.set(requestId, {resolve, reject: () => reject(new Error("amem unavailable"))}));
116
+ input.push({jsonrpc: "2.0", id: requestId, method, params});
117
+ return Promise.race([response, expired, child.then(() => {throw new Error("amem unavailable");})]);
118
+ };
119
+ try {
120
+ const initialized = await call(1, "initialize", {protocolVersion: "2025-03-26", capabilities: {}, clientInfo: {name: "ares-evidence-reader", version: "1"}});
121
+ const info = plain(initialized) && plain(initialized.serverInfo) ? initialized.serverInfo : undefined;
122
+ if (!info || info.name !== "amem" || !supportsScreenedAmem(info.version)) {input.close(); await Promise.race([child, expired]); return result("unsupported");}
123
+ version = info.version;
124
+ input.push({jsonrpc: "2.0", method: "notifications/initialized"});
125
+ if (!showAdvertised(await call(2, "tools/list", {}))) {input.close(); await Promise.race([child, expired]); return result("unsupported");}
126
+ const response = await call(3, "tools/call", {name: "amem_show", arguments: {id}});
127
+ input.close(); await Promise.race([child, expired]);
128
+ if (broken || !plain(response) || response.isError === true || !Array.isArray(response.content) || response.content.length !== 1 || !plain(response.content[0]) || response.content[0].type !== "text" || typeof response.content[0].text !== "string") return result("unavailable");
129
+ let view: unknown; try {view = JSON.parse(response.content[0].text);} catch {return result("unavailable");}
130
+ if (!plain(view) || view.id !== id || typeof view.text !== "string" || typeof view.at !== "string" || !Number.isFinite(Date.parse(view.at)) || typeof view.project !== "string" || !["decision", "finding", "contract", "fail"].includes(String(view.kind)) || Object.hasOwn(view, "view") || Object.hasOwn(view, "capture") || view.evidence === false || view.stale !== undefined && typeof view.stale !== "boolean") return result("unavailable");
131
+ if (view.stale !== true) options.onText?.(view.text);
132
+ return {...result(view.stale === true ? "changed" : "available", sha256(canonical(view))), kind: view.kind as NonNullable<ScreenedAmemInspection["kind"]>};
133
+ } catch {return result("unavailable");}
134
+ finally {clearTimeout(timer); input.close(); stop.abort(); if (!accounted) options.budget?.exhaust();}
135
+ }
@@ -95,3 +95,6 @@ export function createAmemClient(cwd: string, runner: ProcessRunner = spawnRunne
95
95
  },
96
96
  };
97
97
  }
98
+
99
+ // Exact-id evidence reads use the screened MCP contract; existing archive/search CLI behavior stays separate.
100
+ export {readScreenedAmem, supportsScreenedAmem} from "./amem-show.ts";
@@ -1,3 +1,5 @@
1
+ import {recheckLessonExports, boundLessonExportBatch} from "../harness/lesson-candidates.ts";
2
+ import type {SkillCheckOptions} from "./skill-check.ts";
1
3
  import { ACCEPT_ARTIFACTS } from "../autonomy.ts";
2
4
  import { requireCopilotAccept } from "../copilot.ts";
3
5
  import { commit, prepareCommit, openStudy, plain, sha256, type Actor, type LedgerEvent } from "../study.ts";
@@ -8,14 +10,14 @@ import type { ProcessRunner } from "../exp/executor.ts";
8
10
 
9
11
  export const ARCHIVE_NOTES = 200;
10
12
  export interface ArchiveReceipt { sha256: string; id: string }
11
- export interface ArchivePreview { fingerprint: string; notes: { sha256: string; note: AmemNote }[] }
13
+ export interface ArchivePreview { recovery?: string; fingerprint: string; notes: { sha256: string; note: AmemNote }[] }
12
14
  export interface ArchiveResult extends ArchivePreview { written: ArchiveReceipt[]; remaining: number }
13
15
  /** Carries receipt progress for adapters; CLI/MCP retain the existing retry instruction verbatim. */
14
16
  export class ArchivePartialError extends Error {
15
17
  readonly failureMessage: string;
16
18
  constructor(readonly exportedCount: number, failure: unknown) {
17
19
  const detail = failure instanceof Error ? failure.message : "amem failure; check amem --version before retrying";
18
- super(`archive: ${exportedCount} note(s) written and receipted; rerun with the same --confirm to continue; ${detail}`);
20
+ super(`archive: ${exportedCount} note(s) written and receipted; rerun with the same --confirm to continue; ${detail}; receipt-only recovery cannot detect earlier unreceipted writes: reconcile with the owner before retrying an interrupted/crashed archive`);
19
21
  this.failureMessage = detail;
20
22
  }
21
23
  }
@@ -23,7 +25,7 @@ function hex(value: unknown, length: 32 | 64): value is string {
23
25
  return typeof value === "string" && value.length === length && /^[a-f0-9]+$/.test(value);
24
26
  }
25
27
  function badReceipt(): never { throw new Error("archive receipt: malformed or conflicting exported notes; restore the last valid archive.exported ledger event before retrying ares archive"); }
26
- function exported(events: LedgerEvent[]): Set<string> {
28
+ export function archiveReceiptIndex(events: LedgerEvent[]): Map<string, string> {
27
29
  const known = new Map<string, string>();
28
30
  for (const event of events) if (event.type === "archive.exported") {
29
31
  if (!hex(event.data.fingerprint, 64) || !Array.isArray(event.data.notes) || event.data.notes.length > ARCHIVE_NOTES) badReceipt();
@@ -33,21 +35,28 @@ function exported(events: LedgerEvent[]): Set<string> {
33
35
  known.set(row.sha256, row.id);
34
36
  }
35
37
  }
36
- return new Set(known.keys());
38
+ return known;
37
39
  }
38
40
  /** No lock, subprocess or write: confirmation binds the full list, receipts only narrow pending writes. */
39
41
  export function previewArchive(dir: string): ArchivePreview {
40
42
  for (const artifact of ACCEPT_ARTIFACTS) requireCopilotAccept(dir, artifact);
41
- const sources = readLessonSources(dir), notes = deriveLessons(sources), known = exported(sources.events);
43
+ const sources = readLessonSources(dir), notes = deriveLessons(sources), known = new Set(archiveReceiptIndex(sources.events).keys());
42
44
  const unique = new Map(notes.map(note => [sha256(canonical(note)), note]));
43
45
  const pending = [...unique].filter(([hash]) => !known.has(hash)).map(([sha256, note]) => ({ sha256, note }));
44
- return { fingerprint: sha256(canonical(notes)), notes: pending };
46
+ return {fingerprint: sha256(canonical(notes)), notes: pending, ...(sources.contrastNotes?.length ? {recovery: "Receipt-only dedupe: if an earlier archive was interrupted after amem add, operator reconciliation is required before retry; unreceipted writes cannot be detected and may duplicate"} : {})};
47
+ }
48
+ /** Preview and confirmed export use the same note/source bounds and ordered prefix. */
49
+ export function archiveExportBatch(dir: string, notes: ArchivePreview["notes"]) {
50
+ const bounded = notes.slice(0, ARCHIVE_NOTES);
51
+ return openStudy(dir).study.mode === "experiment" ? boundLessonExportBatch(dir, bounded) : bounded;
45
52
  }
46
53
  /** Caller holds the study lock across the confirmed write and its single receipt commit. */
47
- export async function exportArchive(dirArg: string, fingerprint: string, actor: Actor, runner?: ProcessRunner, env: NodeJS.ProcessEnv = process.env): Promise<ArchiveResult> {
54
+ export async function exportArchive(dirArg: string, fingerprint: string, actor: Actor, runner?: ProcessRunner, env: NodeJS.ProcessEnv = process.env, sourceOptions: SkillCheckOptions = {}): Promise<ArchiveResult> {
48
55
  const { dir } = openStudy(dirArg), preview = previewArchive(dir);
49
56
  if (!hex(fingerprint, 64) || fingerprint !== preview.fingerprint) throw new Error("archive: stale fingerprint; run ares archive <dir> again and confirm its current fingerprint");
50
- const batch = preview.notes.slice(0, ARCHIVE_NOTES);
57
+ const batch = archiveExportBatch(dir, preview.notes);
58
+ if (openStudy(dirArg).study.mode === "experiment") await recheckLessonExports(dirArg, batch.map(note => note.sha256), sourceOptions);
59
+ if (previewArchive(dirArg).fingerprint !== preview.fingerprint) throw new Error("archive: lesson sources changed during preflight; open a fresh preview and reconcile any unreceipted prior write before retrying");
51
60
  if (batch.length) {
52
61
  try { prepareCommit(dir, [], [{ actor, type: "archive.exported", data: {
53
62
  fingerprint, notes: batch.map(note => ({ sha256: note.sha256, id: "f".repeat(32) })),
@@ -0,0 +1,77 @@
1
+ import {openStudy} from "../study.ts";
2
+ import {localEvidenceSnapshot, validateExecutionReference, type ExecutionReferenceV1, type ProvenanceNode} from "../provenance.ts";
3
+
4
+ export interface LocalEvidenceInspection {
5
+ ref?: ExecutionReferenceV1;
6
+ state: "available" | "missing" | "changed" | "unavailable" | "unsupported";
7
+ digest: string | null;
8
+ sourceVersion?: {reference: 1; native?: number; ledger?: 1};
9
+ integrity: "record" | "receipt-only" | "unverified";
10
+ outcome: {status: "succeeded" | "failed" | "cancelled" | "unknown" | "unfinished" | "qualified" | "not_qualified" | "winner" | "no-winner" | "closed" | "not-applicable" | "unverified"; success: boolean};
11
+ metadata?: {family?: string; status?: string; winner?: boolean; qualification?: "qualified" | "not_qualified"};
12
+ support: "reviewer-judgment";
13
+ }
14
+ const base = (state: LocalEvidenceInspection["state"], ref?: ExecutionReferenceV1, digest: string | null = null): LocalEvidenceInspection => ({...(ref ? {ref, sourceVersion: {reference: 1 as const}} : {}), state, digest, integrity: "unverified", outcome: {status: "unverified", success: false}, support: "reviewer-judgment"});
15
+ const digestOf = (node: ProvenanceNode) => node.ref.sha256 ?? node.proof.sourceBindingSha256 ?? node.proof.recordSha256 ?? node.proof.sha256;
16
+ const unsupported = (codes: string[]) => codes.some(code => code.startsWith("unsupported"));
17
+
18
+ /** Typed local addresses only. A readable record or recorded successful outcome never establishes claim support. */
19
+ export function inspectLocalEvidence(dir: string, raw: unknown, snapshot?: ReturnType<typeof localEvidenceSnapshot>): LocalEvidenceInspection {
20
+ let ref: ExecutionReferenceV1;
21
+ try {const parsed = validateExecutionReference(raw); if (parsed.tool !== "ares") return base("unsupported"); ref = parsed;} catch {return base("unsupported");}
22
+ let study: ReturnType<typeof openStudy>["study"];
23
+ try {study = snapshot?.study ?? openStudy(dir).study;}
24
+ catch (error) {return base(error instanceof Error && /unsupported/.test(error.message) ? "unsupported" : "unavailable", ref);}
25
+ if (ref.projectKey !== study.id) return base("unsupported", ref);
26
+ const expected = ref.sha256;
27
+ try {
28
+ let matches: ProvenanceNode[], codes: string[], audit: {status: string};
29
+ if (snapshot) {
30
+ codes = snapshot.issues; audit = snapshot;
31
+ if (snapshot.status === "changed") return base("changed", ref);
32
+ if (unsupported(codes)) return base("unsupported", ref);
33
+ if (snapshot.status === "capped") return base("unavailable", ref);
34
+ matches = snapshot.nodes.filter(node => node.ref.projectKey === ref.projectKey && node.ref.kind === ref.kind && node.ref.id === ref.id && (ref.revision === undefined || ref.revision === node.ref.revision));
35
+ } else {
36
+ const shared = localEvidenceSnapshot(dir);
37
+ return inspectLocalEvidence(dir, raw, shared);
38
+ }
39
+ if (matches.length > 1 && expected === undefined) {
40
+ const families = new Set(matches.map(node => node.data?.family ?? node.ref.kind));
41
+ if (families.size > 1 || matches.filter(node => node.state === "current").length !== 1) return base("unsupported", ref);
42
+ }
43
+ const node = matches.find(node => expected !== undefined && digestOf(node) === expected)
44
+ ?? matches.find(node => node.state === "current") ?? matches[0];
45
+ if (!node) return base(codes.length ? "unavailable" : "missing", ref);
46
+ const digest = digestOf(node);
47
+ if (expected !== undefined && expected !== digest || node.state === "corrupt") return base("changed", ref, digest);
48
+ if (node.availability === "missing") return base("missing", ref, digest);
49
+ if (node.state === "unavailable" || node.state === "declared-unresolved" || audit.status !== "ok") return base("unavailable", ref, digest);
50
+ const result = base("available", ref, digest);
51
+ if (ref.kind === "paper-evidence" && node.availability === "available") {
52
+ const version = node.data?.nativeVersion;
53
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 1) return base("unavailable", ref, digest);
54
+ result.sourceVersion!.native = version;
55
+ }
56
+ if (ref.kind === "harness-closure") result.sourceVersion = {reference: 1, native: 1, ledger: 1};
57
+ if (node.state === "historical" || node.availability === "receipt-only") return result;
58
+ if (node.availability === "not-read" || ref.kind === "artifact") {result.integrity = "receipt-only"; return result;}
59
+ result.integrity = "record";
60
+ if (node.proof.ledgerIndex !== undefined) result.sourceVersion!.ledger = 1;
61
+ if (["attempt", "closed-result", "plan-revision"].includes(ref.kind)) result.sourceVersion!.native = 1;
62
+ if (ref.kind === "study") result.sourceVersion!.native = study.v;
63
+ const data = node.data ?? {}, metadata: NonNullable<LocalEvidenceInspection["metadata"]> = {};
64
+ if (["investigate", "ablate", "final", "paper"].includes(String(data.family))) metadata.family = String(data.family);
65
+ if (["succeeded", "failed", "cancelled", "unknown", "running", "qualified", "not_qualified", "open", "pivoted", "proposed", "accepted", "rejected", "withdrawn", "dispatched", "done", "uncertain"].includes(String(data.status))) metadata.status = String(data.status);
66
+ if (data.family === "investigate" && typeof data.winner === "boolean") metadata.winner = data.winner;
67
+ if (data.family === "final" && (data.status === "qualified" || data.status === "not_qualified")) metadata.qualification = data.status;
68
+ if (Object.keys(metadata).length) result.metadata = metadata;
69
+ if (ref.kind === "attempt") {
70
+ const status = data.status;
71
+ result.outcome = {status: status === "succeeded" || status === "failed" || status === "cancelled" ? status : status === "running" ? "unfinished" : "unknown", success: status === "succeeded"};
72
+ } else if (data.family === "final") result.outcome = {status: data.status === "qualified" || data.status === "not_qualified" ? data.status : "unknown", success: data.status === "qualified"};
73
+ else if (data.family === "investigate") result.outcome = {status: typeof data.winner === "boolean" ? data.winner ? "winner" : "no-winner" : "closed", success: false};
74
+ else result.outcome = {status: ref.kind === "closed-result" || ref.kind === "paper-evidence" || ref.kind === "harness-closure" ? "closed" : "not-applicable", success: false};
75
+ return result;
76
+ } catch (cause) {return base(cause instanceof Error && cause.message.includes("unsupported") ? "unsupported" : "unavailable", ref);}
77
+ }
@@ -0,0 +1,39 @@
1
+ import {plain, openStudy} from "../study.ts";
2
+ import {PROVENANCE_KINDS, validateExecutionReference, type ExecutionReferenceV1} from "../provenance.ts";
3
+ import {inspectLocalEvidence, type LocalEvidenceInspection} from "./evidence-local.ts";
4
+ import {readScreenedAmem} from "./amem-show.ts";
5
+ import type {ProcessRunner} from "../exp/executor.ts";
6
+
7
+ export interface AmemEvidenceReference {v: 1; tool: "amem"; id: string}
8
+ export type SkillEvidenceReference = ExecutionReferenceV1 | AmemEvidenceReference;
9
+ export interface EvidenceInspection extends Omit<LocalEvidenceInspection, "ref" | "sourceVersion" | "integrity" | "metadata"> {
10
+ ref?: SkillEvidenceReference;
11
+ sourceVersion?: {reference: 1; native?: number; ledger?: 1; amem?: string};
12
+ integrity: LocalEvidenceInspection["integrity"] | "screened";
13
+ metadata?: LocalEvidenceInspection["metadata"] & {kind?: string};
14
+ observedAt?: string;
15
+ }
16
+ /** Compatibility strings are addresses only, never file paths or resolver instructions. */
17
+ export function skillEvidenceReference(raw: unknown, studyId?: string): SkillEvidenceReference | undefined {
18
+ if (typeof raw === "string") {
19
+ if (raw.length === 32 && /^[a-f0-9]{32}$/.test(raw)) return {v: 1, tool: "amem", id: raw};
20
+ const match = /^ares:([^/]+)\/([^:]+):(.+)$/.exec(raw);
21
+ if (!match || !(PROVENANCE_KINDS as readonly string[]).includes(match[2]!)) return undefined;
22
+ raw = {v: 1, tool: "ares", projectKey: match[1], kind: match[2], id: match[3]};
23
+ }
24
+ if (plain(raw) && raw.v === 1 && raw.tool === "amem" && Object.keys(raw).every(key => ["v", "tool", "id"].includes(key)) && typeof raw.id === "string" && raw.id.length === 32 && /^[a-f0-9]{32}$/.test(raw.id)) return {v: 1, tool: "amem", id: raw.id};
25
+ try {const ref = validateExecutionReference(raw); return ref.tool === "ares" && (studyId === undefined || ref.projectKey === studyId) ? ref : undefined;}
26
+ catch {return undefined;}
27
+ }
28
+ const refused = (state: EvidenceInspection["state"], ref?: SkillEvidenceReference): EvidenceInspection => ({...(ref ? {ref} : {}), state, digest: null, integrity: "unverified", outcome: {status: "unverified", success: false}, support: "reviewer-judgment"});
29
+ /** Single-source compatibility reader. Skill decisions use the aggregate snapshot/budget in skill-check.ts. */
30
+ export async function inspectSkillEvidence(dir: string, raw: unknown, options: {runner?: ProcessRunner; env?: NodeJS.ProcessEnv; now?: () => number} = {}): Promise<EvidenceInspection> {
31
+ let studyId: string, projectDir: string;
32
+ try {const opened = openStudy(dir); studyId = opened.study.id; projectDir = opened.dir;} catch (error) {return refused(error instanceof Error && /unsupported/.test(error.message) ? "unsupported" : "unavailable");}
33
+ const ref = skillEvidenceReference(raw, studyId);
34
+ if (!ref) return refused("unsupported");
35
+ if (ref.tool === "ares") return inspectLocalEvidence(projectDir, ref);
36
+ const result = await readScreenedAmem(projectDir, ref.id, options);
37
+ if (result.state !== "available" && result.state !== "changed") return {...refused(result.state, ref), observedAt: result.observedAt};
38
+ return {ref, state: result.state, digest: result.digest, integrity: result.state === "available" ? "screened" : "unverified", outcome: {status: "not-applicable", success: false}, support: "reviewer-judgment", sourceVersion: {reference: 1, ...(result.sourceVersion ? {amem: result.sourceVersion} : {})}, observedAt: result.observedAt, ...(result.kind ? {metadata: {kind: result.kind}} : {})};
39
+ }
@@ -1,3 +1,4 @@
1
+ import {eligibleLessonNotes} from "../harness/lesson-candidates.ts";
1
2
  import { openStudy, readLedger, type LedgerEvent, type Study } from "../study.ts";
2
3
  import { foldIdeas } from "../exp/ideas.ts";
3
4
  import { readProtocol } from "../exp/protocol.ts";
@@ -9,13 +10,13 @@ import type { AmemNote, AmemHit } from "./amem.ts";
9
10
 
10
11
  export interface LessonSources {
11
12
  study: Pick<Study, "id" | "question">; events: LedgerEvent[];
12
- investigation?: InvestigateResult; final?: FinalResult; selection?: Selection; finalSeeds?: FinalSeeds;
13
+ contrastNotes?: AmemNote[]; investigation?: InvestigateResult; final?: FinalResult; selection?: Selection; finalSeeds?: FinalSeeds;
13
14
  }
14
15
  export const LESSON_EVIDENCE_REFS = 16;
15
16
  /** Read current committed sources only. An absent close yields no lesson; an invalid close refuses. */
16
17
  export function readLessonSources(dirArg: string): LessonSources {
17
18
  const { dir, study } = openStudy(dirArg), events = readLedger(dir), protocol = readProtocol(dir);
18
- const sources: LessonSources = { study, events };
19
+ const sources: LessonSources = {study, events, ...(study.mode === "experiment" ? {contrastNotes: eligibleLessonNotes(dir).map(value => value.note)} : {})};
19
20
  if (protocol) {
20
21
  sources.selection = readSelection(dir, protocol);
21
22
  sources.finalSeeds = readFinalSeeds(dir, protocol);
@@ -65,6 +66,7 @@ export function deriveLessons(sources: LessonSources): AmemNote[] {
65
66
  text: `Review contradiction ${review.id}/${finding.id}: ${finding.text}; resolution: ${resolution.reason}`, evidence: [] });
66
67
  }
67
68
  }
69
+ notes.push(...(sources.contrastNotes ?? []));
68
70
  return notes;
69
71
  }
70
72
 
@@ -0,0 +1,56 @@
1
+ import {openStudy, sha256, assertStudyReadLock, type StudyReadLock} from "../study.ts";
2
+ import {canonical} from "../plan/state.ts";
3
+ import {localEvidenceSnapshot} from "../provenance.ts";
4
+ import {inspectLocalEvidence} from "./evidence-local.ts";
5
+ import {readScreenedAmem} from "./amem-show.ts";
6
+ import {skillEvidenceReference, type SkillEvidenceReference, type EvidenceInspection} from "./evidence.ts";
7
+ import {sourceBudget, SOURCE_BYTES, type SourceBudget} from "./source-budget.ts";
8
+ import type {ProcessRunner} from "../exp/executor.ts";
9
+
10
+ export interface SkillCheckOptions {runner?: ProcessRunner; env?: NodeJS.ProcessEnv; now?: () => number; lock?: StudyReadLock; budget?: SourceBudget}
11
+ const unavailable = (ref: SkillEvidenceReference): EvidenceInspection => ({ref, state: "unavailable", digest: null, integrity: "unverified", outcome: {status: "unverified", success: false}, support: "reviewer-judgment"});
12
+ export function semanticInspection(value: EvidenceInspection) {const {observedAt: _time, ...content} = value; return content;}
13
+ export const evidenceFingerprint = (proposalSha256: string, inspections: EvidenceInspection[], localGeneration: string | null) => sha256(canonical({proposalSha256, inspections, localGeneration}));
14
+ /** One captured local producer view and one aggregate 25s/256KiB response budget across all exact-id reads. */
15
+ export async function inspectSkillEvidenceSet(dirArg: string, raw: readonly SkillEvidenceReference[], options: SkillCheckOptions = {}) {
16
+ const {dir, study} = openStudy(dirArg), budget = options.budget ?? sourceBudget(options.now), refs: SkillEvidenceReference[] = [];
17
+ if (!Array.isArray(raw) || raw.length > 64) throw new Error("skill check: evidence bound exceeded; create a revised proposal with at most 64 sources and honest limitations");
18
+ const unique = new Set<string>();
19
+ for (const value of raw) {const ref = skillEvidenceReference(value, study.id); if (!ref) throw new Error("skill check: unsupported or wrong-study reference; create a revised proposal with current-study typed refs and honest limitations"); const key = canonical(ref); if (!unique.has(key)) {unique.add(key); refs.push(ref);}}
20
+ let local: ReturnType<typeof localEvidenceSnapshot> | undefined, localFailure: "unsupported" | "unavailable" | undefined;
21
+ if (refs.some(ref => ref.tool === "ares")) {
22
+ try {local = localEvidenceSnapshot(dir, options.lock); if (!budget.consume(local.bytes)) {local = undefined; localFailure = "unavailable";}}
23
+ catch (cause) {localFailure = cause instanceof Error && cause.message.includes("unsupported") ? "unsupported" : "unavailable";}
24
+ }
25
+ const inspections: EvidenceInspection[] = [];
26
+ for (const ref of refs) {
27
+ if (budget.remainingMs() <= 0 || budget.remainingBytes <= 0) {inspections.push(unavailable(ref)); continue;}
28
+ if (ref.tool === "ares") {inspections.push(local ? inspectLocalEvidence(dir, ref, local) : {...unavailable(ref), state: localFailure ?? "unavailable"}); continue;}
29
+ const result = await readScreenedAmem(dir, ref.id, {...options, budget});
30
+ inspections.push(result.state === "available" || result.state === "changed" ? {ref, state: result.state, digest: result.digest, integrity: result.state === "available" ? "screened" : "unverified", outcome: {status: "not-applicable", success: false}, support: "reviewer-judgment", sourceVersion: {reference: 1, ...(result.sourceVersion ? {amem: result.sourceVersion} : {})}, observedAt: result.observedAt, ...(result.kind ? {metadata: {kind: result.kind}} : {})} : {...unavailable(ref), state: result.state, observedAt: result.observedAt});
31
+ }
32
+ const recheck = () => {
33
+ if (budget.remainingMs() <= 0) return false;
34
+ try {if (options.lock) assertStudyReadLock(dir, options.lock); if (canonical(openStudy(dir).study) !== canonical(study) || (local ? !local.recheck() : refs.some(ref => ref.tool === "ares"))) return false;} catch {return false;}
35
+ return budget.remainingMs() > 0;
36
+ };
37
+ if (!recheck()) for (let i = 0; i < inspections.length; i++) {
38
+ const row = inspections[i]!, expired = budget.remainingMs() <= 0;
39
+ if (row.ref?.tool === "ares" && local || expired) inspections[i] = {...row, state: expired ? "unavailable" : "changed", digest: expired ? null : row.digest, integrity: "unverified", outcome: {status: "unverified", success: false}};
40
+ }
41
+ return {inspections, localFailure, localGeneration: local?.sourceSha256 ?? null, bytes: SOURCE_BYTES - budget.remainingBytes, remainingMs: budget.remainingMs(), recheck};
42
+ }
43
+ export function compareSkillInspections(pinned: EvidenceInspection[], current: EvidenceInspection[]) {
44
+ const expected = new Map(pinned.map(row => [canonical(row.ref), row]));
45
+ const reasons: string[] = [];
46
+ for (const row of current) {const before = expected.get(canonical(row.ref)); if (!before || row.state !== "available" || before.state !== "available" || canonical(semanticInspection(row)) !== canonical(semanticInspection(before))) reasons.push(row.state === "available" ? "changed-source" : row.state);}
47
+ if (expected.size !== current.length) reasons.push("source-set-changed"); return reasons;
48
+ }
49
+ export function unsupportedSourceGuidance(inspections: readonly EvidenceInspection[]): string {
50
+ const tools = new Set(inspections.filter(row => row.state === "unsupported").map(row => row.ref?.tool));
51
+ return [tools.has("ares") ? "use a compatible ares version or restore the local record, keeping bytes unchanged" : "", tools.has("amem") ? "use amem >=0.22.1 with screened exact-id amem_show" : ""].filter(Boolean).join("; ");
52
+ }
53
+ export function requireSkillEvidence(why: string, operation: "accept" | "propose" = "accept", inspections: readonly EvidenceInspection[] = []): never {
54
+ const next = operation === "propose" ? "retry ares skill propose after restoring source access/budget, or revise the proposal input with honest limitations" : "create a revised proposal with current evidence/counterevidence and honest limitations, then run ares skill check before deciding", source = unsupportedSourceGuidance(inspections);
55
+ throw new Error(`skill ${operation}: ${why}; ${next}${source ? `; ${source}` : ""}`);
56
+ }
@@ -0,0 +1,77 @@
1
+ import {hasHarnessCredential} from "../harness/privacy.ts";
2
+ import {assertWritable, boundedText, onlyKeys, plain, isHarnessGate} from "../study.ts";
3
+ import {SKILL_BYTES, SKILL_EVIDENCE} from "./skills.ts";
4
+ import {skillEvidenceReference, type EvidenceInspection, type SkillEvidenceReference} from "./evidence.ts";
5
+ import {supportsScreenedAmem} from "./amem-show.ts";
6
+
7
+ export interface SkillProposalV2 {
8
+ name: string; summary: string; steps: string[]; evidence: SkillEvidenceReference[];
9
+ applicability?: string; limitations: string[]; counterevidence: SkillEvidenceReference[]; inspections: EvidenceInspection[];
10
+ }
11
+ const STATES = ["available", "missing", "changed", "unavailable", "unsupported"];
12
+ const OUTCOMES = ["succeeded", "failed", "cancelled", "unknown", "unfinished", "qualified", "not_qualified", "winner", "no-winner", "closed", "not-applicable", "unverified"];
13
+ function bad(): never {throw new Error("skill v2: invalid or over-bound proposal/inspection; restore the versioned proposal or revise its bounded references and inspection metadata, then retry");}
14
+ function object(value: unknown, fields: string[]): Record<string, unknown> {
15
+ if (!plain(value)) bad(); try {onlyKeys(value, fields, "skill v2");} catch {bad();} return value;
16
+ }
17
+ function text(value: unknown, bound: number): string {
18
+ try {const result = boundedText(value, "skill v2 text", bound); if (result.includes("\0") || Buffer.byteLength(result) > bound || hasHarnessCredential(result)) bad(); return result;} catch {return bad();}
19
+ }
20
+ function ref(value: unknown, studyId?: string): SkillEvidenceReference {
21
+ const reference = skillEvidenceReference(value, studyId) ?? bad();
22
+ if (Object.values(reference).some(value => typeof value === "string" && hasHarnessCredential(value))) bad(); return reference;
23
+ }
24
+ function refs(value: unknown, required: boolean, studyId?: string): SkillEvidenceReference[] {
25
+ if (!Array.isArray(value) || value.length > SKILL_EVIDENCE || required && !value.length) bad(); return value.map(value => ref(value, studyId));
26
+ }
27
+ function inspection(value: unknown, studyId?: string): EvidenceInspection {
28
+ const row = object(value, ["ref", "state", "digest", "integrity", "outcome", "support", "sourceVersion", "observedAt", "metadata"]), reference = ref(row.ref, studyId);
29
+ if (!STATES.includes(row.state as string) || row.digest !== null && (typeof row.digest !== "string" || !/^[a-f0-9]{64}$/.test(row.digest)) || !["record", "receipt-only", "unverified", "screened"].includes(row.integrity as string) || row.support !== "reviewer-judgment") bad();
30
+ const outcome = object(row.outcome, ["status", "success"]);
31
+ if (!OUTCOMES.includes(outcome.status as string) || typeof outcome.success !== "boolean") bad();
32
+ if (outcome.success && (row.state !== "available" || row.integrity !== "record" || !["succeeded", "qualified"].includes(outcome.status as string))) bad();
33
+ if (row.state === "available" && (row.digest === null || reference.tool === "ares" && reference.sha256 !== undefined && reference.sha256 !== row.digest)) bad();
34
+ if (reference.tool === "ares" && row.integrity === "screened" || reference.tool === "amem" && row.integrity === "record") bad();
35
+ if (reference.tool === "amem" && ["missing", "unavailable", "unsupported"].includes(row.state as string) && row.digest !== null) bad();
36
+ const result = {ref: reference, state: row.state, digest: row.digest, integrity: row.integrity, outcome: {status: outcome.status, success: outcome.success}, support: "reviewer-judgment"} as EvidenceInspection;
37
+ if (row.sourceVersion !== undefined) {
38
+ const version = object(row.sourceVersion, ["reference", "native", "ledger", "amem"]);
39
+ if (version.reference !== 1 || version.native !== undefined && (!Number.isSafeInteger(version.native) || Number(version.native) < 1 || Number(version.native) > 1_000_000) || version.ledger !== undefined && version.ledger !== 1 || version.amem !== undefined && (typeof version.amem !== "string" || version.amem.length > 64)) bad();
40
+ result.sourceVersion = {reference: 1, ...(version.native !== undefined ? {native: version.native as number} : {}), ...(version.ledger === 1 ? {ledger: 1 as const} : {}), ...(version.amem !== undefined ? {amem: version.amem as string} : {})};
41
+ }
42
+ if (row.observedAt !== undefined) {if (typeof row.observedAt !== "string" || row.observedAt.length > 64 || !Number.isFinite(Date.parse(row.observedAt))) bad(); result.observedAt = row.observedAt;}
43
+ if (row.state === "available" && (!result.sourceVersion || reference.tool === "amem" && (row.integrity !== "screened" || !supportsScreenedAmem(result.sourceVersion.amem) || !result.observedAt))) bad();
44
+ if (row.metadata !== undefined) {
45
+ const data = object(row.metadata, ["family", "status", "winner", "qualification", "kind"]);
46
+ if (data.family !== undefined && !["investigate", "ablate", "final", "paper"].includes(data.family as string) || data.status !== undefined && !["succeeded", "failed", "cancelled", "unknown", "running", "qualified", "not_qualified", "open", "pivoted", "proposed", "accepted", "rejected", "withdrawn", "dispatched", "done", "uncertain"].includes(data.status as string) || data.winner !== undefined && typeof data.winner !== "boolean" || data.qualification !== undefined && !["qualified", "not_qualified"].includes(data.qualification as string) || data.kind !== undefined && !["fail", "finding", "decision", "contract", "other"].includes(data.kind as string)) bad();
47
+ result.metadata = {...(data.family !== undefined ? {family: data.family as string} : {}), ...(data.status !== undefined ? {status: data.status as string} : {}), ...(data.winner !== undefined ? {winner: data.winner as boolean} : {}), ...(data.qualification !== undefined ? {qualification: data.qualification as "qualified" | "not_qualified"} : {}), ...(data.kind !== undefined ? {kind: data.kind as string} : {})};
48
+ }
49
+ return result;
50
+ }
51
+ /** Decision receipts validate independently of the immutable proposal Markdown ceiling. */
52
+ export function validateSkillInspections(raw: unknown, references: readonly SkillEvidenceReference[], studyId?: string): EvidenceInspection[] {
53
+ if (!Array.isArray(raw) || raw.length > SKILL_EVIDENCE) bad();
54
+ const observed = raw.map(value => inspection(value, studyId)), expected = new Set(references.map(value => JSON.stringify(ref(value, studyId)))), keys = observed.map(value => JSON.stringify(value.ref));
55
+ if (expected.size > SKILL_EVIDENCE || keys.length !== expected.size || new Set(keys).size !== keys.length || keys.some(key => !expected.has(key))) bad();
56
+ return observed;
57
+ }
58
+ /** New input never supplies source-owned inspection receipts. Historical v1 parsing stays separate. */
59
+ export function validateSkillInputV2(raw: unknown, studyId: string): Omit<SkillProposalV2, "inspections"> {
60
+ const row = object(raw, ["name", "summary", "steps", "evidence", "applicability", "limitations", "counterevidence"]);
61
+ const evidence = refs(row.evidence, true, studyId), counterevidence = refs(row.counterevidence === undefined ? [] : row.counterevidence, false, studyId);
62
+ const unique = [...new Map([...evidence, ...counterevidence].map(value => [JSON.stringify(value), value])).values()];
63
+ const placeholders = unique.map(ref => ({ref, state: "unavailable", digest: null, integrity: "unverified", outcome: {status: "unverified", success: false}, support: "reviewer-judgment"}));
64
+ const {inspections: _unused, ...input} = validateSkillProposalV2({...row, evidence, counterevidence, inspections: placeholders}, studyId); return input;
65
+ }
66
+ export function validateSkillProposalV2(raw: unknown, studyId?: string): SkillProposalV2 {
67
+ const row = object(raw, ["name", "summary", "steps", "evidence", "applicability", "limitations", "counterevidence", "inspections"]);
68
+ if (typeof row.name !== "string" || !isHarnessGate(`harness:${row.name}`) || !Array.isArray(row.steps) || !row.steps.length || row.steps.length > 64 || !Array.isArray(row.inspections) || row.inspections.length > SKILL_EVIDENCE) bad();
69
+ const limitations = row.limitations === undefined ? [] : row.limitations; if (!Array.isArray(limitations) || limitations.length > 16) bad();
70
+ const evidence = refs(row.evidence, true, studyId), counterevidence = refs(row.counterevidence === undefined ? [] : row.counterevidence, false, studyId);
71
+ const proposal: SkillProposalV2 = {name: row.name, summary: text(row.summary, 4000), steps: row.steps.map(value => text(value, 1000)), evidence, ...(row.applicability !== undefined ? {applicability: text(row.applicability, 2000)} : {}), limitations: limitations.map(value => text(value, 1000)), counterevidence, inspections: validateSkillInspections(row.inspections, [...evidence, ...counterevidence], studyId)};
72
+ assertWritable(skillMarkdownV2(proposal), SKILL_BYTES, "skill v2 proposal"); return proposal;
73
+ }
74
+ export function skillMarkdownV2(proposal: SkillProposalV2): string {
75
+ const list = (values: string[]) => values.map(value => `- ${value.replaceAll("\n", "\n ")}`).join("\n");
76
+ return `---\nskillProposal: 2\nname: ${proposal.name}\n---\n\n# ${proposal.name}\n\n${proposal.summary}\n\n## Steps\n\n${list(proposal.steps)}\n\n## Evidence\n\n${list(proposal.evidence.map(value => JSON.stringify(value)))}\n\n## Applicability\n\n${proposal.applicability ?? "not recorded"}\n\n## Limitations\n\n${list(proposal.limitations)}\n\n## Counterevidence\n\n${list(proposal.counterevidence.map(value => JSON.stringify(value)))}\n\n## Inspection receipts\n\n\`\`\`json\n${JSON.stringify(proposal.inspections, null, 2)}\n\`\`\`\n`;
77
+ }