toolroll 0.9.116 → 0.9.118

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 (136) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +93 -16
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +12 -2
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/coding-context.js +16 -2
  31. package/dist/coding-provider.js +7 -3
  32. package/dist/coding-workspace.js +5 -5
  33. package/dist/connect-cli.js +257 -11
  34. package/dist/contracts/chat-actions.js +4 -0
  35. package/dist/contracts/console-api.js +14 -3
  36. package/dist/contracts/engine-api.js +331 -2
  37. package/dist/contracts/lead-tools.js +56 -2
  38. package/dist/contracts/provider.js +1 -1
  39. package/dist/contracts/route.js +1 -1
  40. package/dist/contracts/terminal-connection.js +50 -0
  41. package/dist/converse.js +80 -4
  42. package/dist/device-pair.js +280 -0
  43. package/dist/direct-chat-artifacts.js +347 -0
  44. package/dist/direct-chat-catalog.js +311 -0
  45. package/dist/direct-chat-fence.js +96 -0
  46. package/dist/direct-chat-git.js +343 -0
  47. package/dist/direct-chat-laptop.js +19 -0
  48. package/dist/direct-chat-schema.js +181 -0
  49. package/dist/direct-chat-ship.js +861 -0
  50. package/dist/direct-chat-workspace.js +389 -0
  51. package/dist/direct-chat.js +2107 -0
  52. package/dist/doctor.js +1 -1
  53. package/dist/easy-start.js +18 -0
  54. package/dist/egress.js +25 -4
  55. package/dist/engine-chat.js +454 -0
  56. package/dist/engine-reads.js +141 -13
  57. package/dist/exec.js +4 -3
  58. package/dist/flexible-agents.js +8 -16
  59. package/dist/flexible-session.js +91 -47
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-start.js +4 -1
  62. package/dist/flexible-thread.js +2 -3
  63. package/dist/flexible-turns.js +26 -5
  64. package/dist/flow-triggers.js +13 -4
  65. package/dist/flows-ui.js +54 -20
  66. package/dist/handoff-cli.js +630 -0
  67. package/dist/invoke.js +71 -17
  68. package/dist/lead-contract.js +5 -4
  69. package/dist/lead-doors.js +80 -1
  70. package/dist/lead-progress.js +9 -0
  71. package/dist/lead-tools.js +681 -10
  72. package/dist/lead.js +37 -9
  73. package/dist/live-bus.js +11 -0
  74. package/dist/live-terminal.js +132 -12
  75. package/dist/local-handoff.js +363 -0
  76. package/dist/local-owner-acts.js +264 -2
  77. package/dist/local-owner.js +16 -1
  78. package/dist/multiplayer-handoff.js +528 -0
  79. package/dist/multiplayer-presence.js +471 -0
  80. package/dist/names.js +17 -4
  81. package/dist/needs-you.js +10 -0
  82. package/dist/operate.js +280 -19
  83. package/dist/planner.js +6 -1
  84. package/dist/policy.js +2 -2
  85. package/dist/project-delete-ui.js +18 -11
  86. package/dist/project-delete.js +65 -4
  87. package/dist/project-skills.js +28 -13
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/scout.js +6 -2
  102. package/dist/serve.js +49 -5
  103. package/dist/server/chat.js +94 -13
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +43 -10
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/skills-manifest.js +57 -0
  123. package/dist/store.js +499 -56
  124. package/dist/subscription-chat.js +33 -6
  125. package/dist/subscription-usage.js +233 -0
  126. package/dist/task-live.js +2 -1
  127. package/dist/teardown-git.js +34 -4
  128. package/dist/terminal-connection.js +159 -0
  129. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  130. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  131. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  132. package/dist/tui/linux-x64/toolroll-tui +0 -0
  133. package/dist/tui-contract.js +1 -1
  134. package/dist/tui-launch.js +32 -1
  135. package/dist/workspace-identity-schema.js +21 -0
  136. package/package.json +4 -2
package/dist/builder.js CHANGED
@@ -727,8 +727,11 @@ export async function build(store, request) {
727
727
  lastStates: new Map(),
728
728
  };
729
729
  let projectSkillContext;
730
+ let projectSkills;
730
731
  try {
731
- projectSkillContext = skillsContext(store, root, request.runId);
732
+ let manifest;
733
+ ({ text: projectSkillContext, manifest } = skillsContext(store, root, request.runId));
734
+ projectSkills = { root, manifest };
732
735
  }
733
736
  catch (error) {
734
737
  return { ok: false, reason: "skills-unavailable", message: `Project skills could not be loaded: ${error instanceof Error ? error.message : String(error)}` };
@@ -1016,6 +1019,7 @@ export async function build(store, request) {
1016
1019
  omitEnv: AGENT_ENV_DENYLIST,
1017
1020
  network: launchNetworkOf(store, request.taskRef, effective.profile),
1018
1021
  writes: launchWritesOf(effective.profile), sandbox: launchSandboxOf(effective.profile),
1022
+ skills: projectSkills,
1019
1023
  ...(agent === undefined ? {} : { runner: agent }),
1020
1024
  onSpawn: (pid) => { spawned = true; request.onProviderSpawn?.(pid); },
1021
1025
  onStreamEvent: (event) => liveLog.observe(event),
@@ -1061,6 +1065,7 @@ export async function build(store, request) {
1061
1065
  clock, fenced: () => fencedMidBuild,
1062
1066
  plan: { proposal, revision: planRevisionNumber, authority, progress: progressState },
1063
1067
  ...(liveSession === null ? {} : { live: { close: liveSession.closeReason, maxTurns: liveSession.maxTurns } }),
1068
+ skills: projectSkills,
1064
1069
  };
1065
1070
  return await settleProviderOutcome(captured, result);
1066
1071
  }
@@ -1197,6 +1202,7 @@ export async function settleProviderOutcome(captured, result) {
1197
1202
  }
1198
1203
  const parked = await ingestPark({
1199
1204
  profile: effective.profile,
1205
+ skills: captured.skills ?? null,
1200
1206
  store,
1201
1207
  request,
1202
1208
  agent,
@@ -1665,7 +1671,9 @@ async function settleProof(captured, statArtifactId, sealedHead) {
1665
1671
  }
1666
1672
  else if (batched && repo !== null) {
1667
1673
  verifyCommand = { configured: false };
1668
- queueBatchCheck(store, { runId, taskId: request.taskId, repo, head: sealedHead, base: captured.baseRevision, command: configured }, now());
1674
+ const queued = queueBatchCheck(store, { runId, taskId: request.taskId, repo, head: sealedHead, base: captured.baseRevision, command: configured }, now());
1675
+ if (typeof queued !== "number")
1676
+ recordCheckNote("Checks are on hold after recovery. Earlier execution is unverified.");
1669
1677
  }
1670
1678
  else if (!store.proveRunnerCustodyForSpawn(runId, now())) {
1671
1679
  verifyCommand = { configured: true, ran: false, attemptFailed: true, failure: "custody-lost" };
@@ -2125,6 +2133,7 @@ async function resumeUnhandedWork(captured, sessionId) {
2125
2133
  omitEnv: AGENT_ENV_DENYLIST,
2126
2134
  network: launchNetworkOf(store, request.taskRef, effective.profile),
2127
2135
  writes: launchWritesOf(effective.profile), sandbox: launchSandboxOf(effective.profile),
2136
+ skills: captured.skills ?? null,
2128
2137
  ...(agent === undefined ? {} : { runner: agent }),
2129
2138
  ...(request.onProviderSpawn === undefined ? {} : { onSpawn: request.onProviderSpawn }),
2130
2139
  clock,
@@ -2371,6 +2380,7 @@ async function ingestPark(args) {
2371
2380
  : { timeoutMs: args.profile !== undefined ? args.profile.repairTimeoutSeconds * 1000 : REPAIR_TIMEOUT_MS }),
2372
2381
  omitEnv: AGENT_ENV_DENYLIST,
2373
2382
  ...(args.profile === undefined ? {} : { network: launchNetworkOf(store, request.taskRef, args.profile), writes: launchWritesOf(args.profile), sandbox: launchSandboxOf(args.profile) }),
2383
+ skills: resumableRepair ? (args.skills ?? null) : null,
2374
2384
  ...(agent === undefined ? {} : { runner: agent }),
2375
2385
  ...(request.onProviderSpawn === undefined ? {} : { onSpawn: request.onProviderSpawn }),
2376
2386
  clock,
@@ -0,0 +1,119 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { run as execRun } from "./exec.js";
5
+ import { storeEvidence } from "./evidence.js";
6
+ import { validateHandoffPatch } from "./local-handoff.js";
7
+ import { requestFollowUpChecks } from "./result-follow-ups.js";
8
+ import { teardownGit } from "./teardown-git.js";
9
+ const COMMIT_SHA = /^[0-9a-f]{40}$/;
10
+ export async function materializePromotedCandidate(input) {
11
+ const { store, evidenceRoot, repo, taskRef, taskId, candidateId, author, promoter, baseCommit, patch, patchSha256, note, now } = input;
12
+ if (!COMMIT_SHA.test(baseCommit)) {
13
+ return { ok: false, error: "invalid_base", message: "Candidate base commit is missing or not a valid Git commit SHA." };
14
+ }
15
+ const checked = validateHandoffPatch(patch);
16
+ if (!checked.ok) {
17
+ return { ok: false, error: "invalid_patch", message: checked.error };
18
+ }
19
+ const git = teardownGit(execRun);
20
+ const scratch = mkdtempSync(join(tmpdir(), "so-promote-"));
21
+ const worktree = join(scratch, "wt");
22
+ const patchFile = join(scratch, "candidate.patch");
23
+ const branch = `toolroll/candidate/${candidateId}`;
24
+ let worktreeAdded = false;
25
+ try {
26
+ writeFileSync(patchFile, patch, { encoding: "utf8", mode: 0o600 });
27
+ const added = await git(repo, ["worktree", "add", "--detach", worktree, baseCommit]);
28
+ if (added.code !== 0) {
29
+ return {
30
+ ok: false,
31
+ error: "worktree_failed",
32
+ message: `Could not create central verification worktree at ${baseCommit.slice(0, 8)}: ${(added.stderr || added.stdout).trim().slice(0, 200)}`,
33
+ };
34
+ }
35
+ worktreeAdded = true;
36
+ const applied = await git(worktree, ["apply", "--index", "--", patchFile]);
37
+ if (applied.code !== 0) {
38
+ return {
39
+ ok: false,
40
+ error: "apply_failed",
41
+ message: `Candidate patch did not apply cleanly at ${baseCommit.slice(0, 8)}: ${(applied.stderr || applied.stdout).trim().slice(0, 200)}`,
42
+ };
43
+ }
44
+ const summary = note.trim() === ""
45
+ ? `Promote candidate ${candidateId} for ${taskId}`
46
+ : `Promote candidate ${candidateId} for ${taskId}: ${note.trim().slice(0, 120)}`;
47
+ const body = [
48
+ summary,
49
+ "",
50
+ `Task: ${taskId}`,
51
+ `Candidate: ${candidateId}`,
52
+ `Author: ${author}`,
53
+ `Promoted-by: ${promoter}`,
54
+ `Patch-SHA256: ${patchSha256}`,
55
+ ].join("\n");
56
+ const committed = await git(worktree, [
57
+ "-c", "user.name=Toolroll Candidate Promotion",
58
+ "-c", "user.email=toolroll@local",
59
+ "commit", "--no-verify", "--no-gpg-sign", "-m", body,
60
+ ]);
61
+ if (committed.code !== 0) {
62
+ return {
63
+ ok: false,
64
+ error: "commit_failed",
65
+ message: `Could not commit candidate in central worktree: ${(committed.stderr || committed.stdout).trim().slice(0, 200)}`,
66
+ };
67
+ }
68
+ const headRes = await git(worktree, ["rev-parse", "HEAD"]);
69
+ const headCommit = headRes.stdout.trim();
70
+ if (headRes.code !== 0 || !COMMIT_SHA.test(headCommit)) {
71
+ return { ok: false, error: "commit_failed", message: "Could not read materialized commit SHA." };
72
+ }
73
+ const branched = await git(repo, ["branch", "-f", branch, headCommit]);
74
+ if (branched.code !== 0) {
75
+ return { ok: false, error: "commit_failed", message: `Could not publish central candidate branch ${branch}.` };
76
+ }
77
+ const diffRes = await git(repo, ["diff", `${baseCommit}..${headCommit}`]);
78
+ const canonicalDiff = diffRes.code === 0 && diffRes.stdout.trim() !== "" ? diffRes.stdout : patch;
79
+ const stamp = now.toISOString();
80
+ const runId = store.transact(() => {
81
+ const inserted = store.handle.prepare(`INSERT INTO run (
82
+ task_ref, lease_id, runner, role, provider,
83
+ base_revision, head_revision, branch, worktree, phase,
84
+ outcome, reason, committed, started_at, finished_at
85
+ ) VALUES (?, ?, ?, 'builder', 'claude', ?, ?, ?, ?, 'build', 'built', ?, 1, ?, ?)`).run(taskRef, `promote:${candidateId}`, "candidate-promotion", baseCommit, headCommit, branch, repo, `Promoted local candidate ${candidateId} by ${promoter} (author: ${author})`, stamp, stamp);
86
+ const id = Number(inserted.lastInsertRowid);
87
+ store.recordRunCheck(id, { status: "not-run", exitCode: null, suites: [] }, now);
88
+ return id;
89
+ });
90
+ storeEvidence(store, evidenceRoot, runId, "diff", "diff.patch", Buffer.from(canonicalDiff, "utf8"), `git diff ${baseCommit.slice(0, 12)}..${headCommit.slice(0, 12)} (candidate ${candidateId})`, now, { captureStatus: "ok" });
91
+ storeEvidence(store, evidenceRoot, runId, "terminal-diff", "terminal-diff.patch", Buffer.from(canonicalDiff, "utf8"), `git diff ${baseCommit.slice(0, 12)}..${headCommit.slice(0, 12)} (candidate ${candidateId})`, now, { captureStatus: "ok" });
92
+ storeEvidence(store, evidenceRoot, runId, "diff-stat", "diff-stat.json", Buffer.from(JSON.stringify({
93
+ schema: 1,
94
+ head: headCommit,
95
+ base: baseCommit,
96
+ filesTruncated: false,
97
+ fileCount: checked.files.length,
98
+ files: checked.files.map(path => ({ path })),
99
+ }), "utf8"), "git diff --numstat", now, { captureStatus: "ok" });
100
+ const requested = requestFollowUpChecks(store, { runId, level: "full", actor: promoter, why: "person" }, now);
101
+ const checks = requested.ok
102
+ ? { status: "queued", requestId: requested.request, level: requested.level }
103
+ : {
104
+ status: requested.reason === "no-check" ? "not-configured" : "refused",
105
+ reason: requested.reason,
106
+ message: requested.message,
107
+ };
108
+ return { ok: true, runId, branch, baseCommit, headCommit, checks };
109
+ }
110
+ finally {
111
+ if (worktreeAdded) {
112
+ await git(repo, ["worktree", "remove", "--force", worktree]).catch(() => undefined);
113
+ }
114
+ try {
115
+ rmSync(scratch, { recursive: true, force: true });
116
+ }
117
+ catch { }
118
+ }
119
+ }
@@ -0,0 +1,156 @@
1
+ import { createHash } from "node:crypto";
2
+ import { posix } from "node:path";
3
+ import { z } from "zod";
4
+ import { WORKSPACE_ID_PATTERN, RECOVERY_GENERATION_PATTERN } from "./workspace-identity-schema.js";
5
+ export const ENROLLMENT_RECORD_LIMIT = 65_536;
6
+ const uuid = z.string().regex(WORKSPACE_ID_PATTERN);
7
+ const hex = z.string().regex(RECOVERY_GENERATION_PATTERN);
8
+ const digest = z.string().regex(/^[0-9a-f]{64}$/);
9
+ const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
10
+ const path = z.string().min(2).max(4096).refine(value => value.startsWith("/") && !/[\x00-\x1f\x7f\\]/.test(value)
11
+ && posix.normalize(value) === value && !value.endsWith("/")
12
+ && [...value].every(char => { const code = char.codePointAt(0); return code < 0xd800 || code > 0xdfff; }));
13
+ const identity = z.object({ dev: integer, ino: integer }).strict();
14
+ const common = {
15
+ version: z.literal(1), installationId: uuid, workspaceId: uuid, ownerUid: integer,
16
+ databasePath: path, statePath: path, stateIdentity: identity, protocolVersion: z.literal(1), manifestVersion: z.literal(1), transactionId: hex,
17
+ };
18
+ const expectationSchema = z.object({ ...common, pathDigest: digest, phase: z.enum(["enrolling", "enrolled", "recovery-blocked"]),
19
+ services: z.array(z.string().min(1).max(256)).min(1).max(8).refine(v => new Set(v).size === v.length),
20
+ }).strict();
21
+ const rootSchema = z.object({ ...common, recoveryGeneration: hex, phase: z.enum(["prepared", "committed"]) }).strict();
22
+ const receiptSchema = z.object({ ...common, recoveryGeneration: hex }).strict();
23
+ const bindingSchema = z.object({ version: z.literal(1), installationId: uuid, ownerUid: integer, databasePath: path,
24
+ pathDigest: digest, registryVersion: z.literal(1), centralRecoveryRequired: z.literal(true),
25
+ serviceId: z.string().min(1).max(256), definitionDigest: digest,
26
+ }).strict();
27
+ function decode(raw, schema) {
28
+ if (typeof raw !== "string" || Buffer.byteLength(raw, "utf8") > ENROLLMENT_RECORD_LIMIT)
29
+ return null;
30
+ try {
31
+ const value = JSON.parse(raw);
32
+ if (JSON.stringify(value) !== raw)
33
+ return null;
34
+ const parsed = schema.safeParse(value);
35
+ return parsed.success ? parsed.data : null;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ export const parseEnrollmentExpectation = (raw) => decode(raw, expectationSchema);
42
+ export const parseEnrollmentRoot = (raw) => decode(raw, rootSchema);
43
+ export const parseEnrollmentReceipt = (raw) => decode(raw, receiptSchema);
44
+ export const parseEnrollmentBinding = (raw) => decode(raw, bindingSchema);
45
+ const unavailable = z.object({ observed: z.literal("unavailable"), path, reason: z.enum(["denied", "changed", "invalid", "unknown"]) }).strict();
46
+ const absent = z.object({ observed: z.literal("absent"), path, error: z.literal("ENOENT") }).strict();
47
+ const directory = z.object({ observed: z.literal("directory"), path, uid: integer, mode: integer, dev: integer, ino: integer }).strict();
48
+ const file = z.object({ observed: z.literal("file"), path, uid: integer, mode: integer, nlink: integer,
49
+ dev: integer, ino: integer, size: integer, bytes: z.string().max(ENROLLMENT_RECORD_LIMIT),
50
+ }).strict();
51
+ const node = z.discriminatedUnion("observed", [unavailable, absent, directory, file]);
52
+ const receipt = z.discriminatedUnion("observed", [
53
+ z.object({ observed: z.literal("absent") }).strict(),
54
+ z.object({ observed: z.literal("unavailable") }).strict(),
55
+ z.object({ observed: z.literal("record"), bytes: z.string().max(ENROLLMENT_RECORD_LIMIT) }).strict(),
56
+ ]);
57
+ const captureSchema = z.object({ version: z.literal(1), ownerUid: integer, home: path, databasePath: path,
58
+ homeDirectory: node, stateDirectory: node, registryDirectory: node, expectationsDirectory: node,
59
+ secretsDirectory: node, expectation: node, root: node, binding: node, receipt,
60
+ }).strict();
61
+ export const parseEnrollmentCapture = (raw) => decode(raw, captureSchema);
62
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
63
+ export function capturedEnrollmentNames(home, databasePath) {
64
+ if (!path.safeParse(home).success || !path.safeParse(databasePath).success)
65
+ return null;
66
+ const registry = `${home}/.toolroll-central`, state = posix.dirname(databasePath), pathDigest = hash(databasePath);
67
+ if (!path.safeParse(state).success)
68
+ return null;
69
+ return { registry, expectations: `${registry}/expectations`, expectation: `${registry}/expectations/${pathDigest}.json`,
70
+ state, secrets: `${state}/.toolroll-secrets`, root: `${state}/.toolroll-secrets/central-recovery.json`, pathDigest };
71
+ }
72
+ const privateDirectory = (n, expected, uid) => n.observed === "directory"
73
+ && n.path === expected && n.uid === uid && n.mode === 0o700;
74
+ const privateFile = (n, expected, uid) => n.observed === "file" && n.path === expected
75
+ && n.uid === uid && n.mode === 0o600 && n.nlink === 1 && n.size === Buffer.byteLength(n.bytes, "utf8") ? n.bytes : null;
76
+ const missing = (n, expected) => n.observed === "absent" && n.path === expected;
77
+ const inaccessible = (n) => n.observed === "unavailable";
78
+ const assessment = (classification, reason) => Object.freeze({
79
+ classification, reason, nativeProof: "not-performed", capabilities: Object.freeze({ admission: false, enrollment: false,
80
+ recoveryReady: false, remoteReads: false, dispatch: false }),
81
+ });
82
+ export function assessEnrollmentCapture(raw) {
83
+ const c = parseEnrollmentCapture(raw), blocked = (why) => assessment("blocked-capture", why);
84
+ if (c === null)
85
+ return blocked("invalid-capture");
86
+ const n = capturedEnrollmentNames(c.home, c.databasePath);
87
+ if (n === null)
88
+ return blocked("invalid-path");
89
+ if (c.homeDirectory.observed !== "directory" || c.homeDirectory.path !== c.home || c.homeDirectory.uid !== c.ownerUid
90
+ || (c.homeDirectory.mode & 0o022) !== 0 || !privateDirectory(c.stateDirectory, n.state, c.ownerUid))
91
+ return blocked("unsafe-anchor-capture");
92
+ if ([c.registryDirectory, c.expectationsDirectory, c.secretsDirectory, c.expectation, c.root, c.binding].some(inaccessible)
93
+ || c.receipt.observed === "unavailable")
94
+ return blocked("indeterminate-capture");
95
+ const registryAbsent = missing(c.registryDirectory, n.registry);
96
+ const registryPresent = privateDirectory(c.registryDirectory, n.registry, c.ownerUid);
97
+ const expectationsAbsent = missing(c.expectationsDirectory, n.expectations);
98
+ const expectationsPresent = privateDirectory(c.expectationsDirectory, n.expectations, c.ownerUid);
99
+ const secretsAbsent = missing(c.secretsDirectory, n.secrets);
100
+ const secretsPresent = privateDirectory(c.secretsDirectory, n.secrets, c.ownerUid);
101
+ if ((!registryAbsent && !registryPresent) || (!expectationsAbsent && !expectationsPresent) || (!secretsAbsent && !secretsPresent)
102
+ || (registryAbsent && !expectationsAbsent))
103
+ return blocked("unsafe-directory-capture");
104
+ const noExpectation = missing(c.expectation, n.expectation), noRoot = missing(c.root, n.root);
105
+ if (registryAbsent && !noExpectation || expectationsAbsent && !noExpectation || secretsAbsent && !noRoot)
106
+ return blocked("contradictory-capture");
107
+ if (noExpectation && noRoot && c.binding.observed === "absent" && c.receipt.observed === "absent") {
108
+ return assessment("personal-capture", "no-enrollment-evidence-in-capture");
109
+ }
110
+ if (!registryPresent || !expectationsPresent || !secretsPresent)
111
+ return blocked("expected-records-missing");
112
+ const eRaw = privateFile(c.expectation, n.expectation, c.ownerUid), rRaw = privateFile(c.root, n.root, c.ownerUid);
113
+ const bRaw = privateFile(c.binding, c.binding.path, c.ownerUid);
114
+ const e = eRaw === null ? null : parseEnrollmentExpectation(eRaw), r = rRaw === null ? null : parseEnrollmentRoot(rRaw);
115
+ const b = bRaw === null ? null : parseEnrollmentBinding(bRaw);
116
+ const d = c.receipt.observed === "record" ? parseEnrollmentReceipt(c.receipt.bytes) : null;
117
+ if (e === null || r === null || b === null || d === null)
118
+ return blocked("missing-or-invalid-record");
119
+ const s = c.stateDirectory;
120
+ if (s.observed !== "directory")
121
+ return blocked("unsafe-state");
122
+ for (const record of [e, r, d]) {
123
+ if (record.ownerUid !== c.ownerUid || record.databasePath !== c.databasePath || record.statePath !== n.state
124
+ || record.stateIdentity.dev !== s.dev || record.stateIdentity.ino !== s.ino || record.installationId !== e.installationId
125
+ || record.workspaceId !== e.workspaceId || record.transactionId !== e.transactionId)
126
+ return blocked("record-mismatch");
127
+ }
128
+ if (e.pathDigest !== n.pathDigest || b.pathDigest !== n.pathDigest || b.ownerUid !== c.ownerUid || b.databasePath !== c.databasePath
129
+ || b.installationId !== e.installationId || !e.services.includes(b.serviceId) || r.recoveryGeneration !== d.recoveryGeneration)
130
+ return blocked("binding-mismatch");
131
+ if (e.phase !== "enrolled" || r.phase !== "committed")
132
+ return blocked("incomplete-transaction");
133
+ return assessment("consistent-enrolled-capture", "requires-native-exclusion-and-retirement-proof");
134
+ }
135
+ const phases = ["expectation-durable", "records-prepared", "expectation-enrolled", "service-activated"];
136
+ const transitionSchema = z.object({ before: z.string().max(ENROLLMENT_RECORD_LIMIT), after: z.string().max(ENROLLMENT_RECORD_LIMIT),
137
+ from: z.enum(phases), to: z.enum(phases),
138
+ }).strict();
139
+ export function assessEnrollmentTransition(raw) {
140
+ const input = decode(raw, transitionSchema), blocked = (why) => assessment("blocked-capture", why);
141
+ if (input === null)
142
+ return blocked("invalid-transition");
143
+ const before = parseEnrollmentExpectation(input.before), after = parseEnrollmentExpectation(input.after);
144
+ if (before === null || after === null)
145
+ return blocked("invalid-expected-record");
146
+ const from = phases.indexOf(input.from), to = phases.indexOf(input.to);
147
+ if (to !== from + 1)
148
+ return blocked("nonsequential-transition");
149
+ const expectedBefore = from < 2 ? "enrolling" : "enrolled", expectedAfter = to < 2 ? "enrolling" : "enrolled";
150
+ if (before.phase !== expectedBefore || after.phase !== expectedAfter)
151
+ return blocked("phase-mismatch");
152
+ const { phase: _beforePhase, ...oldFields } = before, { phase: _afterPhase, ...newFields } = after;
153
+ if (JSON.stringify(oldFields) !== JSON.stringify(newFields))
154
+ return blocked("expected-record-changed");
155
+ return assessment("consistent-transition-capture", "transition-represented-only-no-write-authority");
156
+ }