@staix/agent-research 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +261 -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 +201 -34
  7. package/src/exp/artifacts.ts +20 -2
  8. package/src/exp/attempts.ts +505 -65
  9. package/src/exp/executor.ts +264 -17
  10. package/src/exp/final.ts +1 -1
  11. package/src/exp/logs.ts +25 -12
  12. package/src/exp/metrics.ts +8 -9
  13. package/src/exp/pipeline.ts +92 -0
  14. package/src/exp/protocol.ts +87 -20
  15. package/src/exp/retention-script.ts +649 -0
  16. package/src/exp/retention.ts +70 -0
  17. package/src/exp/reuse-admission.ts +65 -0
  18. package/src/exp/reuse-contract.ts +48 -0
  19. package/src/exp/reuse-runtime.ts +91 -0
  20. package/src/exp/reuse.ts +87 -0
  21. package/src/exp/selection.ts +1 -1
  22. package/src/exp/snapshot.ts +30 -10
  23. package/src/exp/stages.ts +117 -0
  24. package/src/harness/experience-source.ts +34 -0
  25. package/src/harness/experience.ts +206 -0
  26. package/src/harness/hub-guidance.ts +140 -0
  27. package/src/harness/hub-reference.ts +18 -0
  28. package/src/harness/lesson-candidates.ts +162 -0
  29. package/src/harness/limits.ts +2 -0
  30. package/src/harness/privacy.ts +4 -0
  31. package/src/harness/receipts.ts +84 -0
  32. package/src/harness/rounds.ts +198 -0
  33. package/src/harness/transitions.ts +152 -0
  34. package/src/lit/candidates.ts +13 -5
  35. package/src/lit/cards.ts +55 -4
  36. package/src/lit/flow.ts +82 -0
  37. package/src/lit/queries.ts +62 -0
  38. package/src/manifest.ts +13 -6
  39. package/src/mcp-tools.ts +123 -25
  40. package/src/mcp.ts +4 -0
  41. package/src/memory/amem-show.ts +135 -0
  42. package/src/memory/amem.ts +3 -0
  43. package/src/memory/archive.ts +17 -8
  44. package/src/memory/evidence-local.ts +77 -0
  45. package/src/memory/evidence.ts +39 -0
  46. package/src/memory/lessons.ts +4 -2
  47. package/src/memory/skill-check.ts +56 -0
  48. package/src/memory/skill-format.ts +77 -0
  49. package/src/memory/skills.ts +72 -26
  50. package/src/memory/source-budget.ts +11 -0
  51. package/src/memory/vault-cards.ts +226 -0
  52. package/src/paper/build.ts +16 -7
  53. package/src/paper/check.ts +37 -10
  54. package/src/paper/headings.ts +39 -0
  55. package/src/paper/hygiene.ts +153 -0
  56. package/src/paper/placeholders.ts +16 -1
  57. package/src/paper/plan.ts +170 -0
  58. package/src/paper/point-evidence.ts +63 -0
  59. package/src/paper/points.ts +83 -0
  60. package/src/paper/review.ts +102 -9
  61. package/src/paper/scopes.ts +51 -0
  62. package/src/plan/definition.ts +5 -1
  63. package/src/plan/hub.ts +6 -0
  64. package/src/plan/state.ts +5 -0
  65. package/src/playbook.ts +35 -20
  66. package/src/privacy.ts +9 -0
  67. package/src/provenance.ts +679 -0
  68. package/src/scope.ts +24 -3
  69. package/src/study-export.ts +55 -27
  70. package/src/study.ts +54 -14
  71. package/src/ui/panel.css +4 -0
  72. package/src/ui/panel.js +263 -6
  73. package/src/ui/plugin.ts +68 -10
@@ -0,0 +1,34 @@
1
+ import {plain} from "../study.ts";
2
+ import {readScreenedAmem, supportsScreenedAmem, type ScreenedAmemInspection} from "../memory/amem-show.ts";
3
+ import type {ProcessRunner} from "../exp/executor.ts";
4
+
5
+ export interface ExperienceSourcePin {id: string; digest: string; sourceVersion: string}
6
+ export interface ExperienceSourceObservation {
7
+ id: string; state: ScreenedAmemInspection["state"]; digest: string | null; sourceVersion?: string; observedAt: string;
8
+ }
9
+ export const EXPERIENCE_SOURCE_LIMIT = 16;
10
+ function fail(): never {
11
+ throw new Error("experience source pins: malformed, duplicate or over-bound snapshot; restore the original snapshot or freeze an explicitly reviewed new round before retrying");
12
+ }
13
+ /** Liveness/version recheck only, never proof of temporal eligibility, applicability or claim support. */
14
+ export async function recheckExperienceSources(dir: string, entries: readonly ExperienceSourcePin[], options: {runner?: ProcessRunner; env?: NodeJS.ProcessEnv; now?: () => number} = {}): Promise<{state: "available" | "unavailable"; observations: ExperienceSourceObservation[]}> {
15
+ if (!Array.isArray(entries) || entries.length > EXPERIENCE_SOURCE_LIMIT) fail();
16
+ const pins = entries.map(entry => {
17
+ if (!plain(entry) || Object.keys(entry).some(key => !["id", "digest", "sourceVersion"].includes(key)) || typeof entry.id !== "string" || entry.id.length !== 32 || !/^[a-f0-9]{32}$/.test(entry.id) || typeof entry.digest !== "string" || entry.digest.length !== 64 || !/^[a-f0-9]{64}$/.test(entry.digest) || typeof entry.sourceVersion !== "string" || entry.sourceVersion.length > 128 || !supportsScreenedAmem(entry.sourceVersion)) fail();
18
+ return {id: entry.id, digest: entry.digest, sourceVersion: entry.sourceVersion};
19
+ });
20
+ if (new Set(pins.map(pin => pin.id)).size !== pins.length) fail();
21
+ const observations: ExperienceSourceObservation[] = [];
22
+ // Sequential and bounded: <=16 owning reads, each with its existing total 25-second lifetime. No retry or fallback.
23
+ for (const pin of pins) {
24
+ let inspected: ScreenedAmemInspection;
25
+ try {inspected = await readScreenedAmem(dir, pin.id, options);}
26
+ catch {
27
+ let time = Date.now(); try {const value = options.now?.(); if (value !== undefined && Number.isFinite(value) && Math.abs(value) <= 8.64e15) time = value;} catch { /* a failed clock cannot bypass the refusal */ }
28
+ inspected = {state: "unavailable", digest: null, observedAt: new Date(time).toISOString()};
29
+ }
30
+ const state = inspected.state === "available" && (inspected.digest !== pin.digest || inspected.sourceVersion !== pin.sourceVersion) ? "changed" : inspected.state;
31
+ observations.push({id: pin.id, state, digest: inspected.digest, ...(inspected.sourceVersion === undefined ? {} : {sourceVersion: inspected.sourceVersion}), observedAt: inspected.observedAt});
32
+ }
33
+ return {state: observations.every(observation => observation.state === "available") ? "available" : "unavailable", observations};
34
+ }
@@ -0,0 +1,206 @@
1
+ import {HARNESS_MODEL_BYTES} from "./limits.ts";
2
+ import {archivedLessonSources, recheckLessonExports} from "./lesson-candidates.ts";
3
+ import {sourceBudget} from "../memory/source-budget.ts";
4
+ import {supportsScreenedAmem} from "../memory/amem-show.ts";
5
+ import {lstatSync} from "node:fs";
6
+ import {join} from "node:path";
7
+ import {commit, openStudy, requireExperiment, isHarnessGate, readLedger, readTextBounded, onlyKeys, plain, sha256, type Actor, type LedgerEvent, type StudyReadLock, assertStudyReadLock} from "../study.ts";
8
+ import {canonical} from "../plan/state.ts";
9
+ import {hasHarnessCredential} from "./privacy.ts";
10
+ import {createAmemClient} from "../memory/amem.ts";
11
+ import {rankLessons} from "../memory/lessons.ts";
12
+ import {readScreenedAmem} from "../memory/amem-show.ts";
13
+ import type {ProcessRunner} from "../exp/executor.ts";
14
+
15
+ export const EXPERIENCE_BYTES = 16_384, EXPERIENCE_INDEX_BYTES = 1_048_576, EXPERIENCE_LIMIT = 16;
16
+ export interface HarnessStream {v: 1; id: string; revision: number; tasks: string[]}
17
+ export interface ExperienceRequest {
18
+ v: 1; round: string; taskId: string; condition: "baseline" | "no-library" | "retrieval-only" | "prior-experience";
19
+ model: string; runtime: string; toolsetSha256?: string; selected: {id: string; reason: string}[];
20
+ }
21
+ export interface FrozenEntry {
22
+ id: string; digest: string; sourceVersion: string; observedAt: string; reason: string;
23
+ lesson: string; lessonSha256: string; dispositionSha256: string; noteSha256: string;
24
+ round: string; taskId: string; roundBinding: string; closureSha256: string; sourceFingerprint: string;
25
+ model: string; runtime: string; toolsetSha256: string; sourceStrength: "synthetic-fixture"; transfer: "not-demonstrated";
26
+ }
27
+ export interface FrozenExperience extends Omit<ExperienceRequest, "selected"> {
28
+ streamSha256: string; entries: FrozenEntry[]; sourceStrength?: "synthetic-fixture"; transfer?: "not-demonstrated";
29
+ }
30
+ export interface ExperienceReadOptions {runner?: ProcessRunner; env?: NodeJS.ProcessEnv; now?: () => number; lock?: StudyReadLock}
31
+ const streamPath = (dir: string) => join(dir, "design", "harness-stream.json");
32
+ const contextPath = (dir: string) => join(dir, "design", "harness-experience.json");
33
+ const hash = (value: unknown) => sha256(canonical(value));
34
+ function fail(cause: string): never {throw new Error(`experience: ${cause}; restore the recorded stream/context or start a new study/round with explicit experience freeze, then retry`);}
35
+ function object(value: unknown, fields: string[]): Record<string, unknown> {
36
+ if (!plain(value)) fail("object required"); try {onlyKeys(value, fields, "experience");} catch {fail(`unknown field; allowed fields: ${fields.join(", ")}`);} return value;
37
+ }
38
+ function text(value: unknown, bound: number): string {
39
+ if (typeof value !== "string" || !value.trim() || value.includes("\0") || Buffer.byteLength(value) > bound || hasHarnessCredential(value)) fail("text is blank, over-bound or contains a URL/credential"); return value;
40
+ }
41
+ function id(value: unknown): string {const result = text(value, 64); if (!isHarnessGate(`harness:${result}`)) fail("round/stream id must follow the ASCII run-name rule"); return result;}
42
+ function digest(value: unknown): string {if (typeof value !== "string" || value.length !== 64 || !/^[a-f0-9]{64}$/.test(value)) fail("lowercase SHA-256 required"); return value;}
43
+ export function validateHarnessStream(raw: unknown): HarnessStream {
44
+ const row = object(raw, ["v", "id", "revision", "tasks"]);
45
+ if (row.v !== 1) fail("unsupported stream version; keep original bytes and use a supporting version");
46
+ if (!Number.isSafeInteger(row.revision) || Number(row.revision) < 1 || !Array.isArray(row.tasks) || !row.tasks.length || row.tasks.length > EXPERIENCE_LIMIT) fail("stream requires a positive revision and 1..16 tasks");
47
+ const tasks = row.tasks.map(value => text(value, 256)); if (new Set(tasks).size !== tasks.length) fail("stream task ids must be unique");
48
+ return {v: 1, id: id(row.id), revision: row.revision as number, tasks};
49
+ }
50
+ export function validateExperienceRequest(raw: unknown): ExperienceRequest {
51
+ const row = object(raw, ["v", "round", "taskId", "condition", "model", "runtime", "toolsetSha256", "selected"]);
52
+ if (row.v !== 1) fail("unsupported context version; keep original bytes and use a supporting version");
53
+ if (!["baseline", "no-library", "retrieval-only", "prior-experience"].includes(row.condition as string) || !Array.isArray(row.selected) || row.selected.length > EXPERIENCE_LIMIT) fail("invalid condition or more than 16 selected entries");
54
+ const selected = row.selected.map(value => {const item = object(value, ["id", "reason"]); if (typeof item.id !== "string" || item.id.length !== 32 || !/^[a-f0-9]{32}$/.test(item.id)) fail("full exact amem id required"); return {id: item.id, reason: text(item.reason, 1000)};});
55
+ if (new Set(selected.map(value => value.id)).size !== selected.length) fail("duplicate selected id");
56
+ if (["baseline", "no-library"].includes(row.condition as string) && selected.length) fail("baseline/no-library conditions cannot receive experience");
57
+ const result = {v: 1 as const, round: id(row.round), taskId: text(row.taskId, 256), condition: row.condition as ExperienceRequest["condition"], model: text(row.model, HARNESS_MODEL_BYTES), runtime: text(row.runtime, 128), ...(row.toolsetSha256 !== undefined ? {toolsetSha256: digest(row.toolsetSha256)} : {}), selected};
58
+ if (Buffer.byteLength(canonical(result)) > EXPERIENCE_BYTES) fail("selection exceeds 16 KiB"); return result;
59
+ }
60
+ function entry(raw: unknown): FrozenEntry {
61
+ const row = object(raw, ["id", "digest", "sourceVersion", "observedAt", "reason", "lesson", "lessonSha256", "dispositionSha256", "noteSha256", "round", "taskId", "roundBinding", "closureSha256", "sourceFingerprint", "model", "runtime", "toolsetSha256", "sourceStrength", "transfer"]);
62
+ if (typeof row.id !== "string" || row.id.length !== 32 || !/^[a-f0-9]{32}$/.test(row.id) || !supportsScreenedAmem(row.sourceVersion) || typeof row.observedAt !== "string" || !Number.isFinite(Date.parse(row.observedAt)) || row.observedAt.length > 64 || row.sourceStrength !== "synthetic-fixture" || row.transfer !== "not-demonstrated") fail("invalid frozen source identity/version/strength");
63
+ return {id: row.id, digest: digest(row.digest), sourceVersion: row.sourceVersion, observedAt: row.observedAt, reason: text(row.reason, 1000), lesson: id(row.lesson), lessonSha256: digest(row.lessonSha256), dispositionSha256: digest(row.dispositionSha256), noteSha256: digest(row.noteSha256), round: id(row.round), taskId: text(row.taskId, 256), roundBinding: digest(row.roundBinding), closureSha256: digest(row.closureSha256), sourceFingerprint: digest(row.sourceFingerprint), model: text(row.model, HARNESS_MODEL_BYTES), runtime: digest(row.runtime), toolsetSha256: digest(row.toolsetSha256), sourceStrength: "synthetic-fixture", transfer: "not-demonstrated"};
64
+ }
65
+ function boundedSnapshot(raw: unknown): FrozenExperience {
66
+ const row = object(raw, ["v", "round", "taskId", "condition", "model", "runtime", "toolsetSha256", "streamSha256", "entries", "sourceStrength", "transfer"]);
67
+ if (!Array.isArray(row.entries) || row.entries.length > EXPERIENCE_LIMIT) fail("frozen entries exceed16 sources");
68
+ const entries = row.entries.map(entry), {streamSha256, entries: _entries, sourceStrength: _strength, transfer: _transfer, ...rest} = row;
69
+ const {selected: _selected, ...request} = validateExperienceRequest({...rest, selected: entries.map(value => ({id: value.id, reason: value.reason}))});
70
+ if (new Set(entries.map(value => value.id)).size !== entries.length || entries.some(value => value.model !== request.model || value.runtime !== request.runtime || value.toolsetSha256 !== request.toolsetSha256)) fail("duplicate/incompatible frozen sources");
71
+ if (entries.length ? row.sourceStrength !== "synthetic-fixture" || row.transfer !== "not-demonstrated" : row.sourceStrength !== undefined || row.transfer !== undefined) fail("frozen context strength differs from its entries");
72
+ if (!entries.length && !["baseline", "no-library"].includes(request.condition)) fail("retrieval/prior context needs admitted sources; use baseline/no-library for an empty control");
73
+ const value: FrozenExperience = {...request, streamSha256: digest(streamSha256), entries, ...(entries.length ? {sourceStrength: "synthetic-fixture" as const, transfer: "not-demonstrated" as const} : {})};
74
+ if (Buffer.byteLength(canonical(value)) > EXPERIENCE_BYTES) fail("frozen snapshot exceeds16KiB"); return value;
75
+ }
76
+ function file(dir: string, name: string, max: number): unknown | undefined {
77
+ try {
78
+ const design = lstatSync(join(dir, "design"), {throwIfNoEntry: false});
79
+ if (design && (!design.isDirectory() || design.isSymbolicLink())) fail("design is not a regular directory");
80
+ const stat = lstatSync(name, {throwIfNoEntry: false}); if (!stat) return undefined;
81
+ if (!stat.isFile() || stat.isSymbolicLink()) fail("record is not a regular file");
82
+ return JSON.parse(readTextBounded(name, max, {noFollow: true}));
83
+ } catch {return fail("record is linked, unreadable, malformed or over-bound");}
84
+ }
85
+ function store(dirArg: string, provided?: LedgerEvent[]) {
86
+ const {dir, study} = openStudy(dirArg); requireExperiment(study); const events = provided ?? readLedger(dir);
87
+ let stream: HarnessStream | undefined; const snapshots = new Map<string, FrozenExperience>();
88
+ const startedRounds = new Set<string>();
89
+ for (const event of events) {
90
+ if (event.type === "harness.round.set") {if (plain(event.data.round) && typeof event.data.round.id === "string") startedRounds.add(event.data.round.id); else fail("malformed round receipt");}
91
+ if (event.type === "experience.stream.set") {
92
+ const value = validateHarnessStream(event.data.stream);
93
+ if (event.data.sha256 !== hash(value) || stream || startedRounds.size) fail("stream receipt differs or stream was changed/created after a round"); stream = value;
94
+ } else if (event.type === "experience.frozen") {
95
+ const value = boundedSnapshot(event.data.snapshot);
96
+ if (!stream || event.data.sha256 !== hash(value) || value.streamSha256 !== hash(stream) || !stream.tasks.includes(value.taskId) || snapshots.has(value.round) || snapshots.size >= EXPERIENCE_LIMIT) fail("frozen context receipt differs, is duplicated, or lacks its stream");
97
+ if (startedRounds.has(value.round)) fail("context was frozen after its round started");
98
+ if ([...snapshots.values()].some(old => old.taskId === value.taskId)) fail("duplicate frozen task identity");
99
+ snapshots.set(value.round, value);
100
+ } else if (event.type.startsWith("experience.")) fail("unsupported experience event; use a supporting version without changing history");
101
+ }
102
+ const diskStream = file(dir, streamPath(dir), EXPERIENCE_BYTES), diskContexts = file(dir, contextPath(dir), EXPERIENCE_INDEX_BYTES);
103
+ if (canonical(diskStream === undefined ? null : validateHarnessStream(diskStream)) !== canonical(stream ?? null)) fail("stream file differs from its receipt");
104
+ if (diskContexts === undefined) {if (snapshots.size) fail("frozen context file missing");}
105
+ else {const index = object(diskContexts, ["v", "contexts"]); if (index.v !== 1) fail("unsupported frozen index version; keep original bytes and use a supporting version"); if (!Array.isArray(index.contexts) || index.contexts.length > EXPERIENCE_LIMIT || canonical(index.contexts.map(boundedSnapshot)) !== canonical([...snapshots.values()])) fail("frozen context index differs from its receipts");}
106
+ return {dir, study, stream, snapshots, events};
107
+ }
108
+ export function readHarnessStream(dir: string) {const current = store(dir); return {v: 1, stream: current.stream ?? null, streamSha256: current.stream ? hash(current.stream) : null};}
109
+ /** Caller holds the study lock. Stream identity and order are immutable, including before a round starts. */
110
+ export function setHarnessStream(dir: string, raw: unknown, actor: Actor) {
111
+ const current = store(dir), stream = validateHarnessStream(raw);
112
+ if (current.stream) {if (canonical(current.stream) === canonical(stream)) return readHarnessStream(dir); fail("stream identity/membership/order is immutable");}
113
+ if (current.events.some(event => event.type === "harness.round.set")) fail("stream must be fixed before the first round");
114
+ commit(current.dir, [[streamPath(current.dir), JSON.stringify(stream, null, 2) + "\n", EXPERIENCE_BYTES]], [{actor, type: "experience.stream.set", data: {stream, sha256: hash(stream)}}]); return readHarnessStream(dir);
115
+ }
116
+ function target(current: ReturnType<typeof store>, request: ExperienceRequest) {
117
+ if (!current.stream || !current.stream.tasks.includes(request.taskId)) fail("task is not in a recorded stream; run ares harness stream set before creating rounds");
118
+ if (current.events.some(event => event.type === "harness.round.set" && plain(event.data.round) && event.data.round.id === request.round)) fail("round already started; freeze context before its first definition");
119
+ return current.stream;
120
+ }
121
+ /** Source ordering never relies on wall clocks, title matching, directory scans or untrusted closure claims. */
122
+ export function experienceSourceEligibility(stream: HarnessStream, studyId: string, targetTask: string, source: {studyId: string; taskId: string; model: string; runtime: string; completed?: boolean}, requested: {model: string; runtime: string}) {
123
+ const from = stream.tasks.indexOf(source.taskId), to = stream.tasks.indexOf(targetTask);
124
+ if (source.studyId !== studyId) return {state: "unavailable" as const, reason: "cross-study-source"};
125
+ if (from < 0 || to < 0) return {state: "unavailable" as const, reason: "unregistered-task"};
126
+ if (from >= to) return {state: "unavailable" as const, reason: "current-or-future-task"};
127
+ if (source.model !== requested.model || source.runtime !== requested.runtime) return {state: "unavailable" as const, reason: "model-runtime-incompatible"};
128
+ return source.completed ? {state: "available" as const, reason: "earlier-reviewed-receipted-fixture-source"} : {state: "unavailable" as const, reason: "completed-round-lesson-receipts-unavailable"};
129
+ }
130
+ async function resolveSelected(current: ReturnType<typeof store>, request: ExperienceRequest, options: ExperienceReadOptions, pins?: readonly FrozenEntry[]) {
131
+ if (!request.selected.length) return {state: "available" as const, entries: [], observations: [], context: "", bytes: 0};
132
+ const sources = archivedLessonSources(current.dir), budget = sourceBudget(options.now), entries: FrozenEntry[] = [], observations: {id: string; state: string; digest: string | null; observedAt?: string; sourceVersion?: string}[] = [], context: string[] = [];
133
+ const eligible = request.selected.filter(selected => {
134
+ const source = sources.get(selected.id), p = source?.row.proposal, compat = p?.compatibility;
135
+ return p && compat && request.toolsetSha256 === compat.toolsetSha256 && experienceSourceEligibility(current.stream!, current.study.id, request.taskId, {studyId: p.studyId, taskId: p.taskId, ...compat, completed: true}, request).state === "available";
136
+ });
137
+ const eligibleIds = new Set(eligible.map(value => value.id));
138
+ if (!eligible.length) return {state: "unavailable" as const, entries, observations: request.selected.map(value => ({id: value.id, state: "unavailable", digest: null})), context: null, bytes: 0};
139
+ let recheckSources = () => false;
140
+ try {recheckSources = await recheckLessonExports(current.dir, eligible.map(selected => sources.get(selected.id)!.noteSha256), {...options, budget});}
141
+ catch {return {state: "unavailable" as const, entries, observations: request.selected.map(value => ({id: value.id, state: "unavailable", digest: null})), context: null, bytes: 0};}
142
+ for (const selected of request.selected) {
143
+ const source = sources.get(selected.id), p = source?.row.proposal, compat = p?.compatibility;
144
+ if (!source || !p || !compat || !eligibleIds.has(selected.id)) {observations.push({id: selected.id, state: "unavailable", digest: null}); continue;}
145
+ let bodyMatched = false;
146
+ const observed = await readScreenedAmem(current.dir, selected.id, {...options, budget, onText: text => {bodyMatched = text === source.note.text;}});
147
+ const value = observed.state === "available" && observed.digest && observed.sourceVersion && observed.kind === source.note.kind && bodyMatched ? entry({id: selected.id, digest: observed.digest, sourceVersion: observed.sourceVersion, observedAt: observed.observedAt, reason: selected.reason, lesson: p.name, lessonSha256: source.row.sha256, dispositionSha256: source.row.disposition!.sha256, noteSha256: source.noteSha256, round: p.round, taskId: p.taskId, roundBinding: p.roundBinding, closureSha256: p.closureSha256, sourceFingerprint: p.sourceFingerprint, ...compat, sourceStrength: "synthetic-fixture", transfer: "not-demonstrated"}) : null;
148
+ const pinned = pins?.find(pin => pin.id === selected.id), content = (row: FrozenEntry) => {const {observedAt: _at, ...rest} = row; return rest;};
149
+ if (!value || pinned && canonical(content(value)) !== canonical(content(pinned))) {observations.push({id: selected.id, state: observed.state === "available" ? "changed" : observed.state, digest: observed.digest, observedAt: observed.observedAt}); continue;}
150
+ entries.push(value); observations.push({id: selected.id, state: "available", digest: value.digest, sourceVersion: value.sourceVersion, observedAt: value.observedAt});
151
+ context.push(source.note.text);
152
+ }
153
+ const refreshed = archivedLessonSources(current.dir), unchanged = entries.every(value => {const source = refreshed.get(value.id); return source?.row.sha256 === value.lessonSha256 && source.row.disposition?.sha256 === value.dispositionSha256 && source.noteSha256 === value.noteSha256;});
154
+ const rendered = context.join("\n\n"), available = recheckSources() && unchanged && entries.length === request.selected.length && Buffer.byteLength(rendered) <= EXPERIENCE_BYTES && budget.remainingMs() > 0;
155
+ return {state: available ? "available" as const : "unavailable" as const, entries, observations, context: available ? rendered : null, bytes: available ? Buffer.byteLength(rendered) : 0};
156
+ }
157
+ /** Ranking is advisory; only chain-proven explicit selections receive an owning exact-id read. */
158
+ export async function selectExperience(dir: string, raw: unknown, options: ExperienceReadOptions = {}) {
159
+ const current = store(dir), request = validateExperienceRequest(raw); target(current, request);
160
+ const now = options.now?.() ?? Date.now(), ranked = rankLessons(await createAmemClient(current.dir, options.runner, options.env).search(current.study.question), now, {limit: EXPERIENCE_LIMIT});
161
+ const resolved = await resolveSelected(current, request, options), empty = ["baseline", "no-library"].includes(request.condition), available = empty || request.selected.length > 0 && resolved.state === "available";
162
+ return {v: 1, ranked, selected: resolved.observations, eligible: !empty && available, state: available ? "available" : "unavailable", prepareOnly: true, liveEligible: false, sourceStrength: resolved.entries.length ? "synthetic-fixture" : null, transfer: "not-demonstrated", cause: available ? null : "source-chain-order-policy-or-compatibility-unavailable", nextStep: "Select reviewed/receipted earlier same-study sources, or use baseline/no-library; fixture entries never qualify a live trial"};
163
+ }
164
+ function requestFields(value: FrozenExperience) {const {streamSha256: _stream, entries: _entries, sourceStrength: _strength, transfer: _transfer, ...rest} = value; return rest;}
165
+ /** Caller holds the lock. Durable snapshots contain source identities only, never the screened body. */
166
+ export async function freezeExperience(dir: string, raw: unknown, actor: Actor, options: ExperienceReadOptions = {}) {
167
+ const current = store(dir), request = validateExperienceRequest(raw);
168
+ if (!options.lock) fail("freeze requires an owned study transaction"); assertStudyReadLock(current.dir, options.lock);
169
+ const existing = current.snapshots.get(request.round);
170
+ if (existing) {
171
+ const {selected: _selected, ...rest} = request;
172
+ if (canonical(request.selected) === canonical(existing.entries.map(value => ({id: value.id, reason: value.reason}))) && canonical(rest) === canonical(requestFields(existing))) return {...existing, improverContextHash: hash(existing)};
173
+ fail("frozen context cannot change; use a new study/round");
174
+ }
175
+ const stream = target(current, request);
176
+ if ([...current.snapshots.values()].some(value => value.taskId === request.taskId)) fail("task already has a frozen context");
177
+ const resolved = await resolveSelected(current, request, options);
178
+ if (resolved.state !== "available" || !request.selected.length && !["baseline", "no-library"].includes(request.condition)) fail("nonempty experience unavailable: use earlier reviewed/receipted same-study sources or an empty baseline/no-library control");
179
+ const {selected: _selected, ...rest} = request, value = boundedSnapshot({...rest, streamSha256: hash(stream), entries: resolved.entries, ...(resolved.entries.length ? {sourceStrength: "synthetic-fixture", transfer: "not-demonstrated"} : {})});
180
+ if (current.snapshots.size >= EXPERIENCE_LIMIT) fail("16-context limit reached");
181
+ const after = store(dir); if (canonical(after.events) !== canonical(current.events)) fail("source journal changed during freeze");
182
+ assertStudyReadLock(current.dir, options.lock);
183
+ commit(current.dir, [[contextPath(current.dir), JSON.stringify({v: 1, contexts: [...current.snapshots.values(), value]}, null, 2) + "\n", EXPERIENCE_INDEX_BYTES]], [{actor, type: "experience.frozen", data: {snapshot: value, sha256: hash(value)}}]);
184
+ return {...value, improverContextHash: hash(value)};
185
+ }
186
+ /** Local integrity check for round writes/imports; never resolves a memory or starts a process. */
187
+ export function requireRoundExperiences(dir: string, rounds: readonly {id: string; task: {id: string}; experience: unknown[]; authoring?: string; context?: {streamSha256: string; improverContextHash: string}}[], events?: LedgerEvent[]) {
188
+ const current = store(dir, events);
189
+ for (const round of rounds) {
190
+ if (!round.context) {if (current.stream) fail("a stream-bound round requires a frozen context"); continue;}
191
+ const value = current.snapshots.get(round.id);
192
+ if (round.authoring === "controlled-lane" && value?.entries.some(entry => entry.sourceStrength === "synthetic-fixture")) fail("controlled-lane refuses synthetic-fixture context; freeze a context from real-source lessons or use baseline/no-library");
193
+ if (!current.stream || !value || value.taskId !== round.task.id || round.context.streamSha256 !== hash(current.stream) || round.context.improverContextHash !== hash(value) || round.experience.length) fail("round context differs from its recorded frozen snapshot");
194
+ }
195
+ }
196
+ export async function checkExperience(dir: string, roundId: string, identity: {model: string; runtime: string; toolsetSha256?: string}, options: ExperienceReadOptions = {}) {
197
+ const checkedIdentity = object(identity, ["model", "runtime", "toolsetSha256"]); text(checkedIdentity.model, HARNESS_MODEL_BYTES); text(checkedIdentity.runtime, 128);
198
+ const current = store(dir), value = current.snapshots.get(id(roundId)); if (!value) fail("frozen context missing; run ares experience freeze");
199
+ if (checkedIdentity.toolsetSha256 !== undefined) digest(checkedIdentity.toolsetSha256);
200
+ const compatible = value.model === checkedIdentity.model && value.runtime === checkedIdentity.runtime && (!value.entries.length || value.toolsetSha256 === checkedIdentity.toolsetSha256);
201
+ const request: ExperienceRequest = {...requestFields(value), selected: value.entries.map(entry => ({id: entry.id, reason: entry.reason}))};
202
+ const observed = compatible ? await resolveSelected(current, request, options, value.entries) : {state: "unavailable" as const, context: null, bytes: 0, observations: []};
203
+ // Re-read after any policy/source observation. Never serve a context from mixed local generations.
204
+ const after = store(dir); if (canonical([...current.snapshots]) !== canonical([...after.snapshots]) || canonical(current.stream) !== canonical(after.stream)) fail("stream/context changed during recheck");
205
+ return {v: 1, round: value.round, state: compatible ? observed.state : "unavailable", cause: !compatible ? "model-runtime-incompatible" : observed.state === "available" ? null : "frozen-source-chain-unavailable-or-changed", nextStep: !compatible ? "Use the frozen model/runtime/toolset or freeze a new round" : observed.state === "available" ? null : "Restore the exact screened source and its reviewed local receipts, or freeze a new context; fixture entries never qualify a controlled/live trial", streamSha256: value.streamSha256, improverContextHash: hash(value), model: value.model, runtime: value.runtime, sourceStrength: value.sourceStrength ?? null, transfer: "not-demonstrated", prepareOnly: true, workerContext: "baseline-only", retrievalGuidanceSlot: compatible && value.condition === "retrieval-only" ? observed.context : null, condition: value.condition, context: compatible && observed.state === "available" ? observed.context : null, bytes: compatible ? observed.bytes : 0, observations: observed.observations, assurance: "observed-policy-source-only; no distributed atomicity"};
206
+ }
@@ -0,0 +1,140 @@
1
+ import {types} from "node:util";
2
+
3
+ export const HUB_GUIDANCE_READ_BYTES = 16 * 32_768 + 4096;
4
+ export type HubGuidanceSection = "Scope" | "Deliverables" | "Evidence";
5
+ export interface HubGuidanceMetadata {
6
+ readonly id: string;
7
+ readonly experimentId: string;
8
+ readonly taskId: number;
9
+ readonly taskCreated: number;
10
+ readonly flowRevision: number;
11
+ readonly roleId: string;
12
+ readonly layer: "shipped" | "project";
13
+ readonly baselineSha256: string;
14
+ readonly candidateSha256: string;
15
+ readonly changedSections: readonly HubGuidanceSection[];
16
+ readonly bytes: Readonly<{baseline: number; candidate: number; record: number}>;
17
+ readonly author: string;
18
+ readonly status: "declared" | "withdrawn";
19
+ readonly applicable: boolean;
20
+ readonly evidence: readonly Readonly<{key: string; status: "declared" | "unavailable"}>[];
21
+ }
22
+ export type HubGuidanceReadProjection = {readonly state: "unavailable"}
23
+ | {readonly state: "available"; readonly records: readonly HubGuidanceMetadata[]; readonly rationaleOmitted: true};
24
+
25
+ function invalid(): never {
26
+ throw new Error("hub guidance read: invalid closed metadata shape or bounds; reload a supported public guidance read result and retry");
27
+ }
28
+
29
+ /** Only inert own JSON data is inspected, including for in-process callers. */
30
+ function object(raw: unknown, fields: readonly string[]): Record<string, unknown> {
31
+ if (!raw || typeof raw !== "object" || types.isProxy(raw) || Array.isArray(raw)) invalid();
32
+ const prototype = Object.getPrototypeOf(raw);
33
+ if (prototype !== Object.prototype && prototype !== null) invalid();
34
+ const keys = Reflect.ownKeys(raw);
35
+ if (keys.length !== fields.length) invalid();
36
+ const result: Record<string, unknown> = Object.create(null);
37
+ for (const key of keys) {
38
+ if (typeof key !== "string" || !fields.includes(key)) invalid();
39
+ const descriptor = Object.getOwnPropertyDescriptor(raw, key);
40
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) invalid();
41
+ result[key] = descriptor.value;
42
+ }
43
+ return result;
44
+ }
45
+
46
+ function array(raw: unknown, maximum: number): unknown[] {
47
+ if (!raw || typeof raw !== "object" || types.isProxy(raw) || !Array.isArray(raw)
48
+ || Object.getPrototypeOf(raw) !== Array.prototype) invalid();
49
+ const length = Object.getOwnPropertyDescriptor(raw, "length");
50
+ if (!length || !("value" in length) || !Number.isSafeInteger(length.value) || length.value < 0 || length.value > maximum) invalid();
51
+ const keys = Reflect.ownKeys(raw);
52
+ if (keys.length !== length.value + 1) invalid();
53
+ const result: unknown[] = [];
54
+ for (let index = 0; index < length.value; index++) {
55
+ const descriptor = Object.getOwnPropertyDescriptor(raw, String(index));
56
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) invalid();
57
+ result.push(descriptor.value);
58
+ }
59
+ return result;
60
+ }
61
+
62
+ function text(raw: unknown, maximum: number): string {
63
+ if (typeof raw !== "string" || !raw.length || raw.length > maximum || Buffer.byteLength(raw) > maximum) invalid();
64
+ return raw;
65
+ }
66
+ function digest(raw: unknown): string {
67
+ if (typeof raw !== "string" || raw.length !== 64 || !/^[a-f0-9]{64}$/.test(raw)) invalid();
68
+ return raw;
69
+ }
70
+ function integer(raw: unknown, minimum: number, maximum = Number.MAX_SAFE_INTEGER): number {
71
+ if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < minimum || raw > maximum) invalid();
72
+ return raw;
73
+ }
74
+ function token(raw: unknown, pattern: RegExp, maximum: number): string {
75
+ const result = text(raw, maximum);
76
+ if (!pattern.test(result)) invalid();
77
+ return result;
78
+ }
79
+ function rationaleBytes(raw: unknown): number {
80
+ const row = object(raw, ["problemHypothesis", "expectedObservableDifference"]);
81
+ const result = {problemHypothesis: text(row.problemHypothesis, 2000), expectedObservableDifference: text(row.expectedObservableDifference, 2000)};
82
+ const bytes = Buffer.byteLength(JSON.stringify(result));
83
+ if (bytes > 2000) invalid();
84
+ return bytes;
85
+ }
86
+
87
+ function record(raw: unknown): {metadata: HubGuidanceMetadata; sourceBytes: number} {
88
+ const row = object(raw, ["id", "experimentId", "taskId", "taskCreated", "flowRevision", "roleId", "layer", "baselineSha256", "candidateSha256", "changedSections", "bytes", "author", "status", "applicable", "rationale", "evidence"]);
89
+ const experimentId = text(row.experimentId, 256);
90
+ if (/[\p{Cc}\p{Cs}]/u.test(experimentId)) invalid();
91
+ if (row.layer !== "shipped" && row.layer !== "project") invalid();
92
+ if (row.status !== "declared" && row.status !== "withdrawn") invalid();
93
+ if (typeof row.applicable !== "boolean" || row.status === "withdrawn" && row.applicable) invalid();
94
+ const changedSections = array(row.changedSections, 3).map(value => {
95
+ if (value !== "Scope" && value !== "Deliverables" && value !== "Evidence") invalid();
96
+ return value;
97
+ });
98
+ if (new Set(changedSections).size !== changedSections.length) invalid();
99
+ const sizes = object(row.bytes, ["baseline", "candidate", "record"]);
100
+ const evidence = array(row.evidence, 16).map(value => {
101
+ const item = object(value, ["key", "status"]);
102
+ if (item.status !== "declared" && item.status !== "unavailable") invalid();
103
+ return Object.freeze({key: digest(item.key), status: item.status});
104
+ });
105
+ if (new Set(evidence.map(value => value.key)).size !== evidence.length) invalid();
106
+ const metadata: HubGuidanceMetadata = Object.freeze({
107
+ id: digest(row.id), experimentId, taskId: integer(row.taskId, 1), taskCreated: integer(row.taskCreated, 0), flowRevision: integer(row.flowRevision, 0),
108
+ roleId: token(row.roleId, /^[a-z][a-z0-9-]{0,47}$/, 48), layer: row.layer,
109
+ baselineSha256: digest(row.baselineSha256), candidateSha256: digest(row.candidateSha256), changedSections: Object.freeze(changedSections),
110
+ bytes: Object.freeze({baseline: integer(sizes.baseline, 1, 8192), candidate: integer(sizes.candidate, 1, 8192), record: integer(sizes.record, 1, 32_768)}),
111
+ author: token(row.author, /^[a-z][a-z0-9-]{0,31}$/, 32), status: row.status, applicable: row.applicable, evidence: Object.freeze(evidence),
112
+ });
113
+ const sourceBytes = Buffer.byteLength(JSON.stringify(metadata)) + Buffer.byteLength(',"rationale":') + rationaleBytes(row.rationale);
114
+ return {metadata, sourceBytes};
115
+ }
116
+
117
+ /** Parse public lifecycle metadata, never private role snapshots or rationale output. */
118
+ export function parseHubGuidanceReadResult(raw: unknown): HubGuidanceReadProjection {
119
+ if (typeof raw === "string") {
120
+ if (raw.length > HUB_GUIDANCE_READ_BYTES || Buffer.byteLength(raw) > HUB_GUIDANCE_READ_BYTES) invalid();
121
+ try {raw = JSON.parse(raw);} catch {invalid();}
122
+ }
123
+ // Inspect state without accessing an untrusted property or selecting a permissive shape.
124
+ if (!raw || typeof raw !== "object" || types.isProxy(raw)) invalid();
125
+ const state = Object.getOwnPropertyDescriptor(raw, "state");
126
+ if (!state || !("value" in state) || !state.enumerable) invalid();
127
+ if (state.value === "unavailable") {
128
+ object(raw, ["state"]);
129
+ return Object.freeze({state: "unavailable"});
130
+ }
131
+ if (state.value !== "available") invalid();
132
+ const row = object(raw, ["state", "records"]);
133
+ const parsed = array(row.records, 16).map(record);
134
+ if (new Set(parsed.map(value => value.metadata.id)).size !== parsed.length) invalid();
135
+ // Rationale text never leaves its validator; only byte counts cross the record boundary.
136
+ const sourceBytes = Buffer.byteLength('{"state":"available","records":[]}')
137
+ + parsed.reduce((sum, value) => sum + value.sourceBytes, 0) + Math.max(0, parsed.length - 1);
138
+ if (sourceBytes > HUB_GUIDANCE_READ_BYTES) invalid();
139
+ return Object.freeze({state: "available", records: Object.freeze(parsed.map(value => value.metadata)), rationaleOmitted: true});
140
+ }
@@ -0,0 +1,18 @@
1
+ import { types } from "node:util";
2
+
3
+ /** Opaque source-owned address; it grants no resolver, path or evidence authority. */
4
+ export interface HubExecutionReferenceV1 {
5
+ v: 1; tool: "ahub"; projectKey: string; kind: string; id: string; revision?: string; sha256?: string;
6
+ }
7
+ const invalid = (): never => { throw new Error("hub execution reference: unsupported fields or identifier bounds; supply a plain ahub v1 address with bounded identities and an optional lowercase 64-hex sha256"); };
8
+ const text = (value: unknown, bound: number): value is string => typeof value === "string" && value.length > 0 && value.length <= bound && Buffer.byteLength(value, "utf8") <= bound && !/[\p{Cc}\p{Cs}]/u.test(value);
9
+ /** Inspect descriptors before values so hostile objects cannot run getters or proxy traps. */
10
+ export function parseHubExecutionReference(raw: unknown): HubExecutionReferenceV1 {
11
+ if (!raw || typeof raw !== "object" || types.isProxy(raw) || Array.isArray(raw) || ![Object.prototype, null].includes(Object.getPrototypeOf(raw)) || Object.getOwnPropertySymbols(raw).length) return invalid();
12
+ const fields = Object.getOwnPropertyDescriptors(raw), keys = ["v", "tool", "projectKey", "kind", "id", "revision", "sha256"];
13
+ if (Object.entries(fields).some(([key, field]) => !keys.includes(key) || !("value" in field))) return invalid();
14
+ const get = (key: string): unknown => fields[key]?.value;
15
+ const projectKey = get("projectKey"), kind = get("kind"), id = get("id"), revision = get("revision"), sha256 = get("sha256");
16
+ if (get("v") !== 1 || get("tool") !== "ahub" || !text(projectKey, 256) || !text(id, 256) || !text(kind, 64) || !/^[a-z][a-z0-9._-]*$/.test(kind) || Object.hasOwn(fields, "revision") && !text(revision, 128) || Object.hasOwn(fields, "sha256") && (typeof sha256 !== "string" || !/^[a-f0-9]{64}$/.test(sha256))) return invalid();
17
+ return {v: 1, tool: "ahub", projectKey, kind, id, ...(revision === undefined ? {} : {revision: revision as string}), ...(sha256 === undefined ? {} : {sha256: sha256 as string})};
18
+ }
@@ -0,0 +1,162 @@
1
+ import {HARNESS_MODEL_BYTES} from "./limits.ts";
2
+ import {validateSkillInspections} from "../memory/skill-format.ts";
3
+ import {archiveReceiptIndex} from "../memory/archive.ts";
4
+ import {lstatSync} from "node:fs";
5
+ import {join} from "node:path";
6
+ import {commit, openStudy, requireExperiment, onlyKeys, plain, readLedger, readTextBounded, sha256, isHarnessGate, type Actor, type LedgerEvent, prepareCommit, assertStudyReadLock} from "../study.ts";
7
+ import {canonical} from "../plan/state.ts";
8
+ import {readHarnessViews, validateHarnessExecution, type DeclaredExecutionRef} from "./rounds.ts";
9
+ import {hasHarnessCredential} from "./privacy.ts";
10
+ import {skillEvidenceReference, type SkillEvidenceReference, type EvidenceInspection} from "../memory/evidence.ts";
11
+ import {inspectSkillEvidenceSet, compareSkillInspections, semanticInspection, type SkillCheckOptions} from "../memory/skill-check.ts";
12
+ import type {AmemNote} from "../memory/amem.ts";
13
+
14
+ export const LESSON_BYTES = 16_384, LESSON_INDEX_BYTES = 1_048_576, LESSON_CANDIDATES = 64;
15
+ export const FIXTURE_LESSON_STRENGTH = "synthetic-fixture; not evidence of real agent behavior";
16
+ export interface LessonInput {
17
+ v: 1; name: string; round: string; closureSha256: string; kind: "observation" | "fail" | "limitation" | "no-lesson";
18
+ summary: string; procedure: string[]; applicability: string; limitations: string[]; whenNotToUse: string[]; failure: string; retryWhen: string;
19
+ change: {kind: "contrast" | "composition"; id: string; sha256: string}[];
20
+ behavior: {probe: string; projectionSha256: string; outputManifestHash?: string}[];
21
+ counterevidence: SkillEvidenceReference[]; reflection?: {model: string; sourceExecution: DeclaredExecutionRef};
22
+ }
23
+ export interface LessonProposal extends LessonInput {
24
+ studyId: string; taskId: string; taskInputSha256: string; roundBinding: string; sourceFingerprint: string;
25
+ sourceStrength: "synthetic-fixture"; transfer: "not-demonstrated"; evidenceLabel: "single-task-observation";
26
+ compatibility: {model: string; runtime: string; toolsetSha256: string} | null; inspections: EvidenceInspection[];
27
+ }
28
+ export interface LessonRow {proposal: LessonProposal; sha256: string; actor: Actor; at: string; state: "proposed" | "accepted" | "rejected" | "withdrawn"; disposition?: {decision: "accept" | "reject" | "withdraw"; proposalSha256: string; evidenceFingerprint: string; reason: string; acknowledgeStrength?: string; actor: Actor; at: string; inspections: EvidenceInspection[]; sha256: string}}
29
+ const hash = (value: unknown) => sha256(canonical(value)), file = (dir: string) => join(dir, "proposals", "lessons.json");
30
+ function fail(cause: string): never {throw new Error(`lesson: ${cause}; inspect ares lesson list/check, restore the recorded source or create a revised proposal with honest limitations before retrying`);}
31
+ function object(value: unknown, fields: string[]) {if (!plain(value)) fail("object required"); try {onlyKeys(value, fields, "lesson");} catch {fail(`unknown field; use ${fields.join(", ")}`);} return value;}
32
+ function text(value: unknown, max = 1000): string {if (typeof value !== "string" || !value.trim() || value.includes("\0") || Buffer.byteLength(value) > max || hasHarnessCredential(value)) fail("text is blank, over-bound or contains URL/credentials"); return value;}
33
+ function id(value: unknown): string {const name = text(value, 64); if (!isHarnessGate(`harness:${name}`)) fail("invalid run-name id"); return name;}
34
+ function digest(value: unknown): string {if (typeof value !== "string" || value.length !== 64 || !/^[a-f0-9]{64}$/.test(value)) fail("lowercase SHA-256 required"); return value;}
35
+ function list(value: unknown, max = 16): unknown[] {if (!Array.isArray(value) || value.length > max) fail(`array exceeds ${max} items`); return value;}
36
+ const INPUT = ["v", "name", "round", "closureSha256", "kind", "summary", "procedure", "applicability", "limitations", "whenNotToUse", "failure", "retryWhen", "change", "behavior", "counterevidence", "reflection"];
37
+ function input(raw: unknown, studyId: string): LessonInput {
38
+ const row = object(raw, INPUT); if (row.v !== 1) fail("unsupported proposal version; keep original bytes and use a supporting ares version");
39
+ if (!["observation", "fail", "limitation", "no-lesson"].includes(row.kind as string)) fail("kind must be observation, fail, limitation or no-lesson; successful improvement/transfer is not supported");
40
+ const change = list(row.change).map(raw => {const r = object(raw, ["kind", "id", "sha256"]); if (r.kind !== "contrast" && r.kind !== "composition") fail("change must cite contrast/composition"); return {kind: r.kind as "contrast" | "composition", id: id(r.id), sha256: digest(r.sha256)};});
41
+ const behavior = list(row.behavior).map(raw => {const r = object(raw, ["probe", "projectionSha256", "outputManifestHash"]); return {probe: text(r.probe, 256), projectionSha256: digest(r.projectionSha256), ...(r.outputManifestHash !== undefined ? {outputManifestHash: digest(r.outputManifestHash)} : {})};});
42
+ if (new Set(change.map(r => `${r.kind}:${r.id}`)).size !== change.length || new Set(behavior.map(r => r.probe)).size !== behavior.length) fail("duplicate source ref");
43
+ const counterevidence = list(row.counterevidence).map(raw => {const ref = skillEvidenceReference(raw, studyId); if (!ref || Object.values(ref).some(value => typeof value === "string" && hasHarnessCredential(value))) fail("unsupported/wrong-study counterevidence"); return ref;});
44
+ const reflection = row.reflection === undefined ? undefined : object(row.reflection, ["model", "sourceExecution"]);
45
+ const result: LessonInput = {v: 1, name: id(row.name), round: id(row.round), closureSha256: digest(row.closureSha256), kind: row.kind as LessonInput["kind"], summary: text(row.summary, 2000), procedure: list(row.procedure).map(value => text(value)), applicability: text(row.applicability, 2000), limitations: list(row.limitations).map(value => text(value)), whenNotToUse: list(row.whenNotToUse).map(value => text(value)), failure: text(row.failure), retryWhen: text(row.retryWhen), change, behavior, counterevidence, ...(reflection ? {reflection: {model: text(reflection.model, HARNESS_MODEL_BYTES), sourceExecution: validateHarnessExecution(reflection.sourceExecution)}} : {})};
46
+ const refs = lessonReferences({...result, studyId}).map(canonical);
47
+ if (new Set(refs).size !== refs.length) fail("duplicate evidence/counterevidence ref; remove repeated refs, including the mandatory harness-closure ref, from the proposal input");
48
+ if (result.kind !== "no-lesson" && (!result.procedure.length || !change.length || !behavior.length)) fail("exportable lessons require procedure and concrete change/behavior refs");
49
+ if (Buffer.byteLength(canonical(result)) > LESSON_BYTES) fail("proposal exceeds 16 KiB"); return result;
50
+ }
51
+ export function currentLessonSource(dir: string, value: Pick<LessonProposal, "round" | "closureSha256" | "change" | "behavior">, views?: ReturnType<typeof readHarnessViews>) {
52
+ const round = (views ?? readHarnessViews(dir, value.round)).find(round => round.definition.id === value.round); if (!round) fail("source view capped or unavailable; inspect a single bounded round");
53
+ const closure = round.transitions.closure;
54
+ if (!closure?.current || closure.sha256 !== value.closureSha256) fail("source round closure is missing, changed or stale");
55
+ for (const ref of value.change) if ((ref.kind === "contrast" ? round.transitions.contrasts.find(r => r.form.id === ref.id) : (round.transitions.composition?.form.id === ref.id ? round.transitions.composition : undefined))?.sha256 !== ref.sha256) fail("change ref is missing or changed");
56
+ for (const ref of value.behavior) {const probe = round.probes.find(r => r.projection.id === ref.probe); if (!probe || probe.projectionSha256 !== ref.projectionSha256 || ref.outputManifestHash !== undefined && ref.outputManifestHash !== probe.projection.outputManifestHash) fail("behavior ref is missing or changed");}
57
+ return round;
58
+ }
59
+ export function lessonReferences(value: Pick<LessonProposal, "studyId" | "round" | "closureSha256" | "counterevidence">): SkillEvidenceReference[] {return [{v: 1, tool: "ares", projectKey: value.studyId, kind: "harness-closure", id: value.round, sha256: value.closureSha256}, ...value.counterevidence];}
60
+ export function lessonEvidenceFingerprint(value: LessonProposal, inspections = value.inspections, currentFingerprint = value.sourceFingerprint): string {return hash({proposal: hash(value), source: currentFingerprint, inspections: inspections.map(semanticInspection)});}
61
+ function parseProposal(raw: unknown, studyId: string): LessonProposal {
62
+ const row = object(raw, [...INPUT, "studyId", "taskId", "taskInputSha256", "roundBinding", "sourceFingerprint", "sourceStrength", "transfer", "evidenceLabel", "compatibility", "inspections"]);
63
+ const authored = input(Object.fromEntries(INPUT.filter(key => Object.hasOwn(row, key)).map(key => [key, row[key]])), studyId);
64
+ if (row.studyId !== studyId || row.sourceStrength !== "synthetic-fixture" || row.transfer !== "not-demonstrated" || row.evidenceLabel !== "single-task-observation" || !Array.isArray(row.inspections)) fail("unsupported source strength/study or inspections");
65
+ const compatibility = row.compatibility === null ? null : object(row.compatibility, ["model", "runtime", "toolsetSha256"]);
66
+ const value: LessonProposal = {...authored, studyId, taskId: text(row.taskId, 256), taskInputSha256: digest(row.taskInputSha256), roundBinding: digest(row.roundBinding), sourceFingerprint: digest(row.sourceFingerprint), sourceStrength: "synthetic-fixture", transfer: "not-demonstrated", evidenceLabel: "single-task-observation", compatibility: compatibility ? {model: text(compatibility.model, HARNESS_MODEL_BYTES), runtime: digest(compatibility.runtime), toolsetSha256: digest(compatibility.toolsetSha256)} : null, inspections: row.inspections as EvidenceInspection[]};
67
+ value.inspections = validateSkillInspections(row.inspections, lessonReferences(value), studyId);
68
+ if (Buffer.byteLength(canonical(value)) > LESSON_BYTES) fail("proposal and source metadata exceed 16 KiB"); return value;
69
+ }
70
+ function fold(events: LedgerEvent[], studyId: string) {
71
+ const rows = new Map<string, LessonRow>();
72
+ for (const event of events) if (event.type === "lesson.proposed") {
73
+ const proposal = parseProposal(event.data.proposal, studyId), sha256 = hash(proposal);
74
+ if (event.data.v !== 1 || event.data.sha256 !== sha256 || rows.has(proposal.name) || rows.size >= LESSON_CANDIDATES) fail("invalid/duplicate/over-bound proposal receipt"); rows.set(proposal.name, {proposal, sha256, actor: event.actor, at: event.at, state: "proposed"});
75
+ } else if (event.type === "lesson.decided") {
76
+ const data = object(event.data, ["v", "name", "decision", "proposalSha256", "evidenceFingerprint", "reason", "acknowledgeStrength", "inspections", "sha256"]), row = rows.get(id(data.name));
77
+ if (data.v !== 1 || !row || row.sha256 !== data.proposalSha256 || !["accept", "reject", "withdraw"].includes(data.decision as string) || row.state !== "proposed" && !(row.state === "accepted" && data.decision === "withdraw")) fail("invalid or terminal disposition");
78
+ const body = {decision: data.decision as "accept" | "reject" | "withdraw", proposalSha256: digest(data.proposalSha256), evidenceFingerprint: digest(data.evidenceFingerprint), reason: text(data.reason, 2000), ...(data.acknowledgeStrength !== undefined ? {acknowledgeStrength: text(data.acknowledgeStrength)} : {}), inspections: validateSkillInspections(data.inspections, lessonReferences(row.proposal), studyId)};
79
+ if (body.decision === "accept" && (body.acknowledgeStrength !== FIXTURE_LESSON_STRENGTH || compareSkillInspections(row.proposal.inspections, body.inspections).length || body.evidenceFingerprint !== lessonEvidenceFingerprint(row.proposal, body.inspections))) fail("accepted lesson lacks unchanged reviewed evidence/explicit fixture strength acknowledgement");
80
+ if (hash({...body, actor: event.actor}) !== data.sha256) fail("disposition hash mismatch");
81
+ row.state = body.decision === "accept" ? "accepted" : body.decision === "reject" ? "rejected" : "withdrawn"; row.disposition = {...body, actor: event.actor, at: event.at, sha256: data.sha256 as string};
82
+ } else if (event.type.startsWith("lesson.")) fail("unsupported lesson event version; keep original bytes and use a supporting ares version");
83
+ return [...rows.values()];
84
+ }
85
+ function read(dirArg: string) {
86
+ const {dir, study} = openStudy(dirArg); requireExperiment(study); const events = readLedger(dir), folded = fold(events, study.id), rows = new Map(folded.map(row => [row.proposal.name, row]));
87
+ for (const parent of [join(dir, "proposals")]) {const stat = lstatSync(parent, {throwIfNoEntry: false}); if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) fail("proposal directory linked or unavailable");}
88
+ const stat = lstatSync(file(dir), {throwIfNoEntry: false});
89
+ if (!stat) {if (rows.size) fail("lesson index missing");}
90
+ else {if (!stat.isFile() || stat.isSymbolicLink()) fail("lesson index must be regular"); let raw: unknown; try {raw = JSON.parse(readTextBounded(file(dir), LESSON_INDEX_BYTES, {noFollow: true}));} catch {return fail("lesson index unreadable/malformed/over-bound");} const index = object(raw, ["v", "proposals"]); if (index.v !== 1 || canonical(index.proposals) !== canonical([...rows.values()].map(row => row.proposal))) fail("lesson index differs from original receipts or has unsupported version");}
91
+ return {dir, study, events, rows: [...rows.values()]};
92
+ }
93
+ export function listLessonCandidates(dir: string) {const current = read(dir); if (!current.rows.length) return []; const views = readHarnessViews(dir); return current.rows.map(row => {let current = false; try {const source = currentLessonSource(dir, row.proposal, views); current = source.binding === row.proposal.roundBinding && source.transitions.fingerprint === row.proposal.sourceFingerprint;} catch { /* explicit stale view */ } return {...row, current, evidenceFingerprint: lessonEvidenceFingerprint(row.proposal), exportable: row.state === "accepted" && current && row.proposal.kind !== "no-lesson", needsSourceRecheck: true};});}
94
+ export async function proposeLesson(dirArg: string, raw: unknown, actor: Actor, options: SkillCheckOptions = {}) {
95
+ const current = read(dirArg); if (!options.lock) fail("proposal requires an owned study transaction"); assertStudyReadLock(current.dir, options.lock);
96
+ const authored = input(raw, current.study.id), source = currentLessonSource(current.dir, authored);
97
+ if (current.rows.length >= LESSON_CANDIDATES || current.rows.some(row => row.proposal.name === authored.name)) fail("64-proposal cap or duplicate name; choose another name/study");
98
+ const selected = authored.behavior.map(ref => source.probes.find(p => p.projection.id === ref.probe)!.projection), first = selected[0];
99
+ const compatibility = first?.servedModel && selected.every(p => p.servedModel === first.servedModel && p.hostRuntimeHash === first.hostRuntimeHash && p.toolsetHash === first.toolsetHash) ? {model: first.servedModel, runtime: first.hostRuntimeHash, toolsetSha256: first.toolsetHash} : null;
100
+ const base: LessonProposal = {...authored, studyId: current.study.id, taskId: source.definition.task.id, taskInputSha256: source.definition.task.inputSha256, roundBinding: source.binding, sourceFingerprint: source.transitions.fingerprint, sourceStrength: "synthetic-fixture", transfer: "not-demonstrated", evidenceLabel: "single-task-observation", compatibility, inspections: []};
101
+ const checked = await inspectSkillEvidenceSet(current.dir, lessonReferences(base), options), proposal = parseProposal({...base, inspections: checked.inspections}, current.study.id);
102
+ candidateNote({proposal, sha256: hash(proposal), actor, at: new Date(0).toISOString(), state: "proposed"});
103
+ if (!checked.recheck() || currentLessonSource(current.dir, proposal).transitions.fingerprint !== proposal.sourceFingerprint) fail("sources changed or source budget expired during proposal");
104
+ if (canonical(read(current.dir).rows) !== canonical(current.rows)) fail("lesson journal/index changed before proposal");
105
+ assertStudyReadLock(current.dir, options.lock);
106
+ commit(current.dir, [[file(current.dir), JSON.stringify({v: 1, proposals: [...current.rows.map(row => row.proposal), proposal]}, null, 2) + "\n", LESSON_INDEX_BYTES]], [{actor, type: "lesson.proposed", data: {v: 1, proposal, sha256: hash(proposal)}}]); return listLessonCandidates(current.dir).find(row => row.proposal.name === proposal.name)!;
107
+ }
108
+ export async function checkLesson(dir: string, name: string, options: SkillCheckOptions = {}) {
109
+ const row = read(dir).rows.find(row => row.proposal.name === id(name)); if (!row) fail("proposal missing");
110
+ let current = false; try {const source = currentLessonSource(dir, row.proposal); current = source.binding === row.proposal.roundBinding && source.transitions.fingerprint === row.proposal.sourceFingerprint;} catch { /* stale */ }
111
+ if (!current) return {name, proposalSha256: row.sha256, state: "changed", acceptReady: false, evidenceFingerprint: lessonEvidenceFingerprint(row.proposal), inspections: row.proposal.inspections, sourceStrength: "synthetic-fixture", nextStep: "Create a revised proposal from a non-stale closed round"};
112
+ const checked = await inspectSkillEvidenceSet(dir, lessonReferences(row.proposal), options), reasons = compareSkillInspections(row.proposal.inspections, checked.inspections);
113
+ let same = false; try {same = currentLessonSource(dir, row.proposal).transitions.fingerprint === row.proposal.sourceFingerprint && canonical(read(dir).rows.find(value => value.proposal.name === name)) === canonical(row);} catch { /* changed source */ }
114
+ const ready = checked.recheck() && same && !reasons.length;
115
+ return {name, proposalSha256: row.sha256, state: ready ? "available" : "unavailable", acceptReady: ready && row.state === "proposed", evidenceFingerprint: lessonEvidenceFingerprint(row.proposal, checked.inspections), inspections: checked.inspections, sourceStrength: "synthetic-fixture", nextStep: "Review the fixture strength and limitations; no improvement/transfer is established"};
116
+ }
117
+ export async function decideLesson(dir: string, name: string, raw: unknown, actor: Actor, options: SkillCheckOptions = {}) {
118
+ const current = read(dir); if (!options.lock) fail("review requires an owned study transaction"); assertStudyReadLock(current.dir, options.lock);
119
+ const row = current.rows.find(row => row.proposal.name === id(name)); if (!row) fail("proposal missing");
120
+ const r = object(raw, ["decision", "proposalSha256", "evidenceFingerprint", "reason", "acknowledgeStrength"]);
121
+ if (!["accept", "reject", "withdraw"].includes(r.decision as string) || r.proposalSha256 !== row.sha256 || r.evidenceFingerprint !== lessonEvidenceFingerprint(row.proposal)) fail("disposition or proposal/evidence fingerprint differs");
122
+ const reason = text(r.reason, 2000), decision = r.decision as "accept" | "reject" | "withdraw";
123
+ if (row.state !== "proposed" && !(row.state === "accepted" && decision === "withdraw")) fail("disposition is final; create a revised proposal");
124
+ let inspections = row.proposal.inspections;
125
+ if (decision === "accept") {
126
+ if (r.acknowledgeStrength !== FIXTURE_LESSON_STRENGTH) fail("accept must explicitly acknowledge synthetic-fixture; not evidence of real agent behavior");
127
+ const checked = await checkLesson(dir, name, options); if (!checked.acceptReady || checked.evidenceFingerprint !== r.evidenceFingerprint) fail("required sources/counterevidence changed or unavailable"); inspections = checked.inspections;
128
+ }
129
+ const body = {decision, proposalSha256: row.sha256, evidenceFingerprint: r.evidenceFingerprint as string, reason, ...(r.acknowledgeStrength !== undefined ? {acknowledgeStrength: text(r.acknowledgeStrength)} : {}), inspections};
130
+ if (canonical(read(dir).rows) !== canonical(current.rows)) fail("lesson journal/index changed before disposition");
131
+ assertStudyReadLock(current.dir, options.lock);
132
+ const pending = [{actor, type: "lesson.decided", data: {v: 1, name, ...body, sha256: hash({...body, actor})}}];
133
+ const prepared = prepareCommit(current.dir, [], pending); fold([...current.events, ...prepared.events], current.study.id);
134
+ commit(current.dir, [], pending); return listLessonCandidates(dir).find(row => row.proposal.name === name)!;
135
+ }
136
+ export function candidateNote(row: LessonRow): AmemNote | null {
137
+ const p = row.proposal; if (p.kind === "no-lesson") return null;
138
+ const text = `${FIXTURE_LESSON_STRENGTH}\nSingle-task observation; transfer: not-demonstrated\nLesson ${p.name} (${row.sha256}); round ${p.round} (${p.closureSha256})\n${p.summary}\nProcedure:\n${p.procedure.map(value => `- ${value}`).join("\n")}\nApplicability: ${p.applicability}\nLimitations: ${p.limitations.join("; ")}\nWhen not to use: ${p.whenNotToUse.join("; ")}\nFailure: ${p.failure}\nRetry when: ${p.retryWhen}`;
139
+ if (Buffer.byteLength(text) > LESSON_BYTES) fail("export text exceeds 16 KiB; create a shorter revised proposal");
140
+ return {kind: p.kind === "observation" ? "finding" : "fail", title: p.name, text, ...(p.kind === "observation" ? {} : {approach: p.summary, symptom: p.failure, cause: "Reviewer-described limitation, not causal proof", retryWhen: p.retryWhen}), evidence: [`ares:${p.studyId}/harness-closure:${p.round}`]};
141
+ }
142
+ export function eligibleLessonNotes(dir: string) {return listLessonCandidates(dir).filter(row => row.exportable).map(row => ({row, note: candidateNote(row)!}));}
143
+ export function boundLessonExportBatch(dir: string, notes: {sha256: string; note: AmemNote}[]) {
144
+ const byHash = new Map(eligibleLessonNotes(dir).map(value => [hash(value.note), value.row])), known = new Set<string>(), batch: typeof notes = [];
145
+ for (const note of notes) {const row = byHash.get(note.sha256), refs = row ? lessonReferences(row.proposal).map(canonical) : []; if (new Set([...known, ...refs]).size > 64) break; refs.forEach(ref => known.add(ref)); batch.push(note);}
146
+ return batch;
147
+ }
148
+ export async function recheckLessonExports(dir: string, hashes: readonly string[], options: SkillCheckOptions = {}) {
149
+ const pending = eligibleLessonNotes(dir).filter(value => hashes.includes(hash(value.note)));
150
+ const refs = [...new Map(pending.flatMap(value => lessonReferences(value.row.proposal)).map(ref => [canonical(ref), ref])).values()];
151
+ if (!refs.length) return () => true;
152
+ const checked = await inspectSkillEvidenceSet(dir, refs, options); if (!checked.recheck()) fail("sources changed or export source budget expired");
153
+ const byRef = new Map(checked.inspections.map(value => [canonical(value.ref), value]));
154
+ for (const {row} of pending) {currentLessonSource(dir, row.proposal); const now = lessonReferences(row.proposal).map(ref => byRef.get(canonical(ref))!); if (compareSkillInspections(row.proposal.inspections, now).length || lessonEvidenceFingerprint(row.proposal, now) !== row.disposition?.evidenceFingerprint) fail("accepted lesson source/counterevidence changed before export");}
155
+ return checked.recheck;
156
+ }
157
+ export function archivedLessonSources(dir: string) {
158
+ const current = read(dir), receipts = archiveReceiptIndex(current.events), counts = new Map<string, number>(), known = new Map<string, {row: LessonRow; note: AmemNote; noteSha256: string}>();
159
+ for (const id of receipts.values()) counts.set(id, (counts.get(id) ?? 0) + 1);
160
+ for (const row of listLessonCandidates(dir)) if (row.exportable) {const note = candidateNote(row); if (!note) continue; const noteSha256 = hash(note), id = receipts.get(noteSha256); if (id && counts.get(id) === 1) known.set(id, {row, note, noteSha256});}
161
+ return known;
162
+ }
@@ -0,0 +1,2 @@
1
+ /** Shared model identity bound across fixture, lesson and experience surfaces. */
2
+ export const HARNESS_MODEL_BYTES = 256;