@staix/agent-research 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +107 -0
- package/README.md +255 -24
- package/package.json +2 -2
- package/src/cli.ts +117 -10
- package/src/commands-table.ts +39 -8
- package/src/commands.ts +192 -32
- package/src/exp/attempts.ts +500 -65
- package/src/exp/executor.ts +235 -12
- package/src/exp/final.ts +1 -1
- package/src/exp/logs.ts +25 -12
- package/src/exp/metrics.ts +6 -5
- package/src/exp/pipeline.ts +92 -0
- package/src/exp/protocol.ts +85 -18
- package/src/exp/retention-script.ts +649 -0
- package/src/exp/retention.ts +70 -0
- package/src/exp/reuse-admission.ts +63 -0
- package/src/exp/reuse-contract.ts +48 -0
- package/src/exp/reuse-runtime.ts +87 -0
- package/src/exp/reuse.ts +87 -0
- package/src/exp/selection.ts +1 -1
- package/src/exp/snapshot.ts +3 -3
- package/src/exp/stages.ts +117 -0
- package/src/harness/experience-source.ts +34 -0
- package/src/harness/experience.ts +206 -0
- package/src/harness/hub-guidance.ts +140 -0
- package/src/harness/hub-reference.ts +18 -0
- package/src/harness/lesson-candidates.ts +162 -0
- package/src/harness/limits.ts +2 -0
- package/src/harness/privacy.ts +4 -0
- package/src/harness/receipts.ts +84 -0
- package/src/harness/rounds.ts +198 -0
- package/src/harness/transitions.ts +152 -0
- package/src/lit/candidates.ts +13 -5
- package/src/lit/cards.ts +55 -4
- package/src/lit/flow.ts +82 -0
- package/src/lit/queries.ts +62 -0
- package/src/manifest.ts +13 -6
- package/src/mcp-tools.ts +123 -25
- package/src/mcp.ts +4 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +17 -8
- package/src/memory/evidence-local.ts +77 -0
- package/src/memory/evidence.ts +39 -0
- package/src/memory/lessons.ts +4 -2
- package/src/memory/skill-check.ts +56 -0
- package/src/memory/skill-format.ts +77 -0
- package/src/memory/skills.ts +72 -26
- package/src/memory/source-budget.ts +11 -0
- package/src/memory/vault-cards.ts +226 -0
- package/src/paper/build.ts +16 -7
- package/src/paper/check.ts +37 -10
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +16 -1
- package/src/paper/plan.ts +170 -0
- package/src/paper/point-evidence.ts +63 -0
- package/src/paper/points.ts +83 -0
- package/src/paper/review.ts +102 -9
- package/src/paper/scopes.ts +51 -0
- package/src/plan/definition.ts +5 -1
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +5 -0
- package/src/playbook.ts +35 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +55 -27
- package/src/study.ts +54 -14
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +263 -6
- package/src/ui/plugin.ts +68 -10
package/src/scope.ts
CHANGED
|
@@ -2,9 +2,28 @@ import { existsSync } from "node:fs";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { boundedText, commit, onlyKeys, plain, readBytesBounded, readJsonFile, sha256, type Actor } from "./study.ts";
|
|
4
4
|
|
|
5
|
-
export interface
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
export interface ExclusionCode { code: string; label: string }
|
|
6
|
+
export interface Scope { question: string; subquestions: string[]; include: string[]; exclude: string[]; yearFrom?: number; yearTo?: number; maxCandidates: number; exclusionCodes?: ExclusionCode[] }
|
|
7
|
+
const KEYS = ["question", "subquestions", "include", "exclude", "yearFrom", "yearTo", "maxCandidates", "exclusionCodes"] as const;
|
|
8
|
+
export const MAX_CANDIDATES = 5000, MAX_EXCLUSION_CODES = 30;
|
|
9
|
+
/** Lower-case slug; "uncoded" names the group of exclusions without a code and is reserved. */
|
|
10
|
+
export const EXCLUSION_CODE = /^[a-z][a-z0-9-]{0,31}$/;
|
|
11
|
+
function exclusionCodes(value: unknown): ExclusionCode[] | undefined {
|
|
12
|
+
if (value === undefined) return undefined;
|
|
13
|
+
if (!Array.isArray(value) || value.length > MAX_EXCLUSION_CODES) throw new Error(`scope.exclusionCodes: list of at most ${MAX_EXCLUSION_CODES} {code, label} objects`);
|
|
14
|
+
const seen = new Set<string>();
|
|
15
|
+
return value.map((item, i) => {
|
|
16
|
+
const at = `scope.exclusionCodes[${i}]`;
|
|
17
|
+
if (!plain(item)) throw new Error(`${at}: object {code, label} required`);
|
|
18
|
+
onlyKeys(item, ["code", "label"], at);
|
|
19
|
+
if (typeof item.code !== "string" || !EXCLUSION_CODE.test(item.code) || item.code === "uncoded") throw new Error(`${at}.code: lower-case slug of at most 32 characters (letters, digits, -), not "uncoded"`);
|
|
20
|
+
if (seen.has(item.code)) throw new Error(`${at}.code: duplicate code ${item.code}`);
|
|
21
|
+
seen.add(item.code);
|
|
22
|
+
const label = boundedText(item.label, `${at}.label`, 200);
|
|
23
|
+
if (/{{|}}|\||[\r\n]/.test(label)) throw new Error(`${at}.label: must not contain {{, }}, | or line breaks, so it can appear in the lit flow table; reword the label`);
|
|
24
|
+
return { code: item.code, label };
|
|
25
|
+
});
|
|
26
|
+
}
|
|
8
27
|
|
|
9
28
|
function list(value: unknown, what: string, maxItems: number, maxText: number): string[] {
|
|
10
29
|
if (value === undefined) return [];
|
|
@@ -24,6 +43,7 @@ export function validateScope(raw: unknown): Scope {
|
|
|
24
43
|
if (yearFrom !== undefined && yearTo !== undefined && yearFrom > yearTo) throw new Error("scope: yearFrom after yearTo");
|
|
25
44
|
const max = raw.maxCandidates ?? 500;
|
|
26
45
|
if (!Number.isSafeInteger(max) || (max as number) < 1 || (max as number) > MAX_CANDIDATES) throw new Error(`scope.maxCandidates: 1..${MAX_CANDIDATES}`);
|
|
46
|
+
const codes = exclusionCodes(raw.exclusionCodes);
|
|
27
47
|
return {
|
|
28
48
|
question: boundedText(raw.question, "scope.question", 2000),
|
|
29
49
|
subquestions: list(raw.subquestions, "scope.subquestions", 30, 1000),
|
|
@@ -31,6 +51,7 @@ export function validateScope(raw: unknown): Scope {
|
|
|
31
51
|
exclude: list(raw.exclude, "scope.exclude", 50, 500),
|
|
32
52
|
...(yearFrom !== undefined ? { yearFrom } : {}), ...(yearTo !== undefined ? { yearTo } : {}),
|
|
33
53
|
maxCandidates: max as number,
|
|
54
|
+
...(codes ? { exclusionCodes: codes } : {}),
|
|
34
55
|
};
|
|
35
56
|
}
|
|
36
57
|
|
package/src/study-export.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { attemptReuseView, retentionDisposalIndex, type RetentionDisposalIndex } from "./provenance.ts";
|
|
2
|
+
import {urlOrKeyLike} from "./privacy.ts";
|
|
1
3
|
import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync } from "node:fs";
|
|
2
4
|
import { basename, dirname, join, relative, resolve, isAbsolute, sep } from "node:path";
|
|
3
5
|
import { readAttemptRecords, type Attempt, type AttemptStatus } from "./exp/attempts.ts";
|
|
@@ -7,7 +9,9 @@ import { readClosedInvestigation } from "./exp/investigate.ts";
|
|
|
7
9
|
import { readSelection } from "./exp/selection.ts";
|
|
8
10
|
import { designBinding, protocolHash, readProtocol } from "./exp/protocol.ts";
|
|
9
11
|
import { FORMAT_VERSIONS } from "./manifest.ts";
|
|
10
|
-
import {
|
|
12
|
+
import { loadCandidates } from "./lit/candidates.ts";
|
|
13
|
+
import { intentSummary } from "./lit/queries.ts";
|
|
14
|
+
import { PAPER_EVIDENCE_BYTES, paperBuildPaths, paperEvidenceVersion } from "./paper/build.ts";
|
|
11
15
|
import { assertWritable, openStudy, plain, readLedger, readTextBounded, sha256, withLock, writeAtomic, type LedgerEvent } from "./study.ts";
|
|
12
16
|
|
|
13
17
|
/** Reader bound for every bundle file; writeAtomic refuses anything larger. */
|
|
@@ -26,19 +30,21 @@ const METRIC_KEYS = new Set(["name", "unit", "metric"]);
|
|
|
26
30
|
/** Closed data keys per ledger event type; unlisted types keep the envelope with empty data. Never host, containerId or hubProject. */
|
|
27
31
|
const LEDGER_KEYS: Record<string, readonly string[]> = {
|
|
28
32
|
"scope.set": ["sha256"], "autonomy.set": ["from", "to", "phase"], "gate.approve": ["gate", "binding"], "gate.reject": ["gate", "binding"],
|
|
29
|
-
"lit.search": ["sources", "added", "merged", "total"], "lit.screen": ["decision"], "lit.card": ["id", "sha256"], "lit.bib": ["entries", "sha256"], "lit.verify": ["verified", "failed"],
|
|
33
|
+
"lit.search": ["intent", "yearFrom", "sources", "added", "merged", "absorbed", "total"], "lit.screen": ["decision", "code"], "lit.card": ["id", "sha256"], "lit.card.exported": ["fingerprint"], "lit.card.imported": [], "lit.bib": ["entries", "sha256"], "lit.verify": ["verified", "failed"],
|
|
30
34
|
"archive.exported": ["fingerprint"], "skill.proposed": ["skillProposal", "sha256"], "skill.decided": ["skillProposal", "decision"], "watch.set": ["sha256"],
|
|
31
35
|
"plan.set": ["revision", "state", "sha256"], "plan.gates": ["revision"], "plan.paused": ["revision"], "plan.control": ["revision"], "node.observed": ["revision", "status"], "node.intent": ["revision"],
|
|
32
|
-
"executor.set": ["kind"], "protocol.set": ["sha256", "protocolHash", "treeHash"], "selection.set": ["sha256", "metric"], "final.seeds.set": ["sha256"],
|
|
36
|
+
"executor.set": ["kind"], "protocol.set": ["sha256", "identitySha256", "protocolHash", "treeHash"], "selection.set": ["sha256", "metric"], "final.seeds.set": ["sha256"],
|
|
33
37
|
"investigate.closed": ["run", "sha256", "ruleSha256", "winner"], "ablate.closed": ["sha256", "investigateSha256"], "final.closed": ["sha256", "status", "investigateSha256"],
|
|
34
38
|
"idea.decided": ["decision"], "paper.built": ["manuscriptSha256", "evidenceSha256", "sourceManuscriptSha256"], "review.added": [], "review.resolved": ["buildSha256"],
|
|
35
39
|
"attempt.started": ["id", "run", "seed", "commit", "treeId"],
|
|
40
|
+
"retention.pruned": ["fingerprint", "refsSha256", "count"],
|
|
41
|
+
"attempt.stage.reused": ["id", "stage", "candidateStage", "key", "sourceAttemptId", "sourceStage", "sourceSha256"],
|
|
36
42
|
};
|
|
37
|
-
for (const t of ["attempt.run", "attempt.snapshot", "attempt.stage.changed", "attempt.stage.evidence", "attempt.stage.recovered", "attempt.stage.started", "attempt.succeeded", "attempt.failed", "attempt.cancelled", "attempt.unknown"]) LEDGER_KEYS[t] = ["id", "run", "stage", "status"];
|
|
43
|
+
for (const t of ["attempt.run", "attempt.snapshot", "attempt.stage.changed", "attempt.stage.evidence", "attempt.stage.recovered", "attempt.stage.started", "attempt.reuse.preflight", "attempt.reuse.fresh-intent", "attempt.reuse.materialized", "attempt.reuse.miss", "attempt.succeeded", "attempt.failed", "attempt.cancelled", "attempt.unknown"]) LEDGER_KEYS[t] = ["id", "run", "stage", "status"];
|
|
38
44
|
|
|
39
45
|
export interface BundleManifest {
|
|
40
46
|
bundle: 1; formats: typeof FORMAT_VERSIONS; studyIdSha256: string; mode: string; protocolHash: string | null; sealBinding: string | null;
|
|
41
|
-
window: { from: string | null; to: string | null }; counts: { attempts: number; byStatus: Record<AttemptStatus, number>; byRun: Record<string, Record<AttemptStatus, number>>; ledgerEvents: number; reviews: number };
|
|
47
|
+
window: { from: string | null; to: string | null }; counts: { attempts: number; byStatus: Record<AttemptStatus, number>; byRun: Record<string, Record<AttemptStatus, number>>; ledgerEvents: number; reviews: number; reviewSections: { sections: { sectionSha256: string; rounds: number; pass: boolean }[]; repairs: Record<string, number> }; litQueries: Record<string, { queries: number; added: number; merged: number; included: number; excluded: number; new: number }> };
|
|
42
48
|
files: Record<string, string>;
|
|
43
49
|
}
|
|
44
50
|
export interface BundleListing { bundle: string; files: string[]; wouldWrite: true }
|
|
@@ -66,8 +72,9 @@ function project(value: unknown): unknown {
|
|
|
66
72
|
const isoAt = (value: unknown): string | null => typeof value === "string" && value.length <= 64 && /^\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:\d{2})$/.test(value) && Number.isFinite(Date.parse(value)) ? value : null;
|
|
67
73
|
function reduceEvent(event: LedgerEvent) {
|
|
68
74
|
const actor = { kind: ACTOR_KINDS.has(event.actor?.kind as string) ? event.actor.kind : "other", ...(event.actor.id !== undefined ? { idSha256: sha256(event.actor.id) } : {}) };
|
|
69
|
-
const at = isoAt(event.at);
|
|
70
|
-
|
|
75
|
+
const at = isoAt(event.at), data = reduceData(plain(event.data) ? event.data : {}, (Object.hasOwn(LEDGER_KEYS, event.type) ? LEDGER_KEYS[event.type]! : []));
|
|
76
|
+
if (event.type === "retention.pruned" && Array.isArray(event.data.refs) && event.data.refs.length > 0 && event.data.refs.length <= 500 && retentionDisposalIndex([event]).size === event.data.refs.length) data.refs = event.data.refs.map(ref => [...ref as string[]]);
|
|
77
|
+
return { v: event.v, at, actor, type: TOKEN.test(event.type) ? event.type : "other", data };
|
|
71
78
|
}
|
|
72
79
|
// Closed codes emitted by attempts.ts, metrics.ts and artifacts.ts; never derive a class from user prose.
|
|
73
80
|
const ATTEMPT_REASON_CODES = new Set([
|
|
@@ -90,18 +97,26 @@ function digest(image: unknown): string | null {
|
|
|
90
97
|
const match = typeof image === "string" ? /@(sha256:[a-f0-9]{64})$/.exec(image) : null;
|
|
91
98
|
return match?.[1] ?? null;
|
|
92
99
|
}
|
|
93
|
-
function attemptRow(a: Attempt) {
|
|
100
|
+
function attemptRow(a: Attempt, disposals: RetentionDisposalIndex) {
|
|
94
101
|
const stages: Record<string, unknown> = {};
|
|
95
102
|
for (const name of ["candidate", "evaluator"] as const) {
|
|
96
103
|
const stage = plain(a.stages) && Object.hasOwn(a.stages, name) ? a.stages[name] : undefined;
|
|
97
104
|
if (!plain(stage)) continue;
|
|
98
105
|
stages[name] = { exitCode: Number.isSafeInteger(stage.exitCode) ? stage.exitCode : null, durationMs: duration(stage.startedAt, stage.endedAt), network: stage.network === "none" ? "none" : "other", limits: plain(stage.limits) ? reduceData(stage.limits, ["cpus", "memoryMb", "pidsLimit", "wallSeconds", "gpus"]) : null, imageDigest: digest(stage.image) };
|
|
99
106
|
}
|
|
100
|
-
const
|
|
107
|
+
for (const parent of a.pipeline?.completed ?? []) {
|
|
108
|
+
const stage = parent.record;
|
|
109
|
+
const borrowed = parent.reuse;
|
|
110
|
+
if (borrowed !== undefined) stages[parent.name] = { execution: "reused", originalExitCode: stage.exitCode ?? null, originalDurationMs: duration(stage.startedAt, stage.endedAt), imageDigest: digest(stage.image), manifestSha256: parent.ref.sha256, inputIndependent: false };
|
|
111
|
+
else stages[parent.name] = { execution: "executed", exitCode: stage.exitCode ?? null, durationMs: duration(stage.startedAt, stage.endedAt), network: "none", imageDigest: digest(stage.image), manifestSha256: parent.ref.sha256, inputIndependent: false };
|
|
112
|
+
}
|
|
113
|
+
const reason = reasonClass(a.reason, a.status), reuse = attemptReuseView(a, disposals);
|
|
101
114
|
return {
|
|
102
115
|
id: a.id, run: a.run, studyIdSha256: sha256(String(a.studyId)), protocolHash: shaped(a.protocolHash, SHA256), sealBinding: shaped(a.sealBinding, SHA256), commit: shaped(a.commit, GIT_ID), treeId: shaped(a.treeId, GIT_ID),
|
|
103
116
|
snapshotSha256: shaped(a.snapshotSha256, SHA256), seed: Number.isSafeInteger(a.seed) ? a.seed : null, labelSha256: sha256(String(a.label ?? "")), retryOf: shaped(a.retryOf, ATTEMPT_ID), status: a.status, stage: a.stage, ...(reason ? { reasonClass: reason } : {}),
|
|
104
|
-
|
|
117
|
+
...(a.verifiedInputs !== undefined ? { inputs: Object.fromEntries(Object.entries(a.verifiedInputs).map(([name, hash]) => [name, shaped(hash, SHA256)])) } : {}),
|
|
118
|
+
...(a.gpuDevices !== undefined ? { gpuDeviceCount: a.gpuDevices.length } : {}),
|
|
119
|
+
durationMs: duration(a.startedAt, a.endedAt), stages, ...(reuse === undefined ? {} : {reuse}),
|
|
105
120
|
metrics: (Array.isArray(a.metrics) ? a.metrics : []).map(m => ({ name: m.name, unit: m.unit, value: finite(m.value), provenance: m.provenance === "ares-observed" ? "ares-observed" : "other" })),
|
|
106
121
|
outputs: (Array.isArray(a.outputs) ? a.outputs : []).map(o => ({ sha256: shaped(o.sha256, SHA256), bytes: finite(o.bytes) })),
|
|
107
122
|
sealing: plain(a.sealing) ? { separateContainers: a.sealing.separateContainers === true, evaluatorReadOnly: a.sealing.evaluatorReadOnly === true, candidateHasNoEvaluator: a.sealing.candidateHasNoEvaluator === true } : null,
|
|
@@ -112,25 +127,42 @@ function closedResult<T>(name: string, read: () => { result: T }): unknown {
|
|
|
112
127
|
catch (error) { throw new Error(`study export: ${name} result is not a verified closed result (${(error as Error).message}); fix it as that message says, then export again`); }
|
|
113
128
|
}
|
|
114
129
|
function reviews(events: LedgerEvent[]) {
|
|
115
|
-
const resolved = new Map<string, number>();
|
|
116
|
-
for (const e of events) if (e.type === "review.resolved" && typeof e.data.reviewId === "string") resolved.set(e.data.reviewId, (resolved.get(e.data.reviewId) ?? 0) + 1);
|
|
130
|
+
const resolved = new Map<string, number>(), resolvedIds = new Set<string>();
|
|
131
|
+
for (const e of events) if (e.type === "review.resolved" && typeof e.data.reviewId === "string") { resolved.set(e.data.reviewId, (resolved.get(e.data.reviewId) ?? 0) + 1); if (typeof e.data.findingId === "string") resolvedIds.add(`${e.data.reviewId}/${e.data.findingId}`); }
|
|
117
132
|
return events.filter(e => e.type === "review.added" && plain(e.data.review)).map(e => {
|
|
118
133
|
const review = e.data.review as Record<string, unknown>, findings = Array.isArray(review.findings) ? review.findings as Record<string, unknown>[] : [];
|
|
119
|
-
const reviewer = plain(review.reviewer) ? review.reviewer : {}, kinds: Record<string, number> = {};
|
|
134
|
+
const reviewer = plain(review.reviewer) ? review.reviewer : {}, kinds: Record<string, number> = {}, repairs: Record<string, number> = {};
|
|
120
135
|
for (const f of findings) { const kind = typeof f.kind === "string" && TOKEN.test(f.kind) ? f.kind : "other"; kinds[kind] = (kinds[kind] ?? 0) + 1; }
|
|
136
|
+
for (const f of findings) { const repair = f.repair === "paragraph" || f.repair === "section" ? f.repair : "edit"; repairs[repair] = (repairs[repair] ?? 0) + 1; }
|
|
121
137
|
const id = typeof e.data.id === "string" ? e.data.id : "";
|
|
122
138
|
const family = typeof reviewer.modelFamily === "string" ? reviewer.modelFamily.trim().toLowerCase() : "";
|
|
123
|
-
|
|
139
|
+
// Section names are reviewer text: export only their hashes with open-at-build markers, never the names.
|
|
140
|
+
const sections = [...new Set(findings.flatMap(f => typeof f.section === "string" && f.section.trim() ? [f.section.trim()] : []))];
|
|
141
|
+
const openSections = [...new Set(findings.flatMap(f => typeof f.section === "string" && f.section.trim() && typeof f.id === "string" && !resolvedIds.has(`${id}/${f.id}`) ? [f.section.trim()] : []))];
|
|
142
|
+
return { idSha256: sha256(id), at: isoAt(e.at), modelFamily: /^[a-z0-9][a-z0-9 ._-]{0,47}$/.test(family) ? family : "other", buildSha256: typeof review.buildSha256 === "string" && HEX.test(review.buildSha256) ? review.buildSha256 : null, findings: findings.length, blocking: findings.filter(f => f.blocking === true).length, kinds, repairs, resolved: resolved.get(id) ?? 0, sections, openSections };
|
|
124
143
|
});
|
|
125
144
|
}
|
|
145
|
+
/** Content-free per-section rounds and pass at the latest built evidence hash, plus the repair-scope histogram. */
|
|
146
|
+
function reviewSections(rows: ReturnType<typeof reviews>, events: LedgerEvent[]) {
|
|
147
|
+
const latest = events.filter(e => e.type === "paper.built" && typeof e.data.evidenceSha256 === "string").at(-1)?.data.evidenceSha256 ?? null;
|
|
148
|
+
const rounds = new Map<string, number>(), open = new Set<string>(), repairs: Record<string, number> = { edit: 0, paragraph: 0, section: 0 };
|
|
149
|
+
for (const row of rows) {
|
|
150
|
+
for (const section of row.sections) rounds.set(section, (rounds.get(section) ?? 0) + 1);
|
|
151
|
+
if (row.buildSha256 !== null && row.buildSha256 === latest) for (const section of row.openSections) open.add(section);
|
|
152
|
+
for (const [repair, n] of Object.entries(row.repairs)) repairs[repair] = (repairs[repair] ?? 0) + n;
|
|
153
|
+
}
|
|
154
|
+
return { sections: [...rounds].map(([section, n]) => ({ sectionSha256: sha256(section), rounds: n, pass: !open.has(section) })).sort((a, b) => a.sectionSha256 < b.sectionSha256 ? -1 : 1), repairs };
|
|
155
|
+
}
|
|
126
156
|
function evidence(dir: string) {
|
|
127
157
|
const path = paperBuildPaths(dir).evidence;
|
|
128
158
|
if (!existsSync(path)) return null;
|
|
129
159
|
let raw: unknown;
|
|
130
160
|
try { raw = JSON.parse(readTextBounded(path, PAPER_EVIDENCE_BYTES)); } catch { throw new Error("study export: paper/build/evidence.json is unreadable, invalid JSON or oversized; rebuild the paper before exporting"); }
|
|
131
|
-
|
|
161
|
+
paperEvidenceVersion(raw);
|
|
162
|
+
if (!plain(raw) || !Array.isArray(raw.placeholders)) throw new Error("study export: paper/build/evidence.json has an unsupported shape; rebuild the paper before exporting");
|
|
132
163
|
return {
|
|
133
164
|
v: 1, manuscriptSha256: typeof raw.manuscriptSha256 === "string" && SHA256.test(raw.manuscriptSha256) ? raw.manuscriptSha256 : null,
|
|
165
|
+
...(raw.v === 2 ? {planSha256: raw.planSha256} : {}),
|
|
134
166
|
placeholders: (raw.placeholders as Record<string, unknown>[]).filter(p => p.kind === "number").map(p => {
|
|
135
167
|
const ref = typeof p.ref === "string" ? p.ref : "", attempt = /^(?:attempt|posthoc):([a-f0-9]{16})\./.exec(ref)?.[1];
|
|
136
168
|
const source = plain(p.source) ? p.source : {};
|
|
@@ -147,13 +179,7 @@ const PATH_SCANS: RegExp[] = [
|
|
|
147
179
|
// Windows root-relative (\Users\x), bare \ and UNC (\\server): any backslash not preceded by a word character or backslash.
|
|
148
180
|
/(?<![\p{L}\p{N}_\\])\\/u,
|
|
149
181
|
];
|
|
150
|
-
|
|
151
|
-
const SCANS: [string, RegExp][] = [
|
|
152
|
-
["url", /\b[a-z][a-z0-9+.-]*:\/\/|\b(?:mailto|urn|file|data):/i],
|
|
153
|
-
["key-like token", /\b(?:sk|pk|rk)[-_][A-Za-z0-9_-]{12,}|\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{12,}|\bxox[abprs]-[A-Za-z0-9-]{8,}|\bAKIA[0-9A-Z]{12,}|\beyJ[A-Za-z0-9_-]{16,}/],
|
|
154
|
-
["key-like token", /(?<![A-Za-z0-9_-])(?=[A-Za-z0-9_-]*[A-Z])(?=[A-Za-z0-9_-]*[a-z])(?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]{32,}(?![A-Za-z0-9_-])/],
|
|
155
|
-
["env value", /(?<![A-Za-z0-9_])[A-Za-z_][A-Za-z0-9_]*=[^\s"]/],
|
|
156
|
-
];
|
|
182
|
+
const ENV_VALUE = /(?<![A-Za-z0-9_])[A-Za-z_][A-Za-z0-9_]*=[^\s"]/;
|
|
157
183
|
/** Every key and string value of a JSON document, or of each JSONL line; text that is not JSON is scanned as one string. */
|
|
158
184
|
function* decodedStrings(text: string): Generator<string> {
|
|
159
185
|
const walk = function* (value: unknown): Generator<string> {
|
|
@@ -175,7 +201,9 @@ export function scanBundle(files: Record<string, string>): void {
|
|
|
175
201
|
for (const [name, text] of Object.entries(files)) {
|
|
176
202
|
for (const value of decodedStrings(text)) {
|
|
177
203
|
if (PATH_SCANS.some(pattern => pattern.test(value))) refuse(name, "absolute path");
|
|
178
|
-
|
|
204
|
+
const marker = urlOrKeyLike(value);
|
|
205
|
+
if (marker) refuse(name, marker);
|
|
206
|
+
if (ENV_VALUE.test(value)) refuse(name, "env value");
|
|
179
207
|
}
|
|
180
208
|
}
|
|
181
209
|
}
|
|
@@ -195,13 +223,13 @@ function realTarget(path: string): string {
|
|
|
195
223
|
/** Caller holds the study lock across every bounded source read. */
|
|
196
224
|
function readBundle(dirArg: string, maxFileBytes: number) {
|
|
197
225
|
const { dir, study } = openStudy(dirArg);
|
|
198
|
-
const events = readLedger(dir);
|
|
226
|
+
const events = readLedger(dir), disposals = retentionDisposalIndex(events);
|
|
199
227
|
const zero = () => Object.fromEntries(STATUSES.map(s => [s, 0])) as Record<AttemptStatus, number>;
|
|
200
228
|
const byStatus = zero(), runCounts = new Map<string, Record<AttemptStatus, number>>(), attemptLines: string[] = [];
|
|
201
229
|
let attemptBytes = 0;
|
|
202
230
|
// One pass; only the projected row and counts outlive each raw record.
|
|
203
231
|
for (const a of study.mode === "experiment" ? readAttemptRecords(dir) : []) {
|
|
204
|
-
const line = JSON.stringify(attemptRow(a)) + "\n";
|
|
232
|
+
const line = JSON.stringify(attemptRow(a, disposals)) + "\n";
|
|
205
233
|
attemptBytes += Buffer.byteLength(line);
|
|
206
234
|
if (attemptBytes > maxFileBytes) throw new Error(`study export: attempts.jsonl would exceed ${maxFileBytes} bytes; nothing was written`);
|
|
207
235
|
attemptLines.push(line);
|
|
@@ -223,14 +251,14 @@ function readBundle(dirArg: string, maxFileBytes: number) {
|
|
|
223
251
|
ablate: experiment && existsSync(ablateResultPath(dir)) ? closedResult("ablate", () => readClosedAblate(dir)) : null,
|
|
224
252
|
final: experiment && existsSync(finalResultPath(dir)) ? closedResult("final", () => readClosedFinal(dir)) : null,
|
|
225
253
|
}, null, 2) + "\n",
|
|
226
|
-
"reviews.jsonl": lines(reviewRows),
|
|
254
|
+
"reviews.jsonl": lines(reviewRows.map(({ sections: _s, openSections: _o, ...row }) => row)),
|
|
227
255
|
"evidence.json": JSON.stringify(evidence(dir), null, 2) + "\n",
|
|
228
256
|
};
|
|
229
257
|
const manifest: BundleManifest = {
|
|
230
258
|
bundle: 1, formats: { ...FORMAT_VERSIONS }, studyIdSha256: sha256(study.id), mode: study.mode,
|
|
231
259
|
protocolHash: protocol ? protocolHash(protocol) : null, sealBinding: study.mode === "experiment" ? designBinding(dir) ?? null : null,
|
|
232
260
|
window: (() => { const ats = events.map(e => isoAt(e.at)).filter((v): v is string => v !== null); return { from: ats[0] ?? null, to: ats.at(-1) ?? null }; })(),
|
|
233
|
-
counts: { attempts: attemptLines.length, byStatus, byRun, ledgerEvents: events.length, reviews: reviewRows.length },
|
|
261
|
+
counts: { attempts: attemptLines.length, byStatus, byRun, ledgerEvents: events.length, reviews: reviewRows.length, reviewSections: reviewSections(reviewRows, events), litQueries: intentSummary(events, loadCandidates(dir)) },
|
|
234
262
|
files: Object.fromEntries(Object.entries(files).map(([name, text]) => [name, sha256(text)])),
|
|
235
263
|
};
|
|
236
264
|
files["manifest.json"] = JSON.stringify(manifest, null, 2) + "\n";
|
package/src/study.ts
CHANGED
|
@@ -2,13 +2,22 @@ import { validateAutonomy, validateAutonomyMode, resolveAutonomy, ACCEPT_ARTIFAC
|
|
|
2
2
|
export type { Autonomy } from "./autonomy.ts";
|
|
3
3
|
import { hostname } from "node:os";
|
|
4
4
|
import { spawnSync } from "node:child_process";
|
|
5
|
-
import { closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readSync, renameSync, statSync, unlinkSync, writeSync, appendFileSync, lstatSync } from "node:fs";
|
|
5
|
+
import { closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readSync, renameSync, statSync, unlinkSync, writeSync, appendFileSync, lstatSync, realpathSync } from "node:fs";
|
|
6
6
|
import { createHash, randomUUID } from "node:crypto";
|
|
7
7
|
import { dirname, join, resolve } from "node:path";
|
|
8
8
|
|
|
9
9
|
export type Mode = "survey" | "experiment";
|
|
10
|
-
export type GateName = "scope" | "screen" | "design" | "final" | "review" | `plan:${string}` | `accept:${AcceptArtifact}`;
|
|
10
|
+
export type GateName = "scope" | "screen" | "design" | "final" | "review" | `plan:${string}` | `accept:${AcceptArtifact}` | `harness:${string}`;
|
|
11
11
|
export const GATES: readonly GateName[] = ["scope", "screen", "design", "final", "review"];
|
|
12
|
+
export const HARNESS_GATE_ID_BYTES = 64;
|
|
13
|
+
export function isHarnessGate(value: unknown): value is `harness:${string}` {
|
|
14
|
+
if (typeof value !== "string" || !value.startsWith("harness:")) return false;
|
|
15
|
+
const id = value.slice("harness:".length);
|
|
16
|
+
return id.length >= 1 && id.length <= HARNESS_GATE_ID_BYTES && /^[A-Za-z0-9]/.test(id) && !/[^A-Za-z0-9_-]/.test(id);
|
|
17
|
+
}
|
|
18
|
+
function invalidHarnessGate(): never {
|
|
19
|
+
throw new Error("harness gate: invalid round id; use harness:<round-id> with 1..64 ASCII letters, digits, underscores or hyphens starting with a letter or digit, then retry");
|
|
20
|
+
}
|
|
12
21
|
export interface Study { v: 1 | 2; id: string; question: string; mode: Mode; autonomy: Autonomy; createdAt: string }
|
|
13
22
|
export interface Actor { kind: "person" | "agent" | "auto"; id?: string }
|
|
14
23
|
export function requireExperiment(study: Study): void {
|
|
@@ -49,25 +58,35 @@ export function writeAtomic(path: string, text: string, maxBytes: number, mode =
|
|
|
49
58
|
|
|
50
59
|
/** Read a regular file, stopping one byte past `maxBytes`: special files and oversize files are refused without buffering them. */
|
|
51
60
|
export interface ReadOptions { noFollow?: boolean; uid?: number }
|
|
52
|
-
|
|
61
|
+
function readChunksBounded(path: string, maxBytes: number, options: ReadOptions, consume: (chunk: Buffer) => void): number {
|
|
53
62
|
// Non-blocking open: a FIFO without a writer would otherwise block before the type check.
|
|
54
63
|
const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | (options.noFollow ? constants.O_NOFOLLOW : 0));
|
|
55
64
|
try {
|
|
56
65
|
const info = fstatSync(fd);
|
|
57
66
|
if (!info.isFile()) throw new Error(`${path}: not a regular file`);
|
|
58
67
|
if (options.uid !== undefined && info.uid !== options.uid) throw new Error(`${path}: owned by another user`);
|
|
59
|
-
const buffer = Buffer.alloc(Math.min(maxBytes + 1, 1 << 20))
|
|
68
|
+
const buffer = Buffer.alloc(Math.min(maxBytes + 1, 1 << 20));
|
|
60
69
|
let total = 0;
|
|
61
70
|
for (;;) {
|
|
62
71
|
const n = readSync(fd, buffer, 0, buffer.length, null);
|
|
63
72
|
if (n === 0) break;
|
|
64
73
|
total += n;
|
|
65
74
|
if (total > maxBytes) throw new Error(`${path}: larger than ${maxBytes} bytes`);
|
|
66
|
-
|
|
75
|
+
consume(buffer.subarray(0, n));
|
|
67
76
|
}
|
|
68
|
-
return
|
|
77
|
+
return total;
|
|
69
78
|
} finally { closeSync(fd); }
|
|
70
79
|
}
|
|
80
|
+
export function readBytesBounded(path: string, maxBytes: number, options: ReadOptions = {}): Buffer {
|
|
81
|
+
const parts: Buffer[] = [];
|
|
82
|
+
readChunksBounded(path, maxBytes, options, chunk => parts.push(Buffer.from(chunk)));
|
|
83
|
+
return Buffer.concat(parts);
|
|
84
|
+
}
|
|
85
|
+
/** Hash a regular file through the bounded reader without retaining its contents. */
|
|
86
|
+
export function hashFileBounded(path: string, maxBytes: number, options: ReadOptions = {}): {sha256: string; bytes: number} {
|
|
87
|
+
const hash = createHash("sha256"), bytes = readChunksBounded(path, maxBytes, options, chunk => { hash.update(chunk); });
|
|
88
|
+
return { sha256: hash.digest("hex"), bytes };
|
|
89
|
+
}
|
|
71
90
|
export function readTextBounded(path: string, maxBytes: number, options: ReadOptions = {}): string {
|
|
72
91
|
try { return new TextDecoder("utf-8", { fatal: true }).decode(readBytesBounded(path, maxBytes, options)); }
|
|
73
92
|
catch (error) { if (error instanceof TypeError) throw new Error(`${path}: not valid UTF-8`); throw error; }
|
|
@@ -102,10 +121,10 @@ export function studyFile(dir: string, ...parts: string[]): string { return join
|
|
|
102
121
|
export function openStudy(dir: string): { dir: string; study: Study } {
|
|
103
122
|
const root = resolve(dir), file = join(root, "study.json");
|
|
104
123
|
if (!existsSync(file)) throw new Error(`${root}: no study.json (run ares init first)`);
|
|
105
|
-
return { dir: root, study:
|
|
124
|
+
return { dir: root, study: validateStudy(readJsonFile(file, STUDY_BYTES)) };
|
|
106
125
|
}
|
|
107
126
|
|
|
108
|
-
function
|
|
127
|
+
export function validateStudy(raw: unknown): Study {
|
|
109
128
|
if (plain(raw) && raw.v !== 1 && raw.v !== 2) throw new Error("study.json: unsupported schema version; use an ares version that supports this study, keeping the original file unchanged");
|
|
110
129
|
if (!plain(raw) || (raw.v !== 1 && raw.v !== 2) || typeof raw.id !== "string" || typeof raw.question !== "string" || typeof raw.createdAt !== "string" ||
|
|
111
130
|
!["survey", "experiment"].includes(raw.mode as string)) throw new Error("study.json: malformed");
|
|
@@ -145,7 +164,17 @@ const ownedStudyLocks = new Set<() => void>();
|
|
|
145
164
|
/** MCP termination only: call immediately before process exit, never while continuing async work. */
|
|
146
165
|
export function releaseStudyLocksForExit(): void { for (const release of [...ownedStudyLocks]) release(); }
|
|
147
166
|
export class StudyLockBusyError extends Error {}
|
|
148
|
-
export
|
|
167
|
+
export interface StudyReadLock {readonly scope: "owned-study-read"}
|
|
168
|
+
const studyReadLocks = new WeakMap<StudyReadLock, {root: string; file: string; dev: number | bigint; ino: number | bigint}>();
|
|
169
|
+
/** Internal capability, never a caller-supplied lock bypass. Revoked on release and inode-checked on every capture. */
|
|
170
|
+
export function assertStudyReadLock(dir: string, permit: StudyReadLock): void {
|
|
171
|
+
const owner = studyReadLocks.get(permit);
|
|
172
|
+
try {
|
|
173
|
+
if (!owner || realpathSync(owner.root) !== realpathSync(dir)) throw new Error();
|
|
174
|
+
const current = lstatSync(owner.file); if (current.dev !== owner.dev || current.ino !== owner.ino) throw new Error();
|
|
175
|
+
} catch {throw new StudyLockBusyError("study read permit is missing, changed or not owned; restore exclusive access and retry inside the current ares study transaction");}
|
|
176
|
+
}
|
|
177
|
+
export async function withLock<T>(dir: string, fn: (permit: StudyReadLock) => Promise<T> | T, inspectOwner: (fd: number) => ReturnType<typeof fstatSync> = fstatSync): Promise<T> {
|
|
149
178
|
const path = join(dir, ".ares.lock");
|
|
150
179
|
let fd: number;
|
|
151
180
|
try { fd = openSync(path, "wx", 0o600); }
|
|
@@ -164,18 +193,20 @@ export async function withLock<T>(dir: string, fn: () => Promise<T> | T, inspect
|
|
|
164
193
|
finally { try { closeSync(fd); } catch { /* preserve the original probe failure */ } }
|
|
165
194
|
throw error;
|
|
166
195
|
}
|
|
196
|
+
const permit: StudyReadLock = Object.freeze({scope: "owned-study-read"});
|
|
197
|
+
studyReadLocks.set(permit, {root: resolve(dir), file: path, dev: owner.dev, ino: owner.ino});
|
|
167
198
|
let released = false;
|
|
168
199
|
const release = () => {
|
|
169
200
|
if (released) return; released = true;
|
|
170
201
|
try { const current = lstatSync(path); if (current.dev === owner.dev && current.ino === owner.ino) unlinkSync(path); }
|
|
171
202
|
catch { /* absent or replaced; never remove a different owner's lock */ }
|
|
172
|
-
finally { try { closeSync(fd); } catch { /* process exit also closes owned descriptors */ } ownedStudyLocks.delete(release); }
|
|
203
|
+
finally { try { closeSync(fd); } catch { /* process exit also closes owned descriptors */ } ownedStudyLocks.delete(release); studyReadLocks.delete(permit); }
|
|
173
204
|
};
|
|
174
205
|
ownedStudyLocks.add(release);
|
|
175
206
|
try { writeSync(fd, `${process.pid} ${new Date().toISOString()}\n`); }
|
|
176
207
|
catch (error) { release(); throw error; }
|
|
177
208
|
// Keep the descriptor open until release so an unlinked inode cannot be reused by a replacement lock.
|
|
178
|
-
try { return await fn(); } finally { release(); }
|
|
209
|
+
try { return await fn(permit); } finally { release(); }
|
|
179
210
|
}
|
|
180
211
|
|
|
181
212
|
export interface PendingEvent { actor: Actor; type: string; data: Record<string, unknown> }
|
|
@@ -212,7 +243,12 @@ export function appendEvent(dir: string, actor: Actor, type: string, data: Recor
|
|
|
212
243
|
export function readLedger(dir: string): LedgerEvent[] {
|
|
213
244
|
const path = join(dir, "ledger.jsonl");
|
|
214
245
|
if (!existsSync(path)) return [];
|
|
215
|
-
|
|
246
|
+
return parseLedger(readTextBounded(path, LEDGER_BYTES));
|
|
247
|
+
}
|
|
248
|
+
/** Shared v1 replay validation for bounded, already captured ledger bytes. */
|
|
249
|
+
export function parseLedger(text: string): LedgerEvent[] {
|
|
250
|
+
if (Buffer.byteLength(text) > LEDGER_BYTES) throw new Error("ledger.jsonl exceeds its reader bound; restore a bounded ledger before reading");
|
|
251
|
+
const lines = text.split("\n");
|
|
216
252
|
const events: LedgerEvent[] = [];
|
|
217
253
|
lines.forEach((line, index) => {
|
|
218
254
|
if (!line.trim()) return;
|
|
@@ -243,9 +279,11 @@ export function gateState(gate: GateName, events: LedgerEvent[], binder: Binder)
|
|
|
243
279
|
}
|
|
244
280
|
|
|
245
281
|
export function decideGate(dir: string, gate: GateName, decision: "approve" | "reject", actor: Actor, binder: Binder, reason?: string): GateState {
|
|
246
|
-
if (
|
|
282
|
+
if (gate.startsWith("harness:")) {if (!isHarnessGate(gate)) invalidHarnessGate(); requireExperiment(openStudy(dir).study);}
|
|
283
|
+
if (!GATES.includes(gate) && !ACCEPT_ARTIFACTS.some(artifact => gate === `accept:${artifact}`) && !gate.startsWith("plan:") && !isHarnessGate(gate)) throw new Error(`unknown gate: ${gate}; run ares gate list to select a gate`);
|
|
247
284
|
const before = gateState(gate, readLedger(dir), binder);
|
|
248
285
|
if (before.state === "none" && gate.startsWith("accept:")) throw new Error(`gate ${gate}: no current copilot draft; inspect ares autonomy show, create the phase artifact, then use ares gate list and ares gate approve <dir> ${gate}`);
|
|
286
|
+
if (before.state === "none" && isHarnessGate(gate)) throw new Error(`gate ${gate}: nothing to decide yet; run ares harness show / ares harness set to create the round, then run ares gate list`);
|
|
249
287
|
if (before.state === "none") throw new Error(`gate ${gate}: nothing to decide yet${gate.startsWith("plan:") ? "; finish every upstream node with output references, then run ares gate list" : ""}`);
|
|
250
288
|
if (decision === "reject" && !reason) throw new Error(`gate ${gate}: a rejection needs --reason`);
|
|
251
289
|
appendEvent(dir, actor, decision === "approve" ? "gate.approve" : "gate.reject", { gate, binding: before.current!, ...(reason ? { reason } : {}) });
|
|
@@ -258,13 +296,15 @@ export function decideGate(dir: string, gate: GateName, decision: "approve" | "r
|
|
|
258
296
|
* changes a gate.
|
|
259
297
|
*/
|
|
260
298
|
export function requireGate(dir: string, study: Study, gate: GateName, binder: Binder, guardedPhase?: Phase): PendingEvent[] {
|
|
261
|
-
if (gate
|
|
299
|
+
if (gate.startsWith("harness:") && !isHarnessGate(gate)) invalidHarnessGate();
|
|
300
|
+
if (gate === "design" || gate === "final" || isHarnessGate(gate)) requireExperiment(study);
|
|
262
301
|
const state = gateState(gate, readLedger(dir), binder);
|
|
263
302
|
if (state.state === "approved") return [];
|
|
264
303
|
if (state.state === "pending" && !gate.startsWith("accept:") && resolveAutonomy(study.autonomy, gate, guardedPhase) === "auto") return [{ actor: { kind: "auto" }, type: "gate.approve", data: { gate, binding: state.current! } }];
|
|
265
304
|
if (state.state === "none" && gate.startsWith("accept:")) throw new Error(`gate ${gate}: no current copilot draft; create the phase artifact, then run ares gate list and ares gate approve <dir> ${gate}`);
|
|
266
305
|
if (state.state === "none" && gate === "final") throw new Error("gate final: complete reserved seeds and close investigate/required ablate inputs before final approval");
|
|
267
306
|
if (state.state === "none" && gate.startsWith("plan:")) throw new Error(`gate ${gate}: upstream outputs are not complete; finish every upstream node and run ares gate list again`);
|
|
307
|
+
if (state.state === "none" && isHarnessGate(gate)) throw new Error(`gate ${gate}: no current round binding; run ares harness show / ares harness set to complete the round inputs, then run ares gate list before retrying`);
|
|
268
308
|
if (state.state === "none") throw new Error(gate === "scope" ? "gate scope: no scope yet (run ares scope)" : gate === "design" ? "gate design: no protocol yet (run ares protocol)" : "gate screen: no included candidates yet");
|
|
269
309
|
if (state.state === "rejected") throw new Error(`gate ${gate} is rejected${state.decided?.reason ? `: ${state.decided.reason}` : ""}; change the content and ask again`);
|
|
270
310
|
throw new Error(`gate ${gate} is pending: run ares gate approve <dir> ${gate}`);
|
package/src/ui/panel.css
CHANGED
|
@@ -9,3 +9,7 @@
|
|
|
9
9
|
.ares-list { margin: 0; padding-left: 1.5em; overflow-wrap: anywhere; }
|
|
10
10
|
.ares-list li + li { margin-top: var(--acon-space-1); }
|
|
11
11
|
@media (max-width: 600px) { .ares-bar { align-items: flex-start; } .ares-bar h2 { flex-basis: 100%; } }
|
|
12
|
+
|
|
13
|
+
.ares-identifiers { min-width: 0; overflow-wrap: anywhere; word-break: break-word; font-variant-numeric: tabular-nums; }
|
|
14
|
+
.ares-identifiers td, .ares-identifiers th { max-width: 28rem; white-space: normal; overflow-wrap: anywhere; }
|
|
15
|
+
.ares-identifiers table { font-size: var(--acon-text-sm); font-variant-numeric: tabular-nums; }
|