@staix/agent-research 0.3.1 → 0.5.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.
package/src/provenance.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { paperEventFor } from "./paper/document.ts";
1
2
  import { types } from "node:util";
2
3
  import {parseHubExecutionReference, type HubExecutionReferenceV1} from "./harness/hub-reference.ts";
3
4
  import { existsSync, lstatSync, opendirSync, realpathSync } from "node:fs";
@@ -365,7 +366,7 @@ function closures(dir: string, graph: Graph, study: ExecutionReferenceV1): void
365
366
  const source = graph.source, records: Closure[] = [], latest = new Map<string, number>();
366
367
  const selected = fileJson(source, "design/selection.json")?.run;
367
368
  for (const [index, event] of source.events.entries()) {
368
- const family = event.type === "investigate.closed" ? "investigate" : event.type === "ablate.closed" ? "ablate" : event.type === "final.closed" ? "final" : event.type === "paper.built" ? "paper" : undefined;
369
+ const family = event.type === "investigate.closed" ? "investigate" : event.type === "ablate.closed" ? "ablate" : event.type === "final.closed" ? "final" : paperEventFor(event, "paper.built") ? "paper" : undefined;
369
370
  if (!family) continue;
370
371
  const run = family === "investigate" ? event.data.run : family;
371
372
  const hash = family === "paper" ? event.data.evidenceSha256 : event.data.sha256;
@@ -383,8 +384,8 @@ function closures(dir: string, graph: Graph, study: ExecutionReferenceV1): void
383
384
  if (matches) {
384
385
  try {
385
386
  record.raw = fileJson(source, record.file);
386
- if (record.raw && record.family === "paper" && (record.raw.v === 1 || record.raw.v === 2)) record.nativeVersion = paperEvidenceVersion(record.raw);
387
- if (!record.raw || (record.raw.v !== 1 && !(record.family === "paper" && record.raw.v === 2))) { state = "unavailable"; graph.issue("unsupported-closed-version", record.ref); }
387
+ if (record.raw && record.family === "paper" && (record.raw.v === 1 || record.raw.v === 2 || record.raw.v === 3)) record.nativeVersion = paperEvidenceVersion(record.raw);
388
+ if (!record.raw || (record.raw.v !== 1 && !(record.family === "paper" && (record.raw.v === 2 || record.raw.v === 3)))) { state = "unavailable"; graph.issue("unsupported-closed-version", record.ref); }
388
389
  else if (record.family === "paper" ? !Array.isArray(record.raw.placeholders) || typeof record.raw.manuscriptSha256 !== "string" : typeof record.raw.inputsSha256 !== "string" || record.family === "final" && !["qualified", "not_qualified"].includes(String(record.raw.status))) { state = "corrupt"; graph.issue("malformed-closed-artifact", record.ref); }
389
390
  else if (record.latest && !(record.family === "investigate" && record.ref.id !== selected)) {
390
391
  try {
@@ -1,3 +1,4 @@
1
+ import { paperEventFor } from "./paper/document.ts";
1
2
  import { attemptReuseView, retentionDisposalIndex, type RetentionDisposalIndex } from "./provenance.ts";
2
3
  import {urlOrKeyLike} from "./privacy.ts";
3
4
  import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync } from "node:fs";
@@ -33,9 +34,9 @@ const LEDGER_KEYS: Record<string, readonly string[]> = {
33
34
  "lit.search": ["intent", "yearFrom", "sources", "added", "merged", "absorbed", "total"], "lit.screen": ["decision", "code"], "lit.card": ["id", "sha256"], "lit.card.exported": ["fingerprint"], "lit.card.imported": [], "lit.bib": ["entries", "sha256"], "lit.verify": ["verified", "failed"],
34
35
  "archive.exported": ["fingerprint"], "skill.proposed": ["skillProposal", "sha256"], "skill.decided": ["skillProposal", "decision"], "watch.set": ["sha256"],
35
36
  "plan.set": ["revision", "state", "sha256"], "plan.gates": ["revision"], "plan.paused": ["revision"], "plan.control": ["revision"], "node.observed": ["revision", "status"], "node.intent": ["revision"],
36
- "executor.set": ["kind"], "protocol.set": ["sha256", "identitySha256", "protocolHash", "treeHash"], "selection.set": ["sha256", "metric"], "final.seeds.set": ["sha256"],
37
+ "executor.set": ["kind"], "protocol.set": ["sha256", "identitySha256", "protocolHash", "treeHash"], "selection.set": ["sha256", "metric"], "selection.calibrated": ["run", "sha256", "protocolHash"], "final.seeds.set": ["sha256"],
37
38
  "investigate.closed": ["run", "sha256", "ruleSha256", "winner"], "ablate.closed": ["sha256", "investigateSha256"], "final.closed": ["sha256", "status", "investigateSha256"],
38
- "idea.decided": ["decision"], "paper.built": ["manuscriptSha256", "evidenceSha256", "sourceManuscriptSha256"], "review.added": [], "review.resolved": ["buildSha256"],
39
+ "idea.decided": ["decision"], "idea.categories.set": ["sha256", "count"], "paper.built": ["doc", "manuscriptSha256", "evidenceSha256", "sourceManuscriptSha256"], "paper.rendered": ["doc", "evidenceSha256", "manuscriptSha256", "outputSha256", "receiptSha256", "bytes"], "review.added": [], "review.resolved": ["buildSha256"],
39
40
  "attempt.started": ["id", "run", "seed", "commit", "treeId"],
40
41
  "retention.pruned": ["fingerprint", "refsSha256", "count"],
41
42
  "attempt.stage.reused": ["id", "stage", "candidateStage", "key", "sourceAttemptId", "sourceStage", "sourceSha256"],
@@ -74,6 +75,8 @@ function reduceEvent(event: LedgerEvent) {
74
75
  const actor = { kind: ACTOR_KINDS.has(event.actor?.kind as string) ? event.actor.kind : "other", ...(event.actor.id !== undefined ? { idSha256: sha256(event.actor.id) } : {}) };
75
76
  const at = isoAt(event.at), data = reduceData(plain(event.data) ? event.data : {}, (Object.hasOwn(LEDGER_KEYS, event.type) ? LEDGER_KEYS[event.type]! : []));
76
77
  if (event.type === "retention.pruned" && Array.isArray(event.data.refs) && event.data.refs.length > 0 && event.data.refs.length <= 500 && retentionDisposalIndex([event]).size === event.data.refs.length) data.refs = event.data.refs.map(ref => [...ref as string[]]);
78
+ // Render receipt (#162): hashes plus renderer identity as closed tokens only, never the document bytes or free text.
79
+ if (event.type === "paper.rendered" && plain(event.data.renderer)) data.renderer = reduceData(event.data.renderer, ["tool", "version", "environment"]);
77
80
  return { v: event.v, at, actor, type: TOKEN.test(event.type) ? event.type : "other", data };
78
81
  }
79
82
  // Closed codes emitted by attempts.ts, metrics.ts and artifacts.ts; never derive a class from user prose.
@@ -144,7 +147,7 @@ function reviews(events: LedgerEvent[]) {
144
147
  }
145
148
  /** Content-free per-section rounds and pass at the latest built evidence hash, plus the repair-scope histogram. */
146
149
  function reviewSections(rows: ReturnType<typeof reviews>, events: LedgerEvent[]) {
147
- const latest = events.filter(e => e.type === "paper.built" && typeof e.data.evidenceSha256 === "string").at(-1)?.data.evidenceSha256 ?? null;
150
+ const latest = events.filter(e => paperEventFor(e, "paper.built") && typeof e.data.evidenceSha256 === "string").at(-1)?.data.evidenceSha256 ?? null;
148
151
  const rounds = new Map<string, number>(), open = new Set<string>(), repairs: Record<string, number> = { edit: 0, paragraph: 0, section: 0 };
149
152
  for (const row of rows) {
150
153
  for (const section of row.sections) rounds.set(section, (rounds.get(section) ?? 0) + 1);
@@ -162,7 +165,7 @@ function evidence(dir: string) {
162
165
  if (!plain(raw) || !Array.isArray(raw.placeholders)) throw new Error("study export: paper/build/evidence.json has an unsupported shape; rebuild the paper before exporting");
163
166
  return {
164
167
  v: 1, manuscriptSha256: typeof raw.manuscriptSha256 === "string" && SHA256.test(raw.manuscriptSha256) ? raw.manuscriptSha256 : null,
165
- ...(raw.v === 2 ? {planSha256: raw.planSha256} : {}),
168
+ ...((raw.v === 2 || raw.v === 3) ? {planSha256: raw.planSha256} : {}),
166
169
  placeholders: (raw.placeholders as Record<string, unknown>[]).filter(p => p.kind === "number").map(p => {
167
170
  const ref = typeof p.ref === "string" ? p.ref : "", attempt = /^(?:attempt|posthoc):([a-f0-9]{16})\./.exec(ref)?.[1];
168
171
  const source = plain(p.source) ? p.source : {};
package/src/study.ts CHANGED
@@ -48,11 +48,15 @@ export const sha256 = (data: string | Uint8Array) => createHash("sha256").update
48
48
  * Write a file by temp + fsync + rename so readers never see a partial file. `maxBytes` must be the bound the
49
49
  * file's reader uses, so nothing is written that the tool cannot read back.
50
50
  */
51
- export function writeAtomic(path: string, text: string, maxBytes: number, mode = 0o644): void {
51
+ export function writeAtomic(path: string, text: string | Uint8Array, maxBytes: number, mode = 0o644): void {
52
52
  assertWritable(text, maxBytes, path);
53
53
  const tmp = `${path}.${randomUUID()}.tmp`;
54
54
  const fd = openSync(tmp, "wx", mode);
55
- try { writeSync(fd, text); fsyncSync(fd); } finally { closeSync(fd); }
55
+ try {
56
+ if (typeof text === "string") writeSync(fd, text);
57
+ else for (let offset = 0; offset < text.length;) offset += writeSync(fd, text, offset, text.length - offset);
58
+ fsyncSync(fd);
59
+ } finally { closeSync(fd); }
56
60
  try { renameSync(tmp, path); } catch (error) { try { unlinkSync(tmp); } catch { /* already gone */ } throw error; }
57
61
  }
58
62
 
@@ -96,7 +100,7 @@ export function readJsonFile(path: string, maxBytes: number): unknown {
96
100
  try { return JSON.parse(text); } catch { throw new Error(`${path}: not valid JSON`); }
97
101
  }
98
102
  /** Refuse a write that the matching bounded read could not load back. */
99
- export function assertWritable(text: string, maxBytes: number, what: string): void {
103
+ export function assertWritable(text: string | Uint8Array, maxBytes: number, what: string): void {
100
104
  if (Buffer.byteLength(text) > maxBytes) throw new Error(`${what} would exceed ${maxBytes} bytes`);
101
105
  }
102
106
 
@@ -210,7 +214,8 @@ export async function withLock<T>(dir: string, fn: (permit: StudyReadLock) => Pr
210
214
  }
211
215
 
212
216
  export interface PendingEvent { actor: Actor; type: string; data: Record<string, unknown> }
213
- export type FileWrite = [path: string, text: string, maxBytes: number];
217
+ /** Text or exact bytes (for example a recorded render); either is bounded by its reader's limit. */
218
+ export type FileWrite = [path: string, text: string | Uint8Array, maxBytes: number];
214
219
 
215
220
  /** Validate command capacity without writing; callers can reserve receipt space before outward effects. */
216
221
  export function prepareCommit(dir: string, files: FileWrite[], pending: PendingEvent[]): { events: LedgerEvent[]; lines: string[] } {
package/src/ui/plugin.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { paperEventFor } from "../paper/document.ts";
1
2
  /** Console api1 contract subset; runtime imports stay within ares/Node/Bun. Real contract/conformance is test-only. */
2
3
  import { lstatSync, realpathSync, statSync } from "node:fs";
3
4
  import { join } from "node:path";
@@ -93,6 +94,7 @@ export function gateWaitingTimes(events: LedgerEvent[], inputs: GateInputs, obse
93
94
  case "ablation.added": hasAblations = true; experiment(event.at); break;
94
95
  case "ablate.closed": if (typeof data.sha256 === "string") ablate = data.sha256; experiment(event.at); break;
95
96
  case "paper.built":
97
+ if (!paperEventFor(event, "paper.built")) break;
96
98
  if (typeof data.manuscriptSha256 === "string" && typeof data.evidenceSha256 === "string") paper = [data.manuscriptSha256, data.evidenceSha256];
97
99
  review(event.at); break;
98
100
  case "review.added": if (typeof data.id === "string" && inputs.review?.ids.has(data.id)) { reviewChanges++; review(event.at); } break;
@@ -192,7 +194,7 @@ function loadStudy(dir: string, features: readonly string[], input: { panel: str
192
194
  }
193
195
  const archive = detailed ? readCall("archive", () => { const preview = previewArchive(dir); return { pendingCount: preview.notes.length, fingerprint: preview.fingerprint }; }, errors) : null;
194
196
  const manuscript = detailed && readCall("manuscript", () => {
195
- const paths = paperBuildPaths(dir), recorded = recordPresent(paths.manuscript) || recordPresent(paths.evidence) || events.some(event => event.type === "paper.built");
197
+ const paths = paperBuildPaths(dir), recorded = recordPresent(paths.manuscript) || recordPresent(paths.evidence) || events.some(event => paperEventFor(event, "paper.built"));
196
198
  return recorded ? readCurrentBuild(dir) : null;
197
199
  }, errors) ? { id: `manuscript:${study.id}` } : null;
198
200
  const failures = Object.entries(errors);