@staix/agent-research 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +137 -0
- package/README.md +356 -31
- package/package.json +4 -2
- package/src/autonomy.ts +50 -0
- package/src/cli.ts +134 -14
- package/src/commands-table.ts +43 -9
- package/src/commands.ts +244 -43
- package/src/copilot.ts +91 -0
- package/src/exp/attempts.ts +512 -69
- package/src/exp/executor.ts +235 -12
- package/src/exp/final.ts +1 -1
- package/src/exp/investigate.ts +7 -2
- 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 +88 -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/http.ts +46 -2
- 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/lit/watch.ts +14 -1
- package/src/manifest.ts +15 -7
- package/src/mcp-tools.ts +140 -32
- package/src/mcp.ts +6 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +20 -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 +20 -8
- package/src/paper/check.ts +40 -12
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +21 -4
- 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 +116 -11
- package/src/paper/scopes.ts +51 -0
- package/src/plan/controller.ts +42 -12
- package/src/plan/definition.ts +22 -6
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +58 -17
- package/src/playbook.ts +47 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +282 -0
- package/src/study.ts +94 -26
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +271 -9
- package/src/ui/plugin.ts +89 -17
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
|
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { attemptReuseView, retentionDisposalIndex, type RetentionDisposalIndex } from "./provenance.ts";
|
|
2
|
+
import {urlOrKeyLike} from "./privacy.ts";
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, join, relative, resolve, isAbsolute, sep } from "node:path";
|
|
5
|
+
import { readAttemptRecords, type Attempt, type AttemptStatus } from "./exp/attempts.ts";
|
|
6
|
+
import { ablateResultPath, readClosedAblate } from "./exp/ablate.ts";
|
|
7
|
+
import { finalResultPath, readClosedFinal } from "./exp/final.ts";
|
|
8
|
+
import { readClosedInvestigation } from "./exp/investigate.ts";
|
|
9
|
+
import { readSelection } from "./exp/selection.ts";
|
|
10
|
+
import { designBinding, protocolHash, readProtocol } from "./exp/protocol.ts";
|
|
11
|
+
import { FORMAT_VERSIONS } from "./manifest.ts";
|
|
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";
|
|
15
|
+
import { assertWritable, openStudy, plain, readLedger, readTextBounded, sha256, withLock, writeAtomic, type LedgerEvent } from "./study.ts";
|
|
16
|
+
|
|
17
|
+
/** Reader bound for every bundle file; writeAtomic refuses anything larger. */
|
|
18
|
+
export const BUNDLE_FILE_BYTES = 64 * 1024 * 1024;
|
|
19
|
+
export const BUNDLE_FILES = ["manifest.json", "ledger.jsonl", "attempts.jsonl", "results.json", "reviews.jsonl", "evidence.json"] as const;
|
|
20
|
+
const STATUSES: AttemptStatus[] = ["running", "succeeded", "failed", "cancelled", "unknown"];
|
|
21
|
+
const SHA256 = /^[a-f0-9]{64}$/;
|
|
22
|
+
const HEX = /^[a-f0-9]{16,64}$/;
|
|
23
|
+
const TOKEN = /^[a-z][a-z0-9_.:-]{0,47}$/;
|
|
24
|
+
const GIT_ID = /^[a-f0-9]{40}$/, ATTEMPT_ID = /^[a-f0-9]{16}$/;
|
|
25
|
+
const ACTOR_KINDS = new Set(["person", "agent", "auto"]), EVIDENCE_FAMILIES = new Set(["attempt", "posthoc", "investigate", "ablate", "final"]);
|
|
26
|
+
/** Exact-shape field or null: hand-edited free text in an identity field is never copied. */
|
|
27
|
+
const shaped = (value: unknown, pattern: RegExp): string | null => typeof value === "string" && pattern.test(value) ? value : null;
|
|
28
|
+
const finite = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
29
|
+
const METRIC_KEYS = new Set(["name", "unit", "metric"]);
|
|
30
|
+
/** Closed data keys per ledger event type; unlisted types keep the envelope with empty data. Never host, containerId or hubProject. */
|
|
31
|
+
const LEDGER_KEYS: Record<string, readonly string[]> = {
|
|
32
|
+
"scope.set": ["sha256"], "autonomy.set": ["from", "to", "phase"], "gate.approve": ["gate", "binding"], "gate.reject": ["gate", "binding"],
|
|
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"],
|
|
34
|
+
"archive.exported": ["fingerprint"], "skill.proposed": ["skillProposal", "sha256"], "skill.decided": ["skillProposal", "decision"], "watch.set": ["sha256"],
|
|
35
|
+
"plan.set": ["revision", "state", "sha256"], "plan.gates": ["revision"], "plan.paused": ["revision"], "plan.control": ["revision"], "node.observed": ["revision", "status"], "node.intent": ["revision"],
|
|
36
|
+
"executor.set": ["kind"], "protocol.set": ["sha256", "identitySha256", "protocolHash", "treeHash"], "selection.set": ["sha256", "metric"], "final.seeds.set": ["sha256"],
|
|
37
|
+
"investigate.closed": ["run", "sha256", "ruleSha256", "winner"], "ablate.closed": ["sha256", "investigateSha256"], "final.closed": ["sha256", "status", "investigateSha256"],
|
|
38
|
+
"idea.decided": ["decision"], "paper.built": ["manuscriptSha256", "evidenceSha256", "sourceManuscriptSha256"], "review.added": [], "review.resolved": ["buildSha256"],
|
|
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"],
|
|
42
|
+
};
|
|
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"];
|
|
44
|
+
|
|
45
|
+
export interface BundleManifest {
|
|
46
|
+
bundle: 1; formats: typeof FORMAT_VERSIONS; studyIdSha256: string; mode: string; protocolHash: string | null; sealBinding: string | null;
|
|
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 }> };
|
|
48
|
+
files: Record<string, string>;
|
|
49
|
+
}
|
|
50
|
+
export interface BundleListing { bundle: string; files: string[]; wouldWrite: true }
|
|
51
|
+
|
|
52
|
+
/** A closed scalar: numbers, booleans, hashes and enum-like tokens survive; free text, paths and URLs do not. */
|
|
53
|
+
function closed(value: unknown): value is number | boolean | string | null {
|
|
54
|
+
if (value === null || typeof value === "boolean") return true;
|
|
55
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
56
|
+
return typeof value === "string" && (HEX.test(value) || TOKEN.test(value));
|
|
57
|
+
}
|
|
58
|
+
function reduceData(data: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {
|
|
59
|
+
const out: Record<string, unknown> = {};
|
|
60
|
+
for (const key of keys) { const value = Object.hasOwn(data, key) ? data[key] : undefined; if (closed(value) || (METRIC_KEYS.has(key) && typeof value === "string")) out[key] = value; else if (Array.isArray(value) && value.every(closed)) out[key] = value; }
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
/** Result keys that hold free text even when a value happens to be one token. */
|
|
64
|
+
const FREE_TEXT_KEYS = new Set(["removes", "description", "note", "notes", "label", "text", "message", "cause", "retryWhen", "method", "question"]);
|
|
65
|
+
/** Keep numbers, booleans, null, hashes and closed tokens recursively; drop free-text keys and every other string. */
|
|
66
|
+
function project(value: unknown): unknown {
|
|
67
|
+
if (Array.isArray(value)) return value.map(project).filter(v => v !== undefined);
|
|
68
|
+
if (plain(value)) { const out: Record<string, unknown> = {}; for (const [k, v] of Object.entries(value)) { if (FREE_TEXT_KEYS.has(k)) continue; const p = METRIC_KEYS.has(k) && typeof v === "string" ? v : project(v); if (p !== undefined) out[k] = p; } return out; }
|
|
69
|
+
return closed(value) ? value : undefined;
|
|
70
|
+
}
|
|
71
|
+
/** A parseable ISO timestamp or null. */
|
|
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;
|
|
73
|
+
function reduceEvent(event: LedgerEvent) {
|
|
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) } : {}) };
|
|
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 };
|
|
78
|
+
}
|
|
79
|
+
// Closed codes emitted by attempts.ts, metrics.ts and artifacts.ts; never derive a class from user prose.
|
|
80
|
+
const ATTEMPT_REASON_CODES = new Set([
|
|
81
|
+
"executor-start", "executor-start-uncertain", "preparation", "lost", "wall-clock", "candidate-exit", "evaluator-exit",
|
|
82
|
+
"evidence-read", "invalid-metrics", "malformed-metrics", "undeclared-metric", "missing-metric", "invalid-metric-value",
|
|
83
|
+
"nonfinite-metric", "metrics-limit", "duplicate-metric", "missing-metrics", "missing-receipt", "changed-output",
|
|
84
|
+
"artifact-limit", "artifact-read", "invalid-artifact", "invalid-log-state", "missing-logs",
|
|
85
|
+
]);
|
|
86
|
+
function reasonClass(reason: string | undefined, status: AttemptStatus): string | undefined {
|
|
87
|
+
if (reason === undefined) return undefined;
|
|
88
|
+
if (status === "cancelled") return "cancel-reason";
|
|
89
|
+
return ATTEMPT_REASON_CODES.has(reason) ? reason : "other";
|
|
90
|
+
}
|
|
91
|
+
function duration(start: unknown, end: unknown): number | null {
|
|
92
|
+
if (typeof start !== "string" || typeof end !== "string") return null;
|
|
93
|
+
const ms = Date.parse(end) - Date.parse(start);
|
|
94
|
+
return Number.isFinite(ms) ? ms : null;
|
|
95
|
+
}
|
|
96
|
+
function digest(image: unknown): string | null {
|
|
97
|
+
const match = typeof image === "string" ? /@(sha256:[a-f0-9]{64})$/.exec(image) : null;
|
|
98
|
+
return match?.[1] ?? null;
|
|
99
|
+
}
|
|
100
|
+
function attemptRow(a: Attempt, disposals: RetentionDisposalIndex) {
|
|
101
|
+
const stages: Record<string, unknown> = {};
|
|
102
|
+
for (const name of ["candidate", "evaluator"] as const) {
|
|
103
|
+
const stage = plain(a.stages) && Object.hasOwn(a.stages, name) ? a.stages[name] : undefined;
|
|
104
|
+
if (!plain(stage)) continue;
|
|
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) };
|
|
106
|
+
}
|
|
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);
|
|
114
|
+
return {
|
|
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),
|
|
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 } : {}),
|
|
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}),
|
|
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" })),
|
|
121
|
+
outputs: (Array.isArray(a.outputs) ? a.outputs : []).map(o => ({ sha256: shaped(o.sha256, SHA256), bytes: finite(o.bytes) })),
|
|
122
|
+
sealing: plain(a.sealing) ? { separateContainers: a.sealing.separateContainers === true, evaluatorReadOnly: a.sealing.evaluatorReadOnly === true, candidateHasNoEvaluator: a.sealing.candidateHasNoEvaluator === true } : null,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function closedResult<T>(name: string, read: () => { result: T }): unknown {
|
|
126
|
+
try { return project(read().result); }
|
|
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`); }
|
|
128
|
+
}
|
|
129
|
+
function reviews(events: LedgerEvent[]) {
|
|
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}`); }
|
|
132
|
+
return events.filter(e => e.type === "review.added" && plain(e.data.review)).map(e => {
|
|
133
|
+
const review = e.data.review as Record<string, unknown>, findings = Array.isArray(review.findings) ? review.findings as Record<string, unknown>[] : [];
|
|
134
|
+
const reviewer = plain(review.reviewer) ? review.reviewer : {}, kinds: Record<string, number> = {}, repairs: Record<string, number> = {};
|
|
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; }
|
|
137
|
+
const id = typeof e.data.id === "string" ? e.data.id : "";
|
|
138
|
+
const family = typeof reviewer.modelFamily === "string" ? reviewer.modelFamily.trim().toLowerCase() : "";
|
|
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 };
|
|
143
|
+
});
|
|
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
|
+
}
|
|
156
|
+
function evidence(dir: string) {
|
|
157
|
+
const path = paperBuildPaths(dir).evidence;
|
|
158
|
+
if (!existsSync(path)) return null;
|
|
159
|
+
let raw: unknown;
|
|
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"); }
|
|
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");
|
|
163
|
+
return {
|
|
164
|
+
v: 1, manuscriptSha256: typeof raw.manuscriptSha256 === "string" && SHA256.test(raw.manuscriptSha256) ? raw.manuscriptSha256 : null,
|
|
165
|
+
...(raw.v === 2 ? {planSha256: raw.planSha256} : {}),
|
|
166
|
+
placeholders: (raw.placeholders as Record<string, unknown>[]).filter(p => p.kind === "number").map(p => {
|
|
167
|
+
const ref = typeof p.ref === "string" ? p.ref : "", attempt = /^(?:attempt|posthoc):([a-f0-9]{16})\./.exec(ref)?.[1];
|
|
168
|
+
const source = plain(p.source) ? p.source : {};
|
|
169
|
+
return { refSha256: sha256(ref), family: ((f: string | undefined) => f && EVIDENCE_FAMILIES.has(f) ? f : "other")(/^[a-z]+/.exec(ref)?.[0]), ...(attempt ? { attempt } : {}), sourceSha256: typeof source.sha256 === "string" && SHA256.test(source.sha256) ? source.sha256 : null };
|
|
170
|
+
}),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Path rules run on decoded keys and string values, so a boundary is a real character (a raw newline or tab included). */
|
|
175
|
+
const PATH_SCANS: RegExp[] = [
|
|
176
|
+
// POSIX: `/` or `~/` not preceded by a letter, digit or underscore; units such as tokens/s keep a word character there.
|
|
177
|
+
/(?<![\p{L}\p{N}_])(?:\/|~\/)/u,
|
|
178
|
+
/\b[A-Za-z]:\\/,
|
|
179
|
+
// Windows root-relative (\Users\x), bare \ and UNC (\\server): any backslash not preceded by a word character or backslash.
|
|
180
|
+
/(?<![\p{L}\p{N}_\\])\\/u,
|
|
181
|
+
];
|
|
182
|
+
const ENV_VALUE = /(?<![A-Za-z0-9_])[A-Za-z_][A-Za-z0-9_]*=[^\s"]/;
|
|
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. */
|
|
184
|
+
function* decodedStrings(text: string): Generator<string> {
|
|
185
|
+
const walk = function* (value: unknown): Generator<string> {
|
|
186
|
+
if (typeof value === "string") yield value;
|
|
187
|
+
else if (Array.isArray(value)) for (const item of value) yield* walk(item);
|
|
188
|
+
else if (value && typeof value === "object") for (const [key, item] of Object.entries(value)) { yield key; yield* walk(item); }
|
|
189
|
+
};
|
|
190
|
+
let whole: unknown, parsed = false;
|
|
191
|
+
try { whole = JSON.parse(text); parsed = true; } catch { /* JSONL or plain text */ }
|
|
192
|
+
if (parsed) { yield* walk(whole); return; }
|
|
193
|
+
for (const line of text.split("\n")) {
|
|
194
|
+
if (!line) continue;
|
|
195
|
+
try { yield* walk(JSON.parse(line)); } catch { yield line; }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Refuse the whole bundle if any file carries a path, URL, env assignment or key-like token. */
|
|
199
|
+
export function scanBundle(files: Record<string, string>): void {
|
|
200
|
+
const refuse = (name: string, kind: string): never => { throw new Error(`study export: refused; ${name} would contain a ${kind}. Remove it from the study record (for example an attempt label or ledger field) and retry; nothing was written`); };
|
|
201
|
+
for (const [name, text] of Object.entries(files)) {
|
|
202
|
+
for (const value of decodedStrings(text)) {
|
|
203
|
+
if (PATH_SCANS.some(pattern => pattern.test(value))) refuse(name, "absolute path");
|
|
204
|
+
const marker = urlOrKeyLike(value);
|
|
205
|
+
if (marker) refuse(name, marker);
|
|
206
|
+
if (ENV_VALUE.test(value)) refuse(name, "env value");
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function emptyDir(path: string): void {
|
|
212
|
+
if (existsSync(path)) { if (!lstatSync(path).isDirectory()) throw new Error("study export: --bundle exists and is not a directory; choose a new or empty directory"); if (readdirSync(path).length) throw new Error("study export: --bundle directory is not empty; choose a new or empty directory"); }
|
|
213
|
+
else mkdirSync(path, { recursive: true });
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Real path of the nearest existing ancestor with the missing tail re-appended, so symlinks cannot hide containment. */
|
|
217
|
+
function realTarget(path: string): string {
|
|
218
|
+
const tail: string[] = [];
|
|
219
|
+
let current = path;
|
|
220
|
+
while (!existsSync(current)) { const parent = dirname(current); if (parent === current) break; tail.unshift(basename(current)); current = parent; }
|
|
221
|
+
return join(realpathSync(current), ...tail);
|
|
222
|
+
}
|
|
223
|
+
/** Caller holds the study lock across every bounded source read. */
|
|
224
|
+
function readBundle(dirArg: string, maxFileBytes: number) {
|
|
225
|
+
const { dir, study } = openStudy(dirArg);
|
|
226
|
+
const events = readLedger(dir), disposals = retentionDisposalIndex(events);
|
|
227
|
+
const zero = () => Object.fromEntries(STATUSES.map(s => [s, 0])) as Record<AttemptStatus, number>;
|
|
228
|
+
const byStatus = zero(), runCounts = new Map<string, Record<AttemptStatus, number>>(), attemptLines: string[] = [];
|
|
229
|
+
let attemptBytes = 0;
|
|
230
|
+
// One pass; only the projected row and counts outlive each raw record.
|
|
231
|
+
for (const a of study.mode === "experiment" ? readAttemptRecords(dir) : []) {
|
|
232
|
+
const line = JSON.stringify(attemptRow(a, disposals)) + "\n";
|
|
233
|
+
attemptBytes += Buffer.byteLength(line);
|
|
234
|
+
if (attemptBytes > maxFileBytes) throw new Error(`study export: attempts.jsonl would exceed ${maxFileBytes} bytes; nothing was written`);
|
|
235
|
+
attemptLines.push(line);
|
|
236
|
+
byStatus[a.status]++;
|
|
237
|
+
let row = runCounts.get(a.run); if (!row) runCounts.set(a.run, row = zero()); row[a.status]++;
|
|
238
|
+
}
|
|
239
|
+
const byRun: Record<string, Record<AttemptStatus, number>> = Object.create(null);
|
|
240
|
+
for (const [run, row] of [...runCounts].sort(([x], [y]) => x < y ? -1 : 1)) byRun[run] = row;
|
|
241
|
+
const experiment = study.mode === "experiment", current = experiment ? readProtocol(dir) : undefined, rule = current ? readSelection(dir, current) : undefined;
|
|
242
|
+
const investigate: Record<string, unknown> = {};
|
|
243
|
+
if (rule && existsSync(join(dir, "runs", rule.run, "investigate.json"))) investigate[rule.run] = closedResult("investigate", () => readClosedInvestigation(dir));
|
|
244
|
+
const reviewRows = reviews(events), protocol = study.mode === "experiment" ? readProtocol(dir) : undefined;
|
|
245
|
+
const lines = (rows: unknown[]) => rows.map(r => JSON.stringify(r)).join("\n") + (rows.length ? "\n" : "");
|
|
246
|
+
const files: Record<string, string> = {
|
|
247
|
+
"ledger.jsonl": lines(events.map(reduceEvent)),
|
|
248
|
+
"attempts.jsonl": attemptLines.join(""),
|
|
249
|
+
"results.json": JSON.stringify({
|
|
250
|
+
investigate,
|
|
251
|
+
ablate: experiment && existsSync(ablateResultPath(dir)) ? closedResult("ablate", () => readClosedAblate(dir)) : null,
|
|
252
|
+
final: experiment && existsSync(finalResultPath(dir)) ? closedResult("final", () => readClosedFinal(dir)) : null,
|
|
253
|
+
}, null, 2) + "\n",
|
|
254
|
+
"reviews.jsonl": lines(reviewRows.map(({ sections: _s, openSections: _o, ...row }) => row)),
|
|
255
|
+
"evidence.json": JSON.stringify(evidence(dir), null, 2) + "\n",
|
|
256
|
+
};
|
|
257
|
+
const manifest: BundleManifest = {
|
|
258
|
+
bundle: 1, formats: { ...FORMAT_VERSIONS }, studyIdSha256: sha256(study.id), mode: study.mode,
|
|
259
|
+
protocolHash: protocol ? protocolHash(protocol) : null, sealBinding: study.mode === "experiment" ? designBinding(dir) ?? null : null,
|
|
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 }; })(),
|
|
261
|
+
counts: { attempts: attemptLines.length, byStatus, byRun, ledgerEvents: events.length, reviews: reviewRows.length, reviewSections: reviewSections(reviewRows, events), litQueries: intentSummary(events, loadCandidates(dir)) },
|
|
262
|
+
files: Object.fromEntries(Object.entries(files).map(([name, text]) => [name, sha256(text)])),
|
|
263
|
+
};
|
|
264
|
+
files["manifest.json"] = JSON.stringify(manifest, null, 2) + "\n";
|
|
265
|
+
return { files, manifest };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Read one locked study snapshot, then validate and publish without holding the study lock. */
|
|
269
|
+
export async function exportBundle(dirArg: string, options: { bundle: string; list?: boolean }, maxFileBytes = BUNDLE_FILE_BYTES): Promise<BundleManifest | BundleListing> {
|
|
270
|
+
const dir = resolve(dirArg), target = resolve(options.bundle), inside = relative(realpathSync(dir), realTarget(target));
|
|
271
|
+
if (inside === "" || (!(inside === ".." || inside.startsWith(".." + sep)) && !isAbsolute(inside))) throw new Error("study export: --bundle is inside the study directory; choose a directory outside the study");
|
|
272
|
+
if (options.list) {
|
|
273
|
+
await withLock(dir, () => openStudy(dir));
|
|
274
|
+
return { bundle: options.bundle, files: [...BUNDLE_FILES], wouldWrite: true };
|
|
275
|
+
}
|
|
276
|
+
const { files, manifest } = await withLock(dir, () => readBundle(dir, maxFileBytes));
|
|
277
|
+
scanBundle(files);
|
|
278
|
+
for (const name of BUNDLE_FILES) assertWritable(files[name]!, maxFileBytes, `study export: ${name}; nothing was written`);
|
|
279
|
+
emptyDir(target);
|
|
280
|
+
for (const name of BUNDLE_FILES) writeAtomic(join(target, name), files[name]!, maxFileBytes);
|
|
281
|
+
return manifest;
|
|
282
|
+
}
|
package/src/study.ts
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
|
+
import { validateAutonomy, validateAutonomyMode, resolveAutonomy, ACCEPT_ARTIFACTS, type Autonomy, type Phase, type AcceptArtifact } from "./autonomy.ts";
|
|
2
|
+
export type { Autonomy } from "./autonomy.ts";
|
|
1
3
|
import { hostname } from "node:os";
|
|
2
4
|
import { spawnSync } from "node:child_process";
|
|
3
|
-
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";
|
|
4
6
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
7
|
import { dirname, join, resolve } from "node:path";
|
|
6
8
|
|
|
7
9
|
export type Mode = "survey" | "experiment";
|
|
8
|
-
export type
|
|
9
|
-
export type GateName = "scope" | "screen" | "design" | "final" | "review" | `plan:${string}`;
|
|
10
|
+
export type GateName = "scope" | "screen" | "design" | "final" | "review" | `plan:${string}` | `accept:${AcceptArtifact}` | `harness:${string}`;
|
|
10
11
|
export const GATES: readonly GateName[] = ["scope", "screen", "design", "final", "review"];
|
|
11
|
-
export
|
|
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
|
+
}
|
|
21
|
+
export interface Study { v: 1 | 2; id: string; question: string; mode: Mode; autonomy: Autonomy; createdAt: string }
|
|
12
22
|
export interface Actor { kind: "person" | "agent" | "auto"; id?: string }
|
|
13
23
|
export function requireExperiment(study: Study): void {
|
|
14
24
|
if (study.mode !== "experiment") throw new Error("experiment command: study mode must be experiment; create a study with ares init <dir> --question TEXT --mode experiment");
|
|
@@ -48,25 +58,35 @@ export function writeAtomic(path: string, text: string, maxBytes: number, mode =
|
|
|
48
58
|
|
|
49
59
|
/** Read a regular file, stopping one byte past `maxBytes`: special files and oversize files are refused without buffering them. */
|
|
50
60
|
export interface ReadOptions { noFollow?: boolean; uid?: number }
|
|
51
|
-
|
|
61
|
+
function readChunksBounded(path: string, maxBytes: number, options: ReadOptions, consume: (chunk: Buffer) => void): number {
|
|
52
62
|
// Non-blocking open: a FIFO without a writer would otherwise block before the type check.
|
|
53
63
|
const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | (options.noFollow ? constants.O_NOFOLLOW : 0));
|
|
54
64
|
try {
|
|
55
65
|
const info = fstatSync(fd);
|
|
56
66
|
if (!info.isFile()) throw new Error(`${path}: not a regular file`);
|
|
57
67
|
if (options.uid !== undefined && info.uid !== options.uid) throw new Error(`${path}: owned by another user`);
|
|
58
|
-
const buffer = Buffer.alloc(Math.min(maxBytes + 1, 1 << 20))
|
|
68
|
+
const buffer = Buffer.alloc(Math.min(maxBytes + 1, 1 << 20));
|
|
59
69
|
let total = 0;
|
|
60
70
|
for (;;) {
|
|
61
71
|
const n = readSync(fd, buffer, 0, buffer.length, null);
|
|
62
72
|
if (n === 0) break;
|
|
63
73
|
total += n;
|
|
64
74
|
if (total > maxBytes) throw new Error(`${path}: larger than ${maxBytes} bytes`);
|
|
65
|
-
|
|
75
|
+
consume(buffer.subarray(0, n));
|
|
66
76
|
}
|
|
67
|
-
return
|
|
77
|
+
return total;
|
|
68
78
|
} finally { closeSync(fd); }
|
|
69
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
|
+
}
|
|
70
90
|
export function readTextBounded(path: string, maxBytes: number, options: ReadOptions = {}): string {
|
|
71
91
|
try { return new TextDecoder("utf-8", { fatal: true }).decode(readBytesBounded(path, maxBytes, options)); }
|
|
72
92
|
catch (error) { if (error instanceof TypeError) throw new Error(`${path}: not valid UTF-8`); throw error; }
|
|
@@ -101,23 +121,26 @@ export function studyFile(dir: string, ...parts: string[]): string { return join
|
|
|
101
121
|
export function openStudy(dir: string): { dir: string; study: Study } {
|
|
102
122
|
const root = resolve(dir), file = join(root, "study.json");
|
|
103
123
|
if (!existsSync(file)) throw new Error(`${root}: no study.json (run ares init first)`);
|
|
104
|
-
return { dir: root, study:
|
|
124
|
+
return { dir: root, study: validateStudy(readJsonFile(file, STUDY_BYTES)) };
|
|
105
125
|
}
|
|
106
126
|
|
|
107
|
-
function
|
|
108
|
-
if (plain(raw) && raw.v !== 1) throw new Error("study.json: unsupported schema version; use an ares version that supports this study, keeping the original file unchanged");
|
|
109
|
-
if (!plain(raw) || raw.v !== 1 || typeof raw.id !== "string" || typeof raw.question !== "string" || typeof raw.createdAt !== "string" ||
|
|
110
|
-
!["survey", "experiment"].includes(raw.mode as string)
|
|
111
|
-
|
|
127
|
+
export function validateStudy(raw: unknown): Study {
|
|
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");
|
|
129
|
+
if (!plain(raw) || (raw.v !== 1 && raw.v !== 2) || typeof raw.id !== "string" || typeof raw.question !== "string" || typeof raw.createdAt !== "string" ||
|
|
130
|
+
!["survey", "experiment"].includes(raw.mode as string)) throw new Error("study.json: malformed");
|
|
131
|
+
let autonomy: Autonomy;
|
|
132
|
+
try { autonomy = validateAutonomy(raw.autonomy); }
|
|
133
|
+
catch { throw new Error("study.json: unsupported or malformed autonomy policy; restore the last valid study.json or use a compatible ares version before retrying"); }
|
|
134
|
+
if (raw.v === 1 && (typeof autonomy !== "string" || autonomy === "copilot" || autonomy === "step")) throw new Error("study.json: this autonomy policy requires study v2; restore the valid v1 study and use ares autonomy set with a compatible ares version");
|
|
135
|
+
return { ...raw, autonomy } as unknown as Study;
|
|
112
136
|
}
|
|
113
137
|
|
|
114
138
|
export function initStudy(dir: string, options: { question: string; mode?: string; autonomy?: string }, actor: Actor): Study {
|
|
115
139
|
const root = resolve(dir);
|
|
116
140
|
if (existsSync(join(root, "study.json"))) throw new Error(`${root}: a study already exists here`);
|
|
117
|
-
const mode = options.mode ?? "survey", autonomy = options.autonomy ?? "gates";
|
|
141
|
+
const mode = options.mode ?? "survey", autonomy = validateAutonomyMode(options.autonomy ?? "gates");
|
|
118
142
|
if (mode !== "survey" && mode !== "experiment") throw new Error("--mode: survey or experiment");
|
|
119
|
-
|
|
120
|
-
const study: Study = { v: 1, id: randomUUID(), question: boundedText(options.question, "--question", QUESTION_MAX), mode, autonomy, createdAt: new Date().toISOString() };
|
|
143
|
+
const study: Study = { v: autonomy === "auto" || autonomy === "gates" ? 1 : 2, id: randomUUID(), question: boundedText(options.question, "--question", QUESTION_MAX), mode, autonomy, createdAt: new Date().toISOString() };
|
|
121
144
|
for (const sub of ["", "literature", "literature/cards", "refs"]) mkdirSync(join(root, sub), { recursive: true });
|
|
122
145
|
// link() refuses an existing target, so two concurrent inits cannot both create the study.
|
|
123
146
|
const text = JSON.stringify(study, null, 2) + "\n", tmp = join(root, `study.json.${randomUUID()}.tmp`);
|
|
@@ -133,10 +156,25 @@ export function initStudy(dir: string, options: { question: string; mode?: strin
|
|
|
133
156
|
|
|
134
157
|
/**
|
|
135
158
|
* Exclusive write lock for one study. A lock older than 10 minutes is treated as abandoned and replaced.
|
|
136
|
-
* ponytail: mtime-based staleness, no owner liveness check
|
|
159
|
+
* ponytail: mtime-based staleness, no owner liveness check. The inode check before unlink is best-effort:
|
|
160
|
+
* a replacement between lstat and unlink can still be removed, after stale takeover of a live owner has
|
|
161
|
+
* already broken exclusion. Upgrade path: an owner liveness probe, including shared-host ownership.
|
|
137
162
|
*/
|
|
163
|
+
const ownedStudyLocks = new Set<() => void>();
|
|
164
|
+
/** MCP termination only: call immediately before process exit, never while continuing async work. */
|
|
165
|
+
export function releaseStudyLocksForExit(): void { for (const release of [...ownedStudyLocks]) release(); }
|
|
138
166
|
export class StudyLockBusyError extends Error {}
|
|
139
|
-
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> {
|
|
140
178
|
const path = join(dir, ".ares.lock");
|
|
141
179
|
let fd: number;
|
|
142
180
|
try { fd = openSync(path, "wx", 0o600); }
|
|
@@ -148,8 +186,27 @@ export async function withLock<T>(dir: string, fn: () => Promise<T> | T): Promis
|
|
|
148
186
|
try { unlinkSync(path); } catch { /* raced with another cleaner */ }
|
|
149
187
|
fd = openSync(path, "wx", 0o600);
|
|
150
188
|
}
|
|
151
|
-
|
|
152
|
-
try {
|
|
189
|
+
let owner: ReturnType<typeof fstatSync>;
|
|
190
|
+
try { owner = inspectOwner(fd); }
|
|
191
|
+
catch (error) {
|
|
192
|
+
try { unlinkSync(path); } catch { /* the just-created lock may already be absent */ }
|
|
193
|
+
finally { try { closeSync(fd); } catch { /* preserve the original probe failure */ } }
|
|
194
|
+
throw error;
|
|
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});
|
|
198
|
+
let released = false;
|
|
199
|
+
const release = () => {
|
|
200
|
+
if (released) return; released = true;
|
|
201
|
+
try { const current = lstatSync(path); if (current.dev === owner.dev && current.ino === owner.ino) unlinkSync(path); }
|
|
202
|
+
catch { /* absent or replaced; never remove a different owner's lock */ }
|
|
203
|
+
finally { try { closeSync(fd); } catch { /* process exit also closes owned descriptors */ } ownedStudyLocks.delete(release); studyReadLocks.delete(permit); }
|
|
204
|
+
};
|
|
205
|
+
ownedStudyLocks.add(release);
|
|
206
|
+
try { writeSync(fd, `${process.pid} ${new Date().toISOString()}\n`); }
|
|
207
|
+
catch (error) { release(); throw error; }
|
|
208
|
+
// Keep the descriptor open until release so an unlinked inode cannot be reused by a replacement lock.
|
|
209
|
+
try { return await fn(permit); } finally { release(); }
|
|
153
210
|
}
|
|
154
211
|
|
|
155
212
|
export interface PendingEvent { actor: Actor; type: string; data: Record<string, unknown> }
|
|
@@ -186,7 +243,12 @@ export function appendEvent(dir: string, actor: Actor, type: string, data: Recor
|
|
|
186
243
|
export function readLedger(dir: string): LedgerEvent[] {
|
|
187
244
|
const path = join(dir, "ledger.jsonl");
|
|
188
245
|
if (!existsSync(path)) return [];
|
|
189
|
-
|
|
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");
|
|
190
252
|
const events: LedgerEvent[] = [];
|
|
191
253
|
lines.forEach((line, index) => {
|
|
192
254
|
if (!line.trim()) return;
|
|
@@ -217,8 +279,11 @@ export function gateState(gate: GateName, events: LedgerEvent[], binder: Binder)
|
|
|
217
279
|
}
|
|
218
280
|
|
|
219
281
|
export function decideGate(dir: string, gate: GateName, decision: "approve" | "reject", actor: Actor, binder: Binder, reason?: string): GateState {
|
|
220
|
-
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`);
|
|
221
284
|
const before = gateState(gate, readLedger(dir), binder);
|
|
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`);
|
|
222
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" : ""}`);
|
|
223
288
|
if (decision === "reject" && !reason) throw new Error(`gate ${gate}: a rejection needs --reason`);
|
|
224
289
|
appendEvent(dir, actor, decision === "approve" ? "gate.approve" : "gate.reject", { gate, binding: before.current!, ...(reason ? { reason } : {}) });
|
|
@@ -230,13 +295,16 @@ export function decideGate(dir: string, gate: GateName, decision: "approve" | "r
|
|
|
230
295
|
* `auto` approval goes into the command's own commit only when the command succeeds, so a failed command never
|
|
231
296
|
* changes a gate.
|
|
232
297
|
*/
|
|
233
|
-
export function requireGate(dir: string, study: Study, gate: GateName, binder: Binder): PendingEvent[] {
|
|
234
|
-
if (gate
|
|
298
|
+
export function requireGate(dir: string, study: Study, gate: GateName, binder: Binder, guardedPhase?: Phase): PendingEvent[] {
|
|
299
|
+
if (gate.startsWith("harness:") && !isHarnessGate(gate)) invalidHarnessGate();
|
|
300
|
+
if (gate === "design" || gate === "final" || isHarnessGate(gate)) requireExperiment(study);
|
|
235
301
|
const state = gateState(gate, readLedger(dir), binder);
|
|
236
302
|
if (state.state === "approved") return [];
|
|
237
|
-
if (state.state === "pending" && study.autonomy === "auto") return [{ actor: { kind: "auto" }, type: "gate.approve", data: { gate, binding: state.current! } }];
|
|
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! } }];
|
|
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}`);
|
|
238
305
|
if (state.state === "none" && gate === "final") throw new Error("gate final: complete reserved seeds and close investigate/required ablate inputs before final approval");
|
|
239
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`);
|
|
240
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");
|
|
241
309
|
if (state.state === "rejected") throw new Error(`gate ${gate} is rejected${state.decided?.reason ? `: ${state.decided.reason}` : ""}; change the content and ask again`);
|
|
242
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; }
|