@staix/agent-research 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/README.md +356 -31
  3. package/package.json +4 -2
  4. package/src/autonomy.ts +50 -0
  5. package/src/cli.ts +134 -14
  6. package/src/commands-table.ts +43 -9
  7. package/src/commands.ts +244 -43
  8. package/src/copilot.ts +91 -0
  9. package/src/exp/attempts.ts +512 -69
  10. package/src/exp/executor.ts +235 -12
  11. package/src/exp/final.ts +1 -1
  12. package/src/exp/investigate.ts +7 -2
  13. package/src/exp/logs.ts +25 -12
  14. package/src/exp/metrics.ts +6 -5
  15. package/src/exp/pipeline.ts +92 -0
  16. package/src/exp/protocol.ts +88 -18
  17. package/src/exp/retention-script.ts +649 -0
  18. package/src/exp/retention.ts +70 -0
  19. package/src/exp/reuse-admission.ts +63 -0
  20. package/src/exp/reuse-contract.ts +48 -0
  21. package/src/exp/reuse-runtime.ts +87 -0
  22. package/src/exp/reuse.ts +87 -0
  23. package/src/exp/selection.ts +1 -1
  24. package/src/exp/snapshot.ts +3 -3
  25. package/src/exp/stages.ts +117 -0
  26. package/src/harness/experience-source.ts +34 -0
  27. package/src/harness/experience.ts +206 -0
  28. package/src/harness/hub-guidance.ts +140 -0
  29. package/src/harness/hub-reference.ts +18 -0
  30. package/src/harness/lesson-candidates.ts +162 -0
  31. package/src/harness/limits.ts +2 -0
  32. package/src/harness/privacy.ts +4 -0
  33. package/src/harness/receipts.ts +84 -0
  34. package/src/harness/rounds.ts +198 -0
  35. package/src/harness/transitions.ts +152 -0
  36. package/src/http.ts +46 -2
  37. package/src/lit/candidates.ts +13 -5
  38. package/src/lit/cards.ts +55 -4
  39. package/src/lit/flow.ts +82 -0
  40. package/src/lit/queries.ts +62 -0
  41. package/src/lit/watch.ts +14 -1
  42. package/src/manifest.ts +15 -7
  43. package/src/mcp-tools.ts +140 -32
  44. package/src/mcp.ts +6 -0
  45. package/src/memory/amem-show.ts +135 -0
  46. package/src/memory/amem.ts +3 -0
  47. package/src/memory/archive.ts +20 -8
  48. package/src/memory/evidence-local.ts +77 -0
  49. package/src/memory/evidence.ts +39 -0
  50. package/src/memory/lessons.ts +4 -2
  51. package/src/memory/skill-check.ts +56 -0
  52. package/src/memory/skill-format.ts +77 -0
  53. package/src/memory/skills.ts +72 -26
  54. package/src/memory/source-budget.ts +11 -0
  55. package/src/memory/vault-cards.ts +226 -0
  56. package/src/paper/build.ts +20 -8
  57. package/src/paper/check.ts +40 -12
  58. package/src/paper/headings.ts +39 -0
  59. package/src/paper/hygiene.ts +153 -0
  60. package/src/paper/placeholders.ts +21 -4
  61. package/src/paper/plan.ts +170 -0
  62. package/src/paper/point-evidence.ts +63 -0
  63. package/src/paper/points.ts +83 -0
  64. package/src/paper/review.ts +116 -11
  65. package/src/paper/scopes.ts +51 -0
  66. package/src/plan/controller.ts +42 -12
  67. package/src/plan/definition.ts +22 -6
  68. package/src/plan/hub.ts +6 -0
  69. package/src/plan/state.ts +58 -17
  70. package/src/playbook.ts +47 -20
  71. package/src/privacy.ts +9 -0
  72. package/src/provenance.ts +679 -0
  73. package/src/scope.ts +24 -3
  74. package/src/study-export.ts +282 -0
  75. package/src/study.ts +94 -26
  76. package/src/ui/panel.css +4 -0
  77. package/src/ui/panel.js +271 -9
  78. package/src/ui/plugin.ts +89 -17
package/src/plan/state.ts CHANGED
@@ -1,13 +1,27 @@
1
+ import { resolvePhaseAutonomy, type Autonomy } from "../autonomy.ts";
1
2
  import { gateState, plain, sha256, boundedText, onlyKeys, type Actor, type GateName, type GateState, type LedgerEvent, type PendingEvent } from "../study.ts";
2
3
  import { PLAN_ID_BYTES, readPlan, validatePlan, type PlanDefinition, type PlanNode } from "./definition.ts";
3
4
 
4
5
  export const PLAN_GATE_BYTES = "plan:".length + PLAN_ID_BYTES;
5
6
 
6
7
  export type NodeStatus = "pending" | "ready" | "dispatched" | "done" | "failed" | "cancelled" | "uncertain" | "stale" | "skipped";
7
- export interface NodeState { id: string; kind: PlanNode["kind"]; status: NodeStatus; dispatchId?: string; dispatchCount?: number; retryOf?: string; output?: unknown; attemptId?: string; taskId?: number; hubProject?: string; reason?: string; gate?: GateState; lastObserved?: { revision: number; dispatchId: string; status: NodeStatus; at: string; output?: unknown; reason?: string } }
8
+ export interface NodeState { stepCancellation?: { revision: number; dispatchId: string; commandId: string }; id: string; kind: PlanNode["kind"]; status: NodeStatus; dispatchId?: string; dispatchCount?: number; retryOf?: string; output?: unknown; attemptId?: string; taskId?: number; hubProject?: string; reason?: string; gate?: GateState; lastObserved?: { revision: number; dispatchId: string; status: NodeStatus; at: string; output?: unknown; reason?: string; step?: true } }
8
9
  export interface ControlRequest { action: "pause" | "resume" | "retry" | "cancel" | "skip"; node?: string; commandId: string; expectedRevision: number }
9
- export interface ControlResult { commandId: string; revision: number; action: ControlRequest["action"]; node?: string; state: "paused" | "running" | "done"; status?: NodeStatus }
10
- export interface PlanState { definition: PlanDefinition; revision: number; state: "paused" | "running" | "done"; nodes: NodeState[]; uncertain: string[] }
10
+ export interface ControlResult { commandId: string; revision: number; action: ControlRequest["action"]; node?: string; state: "paused" | "running" | "done" | "failed"; status?: NodeStatus }
11
+ export interface PlanState { pauseReason?: "step"; definition: PlanDefinition; revision: number; state: "paused" | "running" | "done" | "failed"; nodes: NodeState[]; uncertain: string[] }
12
+ export const TERMINAL_NODE_STATUSES: readonly NodeStatus[] = ["done", "failed", "cancelled", "uncertain", "skipped"];
13
+ export function hasRemainingWork(state: PlanState): boolean { return state.nodes.some(node => !TERMINAL_NODE_STATUSES.includes(node.status)); }
14
+ function hasStepOutcome(node: NodeState): boolean {
15
+ if (node.status === "cancelled" && node.dispatchId === undefined && node.stepCancellation) return true;
16
+ return node.lastObserved?.step === true && node.lastObserved.dispatchId === node.dispatchId && node.lastObserved.status === node.status && TERMINAL_NODE_STATUSES.includes(node.status);
17
+ }
18
+ function matchesStepPause(state: PlanState, node: NodeState, data: Record<string, unknown>): boolean {
19
+ if (typeof data.dispatchId !== "string" || !hasStepOutcome(node)) return false;
20
+ const cancelled = node.stepCancellation;
21
+ if (cancelled && node.status === "cancelled" && node.dispatchId === undefined) return data.revision === state.revision && cancelled.revision === data.revision && cancelled.dispatchId === data.dispatchId && cancelled.commandId === data.commandId;
22
+ const observed = node.lastObserved;
23
+ return !!observed && node.dispatchId === data.dispatchId && observed.dispatchId === data.dispatchId && observed.revision === data.revision;
24
+ }
11
25
  const statuses: readonly NodeStatus[] = ["pending", "ready", "dispatched", "done", "failed", "cancelled", "uncertain", "stale", "skipped"];
12
26
  const recovery = "; run ares plan show and retry with its revision and a new --command-id";
13
27
  function bad(message: string): never { throw new Error(`plan: ${message}${recovery}`); }
@@ -35,7 +49,7 @@ function descendants(definition: PlanDefinition, roots: Set<string>): Set<string
35
49
  }
36
50
  function reset(node: NodeState, status: NodeStatus): void {
37
51
  node.status = status; delete node.output; delete node.reason; delete node.gate;
38
- delete node.dispatchId;
52
+ delete node.dispatchId; delete node.stepCancellation;
39
53
  // A retry must create a child attempt, while hub task references stay read-only.
40
54
  if (status === "pending" && node.attemptId) { node.retryOf = node.attemptId; delete node.attemptId; }
41
55
  }
@@ -90,15 +104,17 @@ function refresh(state: PlanState, decisions: Map<string, LedgerEvent>): void {
90
104
  }
91
105
  for (const node of state.definition.nodes) visit(node.id);
92
106
  state.uncertain = state.nodes.filter(n => n.status === "uncertain").map(n => n.id);
93
- if (state.nodes.length && state.nodes.every(n => n.status === "done" || n.status === "skipped")) state.state = "done";
94
- else if (state.state === "done") state.state = "paused";
107
+ if (state.nodes.length && state.nodes.every(n => n.status === "done" || n.status === "skipped")) { state.state = "done"; delete state.pauseReason; }
108
+ // Only completed step-policy effects introduce terminal failure; legacy plans keep their prior recovery flow.
109
+ else if (state.nodes.length && !hasRemainingWork(state) && state.nodes.some(hasStepOutcome)) { state.state = "failed"; delete state.pauseReason; }
110
+ else if (state.state === "done" || state.state === "failed") state.state = "paused";
95
111
  }
96
112
  /** Sole state authority: replay ledger events; no cache or snapshot is written. */
97
113
  /** Optional observer sees each effective, refreshed event; it must not mutate the folded state. */
98
114
  export function foldPlan(events: LedgerEvent[], onEvent?: (state: PlanState, event: LedgerEvent) => void): PlanState | undefined {
99
115
  let state: PlanState | undefined;
100
116
  const decisions = new Map<string, LedgerEvent>();
101
- const dispatches = new Set<string>();
117
+ const dispatches = new Set<string>(), stepPauses = new Set<string>();
102
118
  for (const event of events) {
103
119
  const d = event.data;
104
120
  if (event.type === "gate.approve" || event.type === "gate.reject") {
@@ -127,19 +143,34 @@ export function foldPlan(events: LedgerEvent[], onEvent?: (state: PlanState, eve
127
143
  }
128
144
  if (!state) continue;
129
145
  if (!["plan.control", "plan.paused", "node.intent", "node.observed", "node.stale"].includes(event.type)) continue;
130
- if (event.type !== "node.observed" && d.revision !== state.revision) continue;
131
- if (event.type === "plan.paused") state.state = "paused";
146
+ const stepPause = event.type === "plan.paused" && d.reason === "step";
147
+ if (event.type !== "node.observed" && !stepPause && d.revision !== state.revision) continue;
148
+ if (event.type === "plan.paused") {
149
+ if (stepPause) {
150
+ const target = state.nodes.find(node => node.id === d.node), key = canonical([d.node, d.dispatchId]);
151
+ if (!target || !matchesStepPause(state, target, d) || stepPauses.has(key)) continue;
152
+ stepPauses.add(key); state.pauseReason = "step";
153
+ } else delete state.pauseReason;
154
+ state.state = "paused";
155
+ }
132
156
  else if (event.type === "plan.control") {
133
157
  const request = validateControl(d.request);
134
158
  if (request.expectedRevision !== state.revision) bad("plan.control revision mismatch; restore the last valid ledger");
135
- if (request.action === "pause") state.state = "paused";
136
- else if (request.action === "resume") state.state = "running";
159
+ if (request.action === "pause") { state.state = "paused"; delete state.pauseReason; }
160
+ else if (request.action === "resume") { state.state = "running"; delete state.pauseReason; }
137
161
  else {
138
162
  const target = state.nodes.find(n => n.id === request.node);
139
163
  if (!target) bad(`control references missing node ${request.node}`);
140
164
  const affected = descendants(state.definition, new Set([target.id]));
141
165
  for (const node of state.nodes) if (affected.has(node.id) && node.id !== target.id && consumed(node)) reset(node, "stale");
166
+ let cancelled = request.action === "cancel" && hasStepOutcome(target)
167
+ ? { revision: state.revision, dispatchId: target.stepCancellation?.dispatchId ?? target.lastObserved!.dispatchId, commandId: request.commandId } : undefined;
168
+ if (d.stepCancel !== undefined) {
169
+ if (request.action !== "cancel" || target.kind === "gate" || target.status !== "dispatched" || typeof d.stepCancel !== "string" || target.dispatchId !== d.stepCancel) bad("step cancellation binding does not match the dispatched effect; restore the valid ledger or inspect ares plan show before retrying with a new command-id");
170
+ cancelled = { revision: state.revision, dispatchId: d.stepCancel, commandId: request.commandId };
171
+ }
142
172
  reset(target, request.action === "retry" ? "pending" : request.action === "skip" ? "skipped" : "cancelled");
173
+ if (cancelled) target.stepCancellation = cancelled;
143
174
  }
144
175
  } else {
145
176
  const node = state.nodes.find(n => n.id === d.node);
@@ -168,17 +199,22 @@ export function foldPlan(events: LedgerEvent[], onEvent?: (state: PlanState, eve
168
199
  if (node.kind !== "hub" || !Number.isSafeInteger(d.taskId) || (d.taskId as number) < 1 || (node.taskId !== undefined && node.taskId !== d.taskId)) {
169
200
  node.status = "failed"; delete node.output;
170
201
  node.reason = "hub child task binding changed or invalid; inspect ahub study show and retry explicitly";
171
- node.lastObserved = { revision: d.revision as number, dispatchId, status: "failed", at: event.at, reason: node.reason };
202
+ node.lastObserved = { revision: d.revision as number, dispatchId, status: "failed", at: event.at, reason: node.reason, ...(d.step === true ? { step: true as const } : {}) };
172
203
  refresh(state, decisions); onEvent?.(state, event); continue;
173
204
  }
174
205
  node.taskId = d.taskId as number;
175
206
  }
176
207
  if (typeof d.hubProject === "string") node.hubProject = boundedText(d.hubProject, `node ${node.id} hub project`, 4096);
208
+ // Admission refusals carry no Attempt; retain the ordinary failed/step outcome semantics.
209
+ if (d.status === "failed" && typeof d.reason === "string" && /^deferred:(devices|load|probe);/.test(d.reason)) {
210
+ const definition = state.definition.nodes.find(value => value.id === node.id);
211
+ if (definition?.kind === "step" && definition.command === "attempt.run") delete node.attemptId;
212
+ }
177
213
  node.status = d.status as NodeStatus;
178
214
  if (node.status === "done" && d.output !== undefined) node.output = d.output;
179
215
  delete node.reason;
180
216
  if (typeof d.reason === "string") node.reason = boundedText(d.reason, `node ${node.id} reason`, 500);
181
- node.lastObserved = { revision: d.revision as number, dispatchId, status: node.status, at: event.at, ...(d.output !== undefined ? { output: d.output } : {}), ...(node.reason !== undefined ? { reason: node.reason } : {}) };
217
+ node.lastObserved = { revision: d.revision as number, dispatchId, status: node.status, at: event.at, ...(d.output !== undefined ? { output: d.output } : {}), ...(node.reason !== undefined ? { reason: node.reason } : {}), ...(d.step === true && TERMINAL_NODE_STATUSES.includes(node.status) ? { step: true as const } : {}) };
182
218
  }
183
219
  }
184
220
  refresh(state, decisions); onEvent?.(state, event);
@@ -211,7 +247,7 @@ function controlRequest(raw: unknown): ControlRequest {
211
247
  if ((action === "pause" || action === "resume") ? node !== undefined : node === undefined) bad(`control ${action} ${node === undefined ? "requires a node" : "takes no node"}`);
212
248
  return { action, commandId, expectedRevision: raw.expectedRevision as number, ...(node !== undefined ? { node } : {}) };
213
249
  }
214
- export function prepareControl(state: PlanState, events: LedgerEvent[], raw: unknown, actor: Actor): { result: ControlResult; event?: PendingEvent } {
250
+ export function prepareControl(state: PlanState, events: LedgerEvent[], raw: unknown, actor: Actor, policy?: Autonomy): { result: ControlResult; event?: PendingEvent; pause?: PendingEvent } {
215
251
  const request = validateControl(raw);
216
252
  for (const e of events) if (e.type === "plan.control" && plain(e.data.request) && e.data.request.commandId === request.commandId) {
217
253
  if (canonical(e.data.request) !== canonical(request)) bad(`command-id ${request.commandId} already has a different payload`);
@@ -226,9 +262,14 @@ export function prepareControl(state: PlanState, events: LedgerEvent[], raw: unk
226
262
  if (request.action === "skip" && (node.kind === "gate" || node.status === "dispatched" || node.status === "done")) bad(`cannot skip ${node.kind} node ${node.id} in ${node.status}; approve its gate or cancel running work first`);
227
263
  if (request.action === "retry" && (node.status === "dispatched" || node.status === "ready" || node.status === "pending")) bad(`cannot retry node ${node.id} in ${node.status}; wait for an outcome first`);
228
264
  }
229
- const pending: PendingEvent = { actor, type: "plan.control", data: { revision: state.revision, request } };
230
- const next = foldPlan([...events, { v: 1, at: new Date().toISOString(), ...pending }])!;
265
+ const target = state.nodes.find(node => node.id === request.node), definition = state.definition.nodes.find(node => node.id === request.node);
266
+ const stepCancel = policy !== undefined && request.action === "cancel" && target?.status === "dispatched" && definition && definition.kind !== "gate" && resolvePhaseAutonomy(policy, definition.kind === "hub" ? undefined : definition.phase) === "step";
267
+ if (stepCancel && !target?.dispatchId) bad("dispatched step has no cancellation binding; restore its intent before retrying plan control");
268
+ const pending: PendingEvent = { actor, type: "plan.control", data: { revision: state.revision, request, ...(stepCancel ? { stepCancel: target!.dispatchId } : {}) } };
269
+ const at = new Date().toISOString(), projected = foldPlan([...events, { v: 1, at, ...pending }])!;
270
+ const pause: PendingEvent | undefined = stepCancel && hasRemainingWork(projected) ? { actor, type: "plan.paused", data: { revision: state.revision, node: target!.id, dispatchId: target!.dispatchId, commandId: request.commandId, reason: "step" } } : undefined;
271
+ const next = pause ? foldPlan([...events, { v: 1, at, ...pending }, { v: 1, at, ...pause }])! : projected;
231
272
  const result: ControlResult = { commandId: request.commandId, revision: state.revision, action: request.action, ...(request.node ? { node: request.node, status: next.nodes.find(n => n.id === request.node)!.status } : {}), state: next.state };
232
273
  pending.data.result = result;
233
- return { result, event: pending };
274
+ return { result, event: pending, ...(pause ? { pause } : {}) };
234
275
  }
package/src/playbook.ts CHANGED
@@ -1,7 +1,17 @@
1
1
  /** Standalone workflow for one agent session. Printed by `ares playbook` and the `ares_playbook` tool. */
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)
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
- Before starting a phase, create its study once: ares init <dir> --question "..." [--mode experiment] [--autonomy gates]. Use --mode experiment for experiment phases; reuse the initialized study thereafter. Install amem 0.20.3 or a compatible CLI for phase lessons and archive; these keep the study cwd and agent attribution.
4
+ 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
+
6
+ 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
+
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.
9
+
10
+ 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
+
12
+ 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
+
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.3.0 or a compatible reader for 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.
5
15
 
6
16
  Literature workflow
7
17
 
@@ -10,9 +20,9 @@ ares lessons <dir> --for "scope and verify the literature"
10
20
  1. Use the initialized study; choose its scope before collecting literature.
11
21
  2. Write scope.json (question, subquestions, include, exclude, yearFrom, yearTo, maxCandidates) and run ares scope <dir> --file scope.json.
12
22
  In gates mode a person or the agent the workspace allows approves it: ares gate approve <dir> scope.
13
- 3. Search each subquestion: ares lit search <dir> "<query>" [--source all]. A source that is rate limited is reported, not fatal; retry later or set S2_API_KEY / OPENALEX_API_KEY.
14
- 4. Screen against include/exclude: ares lit screen <dir> <id>... --include|--exclude --reason "...". Read titles and abstracts with ares lit list.
15
- 5. For each included paper you read, record a card: summary, claims, methods, findings, limitations, relevance (ares lit card <dir> <id> --file card.json). Cards hold what the paper says, never what you hope it says.
23
+ 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.
25
+ 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.
16
26
  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.
17
27
  unknown = the registry could not be reached; run verify again. no / partial / mismatch / no identifier are final: fix the record or exclude it,
18
28
  and re-check one by naming it (ares lit verify <dir> <id>).
@@ -38,12 +48,14 @@ ares lessons <dir> --for "prepare reproducible experiments"
38
48
 
39
49
  1. Use the initialized experiment study (--mode experiment at init). Survey studies refuse experiment commands; study mode is fixed at init.
40
50
  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.
41
- 3. Set design/protocol.json: ares protocol <dir> --file protocol.json. Declare digest-pinned candidate/evaluator images, argv arrays, metrics (name/unit/max|min), seeds, limits, network "none" and budgets. Dependencies belong in images. ARES_SEED is reserved and supplied to both stages from the selected seed; never put secret-like keys in candidate.env.
42
- 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> to check Docker, images and non-root uid:gid; it may pull missing images.
43
- 5. In gates mode approve the sealed inputs: ares gate approve <dir> design. The seal binds exact protocol bytes and the task tree. Editing either reopens approval; a budget-only edit also reopens it while preserving comparable attempt protocol identity.
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> to check Docker, images and non-root uid:gid; it may pull missing images. 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. 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
+ 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 measured benefit pilot and native container proof remain separate from fixture-equivalence checks.
55
+ 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.
44
56
  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.
45
57
  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.
46
- 8. Read logs explicitly with ares attempt logs <dir> <id> [--stage candidate|evaluator] [--stream stdout|stderr] [--tail 16384]. Tail size is 0..65536 bytes, default 16384; without stage/stream filters every recorded stream is returned after checking each copy's size and sha256. Retrieval is read-only; log content stays out of the study. Stage records keep log paths, hashes, sizes and truncation status. Attempt artifacts keep metadata rather than raw output bodies.
58
+ 8. Read logs explicitly with ares attempt logs <dir> <id> [--stage candidate|evaluator] [--candidate-stage NAME] [--stream stdout|stderr] [--tail 16384]. Named v2 candidate receipts remain readable after moving to completed history. Tail size is 0..65536 bytes per stream, default 16384; combined tails are at most 256 KiB, so defaults shrink for many streams and oversized explicit requests require selection or a lower tail; without stage/stream filters every recorded stream is returned after checking each copy's size and sha256. Retrieval is read-only; log content stays out of the study. Stage records keep log paths, hashes, sizes and truncation status. Attempt artifacts keep metadata rather than raw output bodies.
47
59
  9. Numbers come only from the sealed evaluator's /result/metrics.json, an object of all declared metric names and finite numeric values. Candidate output and printed scores never become metrics. Candidate and evaluator run in separate isolated containers; evaluator inputs are read-only. Sealing is ares-observed (argv plus observed container configuration), never host-observed or runner-attested. It does not establish support for a research claim.
48
60
 
49
61
  Investigation workflow
@@ -67,7 +79,7 @@ ares lessons <dir> --for "plan ablation and final evaluation"
67
79
  Before final evaluation: ares lessons <dir> --for "evaluate reserved final seeds"
68
80
 
69
81
  3. Approve ares gate approve <dir> final after current investigate closure and, when declarations exist, ablate closure. It binds SHA-256 of [investigate result sha, ablate result sha or none, design binding]. Changed inputs reopen approval. Run --run final with each reserved seed for both the frozen winner and baseline. Seed/commit/gate checks happen before Git/record/container; auto approval is committed only with a verified candidate start.
70
- 4. Run ares final close <dir> after final attempts stop. First attempt.started per commit/reserved seed decides whatever its status; later retries remain listed and never replace it. Missing pairs, a running final attempt or a non-current gate approval refuse. Qualification needs all decisive successes and direction-adjusted paired delta>0 and >=minDelta, with no significance test. Reapprove changed inputs but keep existing decisive data: old input/seal bindings alone never disqualify it. A changed protocol gives protocol-changed. A different winner after any final attempt (including baseline-only work) gives winner-changed and blocks another final start, with no new-winner pairs required. Reason order is winner-changed, protocol-changed, first decisive failure status, below-margin. Close writes timestamp-free runs/final/final.json plus final.closed; identical inputs record nothing.
82
+ 4. Run ares final close <dir> after final attempts stop. First attempt.started per commit/reserved seed decides whatever its status; later retries remain listed and never replace it. Missing pairs, a running final attempt or a non-current gate approval refuse. Qualification needs all decisive successes and direction-adjusted paired delta>0 and >=minDelta, with no significance test. Reapprove changed inputs but keep existing decisive data: old input/seal bindings alone never disqualify it. A changed comparable evaluation identity gives protocol-changed; locator-only and budget-only edits preserve that identity. A different winner after any final attempt (including baseline-only work) gives winner-changed and blocks another final start, with no new-winner pairs required. Reason order is winner-changed, protocol-changed, first decisive failure status, below-margin. Close writes timestamp-free runs/final/final.json plus final.closed; identical inputs record nothing.
71
83
  Before posthoc exploration: ares lessons <dir> --for "explore posthoc follow-up"
72
84
 
73
85
  5. After a historical final.closed receipt, additional attempts may use --run posthoc on non-reserved seeds. ares posthoc show <dir> lists every status and metrics labeled exploratory. They never change final.json, its fingerprint or close receipt, even while running. Survey studies refuse every new phase command on CLI/MCP.
@@ -78,11 +90,13 @@ Paper and review workflow
78
90
 
79
91
  ares lessons <dir> --for "report and review closed evidence"
80
92
 
81
- 1. Write paper/manuscript.md, at most2MiB. 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.
82
- 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 (first500 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.
83
- 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 exits1. Survey papers check citations without experiment bare-number restrictions but refuse experiment refs with unresolved-ref; citation-only build is supported.
84
- 4. Run ares paper build <dir> --json only after a clean check. It commits rendered paper/build/manuscript.md, paperEvidence v1 paper/build/evidence.json and paper.built with both output hashes together. 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.
85
- 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.
93
+ 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 v1 bytes; formatted 64 KiB total, 64 sections, 300 keys/section; unique ids/headings and keys within a section; 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 and routed/total included 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
+ 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
+ 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.
97
+ 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 v2 (plan-bound) 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
+ 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.
86
100
  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.
87
101
  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.
88
102
 
@@ -94,17 +108,18 @@ ares lessons <dir> --for "review the study in the console"
94
108
  2. Register a readable study with ares console add <dir>; ares console list shows the explicit registry, and ares console remove <dir> removes only its registration, even after the study moved. Registry is a bounded private studies.json under the family research directory, at most 200 canonical absolute directories. No disk scan. Setup console registers API 1 ares.json, or ares@<version>.json under --root, with an absolute plugin module and its sha256.
95
109
  3. Read Studies/Study panels and inbox decisions. Moved/unreadable studies stay listed as unavailable. Watch candidate items are still-new recorded ids; an overflow alert reports unrecorded ids without guessing their provenance. Only a fresh built manuscript of at most 2 MiB is served as text/plain, never a generated PDF or figure.
96
110
  4. Decision wire ids are gate.approve, gate.reject, screen.include, screen.exclude, skill.accept, skill.reject, skill.withdraw and archive.confirm. Each returns a write-free preview first; the console binds confirmation to that input, and ares recomputes its study/content fingerprint under the command lock. The wire id supplies the decision. Gate rejection and every screen/skill decision require reasons; skill accept also needs its reviewed HTTP(S) PR URL. The person actor records verified meta.identity when supplied; page actor/meta fields and other unsupported action fields are refused. acon serve --read-only refuses writes before invoking the provider. Containers, network searches and plan control stay with CLI/MCP.
97
- 5. Use archive.confirm only as the final Archive workflow step below. Console archive has a 25-second total child budget inside the 30-second provider ceiling; partial returned ids are receipted, so refresh and review a new preview before continuing. No live console/amem/vault interoperability is claimed by offline tests.
111
+ 5. The Lineage, attempt comparison, Skills, Harness rounds and frozen experience views are read-only source projections. Refresh changed/capped/unavailable views before relying on them; stored receipts never become a new source check through polling. Stage counts distinguish executed and reused work, fresh evaluation and independent samples; reused source container metadata is not a new container or cost.
112
+ 6. Use archive.confirm only as the final Archive workflow step below. Console archive has a 25-second total child budget inside the 30-second provider ceiling; partial returned ids are receipted, so refresh and review a new preview before continuing. No live console/amem/vault interoperability is claimed by offline tests.
98
113
 
99
114
  Plan and conductor workflow
100
115
 
101
116
  ares lessons <dir> --for "coordinate the study plan"
102
117
 
103
118
  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.
104
- 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, verify takes optional ids, cite.check needs draft, and attempt.run needs repo and a full frozen commit. 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.
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.
105
120
  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.
106
121
  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.
107
- 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. 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.
122
+ 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.
108
123
  6. Changing a consumed node definition or its dependencies marks it and consumed descendants stale; retry them explicitly. Never-run nodes wait normally for their dependencies. After a crash, the controller restores paused and reconciles recorded attempts; an unobservable step becomes uncertain, never an automatic replay. Retry links an existing parent attempt; a predicted but uncreated id is not passed as a retry parent. A live or foreign controller lock is refused; only a dead same-host pid/start identity can be recovered, never by age.
109
124
  7. For hub work, use a hub node with campaign and unit ids from an agent-hub campaign. A planner drafts it and a person activates/approves it there. Ares reads ahub --project <study-dir> status --json and study show <campaign> --json only, using the unit's taskId and state. Only approved completes the node; activation pending waits. hubProject names the resolved board. Unreachable reads stay dispatched with a safe error class; missing units/tasks, cancelled tasks or a changed pinned binding fail. The task id is pinned per plan revision across restarts/retries; a new revision may bind a new task. Hub waits do not consume step slots, and cancelling one is local only. Ares never writes to the hub or redispatches agent work.
110
125
  8. Waiting observations use 1 s to 30 s backoff, reset on progress, and unchanged polls write nothing. run exits 0 when done. SIGINT/SIGTERM stops admission, drains command calls and releases the controller lock; running detached attempts remain for ares attempt reconcile. MCP ares_plan_set, ares_plan_show and ares_plan_control never start a controller: run is CLI-only. Plan state comes from the ledger, not a second snapshot.
@@ -116,13 +131,25 @@ ares lessons <dir> --for "derive reusable skills from study evidence"
116
131
  1. Lessons search this study's amem project with the intent (or study question without --for) and return an intent brief when --for is supplied. Age is fractional days, relevance excludes amem recency, score = relevance * 0.5^(age/halfLife), rank is the 1-based position. Ties put fail first, then lexical id. Default half-life 180 days (1..3650); limit 50 (1..50). No study write or lock.
117
132
  2. Propose a procedure for review: ares skill propose <dir> --file proposal.json, with {name,summary,steps:[...],evidence:[...]}. Require at least one step and 1..64 refs (32-hex amem ids or ares:<study-id>/...). Names follow the run-name rule; at most 100 proposals and 16 KiB per Markdown file, bound to its receipt.
118
133
  3. List every state: ares skill list <dir>. Decide with ares skill decide <dir> <name> accept|reject|withdraw --reason TEXT [--pr URL]. Accept requires a reviewed HTTP(S) PR URL without credentials. Ares stores the actor's reference, never opens, checks or merges it. Every terminal state is final; withdraw is allowed only while proposed.
119
- 4. Survey and experiment studies support lessons, archive and the skill queue. Survey archives can derive resolved review contradictions; experiment pivots/selection/results remain experiment-only. Open contradictions are never exported. Durable vault promotion stays in amem vault-candidates; ares never writes the vault.
134
+ 4. Survey and experiment studies support lessons, archive and the skill queue. Survey archives can derive resolved review contradictions; experiment pivots/selection/results remain experiment-only. Open contradictions are never exported. Durable lesson/skill promotion stays in amem vault-candidates; the separate explicit literature card export/import workflow above is the supported vault card exchange, not skill installation or promotion.
135
+
136
+ Autonomy policy
137
+
138
+ 1. Read ares autonomy show <dir> for the stored policy and each phase's effective mode; change it with ares autonomy set <dir> <auto|gates|copilot|step> [--phase PHASE]. Phases: scope, literature, hypotheses, design, investigate, ablate, final, posthoc, write, review, archive. Only auto approves pending gates automatically; gates, copilot and step need a recorded approval. Policy changes keep earlier gate decisions and record actor, from, to and phase.
139
+ 2. step: the CLI controller runs one effect node at a time and pauses (pauseReason step) after each terminal outcome while work remains; resume with ares plan control <dir> resume --command-id <new-id> --expected-revision <revision>. MCP resume changes the same plan state but starts no controller.
140
+ 3. copilot: a producing phase in copilot mode makes its drafts usable only after ares gate approve <dir> accept:hypotheses|accept:paper|accept:reviews binds their current content hash. Source edits or new relevant journal entries make the accept pending again. Drafting and own-draft checks stay usable before acceptance; acceptance is a checkpoint, not scientific verification.
141
+ 4. Plain auto|gates studies keep study v1; object policies, copilot and step write study v2, which 0.1.0 refuses without changing the file. A plan node may declare phase; 0.1.0 refuses such plans the same way.
142
+
143
+ Study export
144
+
145
+ 1. ares study export <dir> --bundle <new-or-empty-dir-outside-the-study> [--list] writes manifest.json, ledger.jsonl, attempts.jsonl, results.json, reviews.jsonl and evidence.json from committed study files only, never the executor workdir. --list names the files and writes nothing.
146
+ 2. Identities are hashes; values are metrics, seeds, statuses, exit codes, durations, counts and closed enums. Paths, mounts, container ids, argv, env, image names (digests kept) and free text are dropped. The bundle includes content-free query-intent/review-section counts and distinct reuse source, executed/reused, fresh-evaluation and independent-sample projections; it never establishes claim support or a reuse benefit. A planted path, URL, NAME=value assignment or key-like token in any decoded key or string refuses the whole export and writes nothing; inspect the refused source, correct it through its producer workflow while preserving original evidence, then retry.
120
147
 
121
148
  Archive workflow
122
149
 
123
150
  ares lessons <dir> --for "archive the completed study"
124
151
 
125
- Archive is the last study step, after paper/review and skill decisions. Preview lists pending notes and a fingerprint over the full canonical derived note list. Confirm only the inspected fingerprint. Each call writes the first 200 pending notes and returns remaining; repeat the same confirmation for later batches or after a partial failure. Successful hashes/ids are receipted; exported notes are skipped. A changed source note invalidates confirmation. Fail notes retain recorded cause/retryWhen or not recorded; closed outcomes retain negative reasons; evidence is chunked into 16 refs without dropping attempts. Note text travels on stdin; amem option values starting -- receive one leading space for its parser. No raw stdout/stderr enters the study beyond returned ids.
152
+ Archive is the last study step, after paper/review and skill decisions. Preview lists pending notes and a fingerprint over the full canonical derived note list. Confirm only the inspected fingerprint. Each call writes a bounded prefix of at most 200 pending notes (harness lesson/source bounds may make it smaller) and returns remaining; repeat the same confirmation for later batches or after a partial failure. Successful hashes/ids are receipted; exported notes are skipped. After an interrupted/crashed archive, reconcile possible unreceipted amem writes with the owner before retrying; receipt-only recovery may duplicate and is not exactly-once. A changed source note invalidates confirmation. Fail notes retain recorded cause/retryWhen or not recorded; closed outcomes retain negative reasons; evidence is chunked into 16 refs without dropping attempts. Note text travels on stdin; amem option values starting -- receive one leading space for its parser. No raw stdout/stderr enters the study beyond returned ids.
126
153
 
127
154
  ares archive <dir>
128
155
  ares archive <dir> --confirm <fingerprint>
package/src/privacy.ts ADDED
@@ -0,0 +1,9 @@
1
+ /** Canonical URL and key-like markers for persisted text; path and env rules are caller-specific. */
2
+ const URL_KEY_SCANS: readonly (readonly [string, RegExp])[] = [
3
+ ["url", /\b[a-z][a-z0-9+.-]*:\/\/|\b(?:mailto|urn|file|data):/i],
4
+ ["key-like token", /\b(?:sk|pk|rk)[-_][A-Za-z0-9_-]{12,}|\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{12,}|\bxox[abprs]-[A-Za-z0-9-]{8,}|\bAKIA[0-9A-Z]{12,}|\beyJ[A-Za-z0-9_-]{16,}/],
5
+ ["key-like token", /(?<![A-Za-z0-9_-])(?=[A-Za-z0-9_-]*[A-Z])(?=[A-Za-z0-9_-]*[a-z])(?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]{32,}(?![A-Za-z0-9_-])/],
6
+ ];
7
+ export function urlOrKeyLike(value: string): string | undefined {
8
+ return URL_KEY_SCANS.find(([, pattern]) => pattern.test(value))?.[0];
9
+ }