@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
@@ -1,11 +1,36 @@
1
+ import { requireCopilotAccept, CopilotAcceptError } from "../copilot.ts";
1
2
  import { boundedText, commit, onlyKeys, openStudy, plain, readLedger, sha256, type Actor, type LedgerEvent } from "../study.ts";
2
3
  import { readCurrentBuild } from "./build.ts";
3
4
  import { checkPaper } from "./check.ts";
5
+ import { DEFAULT_PAPER_SETTINGS, readPaperSettings, readReviewSettings, type SurveyChecklistMode } from "./hygiene.ts";
4
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 }
5
26
  export interface ReviewReport {
6
27
  v: 1; reviewer: { id: string; modelFamily: string }; buildSha256: string;
7
- checklist: { negativeResults: boolean; denominators: boolean; limitations: boolean; reproducibility: boolean };
8
- 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 }[];
9
34
  }
10
35
  interface Resolution { reason: string; actor: Actor; at: string }
11
36
  interface ReviewRecord { id: string; report: ReviewReport; actor: Actor; at: string; resolutions: Record<string, Resolution> }
@@ -26,20 +51,29 @@ export function validateReview(raw: unknown, strict = true): ReviewReport {
26
51
  try {
27
52
  const value = object(raw, ["v", "reviewer", "buildSha256", "checklist", "findings"], "report", strict);
28
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");
29
- 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);
30
55
  const buildSha256 = text(value.buildSha256, "buildSha256", 64);
31
56
  if (!/^[a-f0-9]{64}$/.test(buildSha256)) bad("buildSha256 must be the 64-hex current evidence hash; run ares paper build");
32
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
+ }
33
64
  if (!Array.isArray(value.findings) || value.findings.length > 200) bad("findings must be an array of at most 200 entries");
34
65
  const ids = new Set<string>();
35
66
  const findings = value.findings.map((raw, index) => {
36
- 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`);
37
68
  if (ids.has(id)) bad(`duplicate finding id ${id}`); ids.add(id);
38
69
  if (!REVIEW_KINDS.includes(finding.kind as typeof REVIEW_KINDS[number])) bad(`finding ${id} has unknown kind; use ${REVIEW_KINDS.join(", ")}`);
39
70
  if (typeof finding.blocking !== "boolean") bad(`finding ${id}.blocking must be a boolean`);
40
- 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() } : {}) };
41
75
  });
42
- 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 };
43
77
  } catch (error) {
44
78
  const message = error instanceof Error ? error.message : "invalid report";
45
79
  if (message.includes("; inspect ares review show") || message.includes("supports this report")) throw error;
@@ -63,7 +97,10 @@ export function foldReviews(events: LedgerEvent[]): ReviewRecord[] {
63
97
  }
64
98
  /** Caller holds the study lock; report ids are generated, findings never disappear by vote. */
65
99
  export function addReview(dirArg: string, raw: unknown, actor: Actor) {
66
- const { dir } = openStudy(dirArg), report = validateReview(raw), current = readCurrentBuild(dir), events = readLedger(dir), rows = foldReviews(events);
100
+ const { dir, study } = openStudy(dirArg);
101
+ requireCopilotAccept(dir, "paper");
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)");
67
104
  if (report.buildSha256 !== current.evidenceSha256) bad("stale buildSha256; use the evidenceSha256 from the current ares paper build output");
68
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");
69
106
  const id = sha256(JSON.stringify([report, events.length])).slice(0, 16);
@@ -73,7 +110,9 @@ export function addReview(dirArg: string, raw: unknown, actor: Actor) {
73
110
  commit(dir, [], [{ actor, type: "review.added", data: { id, review: report } }]); return { id, ...report };
74
111
  }
75
112
  export function resolveReview(dirArg: string, target: string, reason: string, actor: Actor) {
76
- const { dir } = openStudy(dirArg), parts = target.split("/");
113
+ const { dir } = openStudy(dirArg);
114
+ requireCopilotAccept(dir, "paper");
115
+ const parts = target.split("/");
77
116
  if (parts.length !== 2) bad("resolution target must be <review-id>/<finding-id>; use ids from ares review show");
78
117
  const reviewId = identifier(parts[0], "review id"), findingId = identifier(parts[1], "finding id"), why = text(reason, "resolution reason"), row = foldReviews(readLedger(dir)).find(row => row.id === reviewId);
79
118
  if (!row) bad(`unknown review ${reviewId}`);
@@ -97,10 +136,15 @@ export function reviewBinding(dirArg: string): string | undefined {
97
136
  try { const { dir } = openStudy(dirArg), current = readCurrentBuild(dir), events = readLedger(dir); return binding(current, events, foldReviews(events)); } catch { return undefined; }
98
137
  }
99
138
  export function reviewReadiness(dirArg: string) {
100
- 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 }[] = [];
140
+ for (const artifact of ["paper", "reviews"] as const) {
141
+ try { requireCopilotAccept(dir, artifact); }
142
+ catch (error) { unmet.push({ code: `accept:${artifact}`, message: error instanceof Error ? error.message : `copilot ${artifact} acceptance unavailable; inspect ares gate list` }); }
143
+ }
101
144
  let current: ReturnType<typeof readCurrentBuild> | undefined, check: ReturnType<typeof checkPaper> | undefined;
102
145
  try { current = readCurrentBuild(dir); check = current.check; } catch (error) { unmet.push({ code: "build", message: error instanceof Error ? error.message : "current build unavailable; run ares paper build" }); }
103
146
  if (!check) { try { check = checkPaper(dir); } catch (error) { unmet.push({ code: "paper-check", message: error instanceof Error ? error.message : "paper check unavailable; restore paper/manuscript.md" }); } }
147
+ for (const finding of check?.findings ?? []) if (finding.code === "unaccepted-draft" && !unmet.some(item => item.code === "accept-source" && item.message === finding.message)) unmet.unshift({ code: "accept-source", message: finding.message });
104
148
  if (check && !check.ok) unmet.push({ code: "paper-check", message: `paper check has ${check.findings.length} finding(s); run ares paper check --json and fix every finding` });
105
149
  let rows: ReviewRecord[] = [];
106
150
  try { rows = foldReviews(events); } catch (error) { unmet.push({ code: "review-journal", message: error instanceof Error ? error.message : "review journal invalid; restore its valid events" }); }
@@ -108,8 +152,69 @@ export function reviewReadiness(dirArg: string) {
108
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" });
109
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 })));
110
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` });
111
- 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 })) };
112
215
  }
113
216
  export function requireReviewReady(dir: string): void {
114
- const report = reviewReadiness(dir); if (!report.ready) throw new Error(`gate review: ${report.unmet.map(item => `${item.code}: ${item.message}`).join("; ")}; inspect ares review show before approval`);
217
+ const report = reviewReadiness(dir), accept = report.unmet.find(item => item.code.startsWith("accept:") || item.code === "accept-source");
218
+ if (accept) throw new CopilotAcceptError(accept.message);
219
+ if (!report.ready) throw new Error(`gate review: ${report.unmet.map(item => `${item.code}: ${item.message}`).join("; ")}; inspect ares review show before approval`);
115
220
  }
@@ -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
+ }
@@ -1,7 +1,9 @@
1
+ import { CopilotAcceptError } from "../copilot.ts";
1
2
  import { boundHubTask, type HubClient, type HubObservation } from "./hub.ts";
2
- import { assertPlanOwner, commit, openStudy, readLedger, requireGate, withLock, withPlanLock, StudyLockBusyError, type Actor, type PendingEvent, type PlanOwner } from "../study.ts";
3
- import { canonical, nextDispatchId, planGateBinding, readPlanState, type NodeState, type PlanState } from "./state.ts";
4
- import type { PlanNode } from "./definition.ts";
3
+ import { assertPlanOwner, commit, openStudy, readLedger, prepareCommit, requireGate, withLock, withPlanLock, StudyLockBusyError, type Actor, type PendingEvent, type PlanOwner } from "../study.ts";
4
+ import { canonical, foldPlan, hasRemainingWork, TERMINAL_NODE_STATUSES, nextDispatchId, planGateBinding, readPlanState, type NodeState, type PlanState } from "./state.ts";
5
+ import { guardedPlanPhase, type PlanNode } from "./definition.ts";
6
+ import { resolveAutonomy, resolvePhaseAutonomy, type Autonomy } from "../autonomy.ts";
5
7
 
6
8
  export type StepNode = Extract<PlanNode, { kind: "step" }>;
7
9
  export type HubNode = Extract<PlanNode, { kind: "hub" }>;
@@ -36,7 +38,7 @@ async function transaction<T>(dir: string, fn: () => T): Promise<T> {
36
38
  }
37
39
  /** One controller, short transactional study locks, and no replay of unobserved actions. */
38
40
  export async function runPlan(dirArg: string, options: ControllerOptions, runtime: ControllerRuntime): Promise<PlanState> {
39
- const { dir, study } = openStudy(dirArg), parallel = options.parallel ?? 1;
41
+ const { dir } = openStudy(dirArg), parallel = options.parallel ?? 1;
40
42
  if (!Number.isSafeInteger(parallel) || parallel < 1 || parallel > 8) throw new Error("run --parallel: integer in 1..8 required; run ares run <dir> --parallel 1..8");
41
43
  return withPlanLock(dir, async owner => {
42
44
  const state = () => readPlanState(dir, readLedger(dir));
@@ -56,10 +58,20 @@ export async function runPlan(dirArg: string, options: ControllerOptions, runtim
56
58
  if (!target || target.dispatchId !== node.dispatchId || !["dispatched", "uncertain"].includes(target.status)) return;
57
59
  if (observation.status === "dispatched" && target.lastObserved?.dispatchId === node.dispatchId && target.reason === observation.reason && (observation.taskId === undefined || target.taskId === observation.taskId) && (observation.hubProject === undefined || target.hubProject === observation.hubProject)) return;
58
60
  return locked(() => {
59
- const current = state(), target = current.nodes.find(n => n.id === node.id);
61
+ const ledger = readLedger(dir), current = readPlanState(dir, ledger), target = current.nodes.find(n => n.id === node.id);
60
62
  if (!target || target.dispatchId !== node.dispatchId || !["dispatched", "uncertain"].includes(target.status)) return;
61
63
  if (observation.status === "dispatched" && target.status === "dispatched" && target.lastObserved && target.lastObserved.dispatchId === node.dispatchId && target.lastObserved.status === "dispatched" && target.reason === observation.reason && (observation.taskId === undefined || target.taskId === observation.taskId) && (observation.hubProject === undefined || target.hubProject === observation.hubProject)) return;
62
- commit(dir, [], [{ actor: runtime.actor, type: "node.observed", data: { revision: current.revision, node: node.id, dispatchId: node.dispatchId, status: observation.status, ...(observation.output !== undefined ? { output: observation.output } : {}), ...(observation.reason !== undefined ? { reason: observation.reason } : {}), ...(observation.taskId !== undefined ? { taskId: observation.taskId } : {}), ...(observation.hubProject !== undefined ? { hubProject: observation.hubProject } : {}) } }]);
64
+ const events: PendingEvent[] = [{ actor: runtime.actor, type: "node.observed", data: { revision: current.revision, node: node.id, dispatchId: node.dispatchId, status: observation.status, ...(observation.output !== undefined ? { output: observation.output } : {}), ...(observation.reason !== undefined ? { reason: observation.reason } : {}), ...(observation.taskId !== undefined ? { taskId: observation.taskId } : {}), ...(observation.hubProject !== undefined ? { hubProject: observation.hubProject } : {}) } }];
65
+ const definition = current.definition.nodes.find(value => value.id === node.id)!;
66
+ if (definition.kind !== "gate" && nodeMode(openStudy(dir).study.autonomy, definition) === "step") {
67
+ const next = foldPlan([...ledger, ...prepareCommit(dir, [], events).events])!;
68
+ // A hub binding conflict can turn a dispatched observation into a terminal failure in the fold.
69
+ if (TERMINAL_NODE_STATUSES.includes(next.nodes.find(value => value.id === node.id)!.status)) {
70
+ events[0]!.data.step = true; // Preserve the completion-time policy when replaying terminal failure.
71
+ if (hasRemainingWork(next)) events.push({ actor: runtime.actor, type: "plan.paused", data: { revision: current.revision, reason: "step", node: node.id, dispatchId: node.dispatchId } });
72
+ }
73
+ }
74
+ commit(dir, [], events);
63
75
  });
64
76
  };
65
77
  const reconcile = async (node: NodeState): Promise<void> => {
@@ -93,6 +105,7 @@ export async function runPlan(dirArg: string, options: ControllerOptions, runtim
93
105
  try { observation = await runtime.execute(definition, node); break; }
94
106
  catch (error) {
95
107
  if (error instanceof StudyLockBusyError) { await sleep(wait); wait = Math.min(wait * 2, 30_000); continue; }
108
+ if (error instanceof CopilotAcceptError) { observation = { status: "failed", reason: error.message }; break; }
96
109
  if (definition.command === "attempt.run") { await reconcile(node); return; }
97
110
  observation = { status: "uncertain", reason: "step execution interrupted or failed without an observable result; inspect inputs, then retry or skip this node" }; break;
98
111
  }
@@ -107,15 +120,20 @@ export async function runPlan(dirArg: string, options: ControllerOptions, runtim
107
120
  try {
108
121
  while (!runtime.signal?.aborted) {
109
122
  let current = state();
110
- if (current.state === "done") break;
123
+ if (current.state === "done" || current.state === "failed") break;
111
124
  if (current.state === "running") {
112
125
  // Pending auto gates are approved only inside a successful controller transaction.
113
- if (study.autonomy === "auto" && current.nodes.some(n => n.kind === "gate" && n.status === "pending" && n.gate?.state === "pending")) await tryTransaction(dir, () => {
126
+ const pendingGates = current.nodes.filter(n => n.kind === "gate" && n.status === "pending" && n.gate?.state === "pending");
127
+ // Advisory read avoids contending with manual approvals; the transaction still rechecks fresh policy.
128
+ const policy = pendingGates.length ? openStudy(dir).study.autonomy : undefined;
129
+ if (policy !== undefined && pendingGates.some(gate => resolveAutonomy(policy, `plan:${gate.id}`, guardedPlanPhase(current.definition, `plan:${gate.id}`)) === "auto")) await tryTransaction(dir, () => {
114
130
  assertPlanOwner(dir, owner);
115
131
  const events = readLedger(dir), value = readPlanState(dir, events), approvals: PendingEvent[] = [];
132
+ const { study } = openStudy(dir);
116
133
  if (value.state !== "running") return;
117
134
  for (const gate of value.nodes.filter(n => n.kind === "gate" && n.status === "pending" && n.gate?.state === "pending")) {
118
- if (study.autonomy === "auto") approvals.push(...requireGate(dir, study, `plan:${gate.id}`, name => planGateBinding(value, name)));
135
+ const name = `plan:${gate.id}` as const, phase = guardedPlanPhase(value.definition, name);
136
+ if (resolveAutonomy(study.autonomy, name, phase) === "auto") approvals.push(...requireGate(dir, study, name, gateName => planGateBinding(value, gateName), phase));
119
137
  }
120
138
  if (approvals.length) commit(dir, [], [...approvals, { actor: runtime.actor, type: "plan.gates", data: { revision: value.revision } }]);
121
139
  });
@@ -124,6 +142,7 @@ export async function runPlan(dirArg: string, options: ControllerOptions, runtim
124
142
  if (runtime.signal?.aborted || current.state !== "running") break;
125
143
  const definition = current.definition.nodes.find(n => n.id === node.id)!;
126
144
  if (node.status !== "ready" || active.has(node.id)) continue;
145
+ if (!modeAllowsAdmission(current, openStudy(dir).study.autonomy, definition)) continue;
127
146
  if (definition.kind === "hub" && runtime.hub) {
128
147
  const binding = boundHubTask(readLedger(dir), current.revision, node.id);
129
148
  let result: HubObservation;
@@ -140,10 +159,10 @@ export async function runPlan(dirArg: string, options: ControllerOptions, runtim
140
159
  if (definition.command === "attempt.run" && current.nodes.some(n => n.status === "dispatched" && current.definition.nodes.find(d => d.id === n.id)?.kind === "step" && (current.definition.nodes.find(d => d.id === n.id) as StepNode).command === "attempt.run")) continue;
141
160
  let prepared: { attemptId?: string };
142
161
  try { prepared = await runtime.prepare(definition, node); }
143
- catch { // Preparation is read-only; still record a correlated failed dispatch for visibility.
162
+ catch (error) { // Preparation is read-only; still record a correlated failed dispatch for visibility.
144
163
  prepared = {};
145
164
  const intent = await admit(dir, owner, runtime.actor, current, node, definition, prepared, parallel);
146
- if (intent) await observe(intent, { status: "failed", reason: "step preparation failed; check command inputs and retry this node" });
165
+ if (intent) await observe(intent, { status: "failed", reason: error instanceof CopilotAcceptError ? error.message : "step preparation failed; check command inputs and retry this node" });
147
166
  current = state(); continue;
148
167
  }
149
168
  const intent = await admit(dir, owner, runtime.actor, current, node, definition, prepared, parallel);
@@ -155,7 +174,7 @@ export async function runPlan(dirArg: string, options: ControllerOptions, runtim
155
174
  for (const node of state().nodes.filter(n => n.status === "dispatched" && !active.has(n.id))) {
156
175
  if (clock() >= (polls.get(node.dispatchId!)?.at ?? 0)) await reconcile(node);
157
176
  }
158
- if (state().state === "done") break;
177
+ if (["done", "failed"].includes(state().state)) break;
159
178
  const next = canonical(state());
160
179
  wait = next === fingerprint ? Math.min(wait * 2, 30_000) : 1000; fingerprint = next;
161
180
  const live = new Set(state().nodes.filter(n => n.status === "dispatched").map(n => n.dispatchId));
@@ -180,6 +199,7 @@ async function admit(dir: string, owner: PlanOwner, actor: Actor, snapshot: Plan
180
199
  assertPlanOwner(dir, owner);
181
200
  const current = readPlanState(dir, readLedger(dir)), target = current.nodes.find(n => n.id === node.id);
182
201
  if (current.state !== "running" || current.revision !== snapshot.revision || target?.status !== "ready" || canonical(current.definition.nodes.find(n => n.id === node.id)) !== canonical(definition) || (definition.kind === "step" && stepSlots(current) >= parallel)) return undefined;
202
+ if (!modeAllowsAdmission(current, openStudy(dir).study.autonomy, definition)) return undefined;
183
203
  const dispatchId = nextDispatchId(current, node.id);
184
204
  commit(dir, [], [{ actor, type: "node.intent", data: { revision: current.revision, node: node.id, dispatchId, ...prepared } }]);
185
205
  return readPlanState(dir, readLedger(dir)).nodes.find(n => n.id === node.id)!;
@@ -190,3 +210,13 @@ async function admit(dir: string, owner: PlanOwner, actor: Actor, snapshot: Plan
190
210
  function stepSlots(state: PlanState): number {
191
211
  return state.nodes.filter(n => n.kind === "step" && n.status === "dispatched").length;
192
212
  }
213
+
214
+ function nodeMode(policy: Autonomy, node: PlanNode) {
215
+ return resolvePhaseAutonomy(policy, node.kind === "hub" ? undefined : node.phase);
216
+ }
217
+ /** Step effects are exclusive even when ordinary steps may run in parallel. */
218
+ function modeAllowsAdmission(state: PlanState, policy: Autonomy, next: PlanNode): boolean {
219
+ const active = state.nodes.filter(node => node.status === "dispatched" && node.kind !== "gate");
220
+ if (active.some(node => nodeMode(policy, state.definition.nodes.find(value => value.id === node.id)!) === "step")) return false;
221
+ return nodeMode(policy, next) !== "step" || active.length === 0;
222
+ }
@@ -1,13 +1,15 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { validatePhase, type Phase } from "../autonomy.ts";
3
4
  import { COMMANDS } from "../commands-table.ts";
5
+ import { validateIntent } from "../lit/queries.ts";
4
6
  import { boundedText, commit, onlyKeys, plain, readJsonFile, sha256, type Actor } from "../study.ts";
5
7
 
6
8
  export const PLAN_BYTES = 65_536, PLAN_ID_BYTES = 128;
7
9
  export const STEP_COMMANDS = ["lit.search", "lit.verify", "lit.bib", "cite.check", "attempt.run", "investigate.close", "ablate.close", "final.close", "paper.build", "watch.run"] as const;
8
10
  export type StepCommand = typeof STEP_COMMANDS[number];
9
11
  export type StepArgs = Record<string, string | number | boolean | string[]>;
10
- type BaseNode = { id: string; needs: string[] };
12
+ type BaseNode = { id: string; needs: string[]; phase?: Phase };
11
13
  export type PlanNode = BaseNode & (
12
14
  { kind: "step"; command: StepCommand; args: StepArgs } |
13
15
  { kind: "hub"; campaign: string; unit: string } |
@@ -38,6 +40,7 @@ function stepArgs(raw: unknown, command: StepCommand, id: string): StepArgs {
38
40
  if (Buffer.byteLength(query) > 1000) throw new Error(`${field}: at most 1000 bytes`);
39
41
  args[key] = query; continue;
40
42
  }
43
+ if (command === "lit.search" && key === "intent") { args[key] = validateIntent(value, field); continue; }
41
44
  if (command === "cite.check" && key === "draft") {
42
45
  args[key] = boundedText(value, field, 4096); continue;
43
46
  }
@@ -74,20 +77,20 @@ function validateDefinition(raw: unknown): PlanDefinition {
74
77
  const nodes: PlanNode[] = raw.nodes.map((n: unknown, index: number) => {
75
78
  if (!plain(n)) throw new Error(`plan node[${index}]: object required`);
76
79
  const id = nodeId(n.id, `plan node[${index}].id`), needs = n.needs === undefined ? [] : references(n.needs, `plan node ${String(n.id)}.needs`);
77
- const base = { id, needs };
80
+ const base = { id, needs, ...(n.phase === undefined ? {} : { phase: validatePhase(n.phase) }) };
78
81
  switch (n.kind) {
79
82
  case "step": {
80
- onlyKeys(n, ["id", "kind", "needs", "command", "args"], `plan step ${id}`);
83
+ onlyKeys(n, ["id", "kind", "needs", "phase", "command", "args"], `plan step ${id}`);
81
84
  if (!STEP_COMMANDS.includes(n.command as StepCommand)) throw new Error(`plan step ${id}: unknown command ${String(n.command)} (allowed: ${STEP_COMMANDS.join(", ")})`);
82
85
  const command = n.command as StepCommand;
83
86
  return { ...base, kind: "step", command, args: stepArgs(n.args ?? {}, command, id) };
84
87
  }
85
88
  case "hub": {
86
- onlyKeys(n, ["id", "kind", "needs", "campaign", "unit"], `plan hub ${id}`);
89
+ onlyKeys(n, ["id", "kind", "needs", "phase", "campaign", "unit"], `plan hub ${id}`);
87
90
  return { ...base, kind: "hub", campaign: nodeId(n.campaign, `plan hub ${id}.campaign`), unit: nodeId(n.unit, `plan hub ${id}.unit`) };
88
91
  }
89
92
  case "gate":
90
- onlyKeys(n, ["id", "kind", "needs", "binds"], `plan gate ${id}`);
93
+ onlyKeys(n, ["id", "kind", "needs", "phase", "binds"], `plan gate ${id}`);
91
94
  return { ...base, kind: "gate", binds: references(n.binds, `plan gate ${id}.binds`) };
92
95
  default: throw new Error(`plan node ${id}: unknown node kind ${String(n.kind)}; ${compatible}`);
93
96
  }
@@ -137,6 +140,17 @@ function validateDefinition(raw: unknown): PlanDefinition {
137
140
  if (Buffer.byteLength(JSON.stringify(result, null, 2) + "\n") > PLAN_BYTES) throw new Error(`plan: exceeds ${PLAN_BYTES} bytes`);
138
141
  return result;
139
142
  }
143
+ /** A plan gate inherits only one explicitly declared phase shared by all immediate targets. */
144
+ export function guardedPlanPhase(definition: PlanDefinition, gate: string): Phase | undefined {
145
+ if (!gate.startsWith("plan:")) return undefined;
146
+ const id = gate.slice(5);
147
+ if (!definition.nodes.some(node => node.id === id && node.kind === "gate")) return undefined;
148
+ const targets = definition.nodes.filter(node => node.needs.includes(id) || definition.edges.some(([from, to]) => from === id && to === node.id));
149
+ if (!targets.length || targets.some(node => node.kind === "hub" || node.phase === undefined)) return undefined;
150
+ const phases = new Set(targets.map(node => node.phase));
151
+ return phases.size === 1 ? targets[0]!.phase : undefined;
152
+ }
153
+
140
154
  export function readPlan(dir: string): PlanDefinition | undefined {
141
155
  const file = join(dir, "plan.json");
142
156
  if (!existsSync(file)) return undefined;
@@ -147,7 +161,9 @@ export function readPlan(dir: string): PlanDefinition | undefined {
147
161
  }
148
162
  /** Caller holds the study lock; definition and initial state share one transaction. */
149
163
  export function setPlan(dir: string, raw: unknown, actor: Actor) {
150
- 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);
151
167
  definition.revision = (previous?.revision ?? 0) + 1;
152
168
  if (!Number.isSafeInteger(definition.revision)) throw new Error("plan.revision: exhausted; create a new study before setting another plan");
153
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
+ }