@staix/agent-research 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/README.md +93 -22
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +208 -66
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +86 -17
- package/src/exp/artifacts.ts +20 -2
- package/src/exp/attempts.ts +26 -9
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +130 -21
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/metrics.ts +3 -5
- package/src/exp/protocol.ts +28 -3
- package/src/exp/reuse-admission.ts +3 -1
- package/src/exp/reuse-runtime.ts +5 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/snapshot.ts +28 -8
- package/src/exp/stages.ts +3 -1
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +67 -14
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +21 -11
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
package/src/playbook.ts
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
/** Standalone workflow for one agent session. Printed by `ares playbook` and the `ares_playbook` tool. */
|
|
2
2
|
export const PLAYBOOK = `ares research playbook (A1 literature, A2 experiments, A3 plan DAG, investigate/final phases, A4 paper/review, A5 memory/evolution, A6 setup/console/watch, autonomy policy, study export)
|
|
3
3
|
|
|
4
|
+
Reports default to text. Use --json for machine-readable results, ares --help for grouped commands, and ares help <command> for usage and examples. Usage errors exit 2.
|
|
5
|
+
|
|
4
6
|
Before starting a phase, create its study once: ares init <dir> --question "..." [--mode experiment] [--autonomy auto|gates|copilot|step]. Use --mode experiment for experiment phases; reuse the initialized study thereafter. Phase lessons and archive call the amem CLI on PATH (its output parser was written against amem 0.20.3; no amem version is tested live here); these keep the study cwd and agent attribution. Source-inspected skill/experience evidence instead requires amem >=0.22.1 with screened exact-id amem_show advertised by its MCP server; a missing capability is unsupported, never a fallback to search results or private capture.
|
|
5
7
|
|
|
6
8
|
Frozen experience controls (#67): before the first harness round, use ares harness stream set with a bounded ordered stream. Freeze an explicit empty baseline/no-library selection, or a prepare-only nonempty prior-experience/retrieval-only selection with ares experience freeze, then bind streamSha256/improverContextHash in the round context. Nonempty entries need an earlier same-study task, current native harness-closure, accepted unchanged lesson, unique archive receipt and exact screened amem note matching exported text, plus matching model/runtime/toolset identities. Generic ranked ids with no chain refuse before exact-id reads. Before handoff, ares experience check rechecks the chain, current screened digest/version and compatibility (include --toolset-sha256 for nonempty contexts); unavailable/changed/withdrawn blocks use. Durable pins contain no body; context is transient and keeps synthetic-fixture, transfer:not-demonstrated and prepareOnly:true. Selection reports liveEligible:false; controlled/live uses refuse fixture entries. Workers keep baseline-only context; retrieval-only exposes a separate transient guidance slot. No automatic activation, body cache, source fallback or session launch.
|
|
7
9
|
|
|
8
|
-
Harness fixture rounds (#66): declare a bounded round and approve its separate harness:<round-id> gate; set/show/import all require the intended study directory, and import/transition commands also take the explicit round id. Explicitly import baseline/candidate synthetic fixtures; use ares harness show --json to obtain the current evidence fingerprint. Record admitted probe/output refs and uncertainty with ares harness contrast; label deterministic-check, blinded-judgment and actor-claim distinctly; a claim is never an observed event. Use ares harness compose for per-section keep/drop/revise links. A new successor stays unexecuted until its exact separate fixture import; identical existing bytes reuse their execution instead of adding a sample. For adoption, cite the selected arm's admitted probe in checks first; import its exact fixture if missing. An identical-byte successor may cite its reported reused execution. Record independentCheck state/source separately from judgment; current fixtures must say unavailable. Preview ares harness adopt then confirm its fingerprint to write adopted-experimental adoption+closure together. Baseline-kept, inconclusive and withdrawn need no adoption: preview/confirm ares harness close. Each immutable closure keeps binding, evidence fingerprint, outcome, actor and reason; later changes mark it stale and preserve history. Stale evidence refuses; old decisions stay in history. Correctness, live assurance and transfer stay unavailable. Use the read-only console Harness rounds panel for the same comparison/edit table. No fixture result changes native attempt/final metrics, activates guidance or starts a probe/model/hub mutation.
|
|
10
|
+
Harness fixture rounds (#66): declare a bounded round and approve its separate harness:<round-id> gate; set/show/import all require the intended study directory, and import/transition commands also take the explicit round id. Explicitly import baseline/candidate synthetic fixtures; use ares harness show <dir> --json to obtain the current evidence fingerprint. Record admitted probe/output refs and uncertainty with ares harness contrast; label deterministic-check, blinded-judgment and actor-claim distinctly; a claim is never an observed event. Use ares harness compose for per-section keep/drop/revise links. A new successor stays unexecuted until its exact separate fixture import; identical existing bytes reuse their execution instead of adding a sample. For adoption, cite the selected arm's admitted probe in checks first; import its exact fixture if missing. An identical-byte successor may cite its reported reused execution. Record independentCheck state/source separately from judgment; current fixtures must say unavailable. Preview ares harness adopt then confirm its fingerprint to write adopted-experimental adoption+closure together. Baseline-kept, inconclusive and withdrawn need no adoption: preview/confirm ares harness close. Each immutable closure keeps binding, evidence fingerprint, outcome, actor and reason; later changes mark it stale and preserve history. Stale evidence refuses; old decisions stay in history. Correctness, live assurance and transfer stay unavailable. Use the read-only console Harness rounds panel for the same comparison/edit table. No fixture result changes native attempt/final metrics, activates guidance or starts a probe/model/hub mutation.
|
|
11
|
+
|
|
12
|
+
Blinded contrasts can declare two swapped presentations. Agreement on a side determines improved or regressed. Two ties yield unchanged and disagreement yields inconclusive. Inspect orderControl and the round and composition-section counts in ares harness show <dir> --json. These are declared judgments.
|
|
9
13
|
|
|
10
14
|
Hub guidance metadata (#66): the read-only internal mapper understands the public agent-hub GuidanceReadResult contract pinned at 50100a8 and keeps source-owned variant/experiment/task/layer/section/digest identity, lifecycle and declared evidence metadata. Rationale shape is validated but its text is omitted. An available metadata record does not import an executed probe or establish handoff assurance. An ahub execution reference is an inert address, never a local ares record or skill-evidence resolver, even with matching project/id fields. The CLI/MCP harness import remains fixture-only; do not invent a hub command, receipt reader, real trial or activation path.
|
|
11
15
|
|
|
12
16
|
Reviewed harness lessons (#67 T3): after a current harness closure, use ares lesson propose --file, lesson list, lesson check and lesson decide --file. Bind concrete contrast/composition change refs, probe/output behavior, harness-closure hash and typed counterevidence; keep applicability, limitations, when-not-to-use, failure and retry conditions explicit. Current fixtures support only single-task observation/fail/limitation; no-lesson is an honest non-export result. Accept binds proposal/evidence hashes and reviewer reason, rechecks unchanged sources/counterevidence under lock, and requires acknowledgeStrength exactly synthetic-fixture; not evidence of real agent behavior. Accepted current candidates enter ordinary archive with that literal label and limitations; accepted candidates may be withdrawn. Closure, reflection and reviewed receipts never prove improvement or transfer. Interrupted archive writes may lack a receipt: reconcile with the owner before retry, which may duplicate; receipt-only recovery is not exactly-once.
|
|
13
17
|
|
|
14
|
-
Skill evidence decisions (#62): ares skill propose writes v2 with source-owned receipts; never supply inspections. Use typed current-study refs or full exact amem ids, optional applicability/limitations/counterevidence. Explicit ares skill check <dir> <name> reports source availability, integrity, recorded outcome and reviewer support separately. Check and acceptance share one aggregate 25 s/256 KiB response budget across a captured local graph and screened amem MCP reads. Acceptance rechecks evidence AND counterevidence under the owned study lock, fences local generation, and records actual observation times plus an evidence fingerprint in one decision commit. Changed/unavailable sources require a new proposal with honest limitations, never a silently dropped counterexample. Negative/no-winner/unfinished outcomes are not successful support. Stored console receipts are not fresh checks, and polling starts no source reads. Legacy v1 bytes/decisions remain legacy-unresolved; new v2 writes require a compatible reader/minor release. PR URL is supplied reference only. No installation, promotion or export side effect. Use 0.
|
|
18
|
+
Skill evidence decisions (#62): ares skill propose writes v2 with source-owned receipts; never supply inspections. Use typed current-study refs or full exact amem ids, optional applicability/limitations/counterevidence. Explicit ares skill check <dir> <name> reports source availability, integrity, recorded outcome and reviewer support separately. Check and acceptance share one aggregate 25 s/256 KiB response budget across a captured local graph and screened amem MCP reads. Acceptance rechecks evidence AND counterevidence under the owned study lock, fences local generation, and records actual observation times plus an evidence fingerprint in one decision commit. Changed/unavailable sources require a new proposal with honest limitations, never a silently dropped counterexample. Negative/no-winner/unfinished outcomes are not successful support. Stored console receipts are not fresh checks, and polling starts no source reads. Legacy v1 bytes/decisions remain legacy-unresolved; new v2 writes require a compatible reader/minor release. PR URL is supplied reference only. No installation, promotion or export side effect. Use 0.4.0 or a compatible reader for paperPlan v3 and paperEvidence v3; 0.3.0 or a compatible reader covers protocol v2, attempt v2/v3, skillProposal v2, paperPlan v1/v2 and plan-bound paperEvidence v2. Published 0.2.1 refuses the newer protocol/attempt/skill/evidence versions, but has no paper-plan or study.toml reader and ignores those files rather than enforcing their checks. Existing studies and records are not migrated by this workflow.
|
|
15
19
|
|
|
16
20
|
Literature workflow
|
|
17
21
|
|
|
@@ -21,7 +25,7 @@ ares lessons <dir> --for "scope and verify the literature"
|
|
|
21
25
|
2. Write scope.json (question, subquestions, include, exclude, yearFrom, yearTo, maxCandidates) and run ares scope <dir> --file scope.json.
|
|
22
26
|
In gates mode a person or the agent the workspace allows approves it: ares gate approve <dir> scope.
|
|
23
27
|
3. Search each subquestion: ares lit search <dir> "<query>" [--source all] [--intent lexical|semantic|background]. Mix lexical (exact terms, acronyms), semantic (concept descriptions) and background (adjacent foundations) queries; ares lit queries <dir> then shows per-query yield by intent and zero-included queries. Yield is attributed to the search that first created each surviving candidate, not every later search that merged it; old candidates without firstQuery remain unattributed, and omitted/older intent is unspecified. The report reflects current screening status and does not prove that a query was never useful. A source that is rate limited is reported, not fatal; retry later or set S2_API_KEY / OPENALEX_API_KEY.
|
|
24
|
-
4. Screen against include/exclude: ares lit screen <dir> <id>... --include|--exclude [--code CODE] --reason "...". Read titles and abstracts with ares lit list. Optional scope.json exclusionCodes [{code,label}] (at most 30) name exclusion reasons; --code must be declared, and without codes all exclusions are one group. ares lit flow <dir> [--markdown] reports the selection flow from the ledger: records per source, duplicates, unique, screened, excluded by code, unscreened, included, verified, cards. Cite its numbers in the manuscript as {{n:lit.flow.<field>}} (records, duplicates, unique, screened, excluded, excluded.<code>, unscreened, included, verified, cards); they resolve only while the screen gate is approved for the current included set. --markdown prints a table whose numbers are already placeholders.
|
|
28
|
+
4. Screen against include/exclude: ares lit screen <dir> <id>... --include|--exclude [--code CODE] --reason "...". Read titles with ares lit list <dir> and authors/abstracts with ares lit list <dir> --json. Optional scope.json exclusionCodes [{code,label}] (at most 30) name exclusion reasons; --code must be declared, and without codes all exclusions are one group. ares lit flow <dir> [--markdown] reports the selection flow from the ledger: records per source, duplicates, unique, screened, excluded by code, unscreened, included, verified, cards. Cite its numbers in the manuscript as {{n:lit.flow.<field>}} (records, duplicates, unique, screened, excluded, excluded.<code>, unscreened, included, verified, cards); they resolve only while the screen gate is approved for the current included set. --markdown prints a table whose numbers are already placeholders.
|
|
25
29
|
5. For each included paper you read, record a card: summary and claims, with optional methods, findings, limitations, relevance, datasets, results and motivation (ares lit card <dir> <id> --file card.json). Cards hold what the paper says, never what you hope it says. To reuse cards across studies, ares lit card export <dir> <id>... --vault ID previews, and --confirm FINGERPRINT writes them to the matching vault-mem reference note; ares lit card import <dir> <id>... --vault ID copies one back for an included, identifier-verified candidate. A reused card is a planning aid: reread the paper before relying on it; it never verifies, screens, changes gates or counts as support. ares lit card list <dir> and paper check's reusedCards show its provenance. Export accepts only cards extracted in this study with a verified DOI/arXiv identifier and a recording lit.card event, never an imported card; --model-family optionally records the extractor family label. Both import/export require the scope gate. The target vault must already contain exactly one matching reference note; create or disambiguate it there before retrying, rather than treating title similarity as verification. Confirm binds the inspected card payloads and target vault; a changed note hash refuses. Inspect any partial-write receipt before retrying. Cards must be regular physical files: replace linked/special files with the recorded card, and inspect paper check's unreadableCards instead of treating a refusal as missing support.
|
|
26
30
|
6. Verify identifiers: ares lit verify <dir>. "verified" means the DOI or arXiv id exists and its registry title and year match. It never means the paper supports a claim.
|
|
27
31
|
unknown = the registry could not be reached; run verify again. no / partial / mismatch / no identifier are final: fix the record or exclude it,
|
|
@@ -48,10 +52,10 @@ ares lessons <dir> --for "prepare reproducible experiments"
|
|
|
48
52
|
|
|
49
53
|
1. Use the initialized experiment study (--mode experiment at init). Survey studies refuse experiment commands; study mode is fixed at init.
|
|
50
54
|
2. Write task/task.md and task/evaluator/ entrypoint/data, optionally task/rubric.md. Use regular files only, at most 500 files and 64 MiB; symlinks are refused.
|
|
51
|
-
3. Set design/protocol.json: ares protocol <dir> --file protocol.json. For v1, declare digest-pinned candidate/evaluator images, argv arrays, metrics (name/unit/max|min), seeds, limits, network "none" and budgets. For v2, candidate.stages declares 1..16 stages in serial order with unique names, image/command, boolean seed, code:"snapshot", needs, named inputs and outputs. Each needs edge and {stage,output} input must name an earlier stage and its declared output; a task input uses {task:"relative/path"} outside evaluator/, and output ports name disjoint relative paths. V2 does not accept the v1 top-level inputs field. Dependencies belong in images. ARES_SEED is reserved and supplied from the selected seed (to v2 candidate stages only when seed:true, and to the evaluator); never put secret-like keys in candidate.env.
|
|
52
|
-
4. Configure the executor: ares executor set <dir> --kind ssh --host ALIAS --workdir /private/owned/path, or --kind local with an explicit private workdir. Create that host directory owned by the executor user with mode 0700. Run ares executor check <dir>
|
|
55
|
+
3. Set design/protocol.json: ares protocol <dir> --file protocol.json. For v1, declare digest-pinned candidate/evaluator images, argv arrays, metrics (name/unit/max|min), seeds, limits, network "none" and budgets. For v2, candidate.stages declares 1..16 stages in serial order with unique names, image/command, boolean seed, code:"snapshot", needs, named inputs and outputs. Each needs edge and {stage,output} input must name an earlier stage and its declared output; a task input uses {task:"relative/path"} outside evaluator/, and output ports name disjoint relative paths. V2 does not accept the v1 top-level inputs field. Dependencies belong in images. An optional screen declines material held out from the candidate: screen:{evaluatorInputs:true, literals:[...]} refuses a candidate commit carrying a byte copy of an input mounted only for the evaluator, or one of 1..64 declared fixed strings of 8..200 UTF-8 bytes. attempt run screens after the commit is resolved and before any attempt record, budget use or container starts; a hit appends attempt.screen.refused {commit, hits:[{rule, path, line?}]} with the rule and path only, never the matched text, and refuses with the removal-or-design-change step, while a clean screen is summarised in attempt.started as screen:{rules, sha256}. The screen checks exact bytes and fixed literals. Only verbatim material is caught; transformed, compressed or paraphrased material passes. ARES_SEED is reserved and supplied from the selected seed (to v2 candidate stages only when seed:true, and to the evaluator); never put secret-like keys in candidate.env.
|
|
56
|
+
4. Configure the executor: ares executor set <dir> --kind ssh --host ALIAS --workdir /private/owned/path, or --kind local with an explicit private workdir. Create that host directory owned by the executor user with mode 0700. Run ares executor check <dir> for Docker, images and non-root uid:gid. It may pull missing images. Text shows the independent probes and skipped prerequisites. JSON and MCP stop at the first failure. For pre-staged large/private inputs, run ares executor inputs hash <dir> /absolute/input, for protocol v1 declare names/hashes/read-only /in/ stage mounts in protocol.inputs and keep the directories stable. Python3 is required for declared v1 inputs and protocol v2 stages. By default, v2 candidate stages execute fresh: frozen code at /workspace, named read-only inputs at /in/<port>, fresh /out, then a separate evaluator with all sealed stage trees under /candidate/<stage>. Every parent manifest and byte tree is verified before consumption; each stage gets a fresh read-only input copy, and publication follows observed successful termination plus bounded verification. Outputs are cumulative across candidates and evaluator: 500 files, 256 MiB payload, 256 KiB metadata including retained sidecars, and a 1 MiB attempt record. Wall/compute accounting sums stages and never multiplies the attempt allowance. For shared Linux NVIDIA hosts, optionally set --gpu-devices IDS --gpu-min-free-memory-mb MB --gpu-max-load-ratio RATIO together. GPU attempts then get one read-only admission probe; devices/load/probe deferrals return status deferred and exit 75 with no Attempt or budget use. Never queue or automatically retry a deferral; try again explicitly after the named condition improves. A deferred plan node has reason deferred:devices|load|probe with no attempt id; recover with ares plan control <dir> retry <node> --command-id ID --expected-revision N. The chosen UUIDs are frozen across all candidate stages and the evaluator; this advisory check is not a reservation. Without GPU settings, execution is unchanged. New attempt stages store their study-scoped container name for inspection, reconciliation and watchdogs; old stages without it retain their legacy name. Finish or reconcile running attempts before downgrading to 0.3.0. Task archives use the shared content-only tar rule and refuse AppleDouble or unexpected/mismatched streamed members without changing the frozen tree hash. The staged path and all ancestors must be symlink-free; on macOS use /private/tmp rather than /tmp. No input download or copy into the study occurs; evaluator-only inputs stay hidden from the candidate. Hash/mount edits reopen design approval, locator-only edits do not. Manifest hashing runs outside the launch claim/control transaction; the short launch claim rechecks frozen input identities before container start.
|
|
53
57
|
For retention, inspect with ares retention inspect <dir> [--offset N] [--limit N]; page through released-history shards as needed; capacity includes active reservations (default 1 GiB, optional executor --retention-cap-bytes). Prune explicit {attemptId,stage,sha256} refs with ares retention prune <dir> --file refs.json, then --confirm FINGERPRINT. Preview needs no design approval; confirm requires the current design gate and unchanged fingerprint. Active producers/consumers refuse; tombstones remain. Source pruning does not erase an already recorded reuse lineage: show/lineage/export project disposed only from an exact prune ledger witness, otherwise unknown, never invented available. A failed terminal release is reconciled with ares attempt reconcile only after no owned live container is confirmed. Transient seal/transport contention may keep a stopped stage and its reservation for the next reconcile; permanent integrity/limit failures terminate with their cause. An unobserved stop keeps the reservation held. Never rerun uncertain work.
|
|
54
|
-
For optional deterministic artifact reuse, declare stages[].reuse as {v:1,kind:"pure-artifact",inputs:"declared-only",externalState:"none",writableState:"fresh-output-only",modelOutputs:"forbidden",determinism:"byte-exact",toolchain:{description,documentationSha256}}, then review the actual toolchain and approve the current design. Run --reuse eligible only on the selected investigation run; off is default. The key binds this study, frozen selection/reserved-seed population, complete code tree/snapshot, exact declared input hashes, stage/toolchain, seed, runtime and platform ABI. Sources must be actual earlier fresh executions admitted under eligible controls; ordinary fresh/off attempts do not populate the reuse key. Missing/pruned/corrupt/unsupported sources stay fresh under ordinary budgets. GPU ABI reuse is unsupported. Use --force-fresh with an explicit --retry ID to recompute an existing identity. Evaluator/ablate/final/posthoc always stay fresh. Source manifests/bytes are reverified and pinned before a hit is admitted; downstream work still uses fresh read-only input copies. Source receipts and original compute remain distinct from current verification/materialization overhead. Reused computation and retries do not create independent samples; the fresh evaluator count is separate and its metrics are never reused or overwritten. Unknown costs are not zero or savings. The
|
|
58
|
+
For optional deterministic artifact reuse, declare stages[].reuse as {v:1,kind:"pure-artifact",inputs:"declared-only",externalState:"none",writableState:"fresh-output-only",modelOutputs:"forbidden",determinism:"byte-exact",toolchain:{description,documentationSha256}}, then review the actual toolchain and approve the current design. Run --reuse eligible only on the selected investigation run; off is default. Outside a matching investigation run the request still runs fresh and its result carries warnings[{code:"outside-investigation", cause, nextStep}]; this additive warning is not persisted. The key binds this study, frozen selection/reserved-seed population, complete code tree/snapshot, exact declared input hashes, stage/toolchain, seed, runtime and platform ABI. Sources must be actual earlier fresh executions from succeeded attempts admitted under eligible controls; cancelled or unknown sources miss as ineligible-source even with retained stage bytes; ordinary fresh/off attempts do not populate the reuse key. Missing/pruned/corrupt/unsupported sources stay fresh under ordinary budgets. GPU ABI reuse is unsupported. Use --force-fresh with an explicit --retry ID to recompute an existing identity. Evaluator/ablate/final/posthoc always stay fresh. Source manifests/bytes are reverified and pinned before a hit is admitted; downstream work still uses fresh read-only input copies. Source receipts and original compute remain distinct from current verification/materialization overhead. Reused computation and retries do not create independent samples; the fresh evaluator count is separate and its metrics are never reused or overwritten. Unknown costs are not zero or savings. The T3 report (docs/verification/execution-eval-t3-report.md) records harness-observed synthetic trials: Diagnose is insufficient, Reuse is restricted after failed performance gates, and Supervision is at most retained in shadow mode. The T4 closeout (docs/verification/execution-eval-t4-status.md) records defaults and live-evidence gaps. These observations grant no adoption, human-benefit or native-container authority; reuse remains off by default and advisory mode stays unauthorized.
|
|
55
59
|
5. In gates mode approve the sealed inputs: ares gate approve <dir> design. The seal binds the task tree and, for v1 without inputs, exact protocol bytes. With v1 inputs it binds the canonical path-free protocol identity: names, hashes and stage mounts, not executor locators. V2 binds the canonical full stage protocol including its budget and reuse contracts; its comparable protocol hash excludes only budget. Sealed identity edits reopen approval; a same-identity locator relocation does not. A budget-only edit still reopens design approval while preserving comparable attempt protocol identity.
|
|
56
60
|
6. Run a frozen baseline: ares attempt run <dir> --repo /absolute/repo --commit <full-40-hex-SHA> --seed <declared-seed> --run main --label baseline --detach. Run a variant with a different frozen commit or declared seed and --label variant. The same request returns the existing attempt; --retry <id> creates a linked attempt. A different seed or commit is a new attempt, not a reproduction. MCP attempt_run is always detached.
|
|
57
61
|
7. Run ares attempt reconcile <dir> to advance recorded containers, then inspect ares attempt show <dir> <id> for the full record. ares attempt list <dir> returns summaries, default 50 per page; use --limit N (at most 200) and --offset N. Reconcile again while a stage runs. Totals include failed, cancelled and unknown attempts over the whole study regardless of filters or page, all of which count against budgets. Use ares attempt cancel <dir> <id> --reason "..." to stop a stage. Lost containers become unknown; reconciliation never creates a new attempt.
|
|
@@ -64,9 +68,11 @@ ares lessons <dir> --for "compare candidate hypotheses"
|
|
|
64
68
|
|
|
65
69
|
1. Use an experiment study with a protocol and evaluator task as above. Before collecting results, set ares selection <dir> --file selection.json with {v:1, run, metric, baseline:{commit}, minSeeds, minDelta}. metric must be declared; baseline.commit is a full frozen SHA; minSeeds is 1..declared seed count; minDelta is finite and nonnegative in the metric's unit. The metric direction comes from the protocol. The run names ablate, final and posthoc are reserved and refused. A new/changed selection joins the design seal and reopens approval; approve design again. Identical selection bytes record no event and do not move the counting cutoff. A study without selection keeps its prior seal.
|
|
66
70
|
2. Record an idea with ares idea add <dir> --file idea.json: {id,title,hypothesis,parent?,commit?}. Ids are unique run names; parent must exist; each commit has one idea owner. Limits: 1000 ideas, title500 characters and hypothesis4000 characters. Ares records hypotheses and decisions; it does not generate them.
|
|
71
|
+
Selection v2 optionally adds up to eight non-compensatory metric guards and a cost rule on one declared min metric. Both rules apply to the paired investigation and reserved final seeds. Use ares selection calibrate <dir> --from-run RUN to record a recommended margin from at least three non-reserved baseline seeds, or add --null COMMIT to pair identical task trees for A/A. Bind the receipt sha256 with selection.calibration.sha256 to report belowNoise without changing the sealed minDelta or refusing an otherwise eligible winner.
|
|
72
|
+
|
|
67
73
|
3. Run frozen baseline/candidate attempts with --run matching the selection. Execution stays one active attempt per study. Hub peers can work on ideas in parallel; they run ares attempt run for frozen commits in their own tasks. Reconcile and inspect results; every status remains in totals. Only current-protocol attempts with attempt.started after the latest selection.set in ledger order count. For each commit/seed, only the earliest success counts; later successes remain listed as excluded.
|
|
68
74
|
4. After terminal results, record ares idea decide <dir> <id> refine --reason TEXT --attempts ID[,ID...] --commit SHA, or pivot --reason TEXT --attempts ID[,ID...]. Evidence must exist, be non-running and belong to that idea's existing commits, at most200 ids. Reason is at most2000 bytes. Refine attaches a uniquely owned commit; pivot refuses --commit and closes later decisions. An idea with no commit omits --attempts: refine --commit attaches its first commit, or pivot drops it before testing. Pivot accepts optional --cause and --retry-when (2000 bytes each); refine refuses them. Missing values export as not recorded. Pivot never deletes earlier attempts or totals.
|
|
69
|
-
5. Read ares investigate show <dir> --json. Each candidate pairs only seeds with counted baseline and candidate successes; >=minSeeds pairs, delta>0 and delta>=minDelta are required. Rank by direction-adjusted paired delta, not raw candidate mean; paired sets may differ. Exact best-delta tie gives no winner. Other no-winner reasons are no-baseline, baseline-seeds, no-candidate
|
|
75
|
+
5. Read ares investigate show <dir> --json. Each candidate pairs only seeds with counted baseline and candidate successes; >=minSeeds pairs, delta>0 and delta>=minDelta are required. Rank by direction-adjusted paired delta, not raw candidate mean; paired sets may differ. Exact best-delta tie gives no winner. Optionally read ares idea report <dir> --json for advisory prediction hits, per-category recent gain, confounded bundles, a stalled flag and untried categories; it writes nothing and is not a required step. Other no-winner reasons are no-baseline, baseline-seeds, no-candidate, below-margin and constraints (measurable candidates blocked by guard or cost rules). Means are descriptive; there is no significance test. Rows and winner include the owning idea id when one exists; excluded attempts retain reasons.
|
|
70
76
|
6. Run ares investigate close <dir> after every attempt in the selected run is terminal, including excluded ones; otherwise run ares attempt reconcile first. It commits timestamp-free runs/<run>/investigate.json and investigate.closed together; unchanged inputs record nothing. Unknown result/selection versions refuse without overwriting. No executor or hub is started by show/close.
|
|
71
77
|
7. In a conductor plan, use a step {id:"close",kind:"step",command:"investigate.close",args:{},needs:["agent-work"]} after the hub unit that finishes all attempts. Its output reference {sha256,winner} binds a downstream plan gate; winner:null is valid, with the file naming why. Survey studies refuse selection, idea and investigate commands. Archive the completed study after paper/review and skill proposals, as the final step below. All investigate acceptance here uses offline synthetic fixtures, not live hub or executor DAG proof.
|
|
72
78
|
|
|
@@ -91,13 +97,17 @@ Paper and review workflow
|
|
|
91
97
|
ares lessons <dir> --for "report and review closed evidence"
|
|
92
98
|
|
|
93
99
|
1. Write paper/manuscript.md, at most 2 MiB. In experiments, put measured values in {{n:REF}} or {{n:REF|.Nf}} (N=0..6); use {{lit:TEXT}} for explicit reviewer-visible literal exceptions. Combined limit 5000 placeholders. Refs: final.status/reason/delta/mean/baselineMean, final.attempts.<status>; investigate.winner/reason, investigate.winner.delta/mean, investigate.baseline.mean, investigate.totals.<status>; ablate:<id>.delta/mean/referenceMean, ablate.totals.<status>; attempt:<id>.<metric> or posthoc:<id>.<metric>. Counts use every status. Text refs take no format; winner is a12-hex prefix. Metric names are exact, including spaces/punctuation; names containing | or } cannot be referenced in this grammar and need a new protocol/name. Null, absent, unclosed or stale sources are unresolved-ref. Direct metrics require succeeded current-protocol ares-observed records; posthoc appends (exploratory), and the prefixes cannot substitute for each other. Final refs need current final-gate approval.
|
|
94
|
-
Optional citation routing: ares paper plan set <dir> --file PATH|- stores {v:1,sections:[{id,heading,cites}]} in paper/plan.json for point-free plans (v may be omitted on authoring input; any writing point selects stored v2; empty points arrays normalize away and retain
|
|
100
|
+
Optional citation routing: ares paper plan set <dir> --file PATH|- stores {v:1,sections:[{id,heading,cites}]} in paper/plan.json for point-free plans (v may be omitted on authoring input; any writing point selects stored v2 and any dependency selects stored v3; empty points/dependencies arrays normalize away and retain the lower version bytes; formatted 64 KiB total, 64 sections, 300 keys/section, 200 dependencies; unique ids/headings and keys within a section or dependency; ids are lowercase alphanumeric hyphenated slugs <=64 characters). Only current included, identifier-verified bibliography keys pass; unknown fields refuse. ares paper plan show <dir> reports plan, routed/total included coverage and cited/waived/total dependency coverage. The caller chooses routing; ares never generates it or judges relevance. Exact raw heading content (including inner whitespace/inline Markdown and LF/CRLF in multiline Setext) defines scope boundaries at any heading level; code/comments do not. Front matter before the first planned heading has no scope rule, but citation verification still applies. Unplanned H2 warnings do not clear a prior scope. out-of-scope-citation blocks with sectionId/position; unplanned-section and unrouted-reference stay fixed nonblocking warnings, separate from study.toml hygiene blocking.
|
|
95
101
|
Optional writing points: each section may add points:[{id,claim,requires,evidence?}], at most 40/section within the same 64 KiB plan. Point ids are globally unique lowercase alphanumeric slugs <=64 characters; claim is single-line <=500 Unicode characters and is checked for shape only, never matched to prose or judged supported. requires is a unique subset of that section's cites. Place <!-- point:<id> --> before its paragraph in its own section. Every occurrence independently needs its citations before ANY next well-formed point anchor or planned-section boundary; an unknown/wrong-section next anchor still ends the prior window. A satisfied occurrence cannot hide another incomplete one, and no duplicate finding is added. Escaped openers, code, link destinations/titles, reference definitions and ordinary comments do not create anchors; a whole ordinary comment hides nested anchor-looking text. Only a well-formed slug of at most 64 characters makes a boundary. missing-point, missing-required-citation and unresolved-point-evidence block with point/section positions. Optional evidence has <=64 local card:<paper-id>/attempt:<16-hex-id> entries, <=4096 UTF-8 bytes each; set/show requires existence, check reports later disappearance, and existence claims no execution success or claim support. Review location point:<id> groups open findings per point. Points use paperPlan v2, while point-free plans/checks keep v1 behavior; plan-bound builds remain paperEvidence v2 with the existing exact raw plan hash, including point edits.
|
|
96
|
-
|
|
102
|
+
Optional experiment dependencies: the plan may add dependencies:[{id,kind,name,cites?|waiver}], at most 200 entries. kind is dataset, metric, baseline, model, method or software; name is trimmed nonempty single-line text; id follows the point slug rule and is unique among dependencies. Exactly one of a nonempty cites or a waiver of <=500 UTF-8 bytes. Dependency cites use the same known, unambiguous, included and identifier-verified rules as section cites when the plan is set. Dependencies select stored v3; an explicit v3 plan without dependencies keeps v3, and v1/v2 with a nonempty dependencies list refuses. paper check then adds blocking uncited-dependency when no declared key occurs in the manuscript or a cited key is no longer included and identifier-verified, and, when the study has a protocol, undeclared-metric when a trimmed protocol metric name has no metric dependency of the same name. Citing one declared key or a waiver clears the first; a waiver alone satisfies a metric dependency. Plans without dependencies check exactly as before. paper plan show reports cited/waived/total dependency coverage beside routed reference coverage.
|
|
103
|
+
Optional paper plan v3 figures bind local files under paper/ to the build. Declare each image by id, file and kind; plots need current-study card/attempt references or a written waiver, and diagrams need neither. Paper check blocks undeclared or missing assets and unresolved plot evidence. Builds record figure hashes and provenance in paper evidence v3, so changed figures reopen review and make old render receipts stale.
|
|
104
|
+
2. Run ares paper check <dir> --json. Prose digits without placeholders are bare-number, never matched heuristically to an existing metric. Code numbers are nonblocking but listed in codeNumbers (first 500 value/line/column) with codeNumberCount total. Link targets, placeholder/literal payloads, line-start ordered-list markers and citation-key digits are exempt. Citation bracket prose is checked: only locator terms p., pp., sec., §, ch., chap., fig., tbl., table, eq., l., ll., para. followed by integer ranges/lists allow digits. Decimals/percent claims in brackets still fail. Citations inside lit still need included, identifier-verified references; this never judges claim support. Paragraph/list continuations remain prose. Every literal is listed for review. Citation hygiene findings (adjacent-duplicate-citation, citation-stack, repeated-bundle, bare-identifier, duplicate-heading) are severity warning with a section heading path; fix them, or a study.toml [paper] blocking list makes chosen codes block check and build. Optional maxGroup (default 6) and maxBundleRepeats (default 2) tune citation-stack/bundle warnings; unknown keys/codes refuse. These are deterministic shape findings, not claim-support judgments. Declared experiment dependencies also contribute uncited-dependency and undeclared-metric blocking findings under the plan rules above.
|
|
97
105
|
3. With a final file, include {{n:final.status}} in visible prose; with no investigate winner, include {{n:investigate.reason}}. Code, link targets, HTML comments and reference-definition metadata cannot satisfy negative-result presence. Only reference numeric/reason fields when their value exists. A failed check exits 1. Survey papers check citations without experiment bare-number restrictions but refuse experiment refs with unresolved-ref; citation-only build is supported.
|
|
98
|
-
4. Run ares paper build <dir> --json only after a clean check. It commits rendered paper/build/manuscript.md, paperEvidence v1 (no plan) or
|
|
106
|
+
4. Run ares paper build <dir> --json only after a clean check. It commits rendered paper/build/manuscript.md, paperEvidence v1 (no plan), v2 (plan without figures) or v3 (plan with figures) paper/build/evidence.json and paper.built with both output hashes together. Plan-bound evidence binds exact raw paper/plan.json bytes; any plan change/addition/removal invalidates build/review. Without a plan, check reports and v1 evidence bytes keep the prior behavior. Evidence binds the source manuscript sha and every active placeholder value/rendering/position/source path+raw hash; literals source the input manuscript. Bounds:2MiB rendered,8MiB evidence. Identical outputs with a matching receipt are a no-op; provenance changes rebuild even with identical rendered values. Unknown evidence versions preserve bytes. The output manuscriptSha256 is rendered; evidenceSha256 is the review buildSha256.
|
|
99
107
|
5. Have reviewers inspect the build, evidence, lit and codeNumbers. Add each report using ares review add <dir> --file report.json: {v:1,reviewer:{id,modelFamily},buildSha256,checklist:{negativeResults,denominators,limitations,reproducibility},findings:[{id,kind,location,text,blocking}]}. buildSha256 is the current evidence file hash. Family labels are self-reported, trimmed/case-normalized, not attested or launched by ares. Checklist values are booleans, displayed rather than an extra gate requirement. Kinds:contradiction,unsupported-claim,number,citation,method,clarity,other. Contradiction is always blocking even if false was supplied. Limits:100 reports/build,200 findings/report,4000-byte texts/reasons,128-byte identifiers; the existing ledger event ceiling limits combined report payload to60KiB. Unknown fields/stale hashes refuse before writes. Findings may add repair (edit|paragraph|section, default edit) and section (plan section id or heading path); review show reports per-section rounds across builds, open findings by section and repair, and overBudget past study.toml [paper] reviewRounds (default 3) with "replan the section or ask a person". That is information only; the review gate is unchanged. Pick the smallest repair that closes each finding. For surveys, run ares review checklist and answer checklist.survey (taxonomyPrinciple, noEnumeration, specificGaps, citationRelations, selectionReported, scopeControl); study.toml [review] surveyChecklist off|show|require (default show for survey, off for experiment) controls display, and require only demands the block be present. Answers, including false ones, never gate; off hides the answers from the checklist projections. Unreadable settings add an information note rather than silently proving readiness.
|
|
108
|
+
Write optional readback.claims (one to eight single-line claims, at most 500 characters each) from the built manuscript before reading its plan. Review show exposes readbacks and planClaims for comparison by a person. [review] readback defaults to show. Off hides the read-back and require rejects submissions that omit it. Read-backs do not score the paper or change readiness.
|
|
100
109
|
6. Run ares review show <dir> --json for current check/build, reports/families/checklists, open blocking findings and every unmet condition. Resolve an existing item with ares review resolve <dir> <returned-review-id>/<finding-id> --reason TEXT. Resolutions record the actor; clean votes never close a contradiction. Approve ares gate approve <dir> review only with a clean current check/build, two distinct model families for that evidence hash and no open blocker. Approval preflight lives in the shared command under its study lock; reject still needs a reason but no readiness, and no command currently auto-requires review. The binding covers both output hashes and sorted added/resolved event hashes; a new build/report/resolution reopens it, old reports remain in the ledger.
|
|
110
|
+
Use paper check and paper build with --doc slides to validate paper/slides.md using the same evidence placeholders, citation checks and negative-result requirements as the manuscript. The slides use separate rendered Markdown and evidence files. For external decks, use paper render record and paper render show with --doc slides. The manuscript plan and review workflow apply to the manuscript. Ares commits slides.md and slides.evidence.json under paper/build, and stores external slides renders under paper/build/slides.render/. Record a manuscript render with ares paper render record <dir> --file PATH --receipt PATH, optionally adding --doc slides for the deck receipt.
|
|
101
111
|
7. The no-arg paper.build conductor step emits committed evidence {sha256}; a downstream plan:<id> gate binds it, but never replaces the global manuscript review gate. MCP never starts the controller loop. Claim-passage evidence/contradictions await STAIxBWLB/agent-hub#931; claims readiness reports unavailable (STAIxBWLB/agent-hub#931), nonblocking. Claim verdicts remain outside ares. Automatic writing/reviewing, LaTeX/PDF container builds and venue templates are out of scope. Acceptance is offline synthetic fixtures, with no live hub/executor DAG proof claimed.
|
|
102
112
|
|
|
103
113
|
Console workflow
|
|
@@ -116,7 +126,7 @@ Plan and conductor workflow
|
|
|
116
126
|
ares lessons <dir> --for "coordinate the study plan"
|
|
117
127
|
|
|
118
128
|
1. Use the initialized study and set any scope, screened set, design and executor required by its steps. Save a v1 definition with nodes and edges, then run ares plan set <dir> --file plan.json. A plan is revisioned and starts paused; read ares plan show <dir> --json for its revision, states and controller owner.
|
|
119
|
-
2. Use step nodes with command lit.search, lit.verify, lit.bib, cite.check, attempt.run, investigate.close, ablate.close, final.close, paper.build or watch.run; args are named CLI options without -- (including year-from). Search needs query and accepts optional intent lexical|semantic|background, verify takes optional ids, cite.check needs draft, and attempt.run needs repo and a full frozen commit; optional reuse must be off|eligible, and force-fresh is a boolean control with the same retry rules as the CLI. Relative repo and draft are study-relative. Close/build and watch.run steps take no args. watch.run emits {added} from the saved finite pass; an all-source failure fails that node. investigate.close emits {sha256,winner}; ablate.close emits {sha256,status:closed}; final.close emits {sha256,status:qualified|not_qualified}. paper.build emits the committed evidence {sha256}. All are valid done outcomes, including no-winner and not_qualified, and downstream plan gates bind their references. json and detach are controller-owned and refused in args; attempt steps always detach. needs and edges define dependencies; gates bind only upstream nodes. Bounds: 128 nodes, 512 explicit edges, 128-byte ids, no cycles.
|
|
129
|
+
2. Use step nodes with command lit.search, lit.verify, lit.bib, cite.check, attempt.run, investigate.close, ablate.close, final.close, paper.build, paper.render or watch.run; args are named CLI options without -- (including year-from). Search needs query and accepts optional intent lexical|semantic|background, verify takes optional ids, cite.check needs draft, and attempt.run needs repo and a full frozen commit; optional reuse must be off|eligible, and force-fresh is a boolean control with the same retry rules as the CLI. Relative repo and draft are study-relative. Close/build and watch.run steps take no args. watch.run emits {added} from the saved finite pass; an all-source failure fails that node. investigate.close emits {sha256,winner}; ablate.close emits {sha256,status:closed}; final.close emits {sha256,status:qualified|not_qualified}. paper.build emits the committed evidence {sha256}. paper.render takes no args, runs the machine-local renderer (ares renderer set, never plan.json) on the current build and emits the rendered output {sha256}; no renderer, nonzero exit, timeout or a bad receipt fails it with nothing written. All are valid done outcomes, including no-winner and not_qualified, and downstream plan gates bind their references. json and detach are controller-owned and refused in args; attempt steps always detach. needs and edges define dependencies; gates bind only upstream nodes. Bounds: 128 nodes, 512 explicit edges, 128-byte ids, no cycles.
|
|
120
130
|
3. Start ares run <dir> [--parallel 1..8] in terminal A. It stays open, initially paused. In terminal B or MCP, resume with ares plan control <dir> resume --command-id <unique-id> --expected-revision <revision from show>. The default is one step at a time; independent steps may fill the parallel slots, but only one experiment attempt is active per study.
|
|
121
131
|
4. Read ares gate list <dir>. After a plan gate has complete upstream outputs, approve it with ares gate approve <dir> plan:<node-id>. Approvals bind all upstream output references; changed output reopens approval. In auto autonomy pending plan gates are approved with actor auto inside the controller commit. Local approval authority stays workspace policy.
|
|
122
132
|
5. Read ares plan show <dir> --json for pending, ready, dispatched, done, failed, cancelled, uncertain, stale and skipped nodes, the last observation and attempt/retry/task references. Read ares lineage show <dir> --json for bounded source-proven relationships; focus with --root KIND --id ID and continue a stable snapshot with --cursor CURSOR. Restart pagination when source bytes change. Use ares lineage compare <dir> --attempts ID,... or --candidates COMMIT,... for up to eight existing rows; keep failed/unknown outcomes and retry links visible. These local reads add no aggregation, winner, gate decision or result authority. They read bounded committed source metadata, never output bodies or the executor; capped/changed/unavailable is incomplete coverage, and historical/missing/declared-unresolved refs are not current assurance. Foreign ahub addresses never fall back to same-id ares records. pause stops admission; resume allows it. retry <node> makes an eligible node available for a new dispatch once dependencies complete; cancel <node> stops its attempt if present; skip <node> produces no output and cannot bypass a gate. Every control needs --command-id and --expected-revision. Repeating the identical request returns its original receipt, even across revisions; a changed payload under that id or a stale revision on a new request refuses. Controls do not bump the definition revision.
|
package/src/provenance.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { paperEventFor } from "./paper/document.ts";
|
|
1
2
|
import { types } from "node:util";
|
|
2
3
|
import {parseHubExecutionReference, type HubExecutionReferenceV1} from "./harness/hub-reference.ts";
|
|
3
4
|
import { existsSync, lstatSync, opendirSync, realpathSync } from "node:fs";
|
|
@@ -365,7 +366,7 @@ function closures(dir: string, graph: Graph, study: ExecutionReferenceV1): void
|
|
|
365
366
|
const source = graph.source, records: Closure[] = [], latest = new Map<string, number>();
|
|
366
367
|
const selected = fileJson(source, "design/selection.json")?.run;
|
|
367
368
|
for (const [index, event] of source.events.entries()) {
|
|
368
|
-
const family = event.type === "investigate.closed" ? "investigate" : event.type === "ablate.closed" ? "ablate" : event.type === "final.closed" ? "final" : event
|
|
369
|
+
const family = event.type === "investigate.closed" ? "investigate" : event.type === "ablate.closed" ? "ablate" : event.type === "final.closed" ? "final" : paperEventFor(event, "paper.built") ? "paper" : undefined;
|
|
369
370
|
if (!family) continue;
|
|
370
371
|
const run = family === "investigate" ? event.data.run : family;
|
|
371
372
|
const hash = family === "paper" ? event.data.evidenceSha256 : event.data.sha256;
|
|
@@ -383,8 +384,8 @@ function closures(dir: string, graph: Graph, study: ExecutionReferenceV1): void
|
|
|
383
384
|
if (matches) {
|
|
384
385
|
try {
|
|
385
386
|
record.raw = fileJson(source, record.file);
|
|
386
|
-
if (record.raw && record.family === "paper" && (record.raw.v === 1 || record.raw.v === 2)) record.nativeVersion = paperEvidenceVersion(record.raw);
|
|
387
|
-
if (!record.raw || (record.raw.v !== 1 && !(record.family === "paper" && record.raw.v === 2))) { state = "unavailable"; graph.issue("unsupported-closed-version", record.ref); }
|
|
387
|
+
if (record.raw && record.family === "paper" && (record.raw.v === 1 || record.raw.v === 2 || record.raw.v === 3)) record.nativeVersion = paperEvidenceVersion(record.raw);
|
|
388
|
+
if (!record.raw || (record.raw.v !== 1 && !(record.family === "paper" && (record.raw.v === 2 || record.raw.v === 3)))) { state = "unavailable"; graph.issue("unsupported-closed-version", record.ref); }
|
|
388
389
|
else if (record.family === "paper" ? !Array.isArray(record.raw.placeholders) || typeof record.raw.manuscriptSha256 !== "string" : typeof record.raw.inputsSha256 !== "string" || record.family === "final" && !["qualified", "not_qualified"].includes(String(record.raw.status))) { state = "corrupt"; graph.issue("malformed-closed-artifact", record.ref); }
|
|
389
390
|
else if (record.latest && !(record.family === "investigate" && record.ref.id !== selected)) {
|
|
390
391
|
try {
|
package/src/study-export.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { paperEventFor } from "./paper/document.ts";
|
|
1
2
|
import { attemptReuseView, retentionDisposalIndex, type RetentionDisposalIndex } from "./provenance.ts";
|
|
2
3
|
import {urlOrKeyLike} from "./privacy.ts";
|
|
3
4
|
import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync } from "node:fs";
|
|
@@ -33,9 +34,9 @@ const LEDGER_KEYS: Record<string, readonly string[]> = {
|
|
|
33
34
|
"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
35
|
"archive.exported": ["fingerprint"], "skill.proposed": ["skillProposal", "sha256"], "skill.decided": ["skillProposal", "decision"], "watch.set": ["sha256"],
|
|
35
36
|
"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
|
+
"executor.set": ["kind"], "protocol.set": ["sha256", "identitySha256", "protocolHash", "treeHash"], "selection.set": ["sha256", "metric"], "selection.calibrated": ["run", "sha256", "protocolHash"], "final.seeds.set": ["sha256"],
|
|
37
38
|
"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
|
+
"idea.decided": ["decision"], "idea.categories.set": ["sha256", "count"], "paper.built": ["doc", "manuscriptSha256", "evidenceSha256", "sourceManuscriptSha256"], "paper.rendered": ["doc", "evidenceSha256", "manuscriptSha256", "outputSha256", "receiptSha256", "bytes"], "review.added": [], "review.resolved": ["buildSha256"],
|
|
39
40
|
"attempt.started": ["id", "run", "seed", "commit", "treeId"],
|
|
40
41
|
"retention.pruned": ["fingerprint", "refsSha256", "count"],
|
|
41
42
|
"attempt.stage.reused": ["id", "stage", "candidateStage", "key", "sourceAttemptId", "sourceStage", "sourceSha256"],
|
|
@@ -74,6 +75,8 @@ function reduceEvent(event: LedgerEvent) {
|
|
|
74
75
|
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
76
|
const at = isoAt(event.at), data = reduceData(plain(event.data) ? event.data : {}, (Object.hasOwn(LEDGER_KEYS, event.type) ? LEDGER_KEYS[event.type]! : []));
|
|
76
77
|
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[]]);
|
|
78
|
+
// Render receipt (#162): hashes plus renderer identity as closed tokens only, never the document bytes or free text.
|
|
79
|
+
if (event.type === "paper.rendered" && plain(event.data.renderer)) data.renderer = reduceData(event.data.renderer, ["tool", "version", "environment"]);
|
|
77
80
|
return { v: event.v, at, actor, type: TOKEN.test(event.type) ? event.type : "other", data };
|
|
78
81
|
}
|
|
79
82
|
// Closed codes emitted by attempts.ts, metrics.ts and artifacts.ts; never derive a class from user prose.
|
|
@@ -144,7 +147,7 @@ function reviews(events: LedgerEvent[]) {
|
|
|
144
147
|
}
|
|
145
148
|
/** Content-free per-section rounds and pass at the latest built evidence hash, plus the repair-scope histogram. */
|
|
146
149
|
function reviewSections(rows: ReturnType<typeof reviews>, events: LedgerEvent[]) {
|
|
147
|
-
const latest = events.filter(e => e
|
|
150
|
+
const latest = events.filter(e => paperEventFor(e, "paper.built") && typeof e.data.evidenceSha256 === "string").at(-1)?.data.evidenceSha256 ?? null;
|
|
148
151
|
const rounds = new Map<string, number>(), open = new Set<string>(), repairs: Record<string, number> = { edit: 0, paragraph: 0, section: 0 };
|
|
149
152
|
for (const row of rows) {
|
|
150
153
|
for (const section of row.sections) rounds.set(section, (rounds.get(section) ?? 0) + 1);
|
|
@@ -162,7 +165,7 @@ function evidence(dir: string) {
|
|
|
162
165
|
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
166
|
return {
|
|
164
167
|
v: 1, manuscriptSha256: typeof raw.manuscriptSha256 === "string" && SHA256.test(raw.manuscriptSha256) ? raw.manuscriptSha256 : null,
|
|
165
|
-
...(raw.v === 2 ? {planSha256: raw.planSha256} : {}),
|
|
168
|
+
...((raw.v === 2 || raw.v === 3) ? {planSha256: raw.planSha256} : {}),
|
|
166
169
|
placeholders: (raw.placeholders as Record<string, unknown>[]).filter(p => p.kind === "number").map(p => {
|
|
167
170
|
const ref = typeof p.ref === "string" ? p.ref : "", attempt = /^(?:attempt|posthoc):([a-f0-9]{16})\./.exec(ref)?.[1];
|
|
168
171
|
const source = plain(p.source) ? p.source : {};
|
package/src/study.ts
CHANGED
|
@@ -48,11 +48,15 @@ export const sha256 = (data: string | Uint8Array) => createHash("sha256").update
|
|
|
48
48
|
* Write a file by temp + fsync + rename so readers never see a partial file. `maxBytes` must be the bound the
|
|
49
49
|
* file's reader uses, so nothing is written that the tool cannot read back.
|
|
50
50
|
*/
|
|
51
|
-
export function writeAtomic(path: string, text: string, maxBytes: number, mode = 0o644): void {
|
|
51
|
+
export function writeAtomic(path: string, text: string | Uint8Array, maxBytes: number, mode = 0o644): void {
|
|
52
52
|
assertWritable(text, maxBytes, path);
|
|
53
53
|
const tmp = `${path}.${randomUUID()}.tmp`;
|
|
54
54
|
const fd = openSync(tmp, "wx", mode);
|
|
55
|
-
try {
|
|
55
|
+
try {
|
|
56
|
+
if (typeof text === "string") writeSync(fd, text);
|
|
57
|
+
else for (let offset = 0; offset < text.length;) offset += writeSync(fd, text, offset, text.length - offset);
|
|
58
|
+
fsyncSync(fd);
|
|
59
|
+
} finally { closeSync(fd); }
|
|
56
60
|
try { renameSync(tmp, path); } catch (error) { try { unlinkSync(tmp); } catch { /* already gone */ } throw error; }
|
|
57
61
|
}
|
|
58
62
|
|
|
@@ -96,7 +100,7 @@ export function readJsonFile(path: string, maxBytes: number): unknown {
|
|
|
96
100
|
try { return JSON.parse(text); } catch { throw new Error(`${path}: not valid JSON`); }
|
|
97
101
|
}
|
|
98
102
|
/** Refuse a write that the matching bounded read could not load back. */
|
|
99
|
-
export function assertWritable(text: string, maxBytes: number, what: string): void {
|
|
103
|
+
export function assertWritable(text: string | Uint8Array, maxBytes: number, what: string): void {
|
|
100
104
|
if (Buffer.byteLength(text) > maxBytes) throw new Error(`${what} would exceed ${maxBytes} bytes`);
|
|
101
105
|
}
|
|
102
106
|
|
|
@@ -210,7 +214,8 @@ export async function withLock<T>(dir: string, fn: (permit: StudyReadLock) => Pr
|
|
|
210
214
|
}
|
|
211
215
|
|
|
212
216
|
export interface PendingEvent { actor: Actor; type: string; data: Record<string, unknown> }
|
|
213
|
-
|
|
217
|
+
/** Text or exact bytes (for example a recorded render); either is bounded by its reader's limit. */
|
|
218
|
+
export type FileWrite = [path: string, text: string | Uint8Array, maxBytes: number];
|
|
214
219
|
|
|
215
220
|
/** Validate command capacity without writing; callers can reserve receipt space before outward effects. */
|
|
216
221
|
export function prepareCommit(dir: string, files: FileWrite[], pending: PendingEvent[]): { events: LedgerEvent[]; lines: string[] } {
|
package/src/ui/plugin.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { paperEventFor } from "../paper/document.ts";
|
|
1
2
|
/** Console api1 contract subset; runtime imports stay within ares/Node/Bun. Real contract/conformance is test-only. */
|
|
2
3
|
import { lstatSync, realpathSync, statSync } from "node:fs";
|
|
3
4
|
import { join } from "node:path";
|
|
@@ -93,6 +94,7 @@ export function gateWaitingTimes(events: LedgerEvent[], inputs: GateInputs, obse
|
|
|
93
94
|
case "ablation.added": hasAblations = true; experiment(event.at); break;
|
|
94
95
|
case "ablate.closed": if (typeof data.sha256 === "string") ablate = data.sha256; experiment(event.at); break;
|
|
95
96
|
case "paper.built":
|
|
97
|
+
if (!paperEventFor(event, "paper.built")) break;
|
|
96
98
|
if (typeof data.manuscriptSha256 === "string" && typeof data.evidenceSha256 === "string") paper = [data.manuscriptSha256, data.evidenceSha256];
|
|
97
99
|
review(event.at); break;
|
|
98
100
|
case "review.added": if (typeof data.id === "string" && inputs.review?.ids.has(data.id)) { reviewChanges++; review(event.at); } break;
|
|
@@ -192,7 +194,7 @@ function loadStudy(dir: string, features: readonly string[], input: { panel: str
|
|
|
192
194
|
}
|
|
193
195
|
const archive = detailed ? readCall("archive", () => { const preview = previewArchive(dir); return { pendingCount: preview.notes.length, fingerprint: preview.fingerprint }; }, errors) : null;
|
|
194
196
|
const manuscript = detailed && readCall("manuscript", () => {
|
|
195
|
-
const paths = paperBuildPaths(dir), recorded = recordPresent(paths.manuscript) || recordPresent(paths.evidence) || events.some(event => event
|
|
197
|
+
const paths = paperBuildPaths(dir), recorded = recordPresent(paths.manuscript) || recordPresent(paths.evidence) || events.some(event => paperEventFor(event, "paper.built"));
|
|
196
198
|
return recorded ? readCurrentBuild(dir) : null;
|
|
197
199
|
}, errors) ? { id: `manuscript:${study.id}` } : null;
|
|
198
200
|
const failures = Object.entries(errors);
|