@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
@@ -1,19 +1,28 @@
1
+ import { validateStageProtocol, stageProtocolHash, type ProtocolV2 } from "./stages.ts";
1
2
  import { requireCopilotAccept } from "../copilot.ts";
2
3
  import { finalSeedsHash } from "./final.ts";
3
4
  import { selectionHash } from "./selection.ts";
4
5
  import { existsSync, lstatSync, opendirSync } from "node:fs";
5
- import { join } from "node:path";
6
+ import { join, posix } from "node:path";
6
7
  import { commit, openStudy, plain, readBytesBounded, readJsonFile, readTextBounded, requireExperiment, sha256, type Actor } from "../study.ts";
7
8
 
8
9
  export interface Limits { cpus: number; memoryMb: number; pidsLimit: number; wallSeconds: number; gpus: number }
10
+ export interface ProtocolInput { path?: string; sha256: string; mount: { candidate?: string; evaluator?: string } }
9
11
  export interface Protocol {
10
- v: 1; method: string;
12
+ v: 1; method: string; inputs?: Record<string, ProtocolInput>;
11
13
  candidate: { image: string; command: string[]; env?: Record<string, string> };
12
14
  evaluator: { image: string; command: string[] };
13
15
  metrics: { name: string; unit: string; direction: "max" | "min" }[];
14
16
  seeds: number[]; limits: Limits; network: "none";
15
17
  budget: { maxAttempts: number; maxWallHours: number; maxGpuHours: number };
16
18
  }
19
+ export type ProtocolDefinition = Protocol | ProtocolV2;
20
+ export function validateProtocolDefinition(raw: unknown): ProtocolDefinition {
21
+ if (plain(raw) && raw.v === 2) return validateStageProtocol(raw);
22
+ if (!plain(raw) || raw.v !== 1) throw new Error("protocol.v: unsupported version; use a compatible ares release, keeping the original definition unchanged");
23
+ return validateProtocol(raw);
24
+ }
25
+ export const METRIC_LIMIT = 100;
17
26
  export const PROTOCOL_BYTES = 65_536, TASK_FILES = 500, TASK_BYTES = 64 * 1024 * 1024;
18
27
  export const LIMIT_BOUNDS = { cpus: [0.1, 256], memoryMb: [16, 1_048_576], pidsLimit: [1, 65_536], wallSeconds: [1, 604_800], gpus: [0, 64] } as const;
19
28
  function object(raw: unknown, keys: string[], what: string): Record<string, unknown> {
@@ -54,14 +63,50 @@ function stage(raw: unknown, what: string, envAllowed: boolean): Protocol["candi
54
63
  }
55
64
  return { image, command, env: Object.fromEntries(entries) };
56
65
  }
57
- export function validateProtocol(raw: unknown): Protocol {
58
- const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget"], "protocol");
59
- if (p.v !== 1) throw new Error("protocol.v: unsupported version; set protocol.v to 1");
66
+ export function canonicalExecutorPath(value: string): string { return posix.normalize(value).replace(/\/+$/, "") || "/"; }
67
+ /** Input locators stay executor-local; only strict read-only /in targets are supported. */
68
+ export function validateProtocolInputs(raw: unknown): Record<string, ProtocolInput> {
69
+ return protocolInputs(raw, false);
70
+ }
71
+ function protocolInputs(raw: unknown, stored: boolean): Record<string, ProtocolInput> {
72
+ const value = object(raw, Object.keys(plain(raw) ? raw : {}), "protocol.inputs"), entries = Object.entries(value);
73
+ if (entries.length > 8) throw new Error("protocol.inputs: invalid count; declare at most 8 named inputs");
74
+ const result: [string, ProtocolInput][] = [];
75
+ for (const [name, descriptor] of entries) {
76
+ if (["__proto__", "prototype", "constructor"].includes(name)) throw new Error("protocol.inputs: reserved input name; rename __proto__, prototype or constructor before setting the protocol");
77
+ if (!/^[a-z0-9_-]{1,32}$/.test(name)) throw new Error("protocol.inputs: invalid name; use 1..32 lowercase letters, digits, underscores or hyphens");
78
+ if (stored && plain(descriptor) && Object.hasOwn(descriptor, "path")) throw new Error(`stored protocol.inputs.${name}.path: executor locators are forbidden; restore a path-free frozen protocol with sha256 and mount only`);
79
+ const input = object(descriptor, stored ? ["sha256", "mount"] : ["path", "sha256", "mount"], `protocol.inputs.${name}`);
80
+ if (!stored && (typeof input.path !== "string" || input.path.length > 4096 || !input.path.startsWith("/") || /[\0\r\n,"]/.test(input.path))) throw new Error(`protocol.inputs.${name}.path: invalid locator; use an absolute executor path without NUL, newlines, commas or double quotes`);
81
+ if (typeof input.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(input.sha256)) throw new Error(`protocol.inputs.${name}.sha256: invalid manifest hash; run ares executor inputs hash <dir> <path> and use its 64 lowercase hex digest`);
82
+ const targets = object(input.mount, ["candidate", "evaluator"], `protocol.inputs.${name}.mount`);
83
+ if (!Object.keys(targets).length) throw new Error(`protocol.inputs.${name}.mount: missing stage; declare candidate, evaluator or both`);
84
+ const mount: ProtocolInput["mount"] = {};
85
+ for (const stage of ["candidate", "evaluator"] as const) if (Object.hasOwn(targets, stage)) {
86
+ const target = targets[stage];
87
+ if (typeof target !== "string" || target.length > 256 || !/^\/in\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(target) || target.split("/").some(part => part === "." || part === "..")) throw new Error(`protocol.inputs.${name}.mount.${stage}: invalid target; choose a normalized path under /in/ without dot segments`);
88
+ for (const [, prior] of result) {
89
+ const other = prior.mount[stage];
90
+ if (other && (other === target || other.startsWith(`${target}/`) || target.startsWith(`${other}/`))) throw new Error(`protocol.inputs.${name}.mount.${stage}: overlapping targets; use disjoint /in/ targets for each stage`);
91
+ }
92
+ mount[stage] = target;
93
+ }
94
+ result.push([name, { ...(!stored ? { path: canonicalExecutorPath(input.path as string) } : {}), sha256: input.sha256, mount }]);
95
+ }
96
+ return Object.fromEntries(result);
97
+ }
98
+ /** Public configuration always requires executor-local locators for declared inputs. */
99
+ export function validateProtocol(raw: unknown): Protocol { return protocolShape(raw, false); }
100
+ /** Frozen attempt records carry identities only, never executor-host locators. */
101
+ export function validateStoredProtocol(raw: unknown): Protocol { return protocolShape(raw, true); }
102
+ function protocolShape(raw: unknown, stored: boolean): Protocol {
103
+ const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget", "inputs"], "protocol");
104
+ if (p.v !== 1) throw new Error("protocol.v: unsupported version; this executor supports v1 only; use a compatible ares release for stage protocols, keeping the original definition unchanged");
60
105
  if (p.network !== "none") throw new Error('protocol.network: network access is unsupported; set protocol.network to "none"');
61
106
  const limitsRaw = object(p.limits, Object.keys(LIMIT_BOUNDS), "protocol.limits");
62
107
  const limits = Object.fromEntries(Object.entries(LIMIT_BOUNDS).map(([key, [min, max]]) => [key, number(limitsRaw[key], `protocol.limits.${key}`, min, max, key !== "cpus")])) as unknown as Limits;
63
108
  const budget = object(p.budget, ["maxAttempts", "maxWallHours", "maxGpuHours"], "protocol.budget");
64
- const metrics = array(p.metrics, "protocol.metrics", 100).map((rawMetric): Protocol["metrics"][number] => {
109
+ const metrics = array(p.metrics, "protocol.metrics", METRIC_LIMIT).map((rawMetric): Protocol["metrics"][number] => {
65
110
  const m = object(rawMetric, ["name", "unit", "direction"], "metric");
66
111
  if (m.direction !== "max" && m.direction !== "min") throw new Error("metric.direction: unknown direction; set metric.direction to max or min");
67
112
  return { name: literal(m.name, "metric.name", 128).trim(), unit: literal(m.unit, "metric.unit", 64).trim(), direction: m.direction };
@@ -74,21 +119,43 @@ export function validateProtocol(raw: unknown): Protocol {
74
119
  maxWallHours: number(budget.maxWallHours, "budget.maxWallHours", 0.000001, 1_000_000, false),
75
120
  maxGpuHours: number(budget.maxGpuHours, "budget.maxGpuHours", 0, 64_000_000, false),
76
121
  } };
122
+ if (p.inputs !== undefined) protocol.inputs = protocolInputs(p.inputs, stored);
77
123
  if (Buffer.byteLength(JSON.stringify(protocol, null, 2) + "\n") > PROTOCOL_BYTES) throw new Error(`protocol: too large; reduce the formatted protocol to at most ${PROTOCOL_BYTES} bytes`);
78
124
  return protocol;
79
125
  }
80
- function canonical(value: unknown): string {
126
+ export function canonical(value: unknown): string {
81
127
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
82
128
  if (plain(value)) return `{${Object.keys(value).sort().map(k => `${JSON.stringify(k)}:${canonical(value[k])}`).join(",")}}`;
83
129
  return JSON.stringify(value);
84
130
  }
85
- export function protocolHash(protocol: Protocol): string {
86
- const { budget: _budget, ...comparable } = validateProtocol(protocol);
131
+ /** Accept full public or already-frozen records, but never mixed locator/identity descriptors. */
132
+ export function frozenProtocol(protocol: Protocol): Protocol;
133
+ export function frozenProtocol(protocol: ProtocolV2): ProtocolV2;
134
+ export function frozenProtocol(protocol: ProtocolDefinition): ProtocolDefinition;
135
+ export function frozenProtocol(protocol: ProtocolDefinition): ProtocolDefinition {
136
+ if (protocol.v === 2) return validateStageProtocol(protocol);
137
+ const hasLocators = plain(protocol.inputs) && Object.values(protocol.inputs).some(input => plain(input) && Object.hasOwn(input, "path"));
138
+ const normalized = hasLocators ? validateProtocol(protocol) : validateStoredProtocol(protocol);
139
+ if (normalized.inputs !== undefined) normalized.inputs = Object.fromEntries(Object.entries(normalized.inputs).map(([name, input]) => [name, { sha256: input.sha256, mount: { ...input.mount } }]));
140
+ return normalized;
141
+ }
142
+ export function protocolHash(protocol: ProtocolDefinition): string {
143
+ if (protocol.v === 2) return stageProtocolHash(protocol);
144
+ const { budget: _budget, ...comparable } = frozenProtocol(protocol);
87
145
  return sha256(canonical(comparable));
88
146
  }
89
- export function readProtocol(dir: string): Protocol | undefined {
147
+ /** Locator edits do not alter the input identities a frozen attempt consumes. */
148
+ export function sameProtocolInputs(left: Protocol, right: Protocol): boolean {
149
+ return canonical(frozenProtocol(left).inputs ?? {}) === canonical(frozenProtocol(right).inputs ?? {});
150
+ }
151
+ /** Preserve legacy raw-byte design seals when inputs are absent. */
152
+ function protocolSealHash(protocol: ProtocolDefinition, sourceText: string): string {
153
+ if (protocol.v === 2) return sha256(canonical(validateStageProtocol(protocol)));
154
+ return sha256(protocol.inputs === undefined ? sourceText : canonical(frozenProtocol(protocol)));
155
+ }
156
+ export function readProtocol(dir: string): ProtocolDefinition | undefined {
90
157
  const file = join(dir, "design", "protocol.json");
91
- return existsSync(file) ? validateProtocol(readJsonFile(file, PROTOCOL_BYTES)) : undefined;
158
+ return existsSync(file) ? validateProtocolDefinition(readJsonFile(file, PROTOCOL_BYTES)) : undefined;
92
159
  }
93
160
  /** Hash unambiguous sorted [relative path, file hash] pairs; directory entries are never followed. */
94
161
  export function taskTreeHash(dir: string): string {
@@ -124,25 +191,25 @@ export function taskTreeHash(dir: string): string {
124
191
  export function designBinding(dir: string): string | undefined {
125
192
  return readDesign(dir)?.binding;
126
193
  }
127
- /** Capture the validated protocol and its raw-byte seal together for a frozen attempt. */
128
- export function readDesign(dir: string): { protocol: Protocol; treeHash: string; binding: string } | undefined {
194
+ /** Capture the validated protocol and design seal; input identities omit locators, legacy bytes stay bound. */
195
+ export function readDesign(dir: string): { protocol: ProtocolDefinition; treeHash: string; binding: string } | undefined {
129
196
  const file = join(dir, "design", "protocol.json");
130
197
  if (!existsSync(file)) return undefined;
131
198
  const text = readTextBounded(file, PROTOCOL_BYTES);
132
199
  let raw: unknown; try { raw = JSON.parse(text); } catch { throw new Error("protocol: invalid JSON; restore design/protocol.json with a valid ares protocol input"); }
133
- const protocol = validateProtocol(raw), treeHash = taskTreeHash(dir);
200
+ const protocol = validateProtocolDefinition(raw), treeHash = taskTreeHash(dir);
134
201
  const selected = selectionHash(dir, protocol), reserved = finalSeedsHash(dir, protocol);
135
- return { protocol, treeHash, binding: sha256(JSON.stringify([sha256(text), treeHash, ...(selected !== undefined ? [selected] : []), ...(reserved !== undefined ? [reserved] : [])])) };
202
+ return { protocol, treeHash, binding: sha256(JSON.stringify([protocolSealHash(protocol, text), treeHash, ...(selected !== undefined ? [selected] : []), ...(reserved !== undefined ? [reserved] : [])])) };
136
203
  }
137
204
  /** Caller holds the study lock, as with setScope. Validate everything before any write. */
138
- export function setProtocol(dir: string, raw: unknown, actor: Actor): Protocol {
205
+ export function setProtocol(dir: string, raw: unknown, actor: Actor): ProtocolDefinition {
139
206
  requireExperiment(openStudy(dir).study);
140
- const protocol = validateProtocol(raw);
207
+ const protocol = validateProtocolDefinition(raw);
141
208
  requireCopilotAccept(dir, "hypotheses");
142
209
  const treeHash = taskTreeHash(dir), text = JSON.stringify(protocol, null, 2) + "\n";
143
210
  // Never commit a protocol that makes its existing selection unreadable.
144
211
  selectionHash(dir, protocol);
145
212
  finalSeedsHash(dir, protocol);
146
- commit(dir, [[join(dir, "design", "protocol.json"), text, PROTOCOL_BYTES]], [{ actor, type: "protocol.set", data: { sha256: sha256(text), protocolHash: protocolHash(protocol), treeHash } }]);
213
+ commit(dir, [[join(dir, "design", "protocol.json"), text, PROTOCOL_BYTES]], [{ actor, type: "protocol.set", data: { sha256: sha256(text), ...((protocol.v === 1 && protocol.inputs === undefined) ? {} : { identitySha256: protocolSealHash(protocol, text) }), protocolHash: protocolHash(protocol), treeHash } }]);
147
214
  return protocol;
148
215
  }