@staix/agent-research 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +255 -24
  3. package/package.json +2 -2
  4. package/src/cli.ts +117 -10
  5. package/src/commands-table.ts +39 -8
  6. package/src/commands.ts +192 -32
  7. package/src/exp/attempts.ts +500 -65
  8. package/src/exp/executor.ts +235 -12
  9. package/src/exp/final.ts +1 -1
  10. package/src/exp/logs.ts +25 -12
  11. package/src/exp/metrics.ts +6 -5
  12. package/src/exp/pipeline.ts +92 -0
  13. package/src/exp/protocol.ts +85 -18
  14. package/src/exp/retention-script.ts +649 -0
  15. package/src/exp/retention.ts +70 -0
  16. package/src/exp/reuse-admission.ts +63 -0
  17. package/src/exp/reuse-contract.ts +48 -0
  18. package/src/exp/reuse-runtime.ts +87 -0
  19. package/src/exp/reuse.ts +87 -0
  20. package/src/exp/selection.ts +1 -1
  21. package/src/exp/snapshot.ts +3 -3
  22. package/src/exp/stages.ts +117 -0
  23. package/src/harness/experience-source.ts +34 -0
  24. package/src/harness/experience.ts +206 -0
  25. package/src/harness/hub-guidance.ts +140 -0
  26. package/src/harness/hub-reference.ts +18 -0
  27. package/src/harness/lesson-candidates.ts +162 -0
  28. package/src/harness/limits.ts +2 -0
  29. package/src/harness/privacy.ts +4 -0
  30. package/src/harness/receipts.ts +84 -0
  31. package/src/harness/rounds.ts +198 -0
  32. package/src/harness/transitions.ts +152 -0
  33. package/src/lit/candidates.ts +13 -5
  34. package/src/lit/cards.ts +55 -4
  35. package/src/lit/flow.ts +82 -0
  36. package/src/lit/queries.ts +62 -0
  37. package/src/manifest.ts +13 -6
  38. package/src/mcp-tools.ts +123 -25
  39. package/src/mcp.ts +4 -0
  40. package/src/memory/amem-show.ts +135 -0
  41. package/src/memory/amem.ts +3 -0
  42. package/src/memory/archive.ts +17 -8
  43. package/src/memory/evidence-local.ts +77 -0
  44. package/src/memory/evidence.ts +39 -0
  45. package/src/memory/lessons.ts +4 -2
  46. package/src/memory/skill-check.ts +56 -0
  47. package/src/memory/skill-format.ts +77 -0
  48. package/src/memory/skills.ts +72 -26
  49. package/src/memory/source-budget.ts +11 -0
  50. package/src/memory/vault-cards.ts +226 -0
  51. package/src/paper/build.ts +16 -7
  52. package/src/paper/check.ts +37 -10
  53. package/src/paper/headings.ts +39 -0
  54. package/src/paper/hygiene.ts +153 -0
  55. package/src/paper/placeholders.ts +16 -1
  56. package/src/paper/plan.ts +170 -0
  57. package/src/paper/point-evidence.ts +63 -0
  58. package/src/paper/points.ts +83 -0
  59. package/src/paper/review.ts +102 -9
  60. package/src/paper/scopes.ts +51 -0
  61. package/src/plan/definition.ts +5 -1
  62. package/src/plan/hub.ts +6 -0
  63. package/src/plan/state.ts +5 -0
  64. package/src/playbook.ts +35 -20
  65. package/src/privacy.ts +9 -0
  66. package/src/provenance.ts +679 -0
  67. package/src/scope.ts +24 -3
  68. package/src/study-export.ts +55 -27
  69. package/src/study.ts +54 -14
  70. package/src/ui/panel.css +4 -0
  71. package/src/ui/panel.js +263 -6
  72. package/src/ui/plugin.ts +68 -10
@@ -2,11 +2,35 @@ import { requireCopilotAccept, CopilotAcceptError } from "../copilot.ts";
2
2
  import { boundedText, commit, onlyKeys, openStudy, plain, readLedger, sha256, type Actor, type LedgerEvent } from "../study.ts";
3
3
  import { readCurrentBuild } from "./build.ts";
4
4
  import { checkPaper } from "./check.ts";
5
+ import { DEFAULT_PAPER_SETTINGS, readPaperSettings, readReviewSettings, type SurveyChecklistMode } from "./hygiene.ts";
5
6
  export const REVIEW_KINDS = ["contradiction", "unsupported-claim", "number", "citation", "method", "clarity", "other"] as const;
7
+ export const REPAIR_SCOPES = ["edit", "paragraph", "section"] as const;
8
+ export type RepairScope = typeof REPAIR_SCOPES[number];
9
+ export const OVER_BUDGET_ADVICE = "replan the section or ask a person";
10
+ /** Survey checklist questions, written for ares; answers are displayed and never gate. */
11
+ export const SURVEY_CHECKLIST = [
12
+ { key: "taxonomyPrinciple", question: "Does the survey state how it classifies the work, with one primary partition that does not mix unrelated axes?" },
13
+ { key: "noEnumeration", question: "Do the main sections relate neighbouring works to each other instead of summarizing one paper after another?" },
14
+ { key: "specificGaps", question: "Do the stated gaps and future directions follow from named mechanisms, trade-offs or limitations, and appear outside the conclusion too?" },
15
+ { key: "citationRelations", question: "When a claim cites several works together, does the text say how they relate (shared mechanism, contrast, lineage, boundary, trade-off, trend or limitation)?" },
16
+ { key: "selectionReported", question: "Is every corpus-level or 'systematic' claim backed by reported sources, queries, cutoff date, screening counts and inclusion criteria?" },
17
+ { key: "scopeControl", question: "Is adjacent material justified and kept subordinate to the stated topic?" },
18
+ ] as const;
19
+ export type SurveyKey = typeof SURVEY_CHECKLIST[number]["key"];
20
+ export type SurveyAnswers = Record<SurveyKey, boolean>;
21
+ const SURVEY_KEYS: SurveyKey[] = SURVEY_CHECKLIST.map(item => item.key);
22
+ export function reviewChecklist() { return { survey: SURVEY_CHECKLIST.map(item => ({ ...item })) }; }
23
+ /** Unset means show for survey studies and off for experiment studies. */
24
+ export function surveyChecklistMode(dir: string, mode: string): SurveyChecklistMode { return readReviewSettings(dir).surveyChecklist ?? (mode === "survey" ? "show" : "off"); }
25
+ export interface ReviewFinding { id: string; kind: typeof REVIEW_KINDS[number]; location: string; text: string; blocking: boolean; repair?: RepairScope; section?: string }
6
26
  export interface ReviewReport {
7
27
  v: 1; reviewer: { id: string; modelFamily: string }; buildSha256: string;
8
- checklist: { negativeResults: boolean; denominators: boolean; limitations: boolean; reproducibility: boolean };
9
- findings: { id: string; kind: typeof REVIEW_KINDS[number]; location: string; text: string; blocking: boolean }[];
28
+ checklist: { negativeResults: boolean; denominators: boolean; limitations: boolean; reproducibility: boolean; survey?: SurveyAnswers };
29
+ findings: ReviewFinding[];
30
+ }
31
+ export interface ReviewPointFindings {
32
+ point: string; open: number; blocking: number;
33
+ findings: { reviewId: string; findingId: string; kind: ReviewFinding["kind"]; blocking: boolean }[];
10
34
  }
11
35
  interface Resolution { reason: string; actor: Actor; at: string }
12
36
  interface ReviewRecord { id: string; report: ReviewReport; actor: Actor; at: string; resolutions: Record<string, Resolution> }
@@ -27,20 +51,29 @@ export function validateReview(raw: unknown, strict = true): ReviewReport {
27
51
  try {
28
52
  const value = object(raw, ["v", "reviewer", "buildSha256", "checklist", "findings"], "report", strict);
29
53
  if (value.v !== 1) throw new Error("review: unsupported report version; use an ares version that supports this report, keeping the original bytes unchanged");
30
- const reviewer = object(value.reviewer, ["id", "modelFamily"], "reviewer", strict), checklist = object(value.checklist, ["negativeResults", "denominators", "limitations", "reproducibility"], "checklist", strict);
54
+ const reviewer = object(value.reviewer, ["id", "modelFamily"], "reviewer", strict), checklist = object(value.checklist, ["negativeResults", "denominators", "limitations", "reproducibility", "survey"], "checklist", strict);
31
55
  const buildSha256 = text(value.buildSha256, "buildSha256", 64);
32
56
  if (!/^[a-f0-9]{64}$/.test(buildSha256)) bad("buildSha256 must be the 64-hex current evidence hash; run ares paper build");
33
57
  for (const name of ["negativeResults", "denominators", "limitations", "reproducibility"]) if (typeof checklist[name] !== "boolean") bad(`checklist.${name} must be a boolean`);
58
+ let survey: SurveyAnswers | undefined;
59
+ if (checklist.survey !== undefined) {
60
+ const block = object(checklist.survey, SURVEY_KEYS, "checklist.survey", strict);
61
+ for (const key of SURVEY_KEYS) if (typeof block[key] !== "boolean") bad(`checklist.survey.${key} must be a boolean; run ares review checklist for the six questions`);
62
+ survey = Object.fromEntries(SURVEY_KEYS.map(key => [key, block[key] as boolean])) as SurveyAnswers;
63
+ }
34
64
  if (!Array.isArray(value.findings) || value.findings.length > 200) bad("findings must be an array of at most 200 entries");
35
65
  const ids = new Set<string>();
36
66
  const findings = value.findings.map((raw, index) => {
37
- const finding = object(raw, ["id", "kind", "location", "text", "blocking"], `finding[${index}]`, strict), id = identifier(finding.id, `finding[${index}].id`);
67
+ const finding = object(raw, ["id", "kind", "location", "text", "blocking", "repair", "section"], `finding[${index}]`, strict), id = identifier(finding.id, `finding[${index}].id`);
38
68
  if (ids.has(id)) bad(`duplicate finding id ${id}`); ids.add(id);
39
69
  if (!REVIEW_KINDS.includes(finding.kind as typeof REVIEW_KINDS[number])) bad(`finding ${id} has unknown kind; use ${REVIEW_KINDS.join(", ")}`);
40
70
  if (typeof finding.blocking !== "boolean") bad(`finding ${id}.blocking must be a boolean`);
41
- return { id, kind: finding.kind as typeof REVIEW_KINDS[number], location: text(finding.location, `finding ${id}.location`), text: text(finding.text, `finding ${id}.text`), blocking: finding.kind === "contradiction" || finding.blocking };
71
+ if (finding.repair !== undefined && !REPAIR_SCOPES.includes(finding.repair as RepairScope)) bad(`finding ${id} has unknown repair scope; use ${REPAIR_SCOPES.join(", ")} or omit it for edit`);
72
+ // Optional fields are stored only when given, so reports without them keep their existing bytes.
73
+ return { id, kind: finding.kind as typeof REVIEW_KINDS[number], location: text(finding.location, `finding ${id}.location`), text: text(finding.text, `finding ${id}.text`), blocking: finding.kind === "contradiction" || finding.blocking,
74
+ ...(finding.repair !== undefined ? { repair: finding.repair as RepairScope } : {}), ...(finding.section !== undefined ? { section: text(finding.section, `finding ${id}.section`, 256).trim() } : {}) };
42
75
  });
43
- return { v: 1, reviewer: { id: text(reviewer.id, "reviewer.id", 128), modelFamily: text(reviewer.modelFamily, "reviewer.modelFamily", 128).trim().toLowerCase() }, buildSha256, checklist: { negativeResults: checklist.negativeResults as boolean, denominators: checklist.denominators as boolean, limitations: checklist.limitations as boolean, reproducibility: checklist.reproducibility as boolean }, findings };
76
+ return { v: 1, reviewer: { id: text(reviewer.id, "reviewer.id", 128), modelFamily: text(reviewer.modelFamily, "reviewer.modelFamily", 128).trim().toLowerCase() }, buildSha256, checklist: { negativeResults: checklist.negativeResults as boolean, denominators: checklist.denominators as boolean, limitations: checklist.limitations as boolean, reproducibility: checklist.reproducibility as boolean, ...(survey ? { survey } : {}) }, findings };
44
77
  } catch (error) {
45
78
  const message = error instanceof Error ? error.message : "invalid report";
46
79
  if (message.includes("; inspect ares review show") || message.includes("supports this report")) throw error;
@@ -64,9 +97,10 @@ export function foldReviews(events: LedgerEvent[]): ReviewRecord[] {
64
97
  }
65
98
  /** Caller holds the study lock; report ids are generated, findings never disappear by vote. */
66
99
  export function addReview(dirArg: string, raw: unknown, actor: Actor) {
67
- const { dir } = openStudy(dirArg);
100
+ const { dir, study } = openStudy(dirArg);
68
101
  requireCopilotAccept(dir, "paper");
69
102
  const report = validateReview(raw), current = readCurrentBuild(dir), events = readLedger(dir), rows = foldReviews(events);
103
+ if (!report.checklist.survey && surveyChecklistMode(dir, study.mode) === "require") bad("checklist.survey is required by study.toml [review] surveyChecklist = \"require\"; add the six survey answers listed by ares review checklist (false answers are allowed)");
70
104
  if (report.buildSha256 !== current.evidenceSha256) bad("stale buildSha256; use the evidenceSha256 from the current ares paper build output");
71
105
  if (rows.filter(row => row.report.buildSha256 === report.buildSha256).length >= 100) bad("100 reviews already recorded for this build; resolve existing findings or build a revised manuscript");
72
106
  const id = sha256(JSON.stringify([report, events.length])).slice(0, 16);
@@ -102,7 +136,7 @@ export function reviewBinding(dirArg: string): string | undefined {
102
136
  try { const { dir } = openStudy(dirArg), current = readCurrentBuild(dir), events = readLedger(dir); return binding(current, events, foldReviews(events)); } catch { return undefined; }
103
137
  }
104
138
  export function reviewReadiness(dirArg: string) {
105
- const { dir } = openStudy(dirArg), events = readLedger(dir), unmet: { code: string; message: string }[] = [];
139
+ const { dir, study } = openStudy(dirArg), events = readLedger(dir), unmet: { code: string; message: string }[] = [];
106
140
  for (const artifact of ["paper", "reviews"] as const) {
107
141
  try { requireCopilotAccept(dir, artifact); }
108
142
  catch (error) { unmet.push({ code: `accept:${artifact}`, message: error instanceof Error ? error.message : `copilot ${artifact} acceptance unavailable; inspect ares gate list` }); }
@@ -118,7 +152,66 @@ export function reviewReadiness(dirArg: string) {
118
152
  if (families.length < 2) unmet.push({ code: "model-families", message: "fewer than two distinct model families reviewed the current evidence hash; add current-build reviews from two families" });
119
153
  const openBlocking = reviews.flatMap(row => row.report.findings.filter(f => f.blocking && !row.resolutions[f.id]).map(f => ({ reviewId: row.id, findingId: f.id, kind: f.kind, location: f.location, text: f.text })));
120
154
  if (openBlocking.length) unmet.push({ code: "blocking-findings", message: `open blocking findings: ${openBlocking.map(f => `${f.reviewId}/${f.findingId} (${f.kind})`).join(", ")}; resolve each with a reason using ares review resolve` });
121
- return { ready: unmet.length === 0, buildSha256: buildSha256 ?? null, ...(current ? { manuscriptSha256: current.manuscriptSha256 } : {}), check: check ?? null, reviews, families, openBlocking, checklists: reviews.map(row => ({ reviewId: row.id, ...row.report.checklist })), claims: "unavailable (STAIxBWLB/agent-hub#931)", unmet };
155
+ const rounds = roundsView(dir, rows, buildSha256), survey = surveyView(dir, study.mode, reviews), points = pointView(reviews);
156
+ return { ready: unmet.length === 0, buildSha256: buildSha256 ?? null, ...(current ? { manuscriptSha256: current.manuscriptSha256 } : {}), check: check ?? null, reviews, families, openBlocking, ...points, checklists: reviews.map(row => { const { survey: answers, ...rest } = row.report.checklist; return { reviewId: row.id, ...rest, ...(survey.surveyChecklist === "off" || answers === undefined ? {} : { survey: answers }) }; }), claims: "unavailable (STAIxBWLB/agent-hub#931)", unmet, ...rounds, ...survey, info: [...rounds.info, ...survey.info] };
157
+ }
158
+ /** Exact location metadata only: no paper-plan lookup, support judgment or readiness change. */
159
+ function pointView(reviews: ReviewRecord[]): { openByPoint?: ReviewPointFindings[] } {
160
+ const groups = new Map<string, ReviewPointFindings["findings"]>();
161
+ let explicit = false;
162
+ for (const row of reviews) for (const finding of row.report.findings) {
163
+ const match = /^point:([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(finding.location.trim()), point = match?.[1];
164
+ if (point === undefined || point.length > 64) continue;
165
+ explicit = true;
166
+ if (row.resolutions[finding.id]) continue;
167
+ const findings = groups.get(point) ?? [];
168
+ findings.push({ reviewId: row.id, findingId: finding.id, kind: finding.kind, blocking: finding.blocking });
169
+ groups.set(point, findings);
170
+ }
171
+ if (!explicit) return {};
172
+ return { openByPoint: [...groups].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([point, findings]) => ({
173
+ point, open: findings.length, blocking: findings.filter(finding => finding.blocking).length, findings,
174
+ })) };
175
+ }
176
+ /** Display only: answers, including false ones, never enter unmet. Off hides the block and the projection; require is enforced at review add. */
177
+ function surveyView(dir: string, studyMode: string, reviews: ReviewRecord[]) {
178
+ let mode: SurveyChecklistMode, info: { code: string; message: string }[] = [];
179
+ try { mode = surveyChecklistMode(dir, studyMode); }
180
+ catch (error) {
181
+ mode = studyMode === "survey" ? "show" : "off";
182
+ info = [{ code: "review-survey-settings", message: `${error instanceof Error ? error.message : "study.toml unreadable"}; checklist display defaults to ${mode}` }];
183
+ }
184
+ if (mode === "off") return { surveyChecklist: mode, surveyAnswers: [], info };
185
+ return { surveyChecklist: mode, surveyAnswers: reviews.map(row => ({ reviewId: row.id, modelFamily: row.report.reviewer.modelFamily, survey: row.report.checklist.survey ?? null })), info };
186
+ }
187
+ /** Informational only: rounds never enter unmet, so the gate conditions are unchanged. */
188
+ function roundsView(dir: string, rows: ReviewRecord[], buildSha256: string | undefined) {
189
+ let budget = DEFAULT_PAPER_SETTINGS.reviewRounds, settingsError: string | undefined;
190
+ try { budget = readPaperSettings(dir).reviewRounds; } catch (error) { settingsError = error instanceof Error ? error.message : "study.toml unreadable"; }
191
+ const rounds = sectionRounds(rows, buildSha256, budget), info: { code: string; message: string }[] = [];
192
+ if (settingsError) info.push({ code: "review-rounds-settings", message: `${settingsError}; the default budget ${budget} is shown` });
193
+ for (const item of rounds.overBudget) info.push({ code: "review-rounds", message: `section "${item.section.slice(0, 80)}" used ${item.rounds} review rounds, over the budget of ${budget}; ${OVER_BUDGET_ADVICE}` });
194
+ return { roundBudget: budget, sections: rounds.sections, openBySection: rounds.openBySection, overBudget: rounds.overBudget, info };
195
+ }
196
+ const scope = (finding: ReviewFinding): RepairScope => finding.repair ?? "edit";
197
+ /** Rounds: reports with at least one finding for a section, across all evidence hashes. Pass: no open finding for it at the current hash. */
198
+ export function sectionRounds(rows: ReviewRecord[], buildSha256: string | undefined, budget: number) {
199
+ const rounds = new Map<string, number>(), open = new Map<string | null, { reviewId: string; findingId: string; kind: string; blocking: boolean; repair: RepairScope }[]>();
200
+ for (const row of rows) {
201
+ for (const section of new Set(row.report.findings.flatMap(f => f.section === undefined ? [] : [f.section]))) rounds.set(section, (rounds.get(section) ?? 0) + 1);
202
+ if (row.report.buildSha256 !== buildSha256) continue;
203
+ for (const f of row.report.findings) if (!row.resolutions[f.id]) {
204
+ const key = f.section ?? null, list = open.get(key) ?? [];
205
+ list.push({ reviewId: row.id, findingId: f.id, kind: f.kind, blocking: f.blocking, repair: scope(f) }); open.set(key, list);
206
+ }
207
+ }
208
+ const sections = [...rounds].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([section, count]) => ({ section, rounds: count, pass: !(open.get(section)?.length), overBudget: count > budget }));
209
+ const openBySection = [...open].sort(([a], [b]) => a === null ? 1 : b === null ? -1 : a < b ? -1 : 1).map(([section, findings]) => {
210
+ const byRepair: Record<RepairScope, typeof findings> = { edit: [], paragraph: [], section: [] };
211
+ for (const f of findings) byRepair[f.repair].push(f);
212
+ return { section, rounds: section === null ? null : rounds.get(section) ?? 0, byRepair };
213
+ });
214
+ return { sections, openBySection, overBudget: sections.filter(s => s.overBudget).map(s => ({ section: s.section, rounds: s.rounds, advice: OVER_BUDGET_ADVICE })) };
122
215
  }
123
216
  export function requireReviewReady(dir: string): void {
124
217
  const report = reviewReadiness(dir), accept = report.unmet.find(item => item.code.startsWith("accept:") || item.code === "accept-source");
@@ -0,0 +1,51 @@
1
+ import { citationOccurrences } from "../lit/cite.ts";
2
+ import { isVerified, type Candidate } from "../lit/candidates.ts";
3
+ import { markdownHeadings } from "./headings.ts";
4
+ import type { PaperPlan } from "./plan.ts";
5
+
6
+ export const SCOPE_CODES = ["out-of-scope-citation", "unplanned-section", "unrouted-reference"] as const;
7
+ export type ScopeFindingCode = typeof SCOPE_CODES[number];
8
+ export interface PaperPlanHit {
9
+ code: ScopeFindingCode;
10
+ severity: "blocking" | "warning";
11
+ section?: string[];
12
+ sectionId?: string;
13
+ start: number;
14
+ end: number;
15
+ message: string;
16
+ }
17
+
18
+ /** Literal routing only. citationText must preserve the original manuscript's UTF-16 offsets. */
19
+ export function paperPlanFindings(manuscript: string, headingHidden: Uint8Array, citationText: string, plan: PaperPlan, candidates: Candidate[]): PaperPlanHit[] {
20
+ if (citationText.length !== manuscript.length) throw new Error("paper citation scopes: masked citation text changed source offsets; pass offset-preserving citationText before checking the plan");
21
+ const headings = markdownHeadings(manuscript, headingHidden), hits: PaperPlanHit[] = [];
22
+ const sections = new Map(plan.sections.map(section => [section.heading, {id: section.id, cites: new Set(section.cites)}]));
23
+ const routed = new Set(plan.sections.flatMap(section => section.cites));
24
+ for (const heading of headings) if (heading.level === 2 && !sections.has(heading.rawText)) hits.push({
25
+ code: "unplanned-section", severity: "warning", section: heading.path, start: heading.start, end: heading.end,
26
+ message: "level-2 heading is not declared in the paper plan; add its intended section with paper plan set or revise the manuscript heading",
27
+ });
28
+ let cursor = 0, scope: {id: string; cites: Set<string>} | undefined, section: string[] = [];
29
+ for (const citation of citationOccurrences(citationText)) {
30
+ while (cursor < headings.length && headings[cursor]!.start <= citation.start) {
31
+ const heading = headings[cursor++]!;
32
+ section = heading.path;
33
+ const boundary = sections.get(heading.rawText);
34
+ if (boundary) scope = boundary;
35
+ }
36
+ if (scope && !scope.cites.has(citation.key)) hits.push({
37
+ code: "out-of-scope-citation", severity: "blocking", section, sectionId: scope.id, start: citation.start, end: citation.end,
38
+ message: `citation @${citation.key.slice(0, 80)} is outside section ${scope.id}'s declared scope; route the verified reference explicitly with paper plan set or revise this citation`,
39
+ });
40
+ }
41
+ const seen = new Set<string>();
42
+ for (const candidate of candidates) {
43
+ if (candidate.status !== "included" || seen.has(candidate.id)) continue;
44
+ seen.add(candidate.id);
45
+ const key = typeof candidate.citekey === "string" ? candidate.citekey : undefined;
46
+ if (key && routed.has(key) && isVerified(candidate)) continue;
47
+ hits.push({code: "unrouted-reference", severity: "warning", start: 0, end: 0,
48
+ message: `included reference ${(key ?? candidate.id).slice(0, 80)} has no valid section routing; verify it and assign its key explicitly with paper plan set`});
49
+ }
50
+ return hits.sort((a, b) => a.start - b.start || a.code.localeCompare(b.code));
51
+ }
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { validatePhase, type Phase } from "../autonomy.ts";
4
4
  import { COMMANDS } from "../commands-table.ts";
5
+ import { validateIntent } from "../lit/queries.ts";
5
6
  import { boundedText, commit, onlyKeys, plain, readJsonFile, sha256, type Actor } from "../study.ts";
6
7
 
7
8
  export const PLAN_BYTES = 65_536, PLAN_ID_BYTES = 128;
@@ -39,6 +40,7 @@ function stepArgs(raw: unknown, command: StepCommand, id: string): StepArgs {
39
40
  if (Buffer.byteLength(query) > 1000) throw new Error(`${field}: at most 1000 bytes`);
40
41
  args[key] = query; continue;
41
42
  }
43
+ if (command === "lit.search" && key === "intent") { args[key] = validateIntent(value, field); continue; }
42
44
  if (command === "cite.check" && key === "draft") {
43
45
  args[key] = boundedText(value, field, 4096); continue;
44
46
  }
@@ -159,7 +161,9 @@ export function readPlan(dir: string): PlanDefinition | undefined {
159
161
  }
160
162
  /** Caller holds the study lock; definition and initial state share one transaction. */
161
163
  export function setPlan(dir: string, raw: unknown, actor: Actor) {
162
- const definition = validatePlan(raw), previous = readPlan(dir);
164
+ const definition = validatePlan(raw);
165
+ for (const node of definition.nodes) if (node.kind === "step" && node.command === "attempt.run" && node.args.reuse !== undefined && node.args.reuse !== "off" && node.args.reuse !== "eligible") throw new Error(`plan step ${node.id} (attempt.run).args.reuse: off or eligible required; correct args.reuse and run ares plan set again`);
166
+ const previous = readPlan(dir);
163
167
  definition.revision = (previous?.revision ?? 0) + 1;
164
168
  if (!Number.isSafeInteger(definition.revision)) throw new Error("plan.revision: exhausted; create a new study before setting another plan");
165
169
  const text = JSON.stringify(definition, null, 2) + "\n";
package/src/plan/hub.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import {realHubProbeUnavailable} from "../harness/receipts.ts";
1
2
  import { isAbsolute, resolve } from "node:path";
2
3
  import { spawnRunner, type ProcessRunner } from "../exp/executor.ts";
3
4
  import { plain, sha256, type LedgerEvent } from "../study.ts";
@@ -54,3 +55,8 @@ export function createHubClient(project: string, runner: ProcessRunner = spawnRu
54
55
  export function boundHubTask(events: LedgerEvent[], revision: number, node: string): number | undefined {
55
56
  return events.find(e => (e.type === "node.intent" || e.type === "node.observed") && e.data.revision === revision && e.data.node === node && task(e.data.taskId))?.data.taskId as number | undefined;
56
57
  }
58
+
59
+ /** Producer #1225/#1226 has not shipped an admitted receipt reader; no guessed CLI or wire fallback. */
60
+ export async function readHarnessProbeSource(_address: unknown) {
61
+ return realHubProbeUnavailable(_address);
62
+ }
package/src/plan/state.ts CHANGED
@@ -205,6 +205,11 @@ export function foldPlan(events: LedgerEvent[], onEvent?: (state: PlanState, eve
205
205
  node.taskId = d.taskId as number;
206
206
  }
207
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
+ }
208
213
  node.status = d.status as NodeStatus;
209
214
  if (node.status === "done" && d.output !== undefined) node.output = d.output;
210
215
  delete node.reason;
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
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 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.
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,7 +131,7 @@ 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.
120
135
 
121
136
  Autonomy policy
122
137
 
@@ -128,13 +143,13 @@ Autonomy policy
128
143
  Study export
129
144
 
130
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.
131
- 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. A planted path, URL, NAME=value assignment or key-like token in any decoded key or string refuses the whole export and writes nothing; remove it from the study record and retry.
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.
132
147
 
133
148
  Archive workflow
134
149
 
135
150
  ares lessons <dir> --for "archive the completed study"
136
151
 
137
- 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.
138
153
 
139
154
  ares archive <dir>
140
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
+ }