@staix/agent-research 0.2.1 → 0.3.1
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/CHANGELOG.md +129 -0
- package/README.md +261 -24
- package/package.json +2 -2
- package/src/cli.ts +117 -10
- package/src/commands-table.ts +39 -8
- package/src/commands.ts +201 -34
- package/src/exp/artifacts.ts +20 -2
- package/src/exp/attempts.ts +505 -65
- package/src/exp/executor.ts +264 -17
- package/src/exp/final.ts +1 -1
- package/src/exp/logs.ts +25 -12
- package/src/exp/metrics.ts +8 -9
- package/src/exp/pipeline.ts +92 -0
- package/src/exp/protocol.ts +87 -20
- package/src/exp/retention-script.ts +649 -0
- package/src/exp/retention.ts +70 -0
- package/src/exp/reuse-admission.ts +65 -0
- package/src/exp/reuse-contract.ts +48 -0
- package/src/exp/reuse-runtime.ts +91 -0
- package/src/exp/reuse.ts +87 -0
- package/src/exp/selection.ts +1 -1
- package/src/exp/snapshot.ts +30 -10
- package/src/exp/stages.ts +117 -0
- package/src/harness/experience-source.ts +34 -0
- package/src/harness/experience.ts +206 -0
- package/src/harness/hub-guidance.ts +140 -0
- package/src/harness/hub-reference.ts +18 -0
- package/src/harness/lesson-candidates.ts +162 -0
- package/src/harness/limits.ts +2 -0
- package/src/harness/privacy.ts +4 -0
- package/src/harness/receipts.ts +84 -0
- package/src/harness/rounds.ts +198 -0
- package/src/harness/transitions.ts +152 -0
- package/src/lit/candidates.ts +13 -5
- package/src/lit/cards.ts +55 -4
- package/src/lit/flow.ts +82 -0
- package/src/lit/queries.ts +62 -0
- package/src/manifest.ts +13 -6
- package/src/mcp-tools.ts +123 -25
- package/src/mcp.ts +4 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +17 -8
- package/src/memory/evidence-local.ts +77 -0
- package/src/memory/evidence.ts +39 -0
- package/src/memory/lessons.ts +4 -2
- package/src/memory/skill-check.ts +56 -0
- package/src/memory/skill-format.ts +77 -0
- package/src/memory/skills.ts +72 -26
- package/src/memory/source-budget.ts +11 -0
- package/src/memory/vault-cards.ts +226 -0
- package/src/paper/build.ts +16 -7
- package/src/paper/check.ts +37 -10
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +16 -1
- package/src/paper/plan.ts +170 -0
- package/src/paper/point-evidence.ts +63 -0
- package/src/paper/points.ts +83 -0
- package/src/paper/review.ts +102 -9
- package/src/paper/scopes.ts +51 -0
- package/src/plan/definition.ts +5 -1
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +5 -0
- package/src/playbook.ts +35 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +55 -27
- package/src/study.ts +54 -14
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +263 -6
- package/src/ui/plugin.ts +68 -10
package/src/commands.ts
CHANGED
|
@@ -1,25 +1,32 @@
|
|
|
1
|
+
import {proposeLesson, decideLesson, checkLesson, listLessonCandidates} from "./harness/lesson-candidates.ts";
|
|
2
|
+
import type {SkillCheckOptions} from "./memory/skill-check.ts";
|
|
3
|
+
import {setHarnessStream, readHarnessStream, selectExperience, freezeExperience, checkExperience} from "./harness/experience.ts";
|
|
4
|
+
import {harnessRoundBinding, readHarnessRounds, type HarnessRound, setHarnessRound, showHarness, importHarnessFixture, recordHarnessTransition} from "./harness/rounds.ts";
|
|
5
|
+
import { readProvenance, compareLineage, attemptReuseView, type ProvenanceOptions, type ProvenancePage, type LineageComparison } from "./provenance.ts";
|
|
1
6
|
import { validateAutonomyMode, validatePhase, PHASES, ACCEPT_ARTIFACTS, resolveAutonomy, type AcceptArtifact, type Autonomy } from "./autonomy.ts";
|
|
2
7
|
import { copilotBinding, requireCopilotAccept } from "./copilot.ts";
|
|
3
8
|
import { homedir } from "node:os";
|
|
4
9
|
import { addStudy, removeStudy, readRegistry } from "./console/registry.ts";
|
|
5
10
|
import { readWatchSnapshot, setWatch, runWatch, showWatch, recordWatchFailure, watchFailureClass, type WatchSnapshot } from "./lit/watch.ts";
|
|
6
11
|
import { runSetup, type SetupMode } from "./setup.ts";
|
|
7
|
-
import { proposeSkill, decideSkill, listSkills } from "./memory/skills.ts";
|
|
12
|
+
import { proposeSkill, decideSkill, listSkills, checkSkill } from "./memory/skills.ts";
|
|
8
13
|
import { rankLessons, type LessonRankOptions } from "./memory/lessons.ts";
|
|
9
14
|
import { createAmemClient } from "./memory/amem.ts";
|
|
10
15
|
import { previewArchive, exportArchive, type ArchivePreview, type ArchiveResult } from "./memory/archive.ts";
|
|
11
|
-
import { addReview, resolveReview, reviewReadiness, reviewBinding, requireReviewReady } from "./paper/review.ts";
|
|
16
|
+
import { addReview, resolveReview, reviewChecklist, reviewReadiness, reviewBinding, requireReviewReady } from "./paper/review.ts";
|
|
12
17
|
import { buildPaper } from "./paper/build.ts";
|
|
13
18
|
import { checkPaper } from "./paper/check.ts";
|
|
19
|
+
import { setPaperPlan, showPaperPlan } from "./paper/plan.ts";
|
|
14
20
|
import { addAblation, showAblate, closeAblate } from "./exp/ablate.ts";
|
|
15
21
|
import { setFinalSeeds, finalGateBinding, requireFinalInputs, closeFinal, showPosthoc } from "./exp/final.ts";
|
|
16
22
|
import { addIdea, decideIdea } from "./exp/ideas.ts";
|
|
17
23
|
import { showInvestigation, closeInvestigation } from "./exp/investigate.ts";
|
|
18
|
-
import {
|
|
24
|
+
import { isInvestigationRun } from "./exp/reuse-runtime.ts";
|
|
25
|
+
import { readSelection, setSelection } from "./exp/selection.ts";
|
|
19
26
|
import { createHubClient } from "./plan/hub.ts";
|
|
20
27
|
import { runPlan, type ControllerRuntime, type Observation, type StepNode } from "./plan/controller.ts";
|
|
21
28
|
import { resolveSnapshot } from "./exp/snapshot.ts";
|
|
22
|
-
import { spawnRunner } from "./exp/executor.ts";
|
|
29
|
+
import { GpuAdmissionDeferred, spawnRunner } from "./exp/executor.ts";
|
|
23
30
|
import { foldPlan, readPlanState, planGateBinding, prepareControl, type ControlRequest, type ControlResult } from "./plan/state.ts";
|
|
24
31
|
import { setPlan } from "./plan/definition.ts";
|
|
25
32
|
export { manifest } from "./manifest.ts";
|
|
@@ -28,28 +35,38 @@ import { existsSync, readdirSync, utimesSync } from "node:fs";
|
|
|
28
35
|
import { join, resolve } from "node:path";
|
|
29
36
|
import type { Http } from "./http.ts";
|
|
30
37
|
import { readScope, scopeHash, setScope } from "./scope.ts";
|
|
31
|
-
import { boundedText, commit, decideGate, gateState, GATES, initStudy, openStudy, readBytesBounded, readLedger, readTextBounded, requireGate, sha256, withLock, readPlanOwner, type Actor, type Binder, type GateName, type Study, STUDY_BYTES } from "./study.ts";
|
|
38
|
+
import { boundedText, commit, decideGate, gateState, GATES, initStudy, openStudy, readBytesBounded, readLedger, readTextBounded, requireGate, isHarnessGate, sha256, withLock, readPlanOwner, type Actor, type Binder, type GateName, type Study, STUDY_BYTES } from "./study.ts";
|
|
32
39
|
import { candidatesFile, includedHash, isVerified, loadCandidates, mergeCandidates, sameWork, verifySubject, type Candidate } from "./lit/candidates.ts";
|
|
40
|
+
import { litQueries, nextSearchId, validateIntent } from "./lit/queries.ts";
|
|
41
|
+
import { flowMarkdown, litFlow } from "./lit/flow.ts";
|
|
33
42
|
import { searchSource, SOURCES, type SourceName } from "./lit/sources.ts";
|
|
34
43
|
import { verifyCandidates } from "./lit/verify.ts";
|
|
35
44
|
import { assignCitekeys, renderBib } from "./lit/bibtex.ts";
|
|
36
45
|
import { checkCitations } from "./lit/cite.ts";
|
|
37
46
|
import { cardPath, validateCard } from "./lit/cards.ts";
|
|
38
|
-
import {
|
|
47
|
+
import { createVaultClient, exportCards, importCards, listCards, previewCardExport } from "./memory/vault-cards.ts";
|
|
48
|
+
import { designBinding, protocolHash, readDesign, readProtocol, setProtocol } from "./exp/protocol.ts";
|
|
39
49
|
import { requireExperiment } from "./study.ts";
|
|
40
|
-
import { checkExecutor, setExecutor } from "./exp/executor.ts";
|
|
50
|
+
import { checkExecutor, setExecutor, readExecutor, hashExecutorInput, type InputManifest } from "./exp/executor.ts";
|
|
41
51
|
import { cancelAttempt, listAttempts, listAttemptSummaries, reconcileAttempts, runAttempt, showAttempt, type AttemptContext, type AttemptListOptions, type AttemptOptions } from "./exp/attempts.ts";
|
|
42
52
|
import { readAttemptLogs, type LogOptions } from "./exp/logs.ts";
|
|
53
|
+
import { retainedOperation, type RetainedRef, type RetentionResult } from "./exp/retention.ts";
|
|
54
|
+
import { assertStudyReadLock, onlyKeys, plain, prepareCommit, type PendingEvent } from "./study.ts";
|
|
43
55
|
|
|
44
56
|
export type ExperimentRuntime = Omit<AttemptContext, "actor">;
|
|
45
57
|
export interface Ctx extends ExperimentRuntime { actor: Actor; http: Http; signal?: AbortSignal }
|
|
46
58
|
const MAX_IDS = 200, DRAFT_BYTES = 2 * 1024 * 1024, BIB_BYTES = 16 * 1024 * 1024, CARD_BYTES = 65_536;
|
|
47
59
|
|
|
48
|
-
export function binder(dir: string): Binder {
|
|
49
|
-
|
|
60
|
+
export function binder(dir: string, rounds?: readonly HarnessRound[]): Binder {
|
|
61
|
+
let harness = rounds === undefined ? undefined : new Map(rounds.map(round => [round.id, harnessRoundBinding(round)]));
|
|
62
|
+
const harnessHash = (id: string) => {
|
|
63
|
+
harness ??= new Map(readHarnessRounds(dir).map(round => [round.id, harnessRoundBinding(round)]));
|
|
64
|
+
return harness.get(id);
|
|
65
|
+
};
|
|
66
|
+
return gate => isHarnessGate(gate) ? harnessHash(gate.slice(8)) : gate.startsWith("accept:") ? copilotBinding(dir, gate.slice(7) as AcceptArtifact) : gate === "review" ? reviewBinding(dir) : gate === "final" ? finalGateBinding(dir) : gate.startsWith("plan:") ? planGateBinding(readPlanState(dir, readLedger(dir)), gate) : gate === "scope" ? scopeHash(dir) : gate === "design" ? designBinding(dir) : includedHash(loadCandidates(dir));
|
|
50
67
|
}
|
|
51
68
|
function gateName(value: string): GateName {
|
|
52
|
-
if (!GATES.includes(value as GateName) && !ACCEPT_ARTIFACTS.some(artifact => value === `accept:${artifact}`) && !value.startsWith("plan:")) throw new Error("unknown gate: unsupported name; run ares gate list <dir> and choose a listed gate before approval or rejection");
|
|
69
|
+
if (!GATES.includes(value as GateName) && !ACCEPT_ARTIFACTS.some(artifact => value === `accept:${artifact}`) && !value.startsWith("plan:") && !isHarnessGate(value)) throw new Error("unknown gate: unsupported name; run ares gate list <dir> and choose a listed gate before approval or rejection");
|
|
53
70
|
return value as GateName;
|
|
54
71
|
}
|
|
55
72
|
function ids(values: string[]): string[] {
|
|
@@ -97,10 +114,103 @@ export async function executorSet(dirArg: string, raw: unknown, ctx: Ctx) {
|
|
|
97
114
|
const { dir } = openStudy(dirArg);
|
|
98
115
|
return withLock(dir, () => setExecutor(dir, raw, ctx.actor));
|
|
99
116
|
}
|
|
117
|
+
/** Read only configured executor-host inputs; no paths or bodies are recorded in the study. */
|
|
118
|
+
export async function executorInputsHash(dirArg: string, path: string, ctx: Ctx): Promise<InputManifest> {
|
|
119
|
+
const { dir, study } = openStudy(dirArg); requireExperiment(study);
|
|
120
|
+
const executor = readExecutor(dir);
|
|
121
|
+
if (!executor) throw new Error("executor: not configured; run ares executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH");
|
|
122
|
+
return hashExecutorInput(executor, path, ctx.runner);
|
|
123
|
+
}
|
|
100
124
|
export const executorCheck = (dir: string, ctx: Ctx) => checkExecutor(dir, ctx.runner);
|
|
101
|
-
|
|
125
|
+
|
|
126
|
+
function retentionRefs(raw: unknown): RetainedRef[] {
|
|
127
|
+
if (!Array.isArray(raw) || !raw.length || raw.length > 500) throw new Error("retention refs: select 1..500 explicit retained references");
|
|
128
|
+
const seen = new Set<string>();
|
|
129
|
+
return raw.map(value => {
|
|
130
|
+
if (!plain(value)) throw new Error("retention refs: each reference must be an object");
|
|
131
|
+
onlyKeys(value, ["attemptId", "stage", "sha256"], "retention reference");
|
|
132
|
+
if (typeof value.attemptId !== "string" || !/^[a-f0-9]{16}$/.test(value.attemptId) || typeof value.stage !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(value.stage) || ["constructor", "prototype", "__proto__"].includes(value.stage) || typeof value.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.sha256)) throw new Error("retention reference: invalid attempt, stage or manifest digest; use identities from retention inspect");
|
|
133
|
+
const key = `${value.attemptId}/${value.stage}`;
|
|
134
|
+
if (seen.has(key)) throw new Error("retention refs: duplicate source; select each attempt/stage once");
|
|
135
|
+
seen.add(key);
|
|
136
|
+
return { attemptId: value.attemptId, stage: value.stage, sha256: value.sha256 };
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function retentionExecutor(dirArg: string) {
|
|
140
|
+
const { dir, study } = openStudy(dirArg); requireExperiment(study);
|
|
141
|
+
const executor = readExecutor(dir);
|
|
142
|
+
if (!executor) throw new Error("executor: not configured; configure an executor before retention inspect or prune");
|
|
143
|
+
return { dir, study, executor };
|
|
144
|
+
}
|
|
145
|
+
/** Read-only study operation; the executor serializes inventory with producer/consumer/prune state. */
|
|
146
|
+
export async function retentionInspect(dirArg: string, ctx: Pick<Ctx, "runner">, options: { offset?: number; limit?: number } = {}): Promise<RetentionResult> {
|
|
147
|
+
if (!plain(options)) throw new Error("retention inspect: options object required");
|
|
148
|
+
onlyKeys(options, ["offset", "limit"], "retention inspect");
|
|
149
|
+
if (options.offset !== undefined && (!Number.isSafeInteger(options.offset) || options.offset < 0 || options.offset > 16_000_000) || options.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > 500)) throw new Error("retention inspect: use offset 0..16000000 and limit 1..500");
|
|
150
|
+
const { study, executor } = retentionExecutor(dirArg);
|
|
151
|
+
return retainedOperation(executor, { op: "inspect", studyId: study.id, ...options }, ctx.runner ?? spawnRunner);
|
|
152
|
+
}
|
|
153
|
+
/** Preview has no local receipt. Confirmation checks current policy and records only a validated disposal. */
|
|
154
|
+
export async function retentionPrune(dirArg: string, options: { refs: RetainedRef[]; fingerprint?: string }, ctx: Ctx): Promise<RetentionResult> {
|
|
155
|
+
if (!plain(options)) throw new Error("retention prune: options object required");
|
|
156
|
+
onlyKeys(options, ["refs", "fingerprint"], "retention prune");
|
|
157
|
+
const refs = retentionRefs(options.refs), fingerprint = options.fingerprint;
|
|
158
|
+
if (fingerprint !== undefined && (typeof fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(fingerprint))) throw new Error("retention prune: invalid fingerprint; preview the exact references before confirming");
|
|
159
|
+
const initial = retentionExecutor(dirArg);
|
|
160
|
+
const request = { op: "prune" as const, studyId: initial.study.id, refs, ...(fingerprint === undefined ? {} : { fingerprint }) };
|
|
161
|
+
const checked = async (executor: typeof initial.executor) => {
|
|
162
|
+
const result = await retainedOperation(executor, request, ctx.runner ?? spawnRunner);
|
|
163
|
+
if (typeof result.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(result.fingerprint) || result.pruned !== (fingerprint === undefined ? 0 : refs.length) || (fingerprint !== undefined && result.fingerprint !== fingerprint)) throw new Error("retention prune: invalid executor receipt; inspect authoritative tombstones before retrying");
|
|
164
|
+
return { op: "prune" as const, fingerprint: result.fingerprint, pruned: result.pruned };
|
|
165
|
+
};
|
|
166
|
+
if (fingerprint === undefined) return checked(initial.executor);
|
|
167
|
+
return withLock(initial.dir, async lock => {
|
|
168
|
+
const { dir, study, executor } = retentionExecutor(initial.dir);
|
|
169
|
+
requireCopilotAccept(dir, "hypotheses");
|
|
170
|
+
const binding = designBinding(dir), approval = requireGate(dir, study, "design", binder(dir));
|
|
171
|
+
const event: PendingEvent = { actor: ctx.actor, type: "retention.pruned", data: { fingerprint, refsSha256: sha256(JSON.stringify(refs)), count: refs.length, refs: refs.map(ref => [ref.attemptId, ref.stage, ref.sha256]) } };
|
|
172
|
+
prepareCommit(dir, [], [...approval, event]);
|
|
173
|
+
assertStudyReadLock(dir, lock);
|
|
174
|
+
const result = await checked(executor);
|
|
175
|
+
// Executor tombstones are authoritative across a crash before this local audit receipt.
|
|
176
|
+
assertStudyReadLock(dir, lock);
|
|
177
|
+
if (designBinding(dir) !== binding) throw new Error("retention prune: design changed during disposal; inspect authoritative tombstones before retrying");
|
|
178
|
+
commit(dir, [], [...approval, event]);
|
|
179
|
+
return result;
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export const harnessStreamSet = (dir: string, raw: unknown, ctx: Ctx) => withLock(dir, () => setHarnessStream(dir, raw, ctx.actor));
|
|
184
|
+
export const harnessStreamShow = (dir: string) => readHarnessStream(dir);
|
|
185
|
+
export const experienceSelect = (dir: string, raw: unknown, ctx: Pick<Ctx, "runner" | "now">, env: NodeJS.ProcessEnv = process.env) => selectExperience(dir, raw, {...ctx, env});
|
|
186
|
+
export const experienceFreeze = (dir: string, raw: unknown, ctx: Ctx, env: NodeJS.ProcessEnv = process.env) => withLock(dir, lock => freezeExperience(dir, raw, ctx.actor, {...ctx, env, lock}));
|
|
187
|
+
export const experienceCheck = (dir: string, round: string, identity: {model: string; runtime: string; toolsetSha256?: string}, ctx: Pick<Ctx, "runner" | "now">, env: NodeJS.ProcessEnv = process.env) => checkExperience(dir, round, identity, {...ctx, env});
|
|
188
|
+
export const harnessSet = (dir: string, raw: unknown, ctx: Ctx) => withLock(dir, () => setHarnessRound(dir, raw, ctx.actor));
|
|
189
|
+
export const harnessContrast = (dir: string, round: string, raw: unknown, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "contrast", raw, ctx.actor));
|
|
190
|
+
export const harnessCompose = (dir: string, round: string, raw: unknown, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "composition", raw, ctx.actor));
|
|
191
|
+
export const harnessClose = (dir: string, round: string, raw: unknown, confirm: string | undefined, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "closure", raw, ctx.actor, confirm));
|
|
192
|
+
export const harnessAdopt = (dir: string, round: string, raw: unknown, confirm: string | undefined, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "adoption", raw, ctx.actor, confirm));
|
|
193
|
+
export const harnessShow = (dir: string, round?: string) => showHarness(dir, round);
|
|
194
|
+
export const harnessImport = (dir: string, round: string, raw: unknown, ctx: Ctx) => withLock(dir, () => importHarnessFixture(dir, round, raw, ctx.actor));
|
|
195
|
+
export async function attemptRun(dir: string, options: AttemptOptions, ctx: Ctx) {
|
|
196
|
+
if (options.reuse !== undefined && options.reuse !== "off" && options.reuse !== "eligible") throw new Error("attempt reuse: off or eligible required; select --reuse off|eligible (MCP reuse) and retry");
|
|
197
|
+
if (options.forceFresh !== undefined && typeof options.forceFresh !== "boolean") throw new Error("attempt forceFresh: boolean required; set forceFresh to true/false or use --force-fresh, then retry");
|
|
198
|
+
const protocol = options.reuse === "eligible" ? readProtocol(dir) : undefined;
|
|
199
|
+
const selection = protocol ? readSelection(dir, protocol) : undefined;
|
|
200
|
+
const warnings = options.reuse === "eligible" && !isInvestigationRun(options.run ?? "main", selection)
|
|
201
|
+
? [{ code: "outside-investigation", cause: "not an investigation run", nextStep: "declare the selection run, or drop --reuse" }] : undefined;
|
|
202
|
+
let result;
|
|
203
|
+
try { result = await runAttempt(dir, options, ctx); }
|
|
204
|
+
catch (error) { if (error instanceof GpuAdmissionDeferred) result = error.result; else throw error; }
|
|
205
|
+
return warnings ? { ...result, warnings } : result;
|
|
206
|
+
}
|
|
102
207
|
export const attemptList = (dir: string, options: AttemptListOptions = {}) => listAttemptSummaries(dir, options);
|
|
103
|
-
export const attemptShow = (dir: string, id: string) =>
|
|
208
|
+
export const attemptShow = (dir: string, id: string) => {
|
|
209
|
+
const attempt = showAttempt(dir, id);
|
|
210
|
+
if (attempt.v !== 3) return attempt;
|
|
211
|
+
const reuseView = attemptReuseView(attempt, readLedger(dir));
|
|
212
|
+
return reuseView === undefined ? attempt : {...attempt, reuseView};
|
|
213
|
+
};
|
|
104
214
|
export const attemptCancel = (dir: string, id: string, reason: string | undefined, ctx: Ctx) => cancelAttempt(dir, id, reason, ctx);
|
|
105
215
|
export const attemptReconcile = (dir: string, ctx: Ctx) => reconcileAttempts(dir, ctx);
|
|
106
216
|
export const attemptLogs = (dir: string, id: string, options: LogOptions, ctx: Ctx) => readAttemptLogs(dir, id, options, ctx.runner);
|
|
@@ -135,16 +245,17 @@ export async function scope(dirArg: string, raw: unknown, ctx: Ctx) {
|
|
|
135
245
|
}
|
|
136
246
|
|
|
137
247
|
export function gateList(dirArg: string) {
|
|
138
|
-
const { dir, study } = openStudy(dirArg), events = readLedger(dir)
|
|
248
|
+
const { dir, study } = openStudy(dirArg), events = readLedger(dir);
|
|
249
|
+
const harness = study.mode === "experiment" ? readHarnessRounds(dir, events) : [], bind = binder(dir, harness);
|
|
139
250
|
const plan = foldPlan(events);
|
|
140
251
|
const accepts = ACCEPT_ARTIFACTS.filter(artifact => resolveAutonomy(study.autonomy, `accept:${artifact}`) === "copilot").map(artifact => `accept:${artifact}` as GateName);
|
|
141
|
-
const gates: GateName[] = [...accepts, ...GATES.filter(g => (g !== "design" && g !== "final") || study.mode === "experiment"), ...(plan?.nodes.filter(n => n.kind === "gate").map(n => `plan:${n.id}` as GateName) ?? [])];
|
|
252
|
+
const gates: GateName[] = [...accepts, ...GATES.filter(g => (g !== "design" && g !== "final") || study.mode === "experiment"), ...(plan?.nodes.filter(n => n.kind === "gate").map(n => `plan:${n.id}` as GateName) ?? []), ...harness.map(round => `harness:${round.id}` as GateName)];
|
|
142
253
|
return gates.map(g => gateState(g, events, bind));
|
|
143
254
|
}
|
|
144
255
|
|
|
145
256
|
export async function gateDecide(dirArg: string, gate: string, decision: "approve" | "reject", reason: string | undefined, ctx: Ctx, guard?: () => void) {
|
|
146
257
|
const { dir, study } = openStudy(dirArg), name = gateName(gate), why = reason === undefined ? undefined : boundedText(reason, "--reason", 500);
|
|
147
|
-
if (name === "design" || name === "final") requireExperiment(study);
|
|
258
|
+
if (name === "design" || name === "final" || isHarnessGate(name)) requireExperiment(study);
|
|
148
259
|
return withLock(dir, () => {
|
|
149
260
|
guard?.();
|
|
150
261
|
if (name === "final") requireFinalInputs(dir);
|
|
@@ -154,11 +265,12 @@ export async function gateDecide(dirArg: string, gate: string, decision: "approv
|
|
|
154
265
|
});
|
|
155
266
|
}
|
|
156
267
|
|
|
157
|
-
export async function search(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number }, ctx: Ctx) {
|
|
268
|
+
export async function search(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number; intent?: string }, ctx: Ctx) {
|
|
158
269
|
const { dir } = openStudy(dirArg); return withLock(dir, () => searchLocked(dir, query, options, ctx));
|
|
159
270
|
}
|
|
160
|
-
async function searchLocked(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number }, ctx: Ctx) {
|
|
271
|
+
async function searchLocked(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number; intent?: string }, ctx: Ctx) {
|
|
161
272
|
const { dir, study } = openStudy(dirArg), q = boundedText(query, "query", 500);
|
|
273
|
+
const intent = options.intent === undefined ? undefined : validateIntent(options.intent);
|
|
162
274
|
const source = options.source ?? "all";
|
|
163
275
|
if (source !== "all" && !SOURCES.includes(source as SourceName)) throw new Error("--source: openalex, s2, arxiv or all");
|
|
164
276
|
const limit = options.limit ?? 20;
|
|
@@ -172,15 +284,20 @@ async function searchLocked(dirArg: string, query: string, options: { source?: s
|
|
|
172
284
|
const names = source === "all" ? SOURCES : [source as SourceName];
|
|
173
285
|
const results = [];
|
|
174
286
|
for (const name of names) results.push(await searchSource(ctx.http, name, q, { limit, ...(yearFrom !== undefined ? { yearFrom } : {}), ...(sc.yearTo !== undefined ? { yearTo: sc.yearTo } : {}) }));
|
|
175
|
-
const list = loadCandidates(dir), counts = mergeCandidates(list, results.flatMap(r => r.records), sc.maxCandidates);
|
|
287
|
+
const list = loadCandidates(dir), counts = mergeCandidates(list, results.flatMap(r => r.records), sc.maxCandidates, undefined, nextSearchId(readLedger(dir)));
|
|
176
288
|
const sources = results.map(r => ({ source: r.source, ok: r.ok, returned: r.records.length, ...(r.error ? { error: r.error } : {}) }));
|
|
177
289
|
// A search where every source failed is recorded but is not a success, so it approves nothing.
|
|
178
290
|
const answered = sources.some(r => r.ok);
|
|
179
|
-
|
|
180
|
-
|
|
291
|
+
// Intent and year-from are added only when given, so a search without them keeps the earlier event shape.
|
|
292
|
+
commit(dir, [candidatesFile(dir, list)], [...(answered ? approval : []), { actor: ctx.actor, type: "lit.search", data: { query: q, ...(intent ? { intent } : {}), ...(options.yearFrom !== undefined ? { yearFrom: options.yearFrom } : {}), sources, ...counts } }]);
|
|
293
|
+
return { query: q, ...(intent ? { intent } : {}), sources, ...counts, candidates: list.length };
|
|
181
294
|
|
|
182
295
|
}
|
|
183
296
|
|
|
297
|
+
export const queries = (dir: string) => litQueries(dir);
|
|
298
|
+
export const flowMarkdownView = (dir: string) => ({ markdown: flowMarkdown(dir) });
|
|
299
|
+
export const litFlowView = (dir: string) => litFlow(dir);
|
|
300
|
+
export function flow(dir: string, format: "json" | "markdown" = "json") { return format === "markdown" ? flowMarkdownView(dir) : litFlow(dir); }
|
|
184
301
|
export function list(dirArg: string, options: { status?: string; limit?: number }) {
|
|
185
302
|
const { dir } = openStudy(dirArg), limit = options.limit ?? 50;
|
|
186
303
|
if (options.status !== undefined && !["new", "included", "excluded"].includes(options.status)) throw new Error("--status: new, included or excluded");
|
|
@@ -197,10 +314,15 @@ export function list(dirArg: string, options: { status?: string; limit?: number
|
|
|
197
314
|
};
|
|
198
315
|
}
|
|
199
316
|
|
|
200
|
-
export async function screen(dirArg: string, values: string[], decision: "include" | "exclude", reason: string | undefined, ctx: Ctx, guard?: () => void) {
|
|
317
|
+
export async function screen(dirArg: string, values: string[], decision: "include" | "exclude", reason: string | undefined, ctx: Ctx, guard?: () => void, code?: string) {
|
|
201
318
|
const { dir, study } = openStudy(dirArg), wanted = ids(values), why = reason === undefined ? undefined : boundedText(reason, "--reason", 500);
|
|
319
|
+
if (code !== undefined && decision !== "exclude") throw new Error("lit screen: --code applies only with --exclude; drop --code or exclude instead");
|
|
202
320
|
return withLock(dir, () => {
|
|
203
321
|
guard?.();
|
|
322
|
+
if (code !== undefined) {
|
|
323
|
+
const declared = readScope(dir)?.exclusionCodes ?? [];
|
|
324
|
+
if (!declared.some(item => item.code === code)) throw new Error(`lit screen: unknown exclusion code ${JSON.stringify(code).slice(0, 40)}; declare it in scope.json exclusionCodes (${declared.length ? declared.map(item => item.code).join(", ") : "none declared"}) and rerun ares scope, or omit --code`);
|
|
325
|
+
}
|
|
204
326
|
const all = loadCandidates(dir), at = new Date().toISOString(), status = decision === "include" ? "included" : "excluded";
|
|
205
327
|
for (const id of wanted) find(all, id);
|
|
206
328
|
const approval = requireGate(dir, study, "scope", binder(dir));
|
|
@@ -208,8 +330,9 @@ export async function screen(dirArg: string, values: string[], decision: "includ
|
|
|
208
330
|
const c = find(all, id);
|
|
209
331
|
c.status = status; c.decidedBy = ctx.actor; c.decidedAt = at;
|
|
210
332
|
if (why) c.reason = why; else delete c.reason;
|
|
333
|
+
if (code !== undefined) c.exclusionCode = code; else delete c.exclusionCode;
|
|
211
334
|
}
|
|
212
|
-
commit(dir, [candidatesFile(dir, all)], [...approval, { actor: ctx.actor, type: "lit.screen", data: { ids: wanted, decision, ...(why ? { reason: why } : {}) } }]);
|
|
335
|
+
commit(dir, [candidatesFile(dir, all)], [...approval, { actor: ctx.actor, type: "lit.screen", data: { ids: wanted, decision, ...(why ? { reason: why } : {}), ...(code !== undefined ? { code } : {}) } }]);
|
|
213
336
|
return { decision, ids: wanted, gate: gateState("screen", readLedger(dir), binder(dir)) };
|
|
214
337
|
});
|
|
215
338
|
}
|
|
@@ -226,6 +349,20 @@ export async function card(dirArg: string, id: string, raw: unknown, ctx: Ctx) {
|
|
|
226
349
|
});
|
|
227
350
|
}
|
|
228
351
|
|
|
352
|
+
/** Read-only without --confirm; with the current fingerprint, writes each card to its vault reference note. Needs the scope gate. */
|
|
353
|
+
export async function cardExport(dirArg: string, ids: string[], options: { vault: string; confirm?: string; modelFamily?: string }, ctx: Pick<Ctx, "actor" | "runner">, env: NodeJS.ProcessEnv = process.env) {
|
|
354
|
+
const { dir, study } = openStudy(dirArg);
|
|
355
|
+
if (options.confirm === undefined) { const { payloads: _p, ...preview } = previewCardExport(dir, options.vault, ids, options.modelFamily); return { ...preview, wouldWrite: true }; }
|
|
356
|
+
const client = createVaultClient(options.vault, dir, ctx.runner, env);
|
|
357
|
+
return exportCards(dir, options.vault, ids, options.confirm, ctx.actor, client, () => requireGate(dir, study, "scope", binder(dir)), options.modelFamily);
|
|
358
|
+
}
|
|
359
|
+
/** Copies cards from vault reference notes for included, identifier-verified candidates; needs the scope gate and never changes verification, screening or other gates. */
|
|
360
|
+
export async function cardImport(dirArg: string, ids: string[], options: { vault: string }, ctx: Pick<Ctx, "actor" | "runner">, env: NodeJS.ProcessEnv = process.env) {
|
|
361
|
+
const { dir, study } = openStudy(dirArg), client = createVaultClient(options.vault, dir, ctx.runner, env);
|
|
362
|
+
return importCards(dir, options.vault, ids, ctx.actor, client, () => requireGate(dir, study, "scope", binder(dir)));
|
|
363
|
+
}
|
|
364
|
+
export const cardList = (dir: string) => listCards(dir);
|
|
365
|
+
|
|
229
366
|
/**
|
|
230
367
|
* Without ids: included candidates never checked, checked against other identifiers, or left unknown, up to 200.
|
|
231
368
|
* Final results (no identifier, not found, title or year mismatch) are skipped so the batch always advances;
|
|
@@ -322,15 +459,19 @@ function stepNumber(node: StepNode, key: string): number | undefined {
|
|
|
322
459
|
}
|
|
323
460
|
export async function planRun(dirArg: string, options: { parallel?: number }, ctx: Ctx) {
|
|
324
461
|
const { dir } = openStudy(dirArg);
|
|
325
|
-
const attemptOptions = (node: StepNode, retryOf?: string) => {
|
|
462
|
+
const attemptOptions = (node: StepNode, retryOf?: string): AttemptOptions => {
|
|
326
463
|
const parent = retryOf ?? (node.args.retry !== undefined ? stepText(node, "retry") : undefined);
|
|
327
464
|
const retry = parent && listAttempts(dir).attempts.some(a => a.id === parent) ? parent : undefined;
|
|
465
|
+
const reuse = node.args.reuse;
|
|
466
|
+
if (reuse !== undefined && reuse !== "off" && reuse !== "eligible") throw new Error("plan attempt reuse: off or eligible required; correct args.reuse with ares plan set <dir>, then retry the node explicitly");
|
|
467
|
+
const forceFresh = node.args["force-fresh"];
|
|
468
|
+
if (forceFresh !== undefined && typeof forceFresh !== "boolean") throw new Error("plan attempt force-fresh: boolean required; correct args.force-fresh with ares plan set <dir>, then retry the node explicitly");
|
|
328
469
|
return {
|
|
329
470
|
repo: resolve(dir, stepText(node, "repo")), commit: stepText(node, "commit"),
|
|
330
471
|
...(stepNumber(node, "seed") !== undefined ? { seed: stepNumber(node, "seed")! } : {}),
|
|
331
472
|
...(node.args.run !== undefined ? { run: stepText(node, "run") } : {}),
|
|
332
473
|
...(node.args.label !== undefined ? { label: stepText(node, "label") } : {}),
|
|
333
|
-
...(retry ? { retry } : {}), detach: true,
|
|
474
|
+
...(retry ? { retry } : {}), ...(reuse === undefined ? {} : { reuse }), ...(forceFresh === undefined ? {} : { forceFresh }), detach: true,
|
|
334
475
|
};
|
|
335
476
|
};
|
|
336
477
|
const observed = (attempt: ReturnType<typeof showAttempt>): Observation => ({
|
|
@@ -352,7 +493,13 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
|
|
|
352
493
|
return { attemptId: attemptId(protocolHash(design.protocol), snapshot.commit, snapshot.treeId, options.seed ?? design.protocol.seeds[0]!, options.run ?? "main", options.retry) };
|
|
353
494
|
},
|
|
354
495
|
execute: async (node, state) => {
|
|
355
|
-
if (node.command === "attempt.run")
|
|
496
|
+
if (node.command === "attempt.run") {
|
|
497
|
+
try { return observed(await runAttempt(dir, { ...attemptOptions(node, state.retryOf), expectedId: state.attemptId! }, ctx)); }
|
|
498
|
+
catch (error) {
|
|
499
|
+
if (error instanceof GpuAdmissionDeferred) return { status: "failed", reason: `deferred:${error.result.reason}; ${error.result.message}; run ares plan control <dir> retry ${node.id} --command-id ID --expected-revision N` };
|
|
500
|
+
throw error;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
356
503
|
let result: unknown, ok = true;
|
|
357
504
|
switch (node.command) {
|
|
358
505
|
case "watch.run": {
|
|
@@ -360,7 +507,7 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
|
|
|
360
507
|
return result.ok ? { status: "done", output: { added: result.added } } : { status: "failed", reason: "watch: every source failed; inspect ares watch show and retry the plan node" };
|
|
361
508
|
}
|
|
362
509
|
case "lit.search": {
|
|
363
|
-
const value = await search(dir, stepText(node, "query"), { ...(node.args.source !== undefined ? { source: stepText(node, "source") } : {}), ...(stepNumber(node, "limit") !== undefined ? { limit: stepNumber(node, "limit")! } : {}), ...(stepNumber(node, "year-from") !== undefined ? { yearFrom: stepNumber(node, "year-from")! } : {}) }, ctx);
|
|
510
|
+
const value = await search(dir, stepText(node, "query"), { ...(node.args.source !== undefined ? { source: stepText(node, "source") } : {}), ...(stepNumber(node, "limit") !== undefined ? { limit: stepNumber(node, "limit")! } : {}), ...(stepNumber(node, "year-from") !== undefined ? { yearFrom: stepNumber(node, "year-from")! } : {}), ...(node.args.intent !== undefined ? { intent: stepText(node, "intent") } : {}) }, ctx);
|
|
364
511
|
ok = value.sources.some(s => s.ok); result = value; break;
|
|
365
512
|
}
|
|
366
513
|
case "lit.verify": result = await verify(dir, (node.args.ids as string[] | undefined) ?? [], ctx); break;
|
|
@@ -385,9 +532,11 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
|
|
|
385
532
|
}
|
|
386
533
|
return { status: ok ? "done" : "failed", ...(ok ? { output: { sha256: sha256(JSON.stringify(result)) } } : { reason: "step reported failure; inspect its command result and inputs before retry" }) };
|
|
387
534
|
},
|
|
388
|
-
reconcile: async (
|
|
535
|
+
reconcile: async (node, state) => {
|
|
389
536
|
if (!state.attemptId || !listAttempts(dir).attempts.some(a => a.id === state.attemptId)) return { status: "uncertain", reason: "expected attempt record missing; explicitly retry or skip this node" };
|
|
390
|
-
const before = showAttempt(dir, state.attemptId);
|
|
537
|
+
const before = showAttempt(dir, state.attemptId), requested = attemptOptions(node, state.retryOf);
|
|
538
|
+
const recordedMode = before.v === 3 ? before.reuse!.mode : before.freshRequest?.reuse ?? "off", recordedForce = before.v === 3 ? before.reuse!.forceFresh : before.freshRequest?.forceFresh ?? false;
|
|
539
|
+
if ((requested.reuse ?? "off") !== recordedMode || (requested.forceFresh ?? false) !== recordedForce) return { status: "uncertain", reason: `attempt recorded reuse=${recordedMode}, forceFresh=${recordedForce}; inspect ares attempt show, then retry this plan node explicitly` };
|
|
391
540
|
if (before.status === "running") await reconcileAttempts(dir, ctx);
|
|
392
541
|
return observed(showAttempt(dir, state.attemptId));
|
|
393
542
|
},
|
|
@@ -458,6 +607,10 @@ export async function finalClose(dirArg: string, ctx: Pick<Ctx, "actor">) {
|
|
|
458
607
|
export const posthocShow = (dir: string) => showPosthoc(dir);
|
|
459
608
|
|
|
460
609
|
export const paperCheck = (dir: string) => checkPaper(dir);
|
|
610
|
+
export async function paperPlanSet(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
|
|
611
|
+
const { dir } = openStudy(dirArg); return withLock(dir, () => setPaperPlan(dir, raw, ctx.actor));
|
|
612
|
+
}
|
|
613
|
+
export const paperPlanShow = (dir: string) => showPaperPlan(dir);
|
|
461
614
|
|
|
462
615
|
export async function paperBuild(dirArg: string, ctx: Pick<Ctx, "actor">) {
|
|
463
616
|
const { dir } = openStudy(dirArg); return withLock(dir, () => buildPaper(dir, ctx.actor));
|
|
@@ -470,12 +623,13 @@ export async function reviewResolve(dirArg: string, target: string, reason: stri
|
|
|
470
623
|
const { dir } = openStudy(dirArg); return withLock(dir, () => resolveReview(dir, target, reason, ctx.actor));
|
|
471
624
|
}
|
|
472
625
|
export const reviewShow = (dir: string) => reviewReadiness(dir);
|
|
626
|
+
export const reviewChecklistShow = () => reviewChecklist();
|
|
473
627
|
|
|
474
628
|
/** Preview is read-only; confirmed outward writes and receipts share the study lock. */
|
|
475
|
-
export async function archive(dirArg: string, options: { confirm?: string }, ctx: Pick<Ctx, "actor" | "runner">, env: NodeJS.ProcessEnv = process.env, guard?: () => void): Promise<ArchivePreview | ArchiveResult> {
|
|
629
|
+
export async function archive(dirArg: string, options: { confirm?: string }, ctx: Pick<Ctx, "actor" | "runner" | "now">, env: NodeJS.ProcessEnv = process.env, guard?: () => void, sourceOptions?: SkillCheckOptions): Promise<ArchivePreview | ArchiveResult> {
|
|
476
630
|
const { dir } = openStudy(dirArg);
|
|
477
631
|
if (options.confirm === undefined) return previewArchive(dir);
|
|
478
|
-
return withLock(dir,
|
|
632
|
+
return withLock(dir, lock => {guard?.(); return exportArchive(dir, options.confirm!, ctx.actor, ctx.runner, env, {...(sourceOptions ?? ctx), env: sourceOptions?.env ?? env, lock});});
|
|
479
633
|
}
|
|
480
634
|
|
|
481
635
|
/** The study cwd binds amem's project; search and optional intent brief never write study files. */
|
|
@@ -489,12 +643,17 @@ export async function lessons(dirArg: string, options: LessonRankOptions & { for
|
|
|
489
643
|
return { lessons: ranked, ...(brief === undefined ? {} : { brief }) };
|
|
490
644
|
}
|
|
491
645
|
|
|
492
|
-
export
|
|
493
|
-
|
|
646
|
+
export const lessonPropose = (dir: string, raw: unknown, ctx: Ctx, env: NodeJS.ProcessEnv = process.env) => withLock(dir, lock => proposeLesson(dir, raw, ctx.actor, {...ctx, env, lock}));
|
|
647
|
+
export const lessonList = (dir: string) => listLessonCandidates(dir);
|
|
648
|
+
export const lessonCheck = (dir: string, name: string, ctx: Pick<Ctx, "runner" | "now"> = {}, env: NodeJS.ProcessEnv = process.env) => checkLesson(dir, name, {...ctx, env});
|
|
649
|
+
export const lessonDecide = (dir: string, name: string, raw: unknown, ctx: Ctx, env: NodeJS.ProcessEnv = process.env) => withLock(dir, lock => decideLesson(dir, name, raw, ctx.actor, {...ctx, env, lock}));
|
|
650
|
+
export async function skillPropose(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor" | "runner" | "now">, env: NodeJS.ProcessEnv = process.env) {
|
|
651
|
+
const { dir } = openStudy(dirArg); return withLock(dir, lock => proposeSkill(dir, raw, ctx.actor, {...ctx, env, lock}));
|
|
494
652
|
}
|
|
495
|
-
export async function skillDecide(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, ctx: Pick<Ctx, "actor">, guard?: () => void) {
|
|
496
|
-
const { dir } = openStudy(dirArg); return withLock(dir,
|
|
653
|
+
export async function skillDecide(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, ctx: Pick<Ctx, "actor" | "runner" | "now">, guard?: () => void, env: NodeJS.ProcessEnv = process.env) {
|
|
654
|
+
const { dir } = openStudy(dirArg); return withLock(dir, lock => { guard?.(); return decideSkill(dir, name, decision, reason, pr, ctx.actor, {...ctx, env, lock}); });
|
|
497
655
|
}
|
|
656
|
+
export const skillCheck = (dir: string, name: string, ctx: Pick<Ctx, "runner" | "now"> = {}, env: NodeJS.ProcessEnv = process.env) => checkSkill(dir, name, {...ctx, env});
|
|
498
657
|
export const skillList = (dir: string) => listSkills(dir);
|
|
499
658
|
|
|
500
659
|
export const setup = (target: string, mode: SetupMode, env: NodeJS.ProcessEnv, options: { cwd?: string; root?: string } = {}) => runSetup(target, mode, { ...options, env });
|
|
@@ -559,3 +718,11 @@ function consoleHome(env: NodeJS.ProcessEnv): string {
|
|
|
559
718
|
export const consoleAdd = (dir: string, env: NodeJS.ProcessEnv) => addStudy(consoleHome(env), dir);
|
|
560
719
|
export const consoleRemove = (dir: string, env: NodeJS.ProcessEnv) => removeStudy(consoleHome(env), dir);
|
|
561
720
|
export const consoleList = (env: NodeJS.ProcessEnv) => readRegistry(consoleHome(env));
|
|
721
|
+
|
|
722
|
+
/** Local source-derived reads; comparison adds no verdict, winner or result authority. */
|
|
723
|
+
export function lineageShow(dir: string, options: ProvenanceOptions = {}): ProvenancePage {
|
|
724
|
+
return readProvenance(dir, options);
|
|
725
|
+
}
|
|
726
|
+
export function lineageCompare(dir: string, options: Parameters<typeof compareLineage>[1] = {}): LineageComparison {
|
|
727
|
+
return compareLineage(dir, options);
|
|
728
|
+
}
|
package/src/exp/artifacts.ts
CHANGED
|
@@ -4,6 +4,8 @@ import { runOnExecutor, type Executor, type ProcessRunner } from "./executor.ts"
|
|
|
4
4
|
export const ARTIFACT_FILES = 500, ARTIFACT_BYTES = 256 * 1024 * 1024;
|
|
5
5
|
export const ARTIFACT_CAPTURE_BYTES = 65_536;
|
|
6
6
|
export const ARTIFACT_HEADERS = 2048, ARTIFACT_METADATA_BYTES = 65_536;
|
|
7
|
+
/** One entry header plus at most a GNU long-name (`L`) and a PAX (`x`) header, plus one shared global (`g`) slack. */
|
|
8
|
+
const TAR_HEADERS_PER_ENTRY = 4;
|
|
7
9
|
export const ARTIFACT_WIRE_BYTES = ARTIFACT_BYTES + 16 * 1024 * 1024;
|
|
8
10
|
export type ArtifactErrorCode = "invalid-artifact" | "artifact-limit" | "artifact-read";
|
|
9
11
|
export class ArtifactError extends Error {
|
|
@@ -93,7 +95,7 @@ class TarArtifacts {
|
|
|
93
95
|
private pendingMetadata = false;
|
|
94
96
|
private longName?: string;
|
|
95
97
|
private seen = new Map<string, "file" | "directory">();
|
|
96
|
-
constructor(private capture: string | undefined, private captureBytes: number, private maxBytes: number, private maxFiles: number) {}
|
|
98
|
+
constructor(private capture: string | undefined, private captureBytes: number, private maxBytes: number, private maxFiles: number, private maxHeaders = ARTIFACT_HEADERS) {}
|
|
97
99
|
push(chunk: Uint8Array): void {
|
|
98
100
|
if (!(chunk instanceof Uint8Array)) return invalid("non-binary archive stream");
|
|
99
101
|
this.wireBytes += chunk.byteLength;
|
|
@@ -126,7 +128,7 @@ class TarArtifacts {
|
|
|
126
128
|
const header = this.header;
|
|
127
129
|
if (header.every(byte => byte === 0)) { if (++this.zeros === 2) this.ended = true; return; }
|
|
128
130
|
if (this.zeros) return invalid("entry after an incomplete tar end marker");
|
|
129
|
-
if (++this.headers >
|
|
131
|
+
if (++this.headers > this.maxHeaders) return limit(`archive exceeds ${this.maxHeaders} headers`);
|
|
130
132
|
const expected = octal(header.subarray(148, 156));
|
|
131
133
|
let checksum = 0;
|
|
132
134
|
for (let i = 0; i < 512; i++) checksum += i >= 148 && i < 156 ? 32 : header[i]!;
|
|
@@ -206,6 +208,22 @@ class TarArtifacts {
|
|
|
206
208
|
}
|
|
207
209
|
}
|
|
208
210
|
|
|
211
|
+
/**
|
|
212
|
+
* Streaming member scan for an archive the caller transfers elsewhere: the same header, PAX and path validation as
|
|
213
|
+
* artifact reads, exposing each regular member's path and digest when the archive ends. The caller sizes the header
|
|
214
|
+
* budget from its own entry limits (each file or directory: its header plus GNU long-name or PAX headers). Metadata
|
|
215
|
+
* stays bounded per record by ARTIFACT_METADATA_BYTES, which already exceeds the 4096-byte path limit.
|
|
216
|
+
*/
|
|
217
|
+
export class TarMemberScan {
|
|
218
|
+
private readonly parser: TarArtifacts;
|
|
219
|
+
constructor(maxBytes: number, maxFiles: number, maxEntries: number) {
|
|
220
|
+
const entries = bound(maxEntries, 1_000_000, "maxEntries");
|
|
221
|
+
this.parser = new TarArtifacts(undefined, 0, bound(maxBytes, ARTIFACT_BYTES, "maxBytes"), bound(maxFiles, ARTIFACT_FILES, "maxFiles"), Math.max(ARTIFACT_HEADERS, entries * TAR_HEADERS_PER_ENTRY));
|
|
222
|
+
}
|
|
223
|
+
push(chunk: Uint8Array): void { this.parser.push(chunk); }
|
|
224
|
+
finish(): ArtifactFile[] { return this.parser.finish().files; }
|
|
225
|
+
}
|
|
226
|
+
|
|
209
227
|
/** Hash regular artifacts, retaining no payload except an explicitly selected bounded capture. */
|
|
210
228
|
export async function readArtifactArchive(executor: Executor, command: string, args: string[], runner: ProcessRunner, options: ArtifactArchiveOptions = {}): Promise<ArtifactArchive> {
|
|
211
229
|
const capture = options.capture === undefined ? undefined : relative(options.capture), captureBytes = bound(options.captureBytes ?? ARTIFACT_CAPTURE_BYTES, ARTIFACT_CAPTURE_BYTES, "captureBytes");
|