agentpath 0.0.0-stage → 0.1.0-alpha.2

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 (127) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +101 -2
  3. package/THIRD_PARTY_NOTICES +12 -0
  4. package/apps/demo-site/dist/site.js +92 -0
  5. package/apps/studio/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  6. package/apps/studio/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  7. package/apps/studio/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  8. package/apps/studio/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  9. package/apps/studio/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  10. package/apps/studio/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  11. package/apps/studio/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  12. package/apps/studio/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  13. package/apps/studio/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  14. package/apps/studio/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  15. package/apps/studio/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  16. package/apps/studio/dist/assets/index-DH4wJPHm.js +67 -0
  17. package/apps/studio/dist/assets/index-DrnNh2ip.css +1 -0
  18. package/apps/studio/dist/index.html +14 -0
  19. package/audit.md +173 -0
  20. package/autonomous-mode.md +104 -0
  21. package/ci.md +118 -0
  22. package/coding-agents.md +143 -0
  23. package/concepts.md +145 -0
  24. package/contracts.md +356 -0
  25. package/examples/tasks/ambiguous.json +98 -0
  26. package/examples/tasks/assertion-failure.json +98 -0
  27. package/examples/tasks/broken.json +98 -0
  28. package/examples/tasks/fixed.json +98 -0
  29. package/examples/tasks/recovery.json +19 -0
  30. package/images/compare-recovery-desktop.jpg +0 -0
  31. package/images/compare-variants-desktop.jpg +0 -0
  32. package/images/overview-desktop.jpg +0 -0
  33. package/images/run-autonomous-passed-desktop.jpg +0 -0
  34. package/images/run-failed-desktop.jpg +0 -0
  35. package/images/run-failed-mobile.jpg +0 -0
  36. package/images/run-missing-artifact-desktop.jpg +0 -0
  37. package/images/task-editor-laptop.jpg +0 -0
  38. package/installation.md +102 -0
  39. package/ledger.md +62 -0
  40. package/licenses/-fontsource-variable-geist-mono.txt +93 -0
  41. package/licenses/-fontsource-variable-geist.txt +93 -0
  42. package/licenses/lucide-react.txt +43 -0
  43. package/licenses/react-dom.txt +21 -0
  44. package/licenses/react.txt +21 -0
  45. package/licenses/scheduler.txt +21 -0
  46. package/licenses/tailwindcss.txt +21 -0
  47. package/licenses/zod.txt +21 -0
  48. package/package.json +165 -4
  49. package/packages/cli/bin/agentpath.js +39 -0
  50. package/packages/cli/dist/audit-rerun.js +384 -0
  51. package/packages/cli/dist/audit.js +387 -0
  52. package/packages/cli/dist/change-summaries.js +87 -0
  53. package/packages/cli/dist/ci-report.js +88 -0
  54. package/packages/cli/dist/demo.js +88 -0
  55. package/packages/cli/dist/doctor.js +265 -0
  56. package/packages/cli/dist/explain.js +89 -0
  57. package/packages/cli/dist/git.js +7 -0
  58. package/packages/cli/dist/inspect.js +118 -0
  59. package/packages/cli/dist/ledger.js +509 -0
  60. package/packages/cli/dist/local.js +102 -0
  61. package/packages/cli/dist/main.js +708 -0
  62. package/packages/cli/dist/mcp.js +231 -0
  63. package/packages/cli/dist/paths.js +6 -0
  64. package/packages/cli/dist/playwright-fixture.js +185 -0
  65. package/packages/cli/dist/playwright-reporter.js +49 -0
  66. package/packages/cli/dist/tasks.js +37 -0
  67. package/packages/cli/dist/test-source.js +283 -0
  68. package/packages/cli/dist/watch.js +96 -0
  69. package/packages/contracts/dist/agent-settings.js +18 -0
  70. package/packages/contracts/dist/agent.js +175 -0
  71. package/packages/contracts/dist/audit.js +115 -0
  72. package/packages/contracts/dist/guidance.js +339 -0
  73. package/packages/contracts/dist/index.js +14 -0
  74. package/packages/contracts/dist/inspect.js +63 -0
  75. package/packages/contracts/dist/ledger.js +80 -0
  76. package/packages/contracts/dist/local.js +171 -0
  77. package/packages/contracts/dist/outcomes.js +94 -0
  78. package/packages/contracts/dist/platform.js +105 -0
  79. package/packages/contracts/dist/playwright-live.js +76 -0
  80. package/packages/contracts/dist/policy.js +93 -0
  81. package/packages/contracts/dist/run.js +178 -0
  82. package/packages/contracts/dist/task-issues.js +39 -0
  83. package/packages/contracts/dist/task.js +185 -0
  84. package/packages/contracts/dist/watch.js +57 -0
  85. package/packages/core/dist/action-feedback.js +103 -0
  86. package/packages/core/dist/actions.js +160 -0
  87. package/packages/core/dist/agent-loop.js +122 -0
  88. package/packages/core/dist/artifacts.js +156 -0
  89. package/packages/core/dist/assertions.js +120 -0
  90. package/packages/core/dist/autonomous.js +1 -0
  91. package/packages/core/dist/browser.js +196 -0
  92. package/packages/core/dist/compare.js +141 -0
  93. package/packages/core/dist/control-state.js +62 -0
  94. package/packages/core/dist/diagnostics.js +134 -0
  95. package/packages/core/dist/evidence-diff.js +93 -0
  96. package/packages/core/dist/evidence.js +203 -0
  97. package/packages/core/dist/index.js +22 -0
  98. package/packages/core/dist/inspect.js +257 -0
  99. package/packages/core/dist/integrity.js +176 -0
  100. package/packages/core/dist/liveness.js +114 -0
  101. package/packages/core/dist/local-files.js +61 -0
  102. package/packages/core/dist/locators.js +214 -0
  103. package/packages/core/dist/model-provider.js +88 -0
  104. package/packages/core/dist/observation.js +257 -0
  105. package/packages/core/dist/playwright-live.js +519 -0
  106. package/packages/core/dist/playwright-results.js +543 -0
  107. package/packages/core/dist/policy.js +182 -0
  108. package/packages/core/dist/privacy.js +93 -0
  109. package/packages/core/dist/recovery.js +54 -0
  110. package/packages/core/dist/retention.js +204 -0
  111. package/packages/core/dist/run-index.js +177 -0
  112. package/packages/core/dist/run-plan.js +28 -0
  113. package/packages/core/dist/run-repository.js +518 -0
  114. package/packages/core/dist/runner.js +913 -0
  115. package/packages/core/dist/storage.js +63 -0
  116. package/packages/core/dist/task-fingerprint.js +36 -0
  117. package/packages/core/dist/test-change-rerun.js +84 -0
  118. package/packages/core/dist/test-changes.js +896 -0
  119. package/packages/core/dist/timing.js +41 -0
  120. package/packages/core/dist/watch.js +165 -0
  121. package/packages/server/dist/index.js +265 -0
  122. package/packages/server/dist/task-store.js +103 -0
  123. package/quickstart.md +85 -0
  124. package/security.md +136 -0
  125. package/try-on-your-repo.md +54 -0
  126. package/understanding-results.md +159 -0
  127. package/writing-tasks.md +196 -0
@@ -0,0 +1,182 @@
1
+ import { derivePolicyOutcome, httpUrl, policyRecordSchema, SCHEMA_VERSION } from "#agentpath/contracts";
2
+ import { RunFailure } from "./diagnostics.js";
3
+ import { semanticLocator } from "./locators.js";
4
+ export function policyBlocked(ruleIds) {
5
+ return new RunFailure({
6
+ category: "POLICY_BLOCKED",
7
+ expected: "Actions avoid the interactions protected by the configured action policy.",
8
+ observed: `The action matched protected rule${ruleIds.length === 1 ? "" : "s"} ${ruleIds.join(", ")} and was rejected before it ran.`,
9
+ investigation: "Inspect policy.json for the proposed action, the matched rule and the blocking checkpoint.",
10
+ observation: { errorKind: "policy_blocked" },
11
+ });
12
+ }
13
+ /**
14
+ * Evaluates trusted policy rules against proposed actions and browser requests. It never sees the model and
15
+ * never contributes actions. Matching an action rule uses element identity: the action's single resolved
16
+ * element must also be matched by the rule's own semantic locator, so a label and a role/name query for the
17
+ * same control are the same protected target.
18
+ */
19
+ export class PolicyMonitor {
20
+ policy;
21
+ fingerprint;
22
+ baseUrl;
23
+ redact;
24
+ where;
25
+ #decisions = [];
26
+ #requests = [];
27
+ #blocked = new WeakSet();
28
+ #requestsTruncated = false;
29
+ #checked = 0;
30
+ #installed = false;
31
+ constructor(policy, fingerprint, baseUrl, redact, where) {
32
+ this.policy = policy;
33
+ this.fingerprint = fingerprint;
34
+ this.baseUrl = baseUrl;
35
+ this.redact = redact;
36
+ this.where = where;
37
+ }
38
+ get enforce() { return this.policy.mode === "enforce"; }
39
+ actionRules(action) {
40
+ return this.policy.rules.filter((rule) => rule.kind === "action" && rule.actions.includes(action));
41
+ }
42
+ requestRules(method, url) {
43
+ return this.policy.rules.filter((rule) => rule.kind === "request" &&
44
+ (!rule.methods || rule.methods.includes(method)) && (!rule.host || rule.host === url.host) &&
45
+ ((rule.match ?? "exact") === "exact" ? url.pathname === rule.path : url.pathname.startsWith(rule.path)));
46
+ }
47
+ /** True when an action of this kind could match a rule, so execution needs the element guard. */
48
+ guards(step) { return step.action !== "navigate" && this.actionRules(step.action).length > 0; }
49
+ wasBlocked(request) { return this.#blocked.has(request); }
50
+ /** Proposal-time check. It takes a single snapshot and never waits for a target to appear. */
51
+ async check(page, step, deadline) {
52
+ this.#checked++;
53
+ if (step.action === "wait")
54
+ return { decision: "allowed", ruleIds: [], reason: "no-rule-matched", checkpoint: "proposal" };
55
+ if (step.action === "navigate") {
56
+ const url = httpUrl(step.url, this.baseUrl);
57
+ const ids = url ? this.requestRules("GET", url).map((rule) => rule.id) : [];
58
+ return this.verdict(ids, "proposal");
59
+ }
60
+ const rules = this.actionRules(step.action);
61
+ if (!rules.length)
62
+ return { decision: "allowed", ruleIds: [], reason: "no-rule-matched", checkpoint: "proposal" };
63
+ try {
64
+ const untargeted = rules.filter((rule) => !rule.target).map((rule) => rule.id);
65
+ const locator = semanticLocator(page, step.target);
66
+ if (await deadline.observe(() => locator.count()) !== 1) {
67
+ if (untargeted.length)
68
+ return this.verdict(untargeted, "proposal");
69
+ // Identity cannot be established yet; the execution guard checks the element that is actually used.
70
+ return { decision: "allowed", ruleIds: [], reason: "target-unresolved", checkpoint: "proposal" };
71
+ }
72
+ const handle = await deadline.observe(() => locator.elementHandle({ timeout: deadline.remaining() }));
73
+ try {
74
+ return this.verdict([...untargeted, ...await this.matching(page, rules, handle, deadline)], "proposal");
75
+ }
76
+ finally {
77
+ await handle.dispose().catch(() => { });
78
+ }
79
+ }
80
+ catch (error) {
81
+ if (error instanceof RunFailure)
82
+ throw error;
83
+ return { decision: "unevaluated", ruleIds: [], reason: "evaluation-error", checkpoint: "proposal" };
84
+ }
85
+ }
86
+ /** Execution-time guard on the exact element the action is about to use. */
87
+ async guard(page, step, element, deadline) {
88
+ if (step.action === "navigate" || step.action === "wait")
89
+ return { decision: "allowed", ruleIds: [], reason: "no-rule-matched", checkpoint: "execution" };
90
+ try {
91
+ const rules = this.actionRules(step.action);
92
+ return this.verdict([...rules.filter((rule) => !rule.target).map((rule) => rule.id), ...await this.matching(page, rules, element, deadline)], "execution");
93
+ }
94
+ catch {
95
+ return { decision: "unevaluated", ruleIds: [], reason: "evaluation-error", checkpoint: "execution" };
96
+ }
97
+ }
98
+ async matching(page, rules, element, deadline) {
99
+ const ids = [];
100
+ for (const rule of rules) {
101
+ if (!rule.target)
102
+ continue;
103
+ const protectedTargets = semanticLocator(page, rule.target);
104
+ // Read-only identity comparison inside the page; no page-provided code runs.
105
+ if (await deadline.observe(() => protectedTargets.evaluateAll((elements, subject) => elements.includes(subject), element)))
106
+ ids.push(rule.id);
107
+ }
108
+ return ids;
109
+ }
110
+ verdict(ruleIds, checkpoint) {
111
+ if (!ruleIds.length)
112
+ return { decision: "allowed", ruleIds, reason: "no-rule-matched", checkpoint };
113
+ return { decision: this.enforce ? "blocked" : "permitted-violation", ruleIds: [...new Set(ruleIds)], reason: "rule-matched", checkpoint };
114
+ }
115
+ /** Records a check. Proposed fill values are never part of the record; target names pass through redaction. */
116
+ record(step, check, context, execution) {
117
+ const target = "target" in step ? {
118
+ by: step.target.by, ...(step.target.by === "role" ? { role: step.target.role } : {}),
119
+ name: this.redact(step.target.by === "role" ? step.target.name ?? "" : step.target.label).slice(0, 512),
120
+ } : undefined;
121
+ const entry = {
122
+ sequence: this.#decisions.length, source: context.source, ...(context.agentSequence !== undefined ? { agentSequence: context.agentSequence } : {}),
123
+ ...(context.stepIndex !== undefined ? { stepIndex: context.stepIndex } : {}),
124
+ action: step.action, ...(target ? { target: target.name === "[redacted]" ? { ...target, name: "", nameState: "redacted" } : target } : {}),
125
+ ruleIds: check.ruleIds, decision: check.decision, execution, checkpoint: check.checkpoint, reason: check.reason,
126
+ };
127
+ if (this.#decisions.length < 400)
128
+ this.#decisions.push(entry);
129
+ return entry;
130
+ }
131
+ /** Request rules are enforced at the browser route layer, before a request leaves Chromium. */
132
+ async install(context) {
133
+ if (!this.policy.rules.some((rule) => rule.kind === "request")) {
134
+ this.#installed = true;
135
+ return;
136
+ }
137
+ // Registered after the destination guard, so it runs first and falls back to it.
138
+ await context.route("**/*", async (route) => {
139
+ try {
140
+ const request = route.request();
141
+ const url = httpUrl(request.url());
142
+ const rules = url ? this.requestRules(request.method(), url) : [];
143
+ if (!rules.length) {
144
+ await route.fallback();
145
+ return;
146
+ }
147
+ const where = this.where();
148
+ if (this.#requests.length < 200) {
149
+ this.#requests.push({
150
+ sequence: this.#requests.length, ruleIds: rules.map((rule) => rule.id), method: request.method().slice(0, 16),
151
+ decision: this.enforce ? "blocked" : "permitted-violation", resourceType: request.resourceType().slice(0, 32),
152
+ ...(where.stepIndex !== undefined ? { stepIndex: where.stepIndex } : {}),
153
+ });
154
+ }
155
+ else
156
+ this.#requestsTruncated = true;
157
+ if (this.enforce) {
158
+ this.#blocked.add(request);
159
+ await route.abort("blockedbyclient");
160
+ }
161
+ else
162
+ await route.fallback();
163
+ }
164
+ catch {
165
+ // The page or context can close while a request is being handled.
166
+ }
167
+ });
168
+ this.#installed = true;
169
+ }
170
+ /** The finalized record. Completion requires installed request rules and a run that was not interrupted. */
171
+ finalize(runId, interrupted) {
172
+ const base = {
173
+ decisions: this.#decisions, requests: this.#requests, complete: this.#installed && !interrupted && this.#checked === this.#decisions.length,
174
+ ...(this.#requestsTruncated ? { requestsTruncated: true } : {}),
175
+ };
176
+ return policyRecordSchema.parse({
177
+ schemaVersion: SCHEMA_VERSION, runId, mode: this.policy.mode, policyFingerprint: this.fingerprint,
178
+ rules: this.policy.rules.map((rule) => ({ id: rule.id, kind: rule.kind, ...(rule.description ? { description: rule.description } : {}) })),
179
+ checked: this.#checked, ...base, outcome: derivePolicyOutcome(base),
180
+ });
181
+ }
182
+ }
@@ -0,0 +1,93 @@
1
+ const entities = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
2
+ function decode(value) {
3
+ return value.replace(/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos|nbsp);/gi, (original, entity) => {
4
+ if (!entity.startsWith("#"))
5
+ return entities[entity.toLowerCase()] ?? original;
6
+ const point = entity[1]?.toLowerCase() === "x" ? Number.parseInt(entity.slice(2), 16) : Number(entity.slice(1));
7
+ return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff) ? String.fromCodePoint(point) : original;
8
+ });
9
+ }
10
+ function normalize(value) {
11
+ let decoded = decode(value);
12
+ try {
13
+ decoded = decodeURIComponent(decoded);
14
+ }
15
+ catch { /* Preserve malformed escapes for matching. */ }
16
+ return decoded.normalize("NFKC").toLowerCase();
17
+ }
18
+ export class EvidencePrivacy {
19
+ #values;
20
+ #trustedNames;
21
+ #hosts;
22
+ #inputAttempted = false;
23
+ /**
24
+ * with operator-enabled text capture, names observed after input are recorded through the same
25
+ * input-value redaction instead of being withheld. Off by default.
26
+ */
27
+ captureText;
28
+ constructor(task, captureText = false) {
29
+ this.captureText = captureText;
30
+ this.#hosts = new Set(task.allowedHosts);
31
+ this.#values = [...new Set(task.steps.flatMap((step) => step.action === "fill" && step.value ? [normalize(step.value)] : []))];
32
+ this.#trustedNames = new Set([...task.steps, ...task.assertions].flatMap((operation) => {
33
+ if (!("target" in operation))
34
+ return [];
35
+ const name = operation.target.by === "role" ? operation.target.name : operation.target.label;
36
+ return name === undefined ? [] : [name];
37
+ }));
38
+ }
39
+ addValue(value) { if (value)
40
+ this.#values.push(normalize(value)); }
41
+ inputAttempted() { this.#inputAttempted = true; }
42
+ get suppressScreenshots() { return this.#inputAttempted; }
43
+ // Suppress the whole field instead of replacing substrings inside identifiers or semantic names.
44
+ redact(value) {
45
+ const normalized = normalize(value);
46
+ const sensitive = this.#values.some((secret) => {
47
+ if (secret.length >= 4)
48
+ return normalized.includes(secret);
49
+ return normalized.split(/[^\p{L}\p{N}_]+/u).includes(secret) || normalized === secret;
50
+ });
51
+ return sensitive ? "[redacted]" : value;
52
+ }
53
+ /**
54
+ * Free text the operator asked to capture. Every task-supplied input value is replaced in
55
+ * place with "[input value]": values of four or more characters wherever they occur, shorter values only as
56
+ * whole words. Text in which normalization still reveals a value is withheld entirely.
57
+ */
58
+ redactText(value) {
59
+ let text = value;
60
+ for (const secret of this.#values) {
61
+ const escaped = secret.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
62
+ const pattern = secret.length < 4 ? `(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])` : escaped;
63
+ text = text.replace(new RegExp(pattern, "giu"), "[input value]");
64
+ const remaining = normalize(text);
65
+ if (secret.length < 4 ? remaining.split(/[^\p{L}\p{N}_]+/u).includes(secret) : remaining.includes(secret))
66
+ return undefined;
67
+ }
68
+ return text;
69
+ }
70
+ /** Whether names the task does not use are currently withheld because input was typed (and capture is off). */
71
+ get withholdingAfterInput() { return this.#inputAttempted && !this.captureText; }
72
+ name(role, value) {
73
+ if (this.#inputAttempted && !this.captureText && !this.#trustedNames.has(value)) {
74
+ return { name: "", nameState: "withheld" };
75
+ }
76
+ // Free-form rendered text can already contain prefilled or application-owned secrets.
77
+ if (["StaticText", "InlineTextBox", "paragraph", "generic"].includes(role)) {
78
+ return { name: "", nameState: "withheld" };
79
+ }
80
+ const name = this.redact(value);
81
+ return name === "[redacted]" ? { name: "", nameState: "redacted" } : { name: name.slice(0, 1000) };
82
+ }
83
+ origin(url) {
84
+ return this.#inputAttempted && !this.#hosts.has(url.host) ? "[withheld-origin]" : url.origin;
85
+ }
86
+ /** An allowed host is the operator's own text, so it stays; any other host is withheld after input. */
87
+ host(value) {
88
+ return this.#inputAttempted && !this.#hosts.has(value) ? "[withheld-after-input]" : this.redact(value);
89
+ }
90
+ path(value) {
91
+ return this.#inputAttempted && value !== "/" ? "/[withheld-after-input]" : this.redact(value);
92
+ }
93
+ }
@@ -0,0 +1,54 @@
1
+ import { comparePolicies } from "#agentpath/contracts";
2
+ export function taskContract(a, b) {
3
+ const left = a.metadata;
4
+ const right = b.metadata;
5
+ const assertionsEquivalent = Boolean(left && right && left.assertionsFingerprint === right.assertionsFingerprint);
6
+ const status = !left || !right ? "unavailable"
7
+ : left.definitionFingerprint === right.definitionFingerprint && assertionsEquivalent ? "identical" : "changed";
8
+ return {
9
+ status, assertionsEquivalent,
10
+ message: status === "unavailable" ? "Task definition equivalence not established."
11
+ : status === "changed" ? "The task definition changed. Verification applies to each recorded definition individually."
12
+ : "The execution-relevant task definitions and independent assertions are identical.",
13
+ baselineFingerprint: left?.definitionFingerprint, candidateFingerprint: right?.definitionFingerprint,
14
+ };
15
+ }
16
+ export function interpretComparison(a, b, contract) {
17
+ const missingEvidence = [a, b].flatMap((detail) => detail.evidenceAvailability
18
+ ? detail.evidenceAvailability.issues.map((issue) => ({ ...issue, runId: detail.summary.runId }))
19
+ : [{ runId: detail.summary.runId, path: "local artifact store", reason: "Evidence integrity was not checked." }]);
20
+ const baseline = a.result;
21
+ const candidate = b.result;
22
+ if (!baseline || !candidate || baseline.status === "cancelled" || candidate.status === "cancelled") {
23
+ return { status: "inconclusive", label: "Inconclusive comparison", explanation: "Both runs require completed verification.", missingEvidence };
24
+ }
25
+ if (missingEvidence.length) {
26
+ return { status: "inconclusive", label: "Inconclusive comparison", explanation: "Required records are missing, unreadable, inconsistent, or unchecked.", missingEvidence };
27
+ }
28
+ const policy = comparePolicies(a, b);
29
+ if (contract.status === "identical" && baseline.taskId === candidate.taskId && !policy.equivalent &&
30
+ baseline.status === "failed" && candidate.status === "passed") {
31
+ return { status: "observed-improvement", label: "Observed improvement",
32
+ explanation: `The candidate passed the same goal contract after a failed baseline, but strict recovery also requires the same action policy. ${policy.message}`, missingEvidence };
33
+ }
34
+ if (contract.status === "identical" && baseline.taskId === candidate.taskId &&
35
+ baseline.status === "failed" && candidate.status === "passed") {
36
+ return { status: "verified-recovery", label: "Verified task recovery",
37
+ explanation: "The failed baseline and passing candidate use the same task contract. The candidate completed every action and independent assertion. Recovery is verified for this recorded task contract.", missingEvidence };
38
+ }
39
+ if (baseline.status === "failed" && candidate.status === "passed") {
40
+ return { status: "observed-improvement", label: "Observed improvement",
41
+ explanation: "The candidate passed after a failed baseline. Task contract equivalence is required for strict recovery verification.", missingEvidence };
42
+ }
43
+ if (contract.status === "changed") {
44
+ return { status: "different-definitions", label: "Different task definitions", explanation: contract.message, missingEvidence };
45
+ }
46
+ if (contract.status === "unavailable" || baseline.taskId !== candidate.taskId) {
47
+ return { status: "inconclusive", label: "Inconclusive comparison", explanation: contract.message, missingEvidence };
48
+ }
49
+ if (baseline.status === "passed" && candidate.status === "failed") {
50
+ return { status: "regression", label: "Regression detected", explanation: "The unchanged task passed in the baseline and failed in the candidate.", missingEvidence };
51
+ }
52
+ return { status: "unchanged", label: "Verification unchanged",
53
+ explanation: "Both completed runs have the same overall verification outcome. Recorded operation evidence may still differ.", missingEvidence };
54
+ }
@@ -0,0 +1,204 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readdir, rename, rmdir, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { runIdSchema } from "#agentpath/contracts";
5
+ import { isMissing, StoredRecordInvalid } from "./local-files.js";
6
+ /** Detached run directories awaiting removal. Their names are not run IDs, so listings never show them. */
7
+ export const TRASH_DIRECTORY = ".trash";
8
+ const PLAN_CONCURRENCY = 16;
9
+ const units = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 };
10
+ /** Parses a retention age such as 90m, 12h, 30d, or 2w. */
11
+ export function parseAge(value) {
12
+ const match = /^([0-9]{1,5})([mhdw])$/.exec(value.trim());
13
+ if (!match)
14
+ throw new Error("Use an age such as 90m, 12h, 30d, or 2w.");
15
+ return Number(match[1]) * units[match[2]];
16
+ }
17
+ function eligibility(status, options) {
18
+ switch (status) {
19
+ case "passed":
20
+ case "failed":
21
+ case "cancelled": return undefined;
22
+ case "running": return "active";
23
+ case "stale":
24
+ case "incomplete": return options.includeStale ? undefined : "liveness-uncertain";
25
+ case "abandoned": return options.includeAbandoned ? undefined : "abandoned-not-approved";
26
+ case "unreadable": return options.includeUnreadable ? undefined : "unreadable-not-approved";
27
+ }
28
+ }
29
+ /** Measures a directory without following symbolic links. */
30
+ async function measure(path, depth = 0) {
31
+ const info = await lstat(path);
32
+ if (!info.isDirectory() || depth > 8)
33
+ return { bytes: info.size, files: 1 };
34
+ let bytes = 0;
35
+ let files = 0;
36
+ for (const name of await readdir(path)) {
37
+ const child = await measure(join(path, name), depth + 1);
38
+ bytes += child.bytes;
39
+ files += child.files;
40
+ }
41
+ return { bytes, files };
42
+ }
43
+ /** Removes a detached tree. Symbolic links are unlinked, never followed. */
44
+ async function removeTree(path, depth = 0) {
45
+ const info = await lstat(path);
46
+ if (info.isDirectory() && !info.isSymbolicLink()) {
47
+ if (depth > 8)
48
+ throw new Error("Refusing to remove an unexpectedly deep directory.");
49
+ for (const name of await readdir(path))
50
+ await removeTree(join(path, name), depth + 1);
51
+ await rmdir(path);
52
+ }
53
+ else
54
+ await unlink(path);
55
+ }
56
+ async function realDirectory(path) {
57
+ try {
58
+ const info = await lstat(path);
59
+ return info.isDirectory() && !info.isSymbolicLink();
60
+ }
61
+ catch (error) {
62
+ if (isMissing(error))
63
+ return false;
64
+ throw error;
65
+ }
66
+ }
67
+ async function tombstones(root) {
68
+ const trash = join(root, TRASH_DIRECTORY);
69
+ if (!(await realDirectory(trash)))
70
+ return [];
71
+ return (await readdir(trash)).filter((name) => /^[0-9a-f-]{36}\.[0-9a-f-]{36}$/.test(name)).map((name) => join(trash, name));
72
+ }
73
+ async function currentStatus(repository, id) {
74
+ try {
75
+ return (await repository.detail(id)).summary;
76
+ }
77
+ catch (error) {
78
+ if (!(error instanceof StoredRecordInvalid))
79
+ throw error;
80
+ return { runId: id, status: "unreadable" };
81
+ }
82
+ }
83
+ async function directoryAge(repository, id) {
84
+ return (await lstat(join(repository.root, id))).mtimeMs;
85
+ }
86
+ /** Selects runs older than the cutoff. Nothing is changed. */
87
+ export async function planPrune(repository, options) {
88
+ const now = options.now ?? Date.now();
89
+ const cutoff = new Date(now - options.olderThanMs).toISOString();
90
+ const candidates = [];
91
+ const excluded = [];
92
+ if (!(await realDirectory(repository.root))) {
93
+ return { root: repository.root, cutoff, candidates, excluded, totalBytes: 0, interruptedDeletions: 0 };
94
+ }
95
+ const consider = async (summary, age) => {
96
+ const reason = eligibility(summary.status, options);
97
+ if (reason)
98
+ return { exclusion: { runId: summary.runId, status: summary.status, reason } };
99
+ if (!(await realDirectory(join(repository.root, summary.runId)))) {
100
+ return { exclusion: { runId: summary.runId, status: summary.status, reason: "not-a-directory" } };
101
+ }
102
+ return { candidate: {
103
+ runId: summary.runId, status: summary.status, age,
104
+ ...(summary.startedAt ? { startedAt: summary.startedAt } : {}),
105
+ ...await measure(join(repository.root, summary.runId)),
106
+ } };
107
+ };
108
+ // Runs in a page are measured a few at a time; decisions are recorded in listing order. Measuring one run at a time
109
+ // made a dry run over 50,000 runs take about 24 seconds on a laptop.
110
+ const decide = async (summaries, age) => {
111
+ for (let start = 0; start < summaries.length; start += PLAN_CONCURRENCY) {
112
+ for (const decision of await Promise.all(summaries.slice(start, start + PLAN_CONCURRENCY).map((summary) => consider(summary, age)))) {
113
+ if ("candidate" in decision)
114
+ candidates.push(decision.candidate);
115
+ else
116
+ excluded.push(decision.exclusion);
117
+ }
118
+ }
119
+ };
120
+ for (let cursor, first = true; first || cursor; first = false) {
121
+ const page = await repository.list({ until: cutoff, limit: 200, cursor });
122
+ await decide(page.runs, "started-at");
123
+ cursor = page.nextCursor;
124
+ }
125
+ // Unreadable runs have no trustworthy start time, so their directory modification time is used instead.
126
+ for (let cursor, first = true; first || cursor; first = false) {
127
+ const page = await repository.list({ status: ["unreadable"], limit: 200, cursor });
128
+ const old = [];
129
+ for (const summary of page.runs) {
130
+ if (await directoryAge(repository, summary.runId) < now - options.olderThanMs)
131
+ old.push(summary);
132
+ }
133
+ await decide(old, "directory-mtime");
134
+ cursor = page.nextCursor;
135
+ }
136
+ return {
137
+ root: repository.root, cutoff, candidates, excluded,
138
+ totalBytes: candidates.reduce((sum, entry) => sum + entry.bytes, 0),
139
+ interruptedDeletions: (await tombstones(repository.root)).length,
140
+ };
141
+ }
142
+ /**
143
+ * Deletes planned runs. Each run is re-checked immediately before removal, then atomically detached into the
144
+ * trash directory before its files are removed, so an interrupted deletion never leaves a half-deleted run
145
+ * visible. Leftover detached directories are removed on the next execution.
146
+ */
147
+ export async function executePrune(repository, plan, options) {
148
+ const root = repository.root;
149
+ const outcome = { deleted: [], skipped: [], failed: [], reclaimedBytes: 0, completedInterruptedDeletions: 0, remainingInterruptedDeletions: 0 };
150
+ if (!(await realDirectory(root)))
151
+ throw new Error("The runs directory must be a real directory.");
152
+ for (const path of await tombstones(root)) {
153
+ try {
154
+ await removeTree(path);
155
+ outcome.completedInterruptedDeletions++;
156
+ }
157
+ catch {
158
+ outcome.remainingInterruptedDeletions++;
159
+ }
160
+ }
161
+ const trash = join(root, TRASH_DIRECTORY);
162
+ await mkdir(trash, { mode: 0o700, recursive: true });
163
+ if (!(await realDirectory(trash)))
164
+ throw new Error("The trash directory must be a real directory.");
165
+ const cutoff = Date.parse(plan.cutoff);
166
+ for (const candidate of plan.candidates) {
167
+ const id = candidate.runId;
168
+ const skip = (reason, status = candidate.status) => outcome.skipped.push({ runId: id, status, reason });
169
+ if (!runIdSchema.safeParse(id).success) {
170
+ skip("invalid-run-id");
171
+ continue;
172
+ }
173
+ const directory = join(root, id);
174
+ try {
175
+ if (!(await realDirectory(directory))) {
176
+ skip("not-a-directory");
177
+ continue;
178
+ }
179
+ // Liveness and status can change between planning and execution.
180
+ const current = await currentStatus(repository, id);
181
+ const reason = eligibility(current.status, options);
182
+ if (reason) {
183
+ skip(reason, current.status);
184
+ continue;
185
+ }
186
+ const time = current.status === "unreadable" ? await directoryAge(repository, id) : Date.parse(current.startedAt ?? "");
187
+ if (!Number.isFinite(time) || time >= cutoff) {
188
+ skip("not-older-than-cutoff", current.status);
189
+ continue;
190
+ }
191
+ const size = await measure(directory);
192
+ const detached = join(trash, `${id}.${randomUUID()}`);
193
+ await rename(directory, detached);
194
+ await repository.forget(id);
195
+ await removeTree(detached);
196
+ outcome.deleted.push(id);
197
+ outcome.reclaimedBytes += size.bytes;
198
+ }
199
+ catch {
200
+ outcome.failed.push(id);
201
+ }
202
+ }
203
+ return outcome;
204
+ }