@staix/agent-research 0.1.0 → 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 (78) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/README.md +356 -31
  3. package/package.json +4 -2
  4. package/src/autonomy.ts +50 -0
  5. package/src/cli.ts +134 -14
  6. package/src/commands-table.ts +43 -9
  7. package/src/commands.ts +244 -43
  8. package/src/copilot.ts +91 -0
  9. package/src/exp/attempts.ts +512 -69
  10. package/src/exp/executor.ts +235 -12
  11. package/src/exp/final.ts +1 -1
  12. package/src/exp/investigate.ts +7 -2
  13. package/src/exp/logs.ts +25 -12
  14. package/src/exp/metrics.ts +6 -5
  15. package/src/exp/pipeline.ts +92 -0
  16. package/src/exp/protocol.ts +88 -18
  17. package/src/exp/retention-script.ts +649 -0
  18. package/src/exp/retention.ts +70 -0
  19. package/src/exp/reuse-admission.ts +63 -0
  20. package/src/exp/reuse-contract.ts +48 -0
  21. package/src/exp/reuse-runtime.ts +87 -0
  22. package/src/exp/reuse.ts +87 -0
  23. package/src/exp/selection.ts +1 -1
  24. package/src/exp/snapshot.ts +3 -3
  25. package/src/exp/stages.ts +117 -0
  26. package/src/harness/experience-source.ts +34 -0
  27. package/src/harness/experience.ts +206 -0
  28. package/src/harness/hub-guidance.ts +140 -0
  29. package/src/harness/hub-reference.ts +18 -0
  30. package/src/harness/lesson-candidates.ts +162 -0
  31. package/src/harness/limits.ts +2 -0
  32. package/src/harness/privacy.ts +4 -0
  33. package/src/harness/receipts.ts +84 -0
  34. package/src/harness/rounds.ts +198 -0
  35. package/src/harness/transitions.ts +152 -0
  36. package/src/http.ts +46 -2
  37. package/src/lit/candidates.ts +13 -5
  38. package/src/lit/cards.ts +55 -4
  39. package/src/lit/flow.ts +82 -0
  40. package/src/lit/queries.ts +62 -0
  41. package/src/lit/watch.ts +14 -1
  42. package/src/manifest.ts +15 -7
  43. package/src/mcp-tools.ts +140 -32
  44. package/src/mcp.ts +6 -0
  45. package/src/memory/amem-show.ts +135 -0
  46. package/src/memory/amem.ts +3 -0
  47. package/src/memory/archive.ts +20 -8
  48. package/src/memory/evidence-local.ts +77 -0
  49. package/src/memory/evidence.ts +39 -0
  50. package/src/memory/lessons.ts +4 -2
  51. package/src/memory/skill-check.ts +56 -0
  52. package/src/memory/skill-format.ts +77 -0
  53. package/src/memory/skills.ts +72 -26
  54. package/src/memory/source-budget.ts +11 -0
  55. package/src/memory/vault-cards.ts +226 -0
  56. package/src/paper/build.ts +20 -8
  57. package/src/paper/check.ts +40 -12
  58. package/src/paper/headings.ts +39 -0
  59. package/src/paper/hygiene.ts +153 -0
  60. package/src/paper/placeholders.ts +21 -4
  61. package/src/paper/plan.ts +170 -0
  62. package/src/paper/point-evidence.ts +63 -0
  63. package/src/paper/points.ts +83 -0
  64. package/src/paper/review.ts +116 -11
  65. package/src/paper/scopes.ts +51 -0
  66. package/src/plan/controller.ts +42 -12
  67. package/src/plan/definition.ts +22 -6
  68. package/src/plan/hub.ts +6 -0
  69. package/src/plan/state.ts +58 -17
  70. package/src/playbook.ts +47 -20
  71. package/src/privacy.ts +9 -0
  72. package/src/provenance.ts +679 -0
  73. package/src/scope.ts +24 -3
  74. package/src/study-export.ts +282 -0
  75. package/src/study.ts +94 -26
  76. package/src/ui/panel.css +4 -0
  77. package/src/ui/panel.js +271 -9
  78. package/src/ui/plugin.ts +89 -17
@@ -1,3 +1,7 @@
1
+ import {recheckLessonExports, boundLessonExportBatch} from "../harness/lesson-candidates.ts";
2
+ import type {SkillCheckOptions} from "./skill-check.ts";
3
+ import { ACCEPT_ARTIFACTS } from "../autonomy.ts";
4
+ import { requireCopilotAccept } from "../copilot.ts";
1
5
  import { commit, prepareCommit, openStudy, plain, sha256, type Actor, type LedgerEvent } from "../study.ts";
2
6
  import { canonical } from "../plan/state.ts";
3
7
  import { createAmemClient, type AmemNote } from "./amem.ts";
@@ -6,14 +10,14 @@ import type { ProcessRunner } from "../exp/executor.ts";
6
10
 
7
11
  export const ARCHIVE_NOTES = 200;
8
12
  export interface ArchiveReceipt { sha256: string; id: string }
9
- export interface ArchivePreview { fingerprint: string; notes: { sha256: string; note: AmemNote }[] }
13
+ export interface ArchivePreview { recovery?: string; fingerprint: string; notes: { sha256: string; note: AmemNote }[] }
10
14
  export interface ArchiveResult extends ArchivePreview { written: ArchiveReceipt[]; remaining: number }
11
15
  /** Carries receipt progress for adapters; CLI/MCP retain the existing retry instruction verbatim. */
12
16
  export class ArchivePartialError extends Error {
13
17
  readonly failureMessage: string;
14
18
  constructor(readonly exportedCount: number, failure: unknown) {
15
19
  const detail = failure instanceof Error ? failure.message : "amem failure; check amem --version before retrying";
16
- 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`);
17
21
  this.failureMessage = detail;
18
22
  }
19
23
  }
@@ -21,7 +25,7 @@ function hex(value: unknown, length: 32 | 64): value is string {
21
25
  return typeof value === "string" && value.length === length && /^[a-f0-9]+$/.test(value);
22
26
  }
23
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"); }
24
- function exported(events: LedgerEvent[]): Set<string> {
28
+ export function archiveReceiptIndex(events: LedgerEvent[]): Map<string, string> {
25
29
  const known = new Map<string, string>();
26
30
  for (const event of events) if (event.type === "archive.exported") {
27
31
  if (!hex(event.data.fingerprint, 64) || !Array.isArray(event.data.notes) || event.data.notes.length > ARCHIVE_NOTES) badReceipt();
@@ -31,20 +35,28 @@ function exported(events: LedgerEvent[]): Set<string> {
31
35
  known.set(row.sha256, row.id);
32
36
  }
33
37
  }
34
- return new Set(known.keys());
38
+ return known;
35
39
  }
36
40
  /** No lock, subprocess or write: confirmation binds the full list, receipts only narrow pending writes. */
37
41
  export function previewArchive(dir: string): ArchivePreview {
38
- const sources = readLessonSources(dir), notes = deriveLessons(sources), known = exported(sources.events);
42
+ for (const artifact of ACCEPT_ARTIFACTS) requireCopilotAccept(dir, artifact);
43
+ const sources = readLessonSources(dir), notes = deriveLessons(sources), known = new Set(archiveReceiptIndex(sources.events).keys());
39
44
  const unique = new Map(notes.map(note => [sha256(canonical(note)), note]));
40
45
  const pending = [...unique].filter(([hash]) => !known.has(hash)).map(([sha256, note]) => ({ sha256, note }));
41
- 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;
42
52
  }
43
53
  /** Caller holds the study lock across the confirmed write and its single receipt commit. */
44
- 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> {
45
55
  const { dir } = openStudy(dirArg), preview = previewArchive(dir);
46
56
  if (!hex(fingerprint, 64) || fingerprint !== preview.fingerprint) throw new Error("archive: stale fingerprint; run ares archive <dir> again and confirm its current fingerprint");
47
- 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");
48
60
  if (batch.length) {
49
61
  try { prepareCommit(dir, [], [{ actor, type: "archive.exported", data: {
50
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
+ }
@@ -1,14 +1,20 @@
1
- import { existsSync } from "node:fs";
1
+ import {inspectSkillEvidenceSet, compareSkillInspections, evidenceFingerprint, requireSkillEvidence, unsupportedSourceGuidance, type SkillCheckOptions} from "./skill-check.ts";
2
+ import type {EvidenceInspection} from "./evidence.ts";
3
+ import {canonical} from "../plan/state.ts";
4
+ import {skillMarkdownV2, validateSkillProposalV2, validateSkillInputV2, validateSkillInspections, type SkillProposalV2} from "./skill-format.ts";
5
+ import { lstatSync } from "node:fs";
2
6
  import { join } from "node:path";
3
- import { assertWritable, boundedText, commit, onlyKeys, openStudy, plain, readLedger, readTextBounded, sha256, type Actor, type LedgerEvent } from "../study.ts";
7
+ import { assertWritable, boundedText, commit, onlyKeys, openStudy, plain, readLedger, readTextBounded, sha256, assertStudyReadLock, type Actor, type LedgerEvent } from "../study.ts";
4
8
 
5
- export const SKILL_PROPOSAL_VERSION = 1, SKILL_PROPOSALS = 100, SKILL_BYTES = 16 * 1024, SKILL_EVIDENCE = 64;
9
+ export const SKILL_PROPOSAL_VERSION = 2, SKILL_PROPOSALS = 100, SKILL_BYTES = 16 * 1024, SKILL_EVIDENCE = 64;
6
10
  export interface SkillProposal { name: string; summary: string; steps: string[]; evidence: string[] }
7
11
  export type SkillDecision = "accept" | "reject" | "withdraw";
8
- export interface SkillRecord extends SkillProposal {
9
- skillProposal: 1; state: "proposed" | "accepted" | "rejected" | "withdrawn"; sha256: string; actor: Actor; at: string;
10
- decision?: { action: SkillDecision; reason: string; pr?: string; actor: Actor; at: string };
12
+ interface SkillRecordState {
13
+ state: "proposed" | "accepted" | "rejected" | "withdrawn"; sha256: string; actor: Actor; at: string;
14
+ decision?: { action: SkillDecision; reason: string; pr?: string; actor: Actor; at: string; evidenceFingerprint?: string; inspections?: EvidenceInspection[]; localGeneration?: string | null };
11
15
  }
16
+ export type SkillRecord = SkillRecordState & (SkillProposal & {skillProposal: 1; evidenceStatus: "legacy-unresolved"} | SkillProposalV2 & {skillProposal: 2; evidenceStatus: "inspection-required"});
17
+
12
18
  function bad(message: string): never { throw new Error(`skill: ${message}; inspect ares skill list, correct the input or restore the last valid proposal and retry`); }
13
19
  function nameOf(value: unknown): string {
14
20
  if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value)) bad("name must follow the run-name rule (1..64 letters, digits, underscores or hyphens)");
@@ -47,22 +53,32 @@ function prOf(value: unknown, action: SkillDecision): string | undefined {
47
53
  catch { bad("PR must be an HTTP(S) URL without credentials"); }
48
54
  return result;
49
55
  }
50
- function version(event: LedgerEvent): void {
51
- if (event.data.skillProposal !== 1) throw new Error("skill proposal: unsupported version; use an ares version supporting this journal and keep its files unchanged");
56
+ function version(event: LedgerEvent): 1 | 2 {
57
+ if (event.data.skillProposal !== 1 && event.data.skillProposal !== 2) throw new Error("skill proposal: unsupported version; use an ares version supporting this journal and keep its files unchanged");
58
+ return event.data.skillProposal;
52
59
  }
53
60
  export function foldSkills(events: LedgerEvent[]): SkillRecord[] {
54
61
  const rows = new Map<string, SkillRecord>();
55
62
  for (const event of events) {
56
63
  if (event.type === "skill.proposed") {
57
- version(event); const proposal = validateSkillProposal(event.data.proposal, false), hash = sha256(markdown(proposal));
64
+ const v = version(event), proposal = v === 1 ? validateSkillProposal(event.data.proposal, false) : validateSkillProposalV2(event.data.proposal), hash = sha256(v === 1 ? markdown(proposal as SkillProposal) : skillMarkdownV2(proposal as SkillProposalV2));
58
65
  if (event.data.sha256 !== hash || rows.has(proposal.name) || rows.size >= SKILL_PROPOSALS) bad("journal has a mismatched hash, duplicate name or more than 100 proposals");
59
- rows.set(proposal.name, { ...proposal, skillProposal: 1, state: "proposed", sha256: hash, actor: event.actor, at: event.at });
66
+ rows.set(proposal.name, { ...proposal, skillProposal: v, evidenceStatus: v === 1 ? "legacy-unresolved" : "inspection-required", state: "proposed", sha256: hash, actor: event.actor, at: event.at } as SkillRecord);
60
67
  } else if (event.type === "skill.decided") {
61
- version(event); const name = nameOf(event.data.name), row = rows.get(name), action = decisionOf(event.data.decision);
62
- if (!row || row.state !== "proposed") bad("decision references a missing or already decided proposal");
68
+ const v = version(event), name = nameOf(event.data.name), row = rows.get(name), action = decisionOf(event.data.decision);
69
+ if (!row || row.state !== "proposed" || row.skillProposal !== v) bad("decision references a missing, mismatched-version or already decided proposal");
63
70
  const reason = text(event.data.reason, "reason"), pr = prOf(event.data.pr, action);
71
+ if (v === 2 && action === "accept" && (typeof event.data.evidenceFingerprint !== "string" || !/^[a-f0-9]{64}$/.test(event.data.evidenceFingerprint))) bad("v2 acceptance lacks its evidence fingerprint; restore the original decision event");
72
+ let observed: EvidenceInspection[] | undefined, localGeneration: string | null | undefined;
73
+ if (row.skillProposal === 2 && action === "accept") {
74
+ observed = validateSkillInspections(event.data.inspections, [...row.evidence, ...row.counterevidence]);
75
+ localGeneration = event.data.localGeneration as string | null;
76
+ const hasLocal = observed.some(inspection => inspection.ref?.tool === "ares");
77
+ if (hasLocal ? typeof localGeneration !== "string" || localGeneration.length !== 64 || !/^[a-f0-9]{64}$/.test(localGeneration) : localGeneration !== null) bad("v2 acceptance localGeneration must be a 64-hex digest exactly when inspections include ares refs, otherwise null; restore its original receipt");
78
+ if (compareSkillInspections(row.inspections, observed).length || event.data.evidenceFingerprint !== evidenceFingerprint(row.sha256, observed, localGeneration)) bad("v2 acceptance has mismatched evidence inspection/fingerprint; restore its original receipt");
79
+ }
64
80
  row.state = action === "accept" ? "accepted" : action === "reject" ? "rejected" : "withdrawn";
65
- row.decision = { action, reason, ...(pr === undefined ? {} : { pr }), actor: event.actor, at: event.at };
81
+ row.decision = { action, reason, ...(pr === undefined ? {} : { pr }), actor: event.actor, at: event.at, ...(v === 2 && action === "accept" ? {evidenceFingerprint: event.data.evidenceFingerprint as string, inspections: observed!, localGeneration: localGeneration!} : {}) };
66
82
  }
67
83
  }
68
84
  return [...rows.values()];
@@ -71,29 +87,59 @@ function file(dir: string, name: string): string { return join(dir, "proposals",
71
87
  /** Read only tracked proposals; every file is regular/bounded and bound to its original event. */
72
88
  function readSkills(dirArg: string) {
73
89
  const { dir } = openStudy(dirArg), events = readLedger(dir), rows = foldSkills(events);
90
+ for (const parent of [join(dir, "proposals"), join(dir, "proposals", "skills")]) {const stat = lstatSync(parent, {throwIfNoEntry: false}); if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) bad("proposal directory is linked or not regular; restore the committed study tree");}
74
91
  for (const row of rows) {
75
92
  let content: string;
76
- try { content = readTextBounded(file(dir, row.name), SKILL_BYTES); } catch { bad("proposal file missing, unreadable or larger than 16 KiB; restore its committed Markdown"); }
77
- if (!content.startsWith("---\nskillProposal: 1\n")) throw new Error("skill proposal file: unsupported version; use an ares version supporting this file and keep it unchanged");
93
+ try { content = readTextBounded(file(dir, row.name), SKILL_BYTES, {noFollow: true}); } catch { bad("proposal file missing, unreadable or larger than 16 KiB; restore its committed Markdown"); }
94
+ if (!content.startsWith(`---\nskillProposal: ${row.skillProposal}\n`)) throw new Error("skill proposal file: unsupported version; use an ares version supporting this file and keep it unchanged");
78
95
  if (sha256(content) !== row.sha256) bad("proposal file differs from its receipt; restore the original Markdown");
79
96
  }
80
97
  return { dir, events, rows };
81
98
  }
82
99
  export function listSkills(dir: string): SkillRecord[] { return readSkills(dir).rows; }
83
100
  /** Caller holds the study lock. One bounded file and one event share the existing commit preflight. */
84
- export function proposeSkill(dirArg: string, raw: unknown, actor: Actor): SkillRecord {
85
- const proposal = validateSkillProposal(raw), { dir, events, rows } = readSkills(dirArg);
86
- if (rows.length >= SKILL_PROPOSALS) bad("100-proposal limit reached; start a new study for further proposals");
87
- if (rows.some(row => row.name === proposal.name) || existsSync(file(dir, proposal.name))) bad("name or proposal file already exists; choose a new name without replacing prior work");
88
- const content = markdown(proposal), hash = sha256(content);
89
- const added = commit(dir, [[file(dir, proposal.name), content, SKILL_BYTES]], [{ actor, type: "skill.proposed", data: { skillProposal: 1, proposal, sha256: hash } }]);
90
- return foldSkills([...events, ...added]).find(row => row.name === proposal.name)!;
101
+ export async function proposeSkill(dirArg: string, raw: unknown, actor: Actor, options: SkillCheckOptions = {}): Promise<SkillRecord> {
102
+ const {dir, study} = openStudy(dirArg), input = validateSkillInputV2(raw, study.id), current = readSkills(dir);
103
+ if (current.rows.length >= SKILL_PROPOSALS) bad("100-proposal limit reached; start a new study for further proposals");
104
+ if (current.rows.some(row => row.name === input.name) || lstatSync(file(dir, input.name), {throwIfNoEntry: false})) bad("name or proposal file already exists; choose a new name without replacing prior work");
105
+ const refs = [...new Map([...input.evidence, ...input.counterevidence].map(ref => [canonical(ref), ref])).values()];
106
+ const checked = await inspectSkillEvidenceSet(dir, refs, options);
107
+ if (canonical(readSkills(dir).rows) !== canonical(current.rows)) requireSkillEvidence("proposal journal changed during inspection", "propose");
108
+ if (!checked.recheck()) requireSkillEvidence(checked.localFailure === "unsupported" ? "unsupported ares source record version" : "local source changed or aggregate source budget exhausted during proposal inspection", "propose", checked.inspections);
109
+ const proposal = validateSkillProposalV2({...input, inspections: checked.inspections}, study.id);
110
+ const content = skillMarkdownV2(proposal), hash = sha256(content);
111
+ const added = commit(dir, [[file(dir, proposal.name), content, SKILL_BYTES]], [{actor, type: "skill.proposed", data: {skillProposal: 2, proposal, sha256: hash}}]);
112
+ return foldSkills([...current.events, ...added]).find(row => row.name === proposal.name)!;
113
+ }
114
+ export async function checkSkill(dir: string, name: string, options: SkillCheckOptions = {}) {
115
+ const target = nameOf(name); let row: SkillRecord | undefined;
116
+ try {row = readSkills(dir).rows.find(row => row.name === target);}
117
+ catch (cause) {return {name: target, state: cause instanceof Error && cause.message.includes("unsupported") ? "unsupported" : "unavailable", inspections: [], acceptReady: false, support: "reviewer-judgment", nextStep: cause instanceof Error && cause.message.includes("unsupported") ? "use a compatible ares version or restore the local record, keeping bytes unchanged; run ares skill check again" : "Restore the versioned study/proposal and its receipts, then run ares skill check again; keep unsupported versions unchanged"};}
118
+ if (!row) return {name: target, state: "missing", inspections: [], acceptReady: false, support: "reviewer-judgment", nextStep: "Select a recorded name with ares skill list or create a new proposal"};
119
+ if (row.skillProposal === 1) return {name: row.name, proposalSha256: row.sha256, skillProposal: 1, state: "unsupported", legacyUnresolved: true, inspections: [], acceptReady: false, support: "reviewer-judgment", nextStep: row.state === "proposed" ? "Legacy bytes/decisions are preserved; create a new v2 proposal for evidence-backed checks" : "Decision is final; create a revised v2 proposal for new evidence. Legacy bytes and the recorded decision remain unchanged"};
120
+ const refs = [...new Map([...row.evidence, ...row.counterevidence].map(ref => [canonical(ref), ref])).values()], checked = await inspectSkillEvidenceSet(dir, refs, options), reasons = compareSkillInspections(row.inspections, checked.inspections);
121
+ try {if (canonical(readSkills(dir).rows.find(current => current.name === row.name)) !== canonical(row)) reasons.push("proposal-changed");} catch {reasons.push("proposal-changed");}
122
+ if (!checked.recheck()) reasons.push(checked.localFailure ?? "local-source-changed-or-budget-exhausted");
123
+ const sourceGuidance = unsupportedSourceGuidance(checked.inspections);
124
+ const sourcesReady = reasons.length === 0, ready = sourcesReady && row.state === "proposed", state = sourcesReady ? "available" : checked.remainingMs <= 0 ? "unavailable" : reasons.some(reason => reason.includes("changed")) ? "changed" : reasons.includes("unsupported") ? "unsupported" : reasons.includes("missing") ? "missing" : "unavailable";
125
+ return {name: row.name, proposalSha256: row.sha256, skillProposal: 2, state, inspections: checked.inspections, acceptReady: ready, support: "reviewer-judgment", evidenceFingerprint: evidenceFingerprint(row.sha256, checked.inspections, checked.localGeneration), localGeneration: checked.localGeneration, responseBytes: checked.bytes, reasons, nextStep: row.state !== "proposed" ? `Decision is final; create a revised proposal for new evidence${sourceGuidance ? `; ${sourceGuidance}` : ""}` : ready ? "Source integrity is not support: a reviewer decides using the supplied PR reference" : state === "unsupported" ? `${sourceGuidance || "use a supporting source reader"}; create a revised proposal with current evidence/counterevidence and honest limitations` : "Create a revised proposal with current evidence/counterevidence and honest limitations"};
91
126
  }
92
- /** Final actor-recorded decisions never open, inspect or merge a PR. */
93
- export function decideSkill(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, actor: Actor): SkillRecord {
94
- const target = nameOf(name), action = decisionOf(decision), why = text(reason, "reason"), reference = prOf(pr, action), { dir, events, rows } = readSkills(dirArg);
127
+ /** Caller holds the owned study lock. Final decisions never open, inspect or merge a PR. */
128
+ export async function decideSkill(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, actor: Actor, options: SkillCheckOptions = {}): Promise<SkillRecord> {
129
+ const target = nameOf(name), action = decisionOf(decision), why = text(reason, "reason"), reference = prOf(pr, action), {dir, events, rows} = readSkills(dirArg);
95
130
  const row = rows.find(row => row.name === target);
96
131
  if (!row || row.state !== "proposed") bad("proposal is missing or already decided; decisions including withdrawal are final");
97
- const added = commit(dir, [], [{ actor, type: "skill.decided", data: { skillProposal: 1, name: target, decision: action, reason: why, ...(reference === undefined ? {} : { pr: reference }) } }]);
132
+ let evidence: {evidenceFingerprint: string; inspections: EvidenceInspection[]; localGeneration: string | null} | undefined;
133
+ if (row.skillProposal === 2 && action === "accept") {
134
+ if (!options.lock) requireSkillEvidence("v2 acceptance requires an owned study transaction"); assertStudyReadLock(dir, options.lock);
135
+ const checked = await inspectSkillEvidenceSet(dir, [...new Map([...row.evidence, ...row.counterevidence].map(ref => [canonical(ref), ref])).values()], options), reasons = compareSkillInspections(row.inspections, checked.inspections);
136
+ if (reasons.length) requireSkillEvidence(`required evidence or counterevidence is changed/unavailable (${[...new Set(reasons)].join(", ")})`, "accept", checked.inspections);
137
+ if (canonical(readSkills(dir).rows) !== canonical(rows) || !checked.recheck()) requireSkillEvidence("local source/proposal changed or aggregate source budget exhausted before decision");
138
+ assertStudyReadLock(dir, options.lock);
139
+ evidence = {evidenceFingerprint: evidenceFingerprint(row.sha256, checked.inspections, checked.localGeneration), inspections: checked.inspections, localGeneration: checked.localGeneration};
140
+ }
141
+ const pending = {actor, type: "skill.decided", data: {skillProposal: row.skillProposal, name: target, decision: action, reason: why, ...(reference === undefined ? {} : {pr: reference}), ...evidence}};
142
+ foldSkills([...events, {v: 1, at: new Date().toISOString(), ...pending}]);
143
+ const added = commit(dir, [], [pending]);
98
144
  return foldSkills([...events, ...added]).find(row => row.name === target)!;
99
145
  }
@@ -0,0 +1,11 @@
1
+ /** One check/accept owns one response budget; local producer projections and all amem stdio bytes share it. */
2
+ export const SOURCE_MS = 25_000, SOURCE_BYTES = 262_144;
3
+ export interface SourceBudget {remainingBytes: number; remainingMs(): number; consume(bytes: number): boolean; exhaust(): void}
4
+ export function sourceBudget(now: () => number = Date.now): SourceBudget {
5
+ const start = now(), wallStart = performance.now(); let last = start;
6
+ return {remainingBytes: SOURCE_BYTES,
7
+ remainingMs() {const current = now(); if (!Number.isFinite(current) || current < last || !Number.isFinite(start)) return 0; last = current; return Math.max(0, Math.min(SOURCE_MS - (current - start), SOURCE_MS - (performance.now() - wallStart)));},
8
+ consume(bytes) {if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > this.remainingBytes) {this.remainingBytes = 0; return false;} this.remainingBytes -= bytes; return this.remainingMs() > 0;},
9
+ exhaust() {this.remainingBytes = 0;},
10
+ };
11
+ }