@staix/agent-research 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/README.md +356 -31
  3. package/package.json +4 -2
  4. package/src/autonomy.ts +50 -0
  5. package/src/cli.ts +134 -14
  6. package/src/commands-table.ts +43 -9
  7. package/src/commands.ts +244 -43
  8. package/src/copilot.ts +91 -0
  9. package/src/exp/attempts.ts +512 -69
  10. package/src/exp/executor.ts +235 -12
  11. package/src/exp/final.ts +1 -1
  12. package/src/exp/investigate.ts +7 -2
  13. package/src/exp/logs.ts +25 -12
  14. package/src/exp/metrics.ts +6 -5
  15. package/src/exp/pipeline.ts +92 -0
  16. package/src/exp/protocol.ts +88 -18
  17. package/src/exp/retention-script.ts +649 -0
  18. package/src/exp/retention.ts +70 -0
  19. package/src/exp/reuse-admission.ts +63 -0
  20. package/src/exp/reuse-contract.ts +48 -0
  21. package/src/exp/reuse-runtime.ts +87 -0
  22. package/src/exp/reuse.ts +87 -0
  23. package/src/exp/selection.ts +1 -1
  24. package/src/exp/snapshot.ts +3 -3
  25. package/src/exp/stages.ts +117 -0
  26. package/src/harness/experience-source.ts +34 -0
  27. package/src/harness/experience.ts +206 -0
  28. package/src/harness/hub-guidance.ts +140 -0
  29. package/src/harness/hub-reference.ts +18 -0
  30. package/src/harness/lesson-candidates.ts +162 -0
  31. package/src/harness/limits.ts +2 -0
  32. package/src/harness/privacy.ts +4 -0
  33. package/src/harness/receipts.ts +84 -0
  34. package/src/harness/rounds.ts +198 -0
  35. package/src/harness/transitions.ts +152 -0
  36. package/src/http.ts +46 -2
  37. package/src/lit/candidates.ts +13 -5
  38. package/src/lit/cards.ts +55 -4
  39. package/src/lit/flow.ts +82 -0
  40. package/src/lit/queries.ts +62 -0
  41. package/src/lit/watch.ts +14 -1
  42. package/src/manifest.ts +15 -7
  43. package/src/mcp-tools.ts +140 -32
  44. package/src/mcp.ts +6 -0
  45. package/src/memory/amem-show.ts +135 -0
  46. package/src/memory/amem.ts +3 -0
  47. package/src/memory/archive.ts +20 -8
  48. package/src/memory/evidence-local.ts +77 -0
  49. package/src/memory/evidence.ts +39 -0
  50. package/src/memory/lessons.ts +4 -2
  51. package/src/memory/skill-check.ts +56 -0
  52. package/src/memory/skill-format.ts +77 -0
  53. package/src/memory/skills.ts +72 -26
  54. package/src/memory/source-budget.ts +11 -0
  55. package/src/memory/vault-cards.ts +226 -0
  56. package/src/paper/build.ts +20 -8
  57. package/src/paper/check.ts +40 -12
  58. package/src/paper/headings.ts +39 -0
  59. package/src/paper/hygiene.ts +153 -0
  60. package/src/paper/placeholders.ts +21 -4
  61. package/src/paper/plan.ts +170 -0
  62. package/src/paper/point-evidence.ts +63 -0
  63. package/src/paper/points.ts +83 -0
  64. package/src/paper/review.ts +116 -11
  65. package/src/paper/scopes.ts +51 -0
  66. package/src/plan/controller.ts +42 -12
  67. package/src/plan/definition.ts +22 -6
  68. package/src/plan/hub.ts +6 -0
  69. package/src/plan/state.ts +58 -17
  70. package/src/playbook.ts +47 -20
  71. package/src/privacy.ts +9 -0
  72. package/src/provenance.ts +679 -0
  73. package/src/scope.ts +24 -3
  74. package/src/study-export.ts +282 -0
  75. package/src/study.ts +94 -26
  76. package/src/ui/panel.css +4 -0
  77. package/src/ui/panel.js +271 -9
  78. package/src/ui/plugin.ts +89 -17
package/src/ui/plugin.ts CHANGED
@@ -4,18 +4,20 @@ import { join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { version } from "../../package.json";
6
6
  import * as ops from "../commands.ts";
7
+ import { attemptReuseView, validateExecutionReference } from "../provenance.ts";
7
8
  import { foldPlan, canonical, PLAN_GATE_BYTES } from "../plan/state.ts";
8
9
  import { readRegistry, MAX_REGISTERED_STUDIES } from "../console/registry.ts";
9
10
  import { readAttemptRecords, type Attempt } from "../exp/attempts.ts";
10
11
  import { createHttp } from "../http.ts";
11
- import { previewArchive, ARCHIVE_NOTES, ArchivePartialError } from "../memory/archive.ts";
12
+ import { previewArchive, archiveExportBatch, ArchivePartialError } from "../memory/archive.ts";
12
13
  import { spawnRunner, type ProcessRunner } from "../exp/executor.ts";
13
14
  import { readProtocol } from "../exp/protocol.ts";
14
15
  import { readSelection, selectionPath } from "../exp/selection.ts";
16
+ import { investigateResultPath } from "../exp/investigate.ts";
15
17
  import { readClosedFinal, finalResultPath } from "../exp/final.ts";
16
18
  import { readCurrentBuild, paperBuildPaths } from "../paper/build.ts";
17
19
  import { loadCandidates } from "../lit/candidates.ts";
18
- import { openStudy, readLedger, readBytesBounded, readTextBounded, sha256, boundedText, plain, type LedgerEvent } from "../study.ts";
20
+ import { openStudy, readLedger, readBytesBounded, readTextBounded, sha256, boundedText, plain, isHarnessGate, type LedgerEvent } from "../study.ts";
19
21
 
20
22
  type Args = Record<string, unknown>;
21
23
  interface Context { home: string; log(line: string): void; features?: readonly string[] }
@@ -39,12 +41,13 @@ const stamp = (value: unknown, fallback = EPOCH) => typeof value === "string" &&
39
41
  function readCall<T>(name: string, fn: () => T, errors: Record<string, string>): T | null {
40
42
  try { return fn(); } catch (cause) { errors[name] = error(cause); return null; }
41
43
  }
42
- interface GateInputs { selectionRun?: string; review?: { manuscriptSha256: string; evidenceSha256: string; ids: ReadonlySet<string> } }
44
+ export interface GateInputs { selectionRun?: string; review?: { manuscriptSha256: string; evidenceSha256: string; ids: ReadonlySet<string> } }
43
45
  /** Every gate advances only when an input consumed by its binder changes, never merely on an event kind. */
44
- function gateWaitingTimes(events: LedgerEvent[], inputs: GateInputs): Map<string, string> {
46
+ export function gateWaitingTimes(events: LedgerEvent[], inputs: GateInputs, observeSignature?: (gate: string, signature: string | undefined) => void): Map<string, string> {
45
47
  const waiting = new Map<string, string>(), previous = new Map<string, string | undefined>();
46
48
  const observe = (gate: string, input: unknown, at: string) => {
47
49
  const signature = input === undefined ? undefined : canonical(input);
50
+ observeSignature?.(gate, signature);
48
51
  if (previous.get(gate) === signature) return;
49
52
  previous.set(gate, signature);
50
53
  if (signature === undefined) waiting.delete(gate); else waiting.set(gate, at);
@@ -71,6 +74,7 @@ function gateWaitingTimes(events: LedgerEvent[], inputs: GateInputs): Map<string
71
74
  for (const event of events) {
72
75
  const data = event.data;
73
76
  switch (event.type) {
77
+ case "harness.round.set": if (plain(data.round) && isHarnessGate(`harness:${String(data.round.id)}`) && typeof data.binding === "string") observe(`harness:${data.round.id}`, data.binding, event.at); break;
74
78
  case "scope.set": if (typeof data.sha256 === "string") observe("scope", data.sha256, event.at); break;
75
79
  case "lit.screen": {
76
80
  let changed = false;
@@ -81,12 +85,12 @@ function gateWaitingTimes(events: LedgerEvent[], inputs: GateInputs): Map<string
81
85
  if (changed) observe("screen", included.size ? [...included].sort() : undefined, event.at); break;
82
86
  }
83
87
  case "protocol.set":
84
- if (typeof data.sha256 === "string" && typeof data.treeHash === "string") protocol = [data.sha256, data.treeHash];
88
+ if (typeof data.sha256 === "string" && typeof data.treeHash === "string") protocol = [typeof data.identitySha256 === "string" ? data.identitySha256 : data.sha256, data.treeHash];
85
89
  experiment(event.at); break;
86
90
  case "selection.set": if (typeof data.sha256 === "string") selection = data.sha256; experiment(event.at); break;
87
91
  case "final.seeds.set": if (typeof data.sha256 === "string") reserved = data.sha256; experiment(event.at); break;
88
- case "investigate.closed": if (data.run === inputs.selectionRun && typeof data.sha256 === "string") investigate = data.sha256; experiment(event.at); break;
89
- case "ablate.added": hasAblations = true; experiment(event.at); break;
92
+ case "investigate.closed": if (data.run === inputs.selectionRun && typeof data.sha256 === "string") investigate = typeof data.winner === "string" && /^[a-f0-9]{40}$/.test(data.winner) ? data.sha256 : undefined; experiment(event.at); break;
93
+ case "ablation.added": hasAblations = true; experiment(event.at); break;
90
94
  case "ablate.closed": if (typeof data.sha256 === "string") ablate = data.sha256; experiment(event.at); break;
91
95
  case "paper.built":
92
96
  if (typeof data.manuscriptSha256 === "string" && typeof data.evidenceSha256 === "string") paper = [data.manuscriptSha256, data.evidenceSha256];
@@ -100,13 +104,16 @@ function gateWaitingTimes(events: LedgerEvent[], inputs: GateInputs): Map<string
100
104
  function attempts(dir: string, all: boolean) {
101
105
  const byStatus = { running: 0, succeeded: 0, failed: 0, cancelled: 0, unknown: 0 }, rows: Pick<Attempt, "id" | "status" | "reason">[] = [];
102
106
  let total = 0;
107
+ const reuse = {attempts: 0, executedStages: 0, reusedStages: 0, freshEvaluations: 0, independentSamples: 0};
103
108
  for (const row of readAttemptRecords(dir)) {
104
109
  total++; byStatus[row.status]++;
110
+ const view = attemptReuseView(row);
111
+ if (view) { reuse.attempts++; reuse.executedStages += view.executedStages; reuse.reusedStages += view.reusedStages; reuse.freshEvaluations += view.freshEvaluations; reuse.independentSamples += view.independentSamples; }
105
112
  if (!all || (row.status !== "failed" && row.status !== "unknown")) continue;
106
113
  if (row.reason !== undefined && (typeof row.reason !== "string" || row.reason.length > 500)) throw new Error("attempt inbox: malformed reason; restore the last valid bounded attempt record and refresh");
107
114
  rows.push({ id: row.id, status: row.status, ...(row.reason === undefined ? {} : { reason: row.reason }) });
108
115
  }
109
- return { total, byStatus, rows };
116
+ return { total, byStatus, rows, ...(reuse.attempts ? {reuse} : {}) };
110
117
  }
111
118
  /** Presence is not validity: any present artifact is still checked by its existing bounded reader. */
112
119
  function recordPresent(file: string): boolean {
@@ -124,9 +131,16 @@ function loadStudy(dir: string, features: readonly string[], input: { panel: str
124
131
  };
125
132
  const status = ops.status(dir), gates = ops.gateList(dir);
126
133
  const attempt = study.mode === "experiment" ? readCall("attempts", () => attempts(dir, inbox), errors) : null;
134
+ let investigationArtifact: { state: "missing"; recalculated: true; message: string } | undefined;
127
135
  const investigation = detailed && study.mode === "experiment" ? readCall("investigation", () => {
128
136
  const configured = recordPresent(selectionPath(dir)) || events.some(event => event.type === "selection.set" || event.type === "investigate.closed");
129
- return configured ? ops.investigateShow(dir) : null;
137
+ if (!configured) return null;
138
+ const result = ops.investigateShow(dir);
139
+ if (events.some(event => event.type === "investigate.closed" && event.data.run === result.run) && !recordPresent(investigateResultPath(dir, result.run))) {
140
+ investigationArtifact = { state: "missing", recalculated: true,
141
+ message: `Missing receipted artifact runs/${result.run}/investigate.json; this investigation result is recalculated from current inputs. Restore the artifact or run ares investigate close before using a closed result.` };
142
+ }
143
+ return result;
130
144
  }, errors) : null;
131
145
  const final = study.mode === "experiment" ? readCall("final", () => {
132
146
  const recorded = recordPresent(finalResultPath(dir)) || events.some(event => event.type === "final.closed");
@@ -169,7 +183,12 @@ function loadStudy(dir: string, features: readonly string[], input: { panel: str
169
183
  const event = attemptEvents.get(`${row.id}:${row.status}`);
170
184
  add("attempt", row.id, "alert", `${row.status} attempt ${row.id}`, event?.at ?? at, row.reason ?? "Inspect ares attempt show before retrying");
171
185
  }
172
- for (const [index, event] of events.entries()) if (event.type === "watch.ran" && event.data.ok === false) add("watch", event.at + index, "alert", "Every watch source failed", event.at, "Inspect ares watch show and retry after restoring source access");
186
+ for (const [index, event] of events.entries()) if (event.type === "watch.ran" && event.data.ok === false) {
187
+ const cause = event.data.cause, known = typeof cause === "string" && ["terminated", "filesystem", "internal", "network", "rate", "server", "client", "format"].includes(cause);
188
+ const title = cause === undefined ? "Every watch source failed" : known ? `Watch run failed (${cause})` : "Watch run failed (unknown cause)";
189
+ const detail = cause === undefined ? "Inspect ares watch show and retry after restoring source access" : "Inspect ares watch show and lit list; restore study storage or source access as needed, then rerun ares watch run";
190
+ add("watch", event.at + index, "alert", title, event.at, detail);
191
+ }
173
192
  }
174
193
  const archive = detailed ? readCall("archive", () => { const preview = previewArchive(dir); return { pendingCount: preview.notes.length, fingerprint: preview.fingerprint }; }, errors) : null;
175
194
  const manuscript = detailed && readCall("manuscript", () => {
@@ -183,10 +202,10 @@ function loadStudy(dir: string, features: readonly string[], input: { panel: str
183
202
  failures.map(([name, reason]) => `${name}: ${line(reason, Math.max(20, perFailure - name.length - 2))}`).join("; ") + "; Inspect the study panel, restore readable records or use a compatible ares version, then refresh.");
184
203
  }
185
204
  const summary = { id: study.id, dir, available: true, question: status.question, mode: status.mode, autonomy: status.autonomy, gates,
186
- attempts: attempt ? { total: attempt.total, byStatus: attempt.byStatus } : study.mode === "experiment" ? { available: false, reason: errors.attempts ?? "Attempt records could not be read; inspect ares attempt list and restore readable records, then refresh" } : { total: 0, byStatus: {} },
205
+ attempts: attempt ? { total: attempt.total, byStatus: attempt.byStatus, ...(attempt.reuse ? {reuse: attempt.reuse} : {}) } : study.mode === "experiment" ? { available: false, reason: errors.attempts ?? "Attempt records could not be read; inspect ares attempt list and restore readable records, then refresh" } : { total: 0, byStatus: {} },
187
206
  final: final ? { status: final.status, ...(final.reason ? { reason: final.reason } : {}) } : null,
188
207
  review: review ? { ready: review.ready, unmet: review.unmet } : null, lastWatch };
189
- return { summary, targets, detail: detailed ? { ...summary, investigation, final, posthoc, review, skills, watch, archive, manuscript, errors } : null, items, at };
208
+ return { summary, targets, detail: detailed ? { ...summary, investigation, investigationArtifact: investigationArtifact ?? null, final, posthoc, review, skills, watch, archive, manuscript, errors } : null, items, at };
190
209
  }
191
210
  interface Selection { wireAction: string; action: "gate" | "screen" | "skill.decide" | "archive.confirm"; study: string; gate?: string; ids?: string[]; name?: string; decision?: string; reason?: string; pr?: string }
192
211
  const ACTIONS: Record<string, { action: Selection["action"]; decision?: string; fields: readonly string[] }> = {
@@ -254,14 +273,47 @@ function boundAction(value: Selection) {
254
273
  binding = skill; preview.push(`${value.decision} skill ${skill.name}`, `Proposal: ${skill.sha256}`, ...(value.pr ? [`Reviewed PR: ${value.pr}`] : []));
255
274
  } else {
256
275
  const archive = previewArchive(study); archiveFingerprint = archive.fingerprint; binding = { fingerprint: archive.fingerprint, pending: archive.notes.map(row => row.sha256) };
257
- preview.push(`Export ${Math.min(ARCHIVE_NOTES, archive.notes.length)} of ${archive.notes.length} pending lesson(s) to amem`, `Archive fingerprint: ${archive.fingerprint}`);
276
+ preview.push(`Export ${archiveExportBatch(study, archive.notes).length} of ${archive.notes.length} pending lesson(s) to amem`, `Archive fingerprint: ${archive.fingerprint}`, ...(archive.recovery ? [archive.recovery] : []));
258
277
  }
259
278
  if (value.reason) preview.push(`Reason: ${value.reason}`);
260
279
  return { fingerprint: sha256(canonical({ selection: value, study: identity, binding })), preview, archiveFingerprint };
261
280
  }
281
+ const LINEAGE_PARAMS = ["rootKind", "rootId", "rootRevision", "rootSha256", "graphCursor", "attempts", "candidates"] as const;
282
+ function readParam(input: Args, name: typeof LINEAGE_PARAMS[number]): string | undefined {
283
+ const value = input[name]; if (value === undefined) return undefined;
284
+ if (typeof value !== "string" || value.includes("\0") || Buffer.byteLength(value) > 4096) throw new Error(`console ${name}: bounded text required; correct the view parameters and retry`);
285
+ return value;
286
+ }
287
+ /** Explicit read panels only; the ordinary overview/inbox polling paths never call these operations. */
288
+ function executionPanel(dir: string, input: Args): Args {
289
+ if (input.panel === "harness") {
290
+ const harness = ops.harnessShow(dir, input.round as string | undefined), selected = new Set(harness.rounds.filter(row => typeof input.round === "string" ? row.definition.id === input.round : harness.rounds.length === 1).map(row => row.definition.id));
291
+ const candidates = ops.lessonList(dir).filter(row => selected.has(row.proposal.round));
292
+ const lessonCandidates: typeof candidates = [];
293
+ for (const row of candidates) {if (Buffer.byteLength(JSON.stringify({harness, lessonCandidates: [...lessonCandidates, row], remainingLessonCandidates: candidates.length})) > 1_048_576) break; lessonCandidates.push(row);}
294
+ return {harness, lessonCandidates, remainingLessonCandidates: candidates.length - lessonCandidates.length};
295
+ }
296
+ if (input.panel === "compare") {
297
+ if (["rootKind", "rootId", "rootRevision", "rootSha256", "graphCursor"].some(name => input[name] !== undefined)) throw new Error("console compare: use only attempts or candidates selection parameters; clear lineage filters and retry");
298
+ const attempts = readParam(input, "attempts"), candidates = readParam(input, "candidates");
299
+ if (attempts === undefined && candidates === undefined) return {comparison: null};
300
+ return {comparison: ops.lineageCompare(dir, {...(attempts === undefined ? {} : {attempts: attempts.split(",")}), ...(candidates === undefined ? {} : {candidates: candidates.split(",")})})};
301
+ }
302
+ if (input.attempts !== undefined || input.candidates !== undefined) throw new Error("console lineage: use root fields and graphCursor; clear comparison selectors and retry");
303
+ const kind = readParam(input, "rootKind"), id = readParam(input, "rootId"), revision = readParam(input, "rootRevision"), hash = readParam(input, "rootSha256"), cursor = readParam(input, "graphCursor");
304
+ const rooted = [kind, id, revision, hash].some(value => value !== undefined);
305
+ if (rooted && (kind === undefined || id === undefined)) throw new Error("console lineage: partial root; pass rootKind and rootId together and retry");
306
+ let root;
307
+ if (rooted) {
308
+ root = validateExecutionReference({v: 1, tool: "ares", projectKey: "pending-study-identity", kind, id, ...(revision === undefined ? {} : {revision}), ...(hash === undefined ? {} : {sha256: hash})});
309
+ try { root = {...root, projectKey: openStudy(dir).study.id}; }
310
+ catch { return {lineage: ops.lineageShow(dir)}; }
311
+ }
312
+ return {lineage: ops.lineageShow(dir, {...(root === undefined ? {} : {root}), ...(cursor === undefined ? {} : {cursor})})};
313
+ }
262
314
  export function createPlugin(runtime: Runtime = {}) { return {
263
315
  manifest: { api: 1 as const, tool: "ares", version, title: "Research", icon: "agents", pollMs: 15000,
264
- panels: [{ id: "studies", title: "Studies", order: 1 }, { id: "study", title: "Study", order: 2 }],
316
+ panels: [{ id: "studies", title: "Studies", order: 1 }, { id: "study", title: "Study", order: 2 }, { id: "lineage", title: "Lineage", order: 3 }, { id: "compare", title: "Compare attempts", order: 4 }, {id: "harness", title: "Harness rounds", order: 5}],
265
317
  capabilities: { actions: Object.keys(ACTIONS), confirm: true, inbox: true, multiProject: false, search: false } },
266
318
  async open(ctx: Context): Promise<Provider> {
267
319
  const assets = { js: readTextBounded(fileURLToPath(new URL("./panel.js", import.meta.url)), 262144), css: readTextBounded(fileURLToPath(new URL("./panel.css", import.meta.url)), 262144) };
@@ -271,11 +323,18 @@ export function createPlugin(runtime: Runtime = {}) { return {
271
323
  return {
272
324
  assets,
273
325
  async snapshot(input) {
326
+ const explicitRead = input.panel === "lineage" || input.panel === "compare" || input.panel === "harness";
327
+ const emptyRead = input.panel === "harness" ? {harness: null} : {lineage: null, comparison: null};
328
+ if (explicitRead) {
329
+ const allowed = ["panel", "study", "after", ...(input.panel === "harness" ? ["round"] : LINEAGE_PARAMS)], extra = Object.keys(input).find(name => !allowed.includes(name));
330
+ if (extra !== undefined) return {cursor: 0, changed: true, study: null, ...emptyRead, error: `console read snapshot: unknown field ${line(extra, 80)}; allowed fields: ${allowed.join(", ")}; correct the view parameters and retry`};
331
+ if (input.panel === "harness" && input.round !== undefined && (typeof input.round !== "string" || !isHarnessGate(`harness:${input.round}`))) return {cursor: 0, changed: true, study: null, harness: null, error: "console harness: invalid round; pass a 1..64 character ASCII run-name and retry"};
332
+ }
274
333
  const registry = readRegistry(ctx.home);
275
334
  const cursor = registry.studies.reduce((sum, dir) => {
276
335
  try { const info = statSync(join(dir, "ledger.jsonl")); return sum + (info.isFile() ? info.size : 0); } catch { return sum; }
277
336
  }, 0);
278
- const view = `${input.panel}:${str(input.study) ?? str(input.id) ?? ""}`;
337
+ const view = canonical([input.panel, str(input.study) ?? str(input.id) ?? "", ...(input.panel === "harness" ? ["round"] : LINEAGE_PARAMS).map(name => typeof input[name] === "string" ? sha256(input[name] as string) : typeof input[name])]);
279
338
  const deliver = (payload: Args): Args => {
280
339
  const hash = sha256(canonical(payload));
281
340
  if (input.after === cursor && seen.get(view) === hash) return { cursor, changed: false };
@@ -283,6 +342,19 @@ export function createPlugin(runtime: Runtime = {}) { return {
283
342
  seen.set(view, hash);
284
343
  return { ...payload, changed: true };
285
344
  };
345
+ if (explicitRead) {
346
+ const choices = registry.studies.map(dir => ({dir})), selected = str(input.study);
347
+ if (!selected || !registry.studies.includes(selected)) return deliver({cursor, studies: choices, study: null, ...emptyRead, error: selected ? "Requested study is not registered; use ares console add or choose a registered study" : "Choose a registered study"});
348
+ if (input.panel === "harness") {
349
+ try {if (realpathSync(selected) !== selected) throw new Error();}
350
+ catch {return deliver({cursor, studies: choices, study: {dir: selected, available: false}, harness: null, error: "Registered study is missing or now resolves elsewhere; restore its canonical directory and refresh"});}
351
+ }
352
+ let summary: Args = {dir: selected};
353
+ try { const {study} = openStudy(selected); summary = {...summary, id: study.id, question: study.question, mode: study.mode, available: true}; }
354
+ catch { summary = {...summary, available: false, reason: "Study metadata unavailable; restore valid study.json and refresh"}; }
355
+ try { return deliver({cursor, studies: choices, study: summary, ...executionPanel(selected, input)}); }
356
+ catch (cause) { return deliver({cursor, studies: choices, study: summary, ...emptyRead, error: error(cause)}); }
357
+ }
286
358
  const registered = new Set(registry.studies); for (const dir of lastAt.keys()) if (!registered.has(dir)) lastAt.delete(dir);
287
359
  if (input.panel === "inbox") targets.clear();
288
360
  const studies: Args[] = [], details = new Map<string, Args>(), items: Item[] = [];
@@ -333,8 +405,8 @@ export function createPlugin(runtime: Runtime = {}) { return {
333
405
  };
334
406
  if (target.action === "gate") await ops.gateDecide(target.study, target.gate!, target.decision as "approve" | "reject", target.reason, command, guard);
335
407
  else if (target.action === "screen") await ops.screen(target.study, target.ids!, target.decision as "include" | "exclude", target.reason, command, guard);
336
- else if (target.action === "skill.decide") await ops.skillDecide(target.study, target.name!, target.decision!, target.reason!, target.pr, command, guard);
337
- else await ops.archive(target.study, archive, command, env, guard);
408
+ else if (target.action === "skill.decide") await ops.skillDecide(target.study, target.name!, target.decision!, target.reason!, target.pr, {actor, ...(runtime.runner ? {runner: runtime.runner} : {}), ...(runtime.now ? {now: runtime.now} : {})}, guard, env);
409
+ else await ops.archive(target.study, archive, command, env, guard, {...runtime, env});
338
410
  seen.clear(); return { ok: true, message: `${target.wireAction} recorded; refresh the study to inspect its ledger` };
339
411
  } catch (cause) {
340
412
  const message = cause instanceof ArchivePartialError