toolroll 0.9.115 → 0.9.117

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 (145) hide show
  1. package/CHANGELOG.md +55 -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 +39 -10
  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 +3 -1
  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/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +15 -4
  33. package/dist/contracts/engine-api.js +344 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-authority-end.js +2 -0
  57. package/dist/flexible-interactive-schema.js +133 -0
  58. package/dist/flexible-interactive.js +94 -0
  59. package/dist/flexible-session.js +117 -49
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-sign-in.js +10 -0
  62. package/dist/flexible-start.js +21 -3
  63. package/dist/flexible-thread.js +2 -3
  64. package/dist/flexible-turns.js +26 -5
  65. package/dist/flexible.js +13 -0
  66. package/dist/flow-triggers.js +13 -4
  67. package/dist/flows-ui.js +54 -20
  68. package/dist/handoff-cli.js +630 -0
  69. package/dist/invoke.js +55 -13
  70. package/dist/lead-contract.js +5 -4
  71. package/dist/lead-doors.js +80 -1
  72. package/dist/lead-progress.js +9 -0
  73. package/dist/lead-tools.js +682 -10
  74. package/dist/lead.js +37 -9
  75. package/dist/live-bus.js +11 -0
  76. package/dist/live-terminal.js +132 -12
  77. package/dist/local-handoff.js +363 -0
  78. package/dist/local-owner-acts.js +264 -2
  79. package/dist/local-owner.js +16 -1
  80. package/dist/multiplayer-handoff.js +528 -0
  81. package/dist/multiplayer-presence.js +471 -0
  82. package/dist/names.js +17 -4
  83. package/dist/needs-you.js +10 -0
  84. package/dist/operate.js +280 -19
  85. package/dist/policy.js +2 -2
  86. package/dist/project-delete-ui.js +18 -11
  87. package/dist/project-delete.js +65 -4
  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/serve.js +49 -5
  102. package/dist/server/chat.js +94 -13
  103. package/dist/server/console.css +9 -9
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +47 -13
  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/spend-report.js +2 -2
  123. package/dist/spend.js +3 -3
  124. package/dist/store.js +600 -59
  125. package/dist/subagent-admin.js +23 -10
  126. package/dist/subagent-backup-schema.js +36 -0
  127. package/dist/subagent-backup.js +92 -0
  128. package/dist/subagent-week.js +2 -2
  129. package/dist/subagent-work.js +70 -47
  130. package/dist/subagents-ui.js +6 -2
  131. package/dist/subagents.js +5 -2
  132. package/dist/subscription-chat.js +36 -5
  133. package/dist/subscription-usage.js +233 -0
  134. package/dist/task-live.js +2 -1
  135. package/dist/teardown-git.js +34 -4
  136. package/dist/terminal-connection.js +159 -0
  137. package/dist/terminal-safety.js +114 -0
  138. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  139. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  140. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  141. package/dist/tui/linux-x64/toolroll-tui +0 -0
  142. package/dist/tui-contract.js +1 -1
  143. package/dist/tui-launch.js +32 -1
  144. package/dist/workspace-identity-schema.js +21 -0
  145. package/package.json +4 -2
package/dist/store.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CHECK_RECOVERY_HELD, readCheckRecoveryHoldsForTaskRef } from "./check-recovery-hold.js";
1
2
  import { verifyResultImage } from "./chat-evidence.js";
2
3
  import { parseFeedbackImage } from "./result-review.js";
3
4
  import { agentSaidTail } from "./agent-said.js";
@@ -31,6 +32,12 @@ import { V170_ADDED_COLUMNS, V170_STEPS } from "./agent-said-schema.js";
31
32
  import { V171_SCHEMA, V171_STEPS } from "./flexible-setting-schema.js";
32
33
  import { V172_ADDED_COLUMNS, V172_OBJECTS, V172_SCHEMA, V172_STEPS } from "./flexible-sign-in-schema.js";
33
34
  import { V173_ADDED_COLUMNS, V173_STEPS } from "./plan-problems-schema.js";
35
+ import { V175_OBJECTS, V175_SCHEMA, V175_STEPS } from "./flexible-interactive-schema.js";
36
+ import { V176_ADDED_COLUMNS, V176_STEPS, V176_SCHEMA, V176_OBJECTS } from "./subagent-backup-schema.js";
37
+ import { V178_STEPS, V178_SCHEMA, V178_INDEX } from "./check-recovery-index-schema.js";
38
+ import { V180_SCHEMA, V180_STEPS } from "./agent-change-schema.js";
39
+ import { V181_REQUIRED_COLUMNS, V181_SCHEMA, V181_STEPS, V181_TABLES, V182_REQUIRED_COLUMNS, V182_SCHEMA, V182_STEPS, V182_TABLES, V183_ADDED_COLUMNS, V183_STEPS, V184_ADDED_COLUMNS, V184_STEPS } from "./direct-chat-schema.js";
40
+ import { V177_STEPS, V177_SCHEMA, V177_OBJECTS, WORKSPACE_ID_PATTERN, RECOVERY_GENERATION_PATTERN } from "./workspace-identity-schema.js";
34
41
  import { V174_OBJECTS, V174_SCHEMA, V174_STEPS } from "./flexible-everyday-schema.js";
35
42
  import { endThreadAuthorityFor } from "./flexible-authority-end.js";
36
43
  import { relayCancel } from "./flexible-relay-cancel.js";
@@ -101,7 +108,7 @@ import { BUILDER_SERVICE_SCHEMA, CHECK_ONLY_SCHEMA, FAST_PREVIEW_SCHEMA, ROUTE_C
101
108
  export { V153_ADDED_COLUMNS } from "./plain-schema.js";
102
109
  import { releasePolicyDigest, serializeReleaseCheckPurpose, storedReleaseCheckPurpose, storedReleaseTerms, readReleaseTerms, readReleasePolicy } from "./contracts/release-terms.js";
103
110
  import { accountReachesSql, normalizeProjectAccess, projectAccessAllows, readProjectAccess } from "./project-access.js";
104
- import { LEDGER_COLUMNS, LEDGER_SCHEMA, LEDGER_TABLE, LEDGER_V99_TABLE, installLedgerTriggers } from "./action-ledger.js";
111
+ import { LEDGER_COLUMNS, LEDGER_SCHEMA, LEDGER_TABLE, LEDGER_V99_TABLE, installLedgerTriggers, recordActionWhole } from "./action-ledger.js";
105
112
  import { PLAN_AUTO_SCHEMA } from "./plan-auto.js";
106
113
  import { CONSOLE_INSTANCE_SCHEMA } from "./console-instance.js";
107
114
  import { endUnattendedGrants, FLOW_UNATTENDED_SCHEMA, grantStandsSql } from "./flow-unattended.js";
@@ -118,7 +125,7 @@ import { CHECKOUT_CLEANUP_SCHEMA, LANDED_CLEANUP_SCHEMA, STORAGE_SWEEP_SCHEMA, D
118
125
  import { inReadOnlyRequest } from "./read-only-request.js";
119
126
  import { IN_RANGE, LEDGER_CHAIN_SCHEMA, safeWhole, sealLedger, verifyLedgerChain } from "./ledger-chain.js";
120
127
  import { NO_RULES, filerFor, isProtectedWork, protectedChanges, rulesWords } from "./approval-policy.js";
121
- import { configBase, envValue, namedPath } from "./names.js";
128
+ import { configBase, envValue, namedPath, headWithin } from "./names.js";
122
129
  import { PULL_REQUEST_SCHEMA } from "./pull-request-schema.js";
123
130
  import { chatTurnAmountOf, combineReportedModels, providerTurnsOf, reportedCostUsdOf, reportedModelOf, runAmountOf } from "./reported-usage.js";
124
131
  import { usageOf } from "./run-efficiency.js";
@@ -838,7 +845,8 @@ export function checkSuitesOf(value) {
838
845
  }
839
846
  }
840
847
  const REGISTERED_AT_FILING = "again, as it was filed";
841
- export const SCHEMA_VERSION = 174;
848
+ export const SCHEMA_VERSION = 184;
849
+ export const V179_STEPS = Object.freeze(["antigravity-provider"]);
842
850
  export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
843
851
  const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
844
852
  const V118_COORDINATOR_COLUMNS = [["task_ref", "coordinator_cid"], ["coordinator_event", "cid"], ["mcp_idempotency", "cid"], ["coordinator_proposal", "cid"]];
@@ -903,7 +911,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
903
911
  "fallback_config", "fallback_cycle", "fallback_transition",
904
912
  ]);
905
913
  const V115_DROPPED_REFERENCES = /\s+REFERENCES (?:contestant|contest|tournament_terms|session_turn|attended_authorization|held_session|fallback_cycle|fallback_config|fallback_transition|routine|routine_fire)\(id\)(?: ON DELETE CASCADE)?/g;
906
- export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174]);
914
+ export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184]);
907
915
  export const V119_ADDED_COLUMNS = Object.freeze({
908
916
  task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
909
917
  run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
@@ -1446,7 +1454,7 @@ export { V156_STEPS };
1446
1454
  export { V157_STEPS };
1447
1455
  export { V158_STEPS };
1448
1456
  export { V159_STEPS };
1449
- export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS };
1457
+ export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS, V177_STEPS, V178_STEPS, V180_STEPS, V181_STEPS, V182_STEPS, V183_STEPS, V184_STEPS };
1450
1458
  export const RELEASE_ONCE_SCHEMA = `
1451
1459
  CREATE TABLE IF NOT EXISTS release_authority (
1452
1460
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -1799,7 +1807,7 @@ function readSubagentGrant(row) {
1799
1807
  }
1800
1808
  function readSubagentRow(row) {
1801
1809
  return { id: Number(row["id"]), repo: String(row["repo"]), handle: String(row["handle"]), state: String(row["state"]), version: Number(row["version"]), soul: String(row["soul"]),
1802
- model: row["model"] === null ? null : String(row["model"]), dailyTurns: Number(row["daily_turns"]), manager: String(row["manager"]), createdBy: String(row["created_by"]), createdAt: String(row["created_at"]),
1810
+ model: row["model"] === null ? null : String(row["model"]), codexBackupModel: typeof row["codex_backup_model"] === "string" ? row["codex_backup_model"] : null, authorityGeneration: Number(row["authority_generation"] ?? 0), dailyTurns: Number(row["daily_turns"]), manager: String(row["manager"]), createdBy: String(row["created_by"]), createdAt: String(row["created_at"]),
1803
1811
  updatedBy: String(row["updated_by"]), updatedAt: String(row["updated_at"]), summaryAt: row["summary_at"] === null ? null : String(row["summary_at"]),
1804
1812
  deskFlow: row["desk_flow"] === null || row["desk_flow"] === undefined ? null : Number(row["desk_flow"]),
1805
1813
  weeklyAt: row["weekly_at"] === null || row["weekly_at"] === undefined ? null : String(row["weekly_at"]) };
@@ -2103,7 +2111,7 @@ CREATE TABLE IF NOT EXISTS mcp_idempotency (
2103
2111
  CREATE TABLE IF NOT EXISTS phase_config (
2104
2112
  scope TEXT NOT NULL,
2105
2113
  phase TEXT NOT NULL CHECK (phase IN ('plan','build','repair','review')),
2106
- provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose')),
2114
+ provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose','antigravity')),
2107
2115
  model TEXT,
2108
2116
  updated_at TEXT NOT NULL,
2109
2117
  updated_by TEXT NOT NULL,
@@ -2119,7 +2127,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_config (
2119
2127
  scope TEXT NOT NULL,
2120
2128
  phase TEXT NOT NULL CHECK (phase IN ('plan','build','repair','review')),
2121
2129
  tier TEXT NOT NULL CHECK (tier IN ('light','strong')),
2122
- provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose')),
2130
+ provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose','antigravity')),
2123
2131
  model TEXT,
2124
2132
  updated_at TEXT NOT NULL,
2125
2133
  updated_by TEXT NOT NULL,
@@ -2135,7 +2143,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_config (
2135
2143
  -- substitutes for it.
2136
2144
  CREATE TABLE IF NOT EXISTS provider_readiness (
2137
2145
  runner TEXT NOT NULL REFERENCES runner(name) ON DELETE CASCADE,
2138
- provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose')),
2146
+ provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose','antigravity')),
2139
2147
  state TEXT NOT NULL CHECK (state IN ('ready','unavailable','unknown')),
2140
2148
  reason TEXT NOT NULL,
2141
2149
  probe TEXT NOT NULL,
@@ -4146,6 +4154,17 @@ function initializeStore(db, file, options = {}) {
4146
4154
  const read = schemaVersionPreflight(db, file);
4147
4155
  if (read !== null && Math.abs(read) < BASELINE_SCHEMA_VERSION)
4148
4156
  throw new Error(olderThanBaseline(file, read));
4157
+ if (read !== null && Math.abs(read) >= 177) {
4158
+ const identityProblem = workspaceIdentityShapeProblem(db);
4159
+ if (identityProblem !== null)
4160
+ throw new Error(`${file}: refusing to open — ${identityProblem}, though the schema says v${read}`);
4161
+ const indexProblem = checkRecoveryIndexShapeProblem(db, Math.abs(read) >= 178);
4162
+ if (indexProblem !== null)
4163
+ throw new Error(`${file}: refusing to open — ${indexProblem}, though the schema says v${read}`);
4164
+ }
4165
+ if (read === SCHEMA_VERSION && findingSourcesStale(db)) {
4166
+ throw new Error(`${file}: refusing to open — the current finding schema is stale; no epoch or DDL was applied`);
4167
+ }
4149
4168
  const fresh = read === null;
4150
4169
  const preflight = fresh ? createBaseline(db, file, options.createdBy) : read;
4151
4170
  if (!tableExists(db, "service_cursor")) {
@@ -4224,7 +4243,7 @@ function initializeStore(db, file, options = {}) {
4224
4243
  throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
4225
4244
  }
4226
4245
  if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
4227
- const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db);
4246
+ const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db) ?? workspaceIdentityShapeProblem(db) ?? pendingAgentChangeShapeProblem(db) ?? directChatShapeProblem(db) ?? directChatPhase1bShapeProblem(db) ?? directChatHardeningShapeProblem(db);
4228
4247
  if (missing !== null)
4229
4248
  throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
4230
4249
  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -4642,6 +4661,73 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
4642
4661
  if (everydayDamaged !== null)
4643
4662
  throw new Error(`${file}: refusing to open — ${everydayDamaged}`);
4644
4663
  step("flexible-everyday");
4664
+ db.exec(V175_SCHEMA);
4665
+ db.prepare("INSERT INTO flexible_thread_runtime (thread, runtime, chosen) SELECT id, 'stream-json', 1 FROM flexible_thread WHERE id NOT IN (SELECT thread FROM flexible_thread_runtime)").run();
4666
+ const interactiveDamaged = flexibleInteractiveShapeProblem(db);
4667
+ if (interactiveDamaged !== null)
4668
+ throw new Error(`${file}: refusing to open — ${interactiveDamaged}`);
4669
+ step("flexible-interactive");
4670
+ for (const [table, columns] of Object.entries(V176_ADDED_COLUMNS))
4671
+ for (const [column, { definition }] of Object.entries(columns))
4672
+ addColumn(db, table, column, definition);
4673
+ db.exec(V176_SCHEMA);
4674
+ const backupDamaged = subagentBackupShapeProblem(db);
4675
+ if (backupDamaged !== null)
4676
+ throw new Error(`${file}: refusing to open — ${backupDamaged}`);
4677
+ step("subagent-backup-columns");
4678
+ db.exec(V177_SCHEMA);
4679
+ const identityBefore = workspaceIdentityShapeProblem(db, false);
4680
+ if (identityBefore !== null)
4681
+ throw new Error(`${file}: refusing to open — ${identityBefore}`);
4682
+ if (db.prepare("SELECT singleton FROM workspace_identity").all().length === 0) {
4683
+ db.prepare("INSERT INTO workspace_identity (singleton, workspace_id, recovery_generation, created_at) VALUES (1, ?, ?, ?)")
4684
+ .run(randomUUID(), randomBytes(16).toString("hex"), new Date().toISOString());
4685
+ }
4686
+ const identityDamaged = workspaceIdentityShapeProblem(db);
4687
+ if (identityDamaged !== null)
4688
+ throw new Error(`${file}: refusing to open — ${identityDamaged}`);
4689
+ step("workspace-identity");
4690
+ db.exec(V178_SCHEMA);
4691
+ const indexDamaged = checkRecoveryIndexShapeProblem(db);
4692
+ if (indexDamaged !== null)
4693
+ throw new Error(`${file}: refusing to open — ${indexDamaged}`);
4694
+ step("action-ledger-index");
4695
+ widenForAntigravity(db);
4696
+ db.exec(ACP_ATTESTATION_SCHEMA);
4697
+ db.exec(ACP_BILLING_SCHEMA);
4698
+ db.exec(ACP_CHECK_SCHEMA);
4699
+ step("antigravity-provider");
4700
+ db.exec(V180_SCHEMA);
4701
+ const pendingDamaged = pendingAgentChangeShapeProblem(db);
4702
+ if (pendingDamaged !== null)
4703
+ throw new Error(`${file}: refusing to open — ${pendingDamaged}`);
4704
+ step("pending-agent-change");
4705
+ db.exec(V181_SCHEMA);
4706
+ const directChatDamaged = directChatShapeProblem(db);
4707
+ if (directChatDamaged !== null)
4708
+ throw new Error(`${file}: refusing to open — ${directChatDamaged}`);
4709
+ step("direct-chat-tables");
4710
+ db.exec(V182_SCHEMA);
4711
+ const directChatPhase1bDamaged = directChatPhase1bShapeProblem(db);
4712
+ if (directChatPhase1bDamaged !== null)
4713
+ throw new Error(`${file}: refusing to open — ${directChatPhase1bDamaged}`);
4714
+ step("direct-chat-phase1b-tables");
4715
+ for (const [table, columns] of Object.entries(V183_ADDED_COLUMNS)) {
4716
+ for (const [column, { definition }] of Object.entries(columns))
4717
+ addColumn(db, table, column, definition);
4718
+ }
4719
+ const directChatHardeningDamaged = directChatHardeningShapeProblem(db);
4720
+ if (directChatHardeningDamaged !== null)
4721
+ throw new Error(`${file}: refusing to open — ${directChatHardeningDamaged}`);
4722
+ step("direct-chat-hardening-columns");
4723
+ for (const [table, columns] of Object.entries(V184_ADDED_COLUMNS)) {
4724
+ for (const [column, { definition }] of Object.entries(columns))
4725
+ addColumn(db, table, column, definition);
4726
+ }
4727
+ const directChatEffortDamaged = directChatEffortUsageShapeProblem(db);
4728
+ if (directChatEffortDamaged !== null)
4729
+ throw new Error(`${file}: refusing to open — ${directChatEffortDamaged}`);
4730
+ step("direct-chat-effort-usage-columns");
4645
4731
  if (!fresh)
4646
4732
  reclaimDatabase(db, "migration");
4647
4733
  const expectedMarker = preflight < 0 ? preflight : -preflight;
@@ -5381,7 +5467,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_alternate (
5381
5467
  scope TEXT NOT NULL,
5382
5468
  phase TEXT NOT NULL CHECK (phase IN ('plan','build')),
5383
5469
  tier TEXT NOT NULL CHECK (tier IN ('light','routine','strong')),
5384
- provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose')),
5470
+ provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose','antigravity')),
5385
5471
  model TEXT NOT NULL,
5386
5472
  updated_at TEXT NOT NULL,
5387
5473
  updated_by TEXT NOT NULL,
@@ -5391,7 +5477,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_alternate (
5391
5477
  export const ACP_ATTESTATION_SCHEMA = `
5392
5478
  CREATE TABLE IF NOT EXISTS acp_attestation (
5393
5479
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5394
- provider TEXT NOT NULL CHECK (provider IN ('opencode','cursor','cline','qwen','goose')),
5480
+ provider TEXT NOT NULL CHECK (provider IN ('opencode','cursor','cline','qwen','goose','antigravity')),
5395
5481
  runner TEXT NOT NULL,
5396
5482
  conformance_version INTEGER NOT NULL,
5397
5483
  launch_json TEXT NOT NULL,
@@ -5410,7 +5496,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS acp_attestation_live ON acp_attestation (provi
5410
5496
  export const ACP_CHECK_SCHEMA = `
5411
5497
  CREATE TABLE IF NOT EXISTS acp_check_request (
5412
5498
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5413
- provider TEXT NOT NULL CHECK (provider IN ('opencode','cursor','cline','qwen','goose')),
5499
+ provider TEXT NOT NULL CHECK (provider IN ('opencode','cursor','cline','qwen','goose','antigravity')),
5414
5500
  runner TEXT NOT NULL,
5415
5501
  model TEXT NOT NULL,
5416
5502
  conformance_version INTEGER NOT NULL,
@@ -5439,7 +5525,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS acp_check_running ON acp_check_request (runner
5439
5525
  export const ACP_BILLING_SCHEMA = `
5440
5526
  CREATE TABLE IF NOT EXISTS acp_billing (
5441
5527
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5442
- provider TEXT NOT NULL CHECK (provider IN ('opencode','cursor','cline','qwen','goose')),
5528
+ provider TEXT NOT NULL CHECK (provider IN ('opencode','cursor','cline','qwen','goose','antigravity')),
5443
5529
  runner TEXT NOT NULL,
5444
5530
  model TEXT NOT NULL,
5445
5531
  kind TEXT NOT NULL CHECK (kind IN ('metered','plan')),
@@ -5450,26 +5536,17 @@ CREATE INDEX IF NOT EXISTS acp_billing_by ON acp_billing (provider, runner, mode
5450
5536
  `;
5451
5537
  const PROVIDERS_BEFORE_ACP = "CHECK (provider IN ('claude','codex','openrouter','gemini'))";
5452
5538
  const PROVIDERS_WITH_ACP = "CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose'))";
5539
+ const PROVIDERS_WITH_ANTIGRAVITY = "CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose','antigravity'))";
5540
+ const ACP_PROVIDERS_BEFORE_ANTIGRAVITY = "CHECK (provider IN ('opencode','cursor','cline','qwen','goose'))";
5541
+ const ACP_PROVIDERS_WITH_ANTIGRAVITY = "CHECK (provider IN ('opencode','cursor','cline','qwen','goose','antigravity'))";
5453
5542
  const AUTH_MODES_BEFORE_ACP = "CHECK (auth_mode IN ('subscription', 'api-key'))";
5454
5543
  const AUTH_MODES_WITH_ACP = "CHECK (auth_mode IN ('subscription', 'api-key', 'agent-login'))";
5455
5544
  function widenForAcp(db) {
5456
- const widen = (table, before, after) => {
5457
- const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
5458
- if (row === undefined)
5459
- return;
5460
- const stored = String(row["sql"]);
5461
- if (stored.includes(after))
5462
- return;
5463
- if (stored.split(before).length !== 2)
5464
- throw new Error(`the ${table} table's DDL is not a shape this migration knows — refusing to widen it`);
5465
- const named = (sql) => (name) => sql.replace(new RegExp(`^CREATE TABLE (?:IF NOT EXISTS )?"?${table}"?`), `CREATE TABLE ${name}`);
5466
- const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(one => String(one["name"]));
5467
- rebuildExact(db, table, named(stored), named(stored.replace(before, after)), columns);
5468
- };
5469
- for (const table of ["phase_config", "phase_tier_config", "phase_tier_alternate", "provider_readiness"])
5470
- widen(table, PROVIDERS_BEFORE_ACP, PROVIDERS_WITH_ACP);
5471
- widen("provider_auth_pause", AUTH_MODES_BEFORE_ACP, AUTH_MODES_WITH_ACP);
5472
- widen("quota", "CHECK (auth_mode IN ('subscription','api-key'))", "CHECK (auth_mode IN ('subscription','api-key','agent-login'))");
5545
+ for (const table of ["phase_config", "phase_tier_config", "phase_tier_alternate", "provider_readiness"]) {
5546
+ widenTableCheck(db, table, PROVIDERS_BEFORE_ACP, PROVIDERS_WITH_ACP, [PROVIDERS_WITH_ACP, PROVIDERS_WITH_ANTIGRAVITY]);
5547
+ }
5548
+ widenTableCheck(db, "provider_auth_pause", AUTH_MODES_BEFORE_ACP, AUTH_MODES_WITH_ACP);
5549
+ widenTableCheck(db, "quota", "CHECK (auth_mode IN ('subscription','api-key'))", "CHECK (auth_mode IN ('subscription','api-key','agent-login'))");
5473
5550
  }
5474
5551
  function widenPhaseTierSchema(db) {
5475
5552
  const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'phase_tier_config'").get();
@@ -5481,7 +5558,7 @@ function widenPhaseTierSchema(db) {
5481
5558
  scope TEXT NOT NULL,
5482
5559
  phase TEXT NOT NULL CHECK (phase IN ('plan','build','repair','review')),
5483
5560
  tier TEXT NOT NULL CHECK (tier IN ('light','strong')),
5484
- provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose')),
5561
+ provider TEXT NOT NULL CHECK (provider IN ('claude','codex','openrouter','gemini','opencode','cursor','cline','qwen','goose','antigravity')),
5485
5562
  model TEXT,
5486
5563
  updated_at TEXT NOT NULL,
5487
5564
  updated_by TEXT NOT NULL,
@@ -5646,6 +5723,14 @@ export class Store {
5646
5723
  const ref = this.db
5647
5724
  .prepare("SELECT id, coordinator_cid FROM task_ref WHERE backend = ? AND external_id = ?")
5648
5725
  .get(BUILT_IN, taskId);
5726
+ if (replacedBy !== undefined && this.db.prepare("SELECT 1 FROM action_ledger WHERE action = ? LIMIT 1").get(CHECK_RECOVERY_HELD) !== undefined) {
5727
+ const successor = this.lookupRef(replacedBy);
5728
+ if ((ref === undefined && this.getTask(taskId) !== null) || (successor === null && this.getTask(replacedBy) !== null))
5729
+ return { changed: false, reason: "recovery-held" };
5730
+ const refs = [...(ref === undefined ? [] : [Number(ref["id"])]), ...(successor === null ? [] : [successor.id])];
5731
+ if (unresolvedRecoveryCheckFamily(this, refs) !== null)
5732
+ return { changed: false, reason: "recovery-held" };
5733
+ }
5649
5734
  const coordinator = ref?.["coordinator_cid"] != null;
5650
5735
  if (reason.kind === "operator") {
5651
5736
  if (coordinator) {
@@ -5678,6 +5763,8 @@ export class Store {
5678
5763
  releaseTrialPlaces(this, Number(ref["id"]), now);
5679
5764
  if (ref !== undefined)
5680
5765
  this.supersedeSteerNotes(Number(ref["id"]), now);
5766
+ if (ref !== undefined)
5767
+ this.db.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(Number(ref["id"]));
5681
5768
  if (ref !== undefined)
5682
5769
  this.closeQuestionsLocked(Number(ref["id"]), "cancelled", now);
5683
5770
  if (ref !== undefined && coordinator) {
@@ -7067,7 +7154,9 @@ export class Store {
7067
7154
  continue;
7068
7155
  this.noteLifecycle({ taskRef: ref.id, kind: "approval-withdrawn", identity: `t${ref.id}`, subject: "Approval needs renewing", body: "The automatic approval it ran under has ended. Approve it again before it runs.", link: chatControlHref("approval", taskId) }, now);
7069
7156
  }
7070
- const repoIntents = `publication IN (
7157
+ const frozenIntents = this.db.prepare("SELECT 1 FROM action_ledger WHERE action=? LIMIT 1").get(CHECK_RECOVERY_HELD) === undefined ? []
7158
+ : this.db.prepare("SELECT i.id,i.publication FROM merge_intent i JOIN publication p ON p.id=i.publication JOIN run r ON r.id=p.run JOIN task_ref t ON t.id=r.task_ref WHERE i.state IN ('waiting-human','pending','claimed') AND t.repo=?").all(repo).filter(row => mergeIntentRecoveryHeld(this, Number(row["publication"]))).map(row => Number(row["id"]));
7159
+ const repoIntents = `id NOT IN (SELECT value FROM json_each('${JSON.stringify(frozenIntents)}')) AND publication IN (
7071
7160
  SELECT publication.id FROM publication
7072
7161
  JOIN run ON run.id = publication.run
7073
7162
  JOIN task_ref ON task_ref.id = run.task_ref
@@ -7567,6 +7656,8 @@ export class Store {
7567
7656
  return this.ledgerHeadId();
7568
7657
  }
7569
7658
  recordAction(entry) {
7659
+ if (entry.action === MERGE_FIRING_ADMITTED)
7660
+ throw new Error("Merge firing admission is written only by the firing transaction");
7570
7661
  const detail = entry.detail == null ? null : entry.detail.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 300);
7571
7662
  const row = this.db.prepare("INSERT INTO action_ledger(at,actor,repo,task_id,run_id,action,outcome,source,detail) VALUES (?,?,?,?,?,?,?,?,?)")
7572
7663
  .run(entry.at, entry.actor, entry.repo, entry.taskId, entry.runId, entry.action, entry.outcome, entry.source, detail);
@@ -9682,6 +9773,10 @@ export class Store {
9682
9773
  .get(BUILT_IN, taskId);
9683
9774
  if (ref === undefined)
9684
9775
  return { ok: false, reason: "unknown-task" };
9776
+ const cancellable = ["queued", "failed", "running"];
9777
+ const stateNow = String(this.db.prepare("SELECT state FROM task WHERE id = ?").get(taskId)?.["state"]);
9778
+ if (!cancellable.includes(stateNow))
9779
+ return { ok: false, reason: "already-terminal" };
9685
9780
  if (seen !== undefined) {
9686
9781
  const state = this.db.prepare("SELECT state FROM task WHERE id = ?").get(taskId)?.["state"];
9687
9782
  const last = this.db.prepare("SELECT MAX(id) AS id FROM run WHERE task_ref = ?").get(Number(ref["id"]))?.["id"];
@@ -9691,7 +9786,7 @@ export class Store {
9691
9786
  }
9692
9787
  if (this.hasLiveClaim(Number(ref["id"]), now))
9693
9788
  return { ok: false, reason: "claimed" };
9694
- const done = this.applyCancellation(taskId, { kind: "operator", text: reason ?? null }, now, ["queued", "failed", "running"]);
9789
+ const done = this.applyCancellation(taskId, { kind: "operator", text: reason ?? null }, now, cancellable);
9695
9790
  if (done.reason !== undefined)
9696
9791
  return { ok: false, reason: done.reason };
9697
9792
  if (!done.changed)
@@ -10693,8 +10788,8 @@ export class Store {
10693
10788
  sweepStaleChatTurns(now) {
10694
10789
  const swept = this.db
10695
10790
  .prepare(`UPDATE chat_turn SET state = 'failed', failure_reason = 'crashed', generation = generation + 1,
10696
- unknown_spend = CASE WHEN started_at IS NOT NULL THEN 1 ELSE 0 END,
10697
- settled_microusd = CASE WHEN started_at IS NOT NULL THEN settled_microusd ELSE 0 END,
10791
+ unknown_spend = CASE WHEN started_at IS NOT NULL AND billing_reported IS NOT 'subscription' THEN 1 ELSE 0 END,
10792
+ settled_microusd = CASE WHEN started_at IS NOT NULL AND billing_reported IS NOT 'subscription' THEN settled_microusd ELSE 0 END,
10698
10793
  finished_at = ?
10699
10794
  WHERE state IN ('queued','running') AND deadline_at < ?`)
10700
10795
  .run(now.toISOString(), now.toISOString());
@@ -12941,7 +13036,10 @@ export class Store {
12941
13036
  });
12942
13037
  }
12943
13038
  reserveObservation(githubRepo, prNumber) {
12944
- return this.transact(() => {
13039
+ const key = `${githubRepo}:${prNumber}`;
13040
+ mergeObservationReservations.get(this)?.delete(key);
13041
+ const eligible = this.handle.isTransaction === false;
13042
+ const generation = this.transact(() => {
12945
13043
  const row = this.db
12946
13044
  .prepare("SELECT generation FROM ci_observation WHERE github_repo = ? AND pr_number = ?")
12947
13045
  .get(githubRepo, prNumber);
@@ -12958,6 +13056,18 @@ export class Store {
12958
13056
  }
12959
13057
  return generation;
12960
13058
  });
13059
+ if (eligible && Number.isSafeInteger(generation) && generation > 0) {
13060
+ const dataVersion = this.db.prepare("PRAGMA data_version").get()?.["data_version"];
13061
+ if (typeof dataVersion === "number" && Number.isSafeInteger(dataVersion) && dataVersion >= 0) {
13062
+ let reservations = mergeObservationReservations.get(this);
13063
+ if (reservations === undefined) {
13064
+ reservations = new Map();
13065
+ mergeObservationReservations.set(this, reservations);
13066
+ }
13067
+ reservations.set(key, { generation, dataVersion, scope: mergeObservationScope(this, githubRepo, prNumber), writeStamp: mergeObservationWriteStamp(this) });
13068
+ }
13069
+ }
13070
+ return generation;
12961
13071
  }
12962
13072
  settleObservation(observation, now) {
12963
13073
  const { changes } = this.db
@@ -12985,7 +13095,9 @@ export class Store {
12985
13095
  .run(now.toISOString(), by, publication).changes) > 0);
12986
13096
  }
12987
13097
  createMergeIntent(intent, now) {
12988
- this.transact(() => {
13098
+ return this.transact(() => {
13099
+ if (mergeIntentRecoveryHeld(this, intent.publication))
13100
+ return "recovery-held";
12989
13101
  if (nightlyPublication(this, intent.publication))
12990
13102
  throw new Error(NIGHTLY_CHECK_ONLY);
12991
13103
  if (releasePublication(this, intent.publication))
@@ -13019,8 +13131,8 @@ export class Store {
13019
13131
  }
13020
13132
  claimMergeIntent(id, by, leaseMs, now) {
13021
13133
  return this.transact(() => {
13022
- const row = this.db.prepare("SELECT state, claimed_until, generation FROM merge_intent WHERE id = ?").get(id);
13023
- if (row === undefined)
13134
+ const row = this.db.prepare("SELECT state, claimed_until, generation, publication FROM merge_intent WHERE id = ?").get(id);
13135
+ if (row === undefined || mergeIntentRecoveryHeld(this, Number(row["publication"])))
13024
13136
  return null;
13025
13137
  const state = String(row["state"]);
13026
13138
  const expired = row["claimed_until"] !== null && String(row["claimed_until"]) <= now.toISOString();
@@ -13035,9 +13147,17 @@ export class Store {
13035
13147
  });
13036
13148
  }
13037
13149
  settleMergeIntent(id, generation, state, now, detail = {}) {
13038
- const from = detail.from ?? "nonterminal";
13039
- const { changes } = this.db
13040
- .prepare(`UPDATE merge_intent SET state = ?, claimed_by = NULL, claimed_until = NULL,
13150
+ return this.transact(() => {
13151
+ const observed = validMergeIntentObservation(this, id, generation);
13152
+ const current = this.db.prepare("SELECT publication, state, generation FROM merge_intent WHERE id=?").get(id);
13153
+ if (current === undefined)
13154
+ return false;
13155
+ if (mergeIntentRecoveryHeld(this, Number(current["publication"])) &&
13156
+ (state !== "merged" || !observed))
13157
+ return false;
13158
+ const from = detail.from ?? "nonterminal";
13159
+ const { changes } = this.db
13160
+ .prepare(`UPDATE merge_intent SET state = ?, claimed_by = NULL, claimed_until = NULL,
13041
13161
  firing_at = NULL, firing_deadline = NULL,
13042
13162
  authority_basis = CASE WHEN ? = 'waiting-human' THEN 'human' ELSE authority_basis END,
13043
13163
  mode_digest = CASE WHEN ? = 'waiting-human' THEN NULL ELSE mode_digest END,
@@ -13047,13 +13167,16 @@ export class Store {
13047
13167
  WHERE id = ? AND generation = ?
13048
13168
  AND state NOT IN ('merged','refused','superseded')
13049
13169
  AND (? = 'nonterminal' OR state = ?)`)
13050
- .run(state, state, state, detail.bumpGeneration === true ? 1 : 0, detail.countAttempt === true ? 1 : 0, detail.error ?? null, detail.receipt ?? null, state, now.toISOString(), id, generation, from, from);
13051
- return Number(changes) === 1;
13170
+ .run(state, state, state, detail.bumpGeneration === true ? 1 : 0, detail.countAttempt === true ? 1 : 0, detail.error ?? null, detail.receipt ?? null, state, now.toISOString(), id, generation, from, from);
13171
+ return Number(changes) === 1;
13172
+ });
13052
13173
  }
13053
13174
  authorizeMergeIntent(id, expectedHeadSha, by, now) {
13054
13175
  void by;
13055
13176
  void now;
13056
13177
  return this.transact(() => {
13178
+ if (mergeIntentRecoveryHeldById(this, id))
13179
+ return { ok: false, reason: "recovery-held" };
13057
13180
  const row = this.db.prepare("SELECT state, head_sha FROM merge_intent WHERE id = ?").get(id);
13058
13181
  if (row === undefined || String(row["state"]) !== "waiting-human")
13059
13182
  return { ok: false, reason: "not-waiting" };
@@ -13069,10 +13192,12 @@ export class Store {
13069
13192
  });
13070
13193
  }
13071
13194
  fireMergeIntent(id, generation, proof, now) {
13072
- return this.transact(() => {
13195
+ return this.transact(() => this.savepoint(() => {
13073
13196
  const row = this.db
13074
13197
  .prepare("SELECT state, generation, head_sha, grant_terms_hash, authority_basis, mode_digest, publication FROM merge_intent WHERE id = ?")
13075
13198
  .get(id);
13199
+ if (mergeIntentRecoveryHeldById(this, id))
13200
+ return { ok: false, outcome: "recovery-held", why: MERGE_RECOVERY_HELD };
13076
13201
  if (row !== undefined && nightlyPublication(this, Number(row["publication"]))) {
13077
13202
  this.settleMergeIntent(id, generation, "refused", now, { error: NIGHTLY_CHECK_ONLY, from: "claimed" });
13078
13203
  return { ok: false, outcome: "superseded", why: NIGHTLY_CHECK_ONLY };
@@ -13102,8 +13227,15 @@ export class Store {
13102
13227
  if (proof.liveGrantTermsHash === null || proof.liveGrantTermsHash !== String(row["grant_terms_hash"])) {
13103
13228
  return supersede("the grant was revoked or its merge terms changed since this intent was written");
13104
13229
  }
13230
+ const admission = mergeAdmissionScope(this, id, generation, null);
13231
+ if (admission === null || proof.repo !== admission.repo || proof.headSha !== admission.head || proof.liveGrantTermsHash !== admission.grantHash) {
13232
+ return { ok: false, outcome: "raced", why: "the actual publication and live merge grant no longer bind this claim" };
13233
+ }
13234
+ const prior = readMergeAdmissionCandidates(this, admission);
13235
+ if (prior === null || prior.some(c => c.g === generation))
13236
+ return { ok: false, outcome: "raced", why: "the firing admission history is inconsistent" };
13105
13237
  const basis = String(row["authority_basis"]);
13106
- const mode = this.activeMode(proof.repo, now);
13238
+ const mode = this.activeMode(admission.repo, now);
13107
13239
  if (basis === "mode") {
13108
13240
  let publication;
13109
13241
  try {
@@ -13131,14 +13263,17 @@ export class Store {
13131
13263
  .prepare(`UPDATE merge_intent SET state = 'firing', firing_at = ?, firing_deadline = ?
13132
13264
  WHERE id = ? AND state = 'claimed' AND generation = ?`)
13133
13265
  .run(now.toISOString(), new Date(now.getTime() + proof.graceMs).toISOString(), id, generation);
13134
- return Number(changes) === 1
13135
- ? { ok: true }
13136
- : { ok: false, outcome: "raced", why: "the claim moved" };
13137
- });
13266
+ if (Number(changes) !== 1)
13267
+ return { ok: false, outcome: "raced", why: "the claim moved" };
13268
+ writeMergeAdmission(this, admission, now);
13269
+ return { ok: true };
13270
+ }));
13138
13271
  }
13139
13272
  refireMergeIntent(id, by, now) {
13140
13273
  void by;
13141
13274
  return this.transact(() => {
13275
+ if (mergeIntentRecoveryHeldById(this, id))
13276
+ return { ok: false, reason: "recovery-held" };
13142
13277
  const row = this.db.prepare("SELECT state, firing_deadline FROM merge_intent WHERE id = ?").get(id);
13143
13278
  if (row === undefined || String(row["state"]) !== "firing")
13144
13279
  return { ok: false, reason: "not-firing" };
@@ -13153,10 +13288,14 @@ export class Store {
13153
13288
  });
13154
13289
  }
13155
13290
  rearmMergeIntent(publication) {
13156
- const { changes } = this.db
13157
- .prepare("UPDATE merge_intent SET state = 'pending', last_error = NULL WHERE publication = ? AND state = 'refused'")
13158
- .run(publication);
13159
- return Number(changes) > 0;
13291
+ return this.transact(() => {
13292
+ if (mergeIntentRecoveryHeld(this, publication))
13293
+ return "recovery-held";
13294
+ const { changes } = this.db
13295
+ .prepare("UPDATE merge_intent SET state = 'pending', last_error = NULL WHERE publication = ? AND state = 'refused'")
13296
+ .run(publication);
13297
+ return Number(changes) > 0;
13298
+ });
13160
13299
  }
13161
13300
  mergeIntentFor(publication) {
13162
13301
  const row = this.db
@@ -13346,11 +13485,13 @@ export class Store {
13346
13485
  const projects = readProjectAccess(row["projects_json"]);
13347
13486
  return projects !== null && projects.length > 0 && projects.every(repo => projectAccessAllows(account.projects, repo) && this.db.prepare("SELECT 1 FROM team_lead_project lp JOIN team_conversation tc ON tc.lead=lp.lead WHERE tc.thread=? AND lp.project=?").get(thread, repo) !== undefined);
13348
13487
  }
13349
- activeLeadSession(approver) {
13488
+ activeLeadSession(approver, credentialKey) {
13350
13489
  const row = this.db
13351
13490
  .prepare("SELECT * FROM lead_session WHERE approver = ? AND ended_at IS NULL AND NOT EXISTS (SELECT 1 FROM team_mate_session tm WHERE tm.session=lead_session.id) ORDER BY id DESC LIMIT 1")
13352
13491
  .get(approver);
13353
- return row === undefined ? null : readLeadSession(row);
13492
+ if (row === undefined || (credentialKey !== undefined && row["credential_key"] !== credentialKey))
13493
+ return null;
13494
+ return readLeadSession(row);
13354
13495
  }
13355
13496
  getLeadSession(id) {
13356
13497
  const row = this.db.prepare("SELECT * FROM lead_session WHERE id = ?").get(id);
@@ -13599,8 +13740,12 @@ export class Store {
13599
13740
  }));
13600
13741
  }
13601
13742
  subagentTurnsSince(subagent, since) {
13602
- return Number(this.db.prepare("SELECT COUNT(*) AS n FROM subagent_event WHERE subagent = ? AND at >= ? AND kind IN ('decided','handled','handed','asked','failed')").get(subagent, since)?.["n"] ?? 0)
13743
+ const legacy = Number(this.db.prepare("SELECT COUNT(*) AS n FROM subagent_event WHERE subagent = ? AND at >= ? AND kind IN ('decided','handled','handed','asked','failed')").get(subagent, since)?.["n"] ?? 0)
13603
13744
  + Number(this.db.prepare("SELECT COUNT(*) AS n FROM subagent_call WHERE subagent = ? AND created_at >= ?").get(subagent, since)?.["n"] ?? 0);
13745
+ const hasAttempts = this.db.prepare("SELECT 1 FROM subagent_turn WHERE subagent = ? AND at >= ? AND counted_attempt = 1 LIMIT 1").get(subagent, since) !== undefined;
13746
+ if (this.getSubagent(subagent)?.codexBackupModel === null && !hasAttempts)
13747
+ return legacy;
13748
+ return Math.max(legacy, Number(this.db.prepare("SELECT COUNT(*) AS n FROM subagent_turn WHERE subagent = ? AND at >= ?").get(subagent, since)?.["n"] ?? 0));
13604
13749
  }
13605
13750
  openSubagentQuestion(question, now) {
13606
13751
  const { changes, lastInsertRowid } = this.db.prepare("INSERT OR IGNORE INTO subagent_question (subagent, card, entry, question, options_json, asked_of, state, created_at, tool_call, suggestion) VALUES (?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)")
@@ -13748,7 +13893,7 @@ export class Store {
13748
13893
  }
13749
13894
  subagentTurns(subagent, since) {
13750
13895
  return this.db.prepare("SELECT * FROM subagent_turn WHERE subagent = ? AND at >= ? ORDER BY id").all(subagent, since).map(row => ({
13751
- id: Number(row["id"]), subagent: Number(row["subagent"]), card: row["card"] === null ? null : Number(row["card"]), model: String(row["model"]), ok: Number(row["ok"]) === 1, ms: Number(row["ms"]),
13896
+ id: Number(row["id"]), subagent: Number(row["subagent"]), card: row["card"] === null ? null : Number(row["card"]), model: String(row["model"]), provider: row["provider"] === "codex" ? "codex" : "claude", pending: Number(row["pending"]) === 1, modelReported: typeof row["model_reported"] === "string" ? row["model_reported"] : null, ok: Number(row["ok"]) === 1, ms: Number(row["ms"]),
13752
13897
  costUsd: row["cost_usd"] === null ? null : Number(row["cost_usd"]), tokensIn: row["tokens_in"] === null ? null : Number(row["tokens_in"]), tokensOut: row["tokens_out"] === null ? null : Number(row["tokens_out"]), at: String(row["at"])
13753
13898
  }));
13754
13899
  }
@@ -16561,6 +16706,60 @@ export class Store {
16561
16706
  flowFencePolicy(flow) {
16562
16707
  return this.db.prepare("SELECT fence_policy FROM flow WHERE id = ?").get(flow)?.["fence_policy"] === 2 ? 2 : 1;
16563
16708
  }
16709
+ setSubagentCodexBackup(id, model, by, now) {
16710
+ this.db.prepare("UPDATE subagent SET codex_backup_model = ?, updated_by = ?, updated_at = ? WHERE id = ?").run(model, by, now.toISOString(), id);
16711
+ this.addSubagentEvent({ subagent: id, kind: "note", said: model === null ? "Codex backup turned off." : `Codex backup enabled (${model}); every provider attempt counts toward the daily limit.`, by }, now);
16712
+ }
16713
+ reserveSubagentAttempt(input, now) {
16714
+ return this.transact(() => {
16715
+ const mate = this.getSubagent(input.subagent);
16716
+ if (mate === null || mate.state !== "active" || mate.codexBackupModel === null || mate.authorityGeneration !== input.authorityGeneration)
16717
+ return { ok: false, why: "The subagent or its backup is no longer enabled." };
16718
+ const card = this.getFlowCard(input.card);
16719
+ if (card === null || card.state !== "active" || card.entry !== input.cardEntry || card.stage !== input.stage || this.getFlow(card.flow)?.repo !== mate.repo || this.getFlow(card.flow)?.revision !== input.flowRevision || this.getFlow(card.flow)?.state !== "active")
16720
+ return { ok: false, why: "The card no longer belongs to this project." };
16721
+ if (this.db.prepare("SELECT 1 FROM subagent_turn WHERE subagent = ? AND card = ? AND card_entry = ? AND pending = 1").get(mate.id, input.card, input.cardEntry) !== undefined)
16722
+ return { ok: false, why: "An earlier attempt on this card is unfinished; inspect it before trying again." };
16723
+ if (input.provider === "claude") {
16724
+ const model = mate.model ?? (this.getChatConfig()?.provider === "claude-subscription" ? this.getChatConfig().model : "default");
16725
+ if (input.model !== model)
16726
+ return { ok: false, why: "The primary model changed." };
16727
+ }
16728
+ if (input.provider === "codex") {
16729
+ const parent = this.db.prepare("SELECT * FROM subagent_turn WHERE id = ? AND subagent = ? AND card = ? AND provider = 'claude' AND ok = 0 AND pending = 0 AND failure_kind IN ('usage-limit','unavailable') AND authority_generation = ? AND card_entry = ?").get(input.backupOf ?? -1, mate.id, input.card, mate.authorityGeneration, input.cardEntry);
16730
+ if (parent === undefined || mate.codexBackupModel !== input.model || input.billing !== "subscription")
16731
+ return { ok: false, why: "The approved backup or its primary attempt changed." };
16732
+ if (this.db.prepare("SELECT 1 FROM subagent_turn WHERE backup_of = ?").get(input.backupOf) !== undefined)
16733
+ return { ok: false, why: "This primary attempt already used its backup." };
16734
+ }
16735
+ const policy = this.agentPolicyRefusal(input.provider, input.model);
16736
+ if (policy !== null)
16737
+ return { ok: false, why: policy };
16738
+ const day = new Date(now);
16739
+ day.setHours(0, 0, 0, 0);
16740
+ if (this.subagentTurnsSince(mate.id, day.toISOString()) >= mate.dailyTurns)
16741
+ return { ok: false, why: "The daily turn limit is reached." };
16742
+ const budget = this.budgetGate(now)({ project: mate.repo, person: null, subagent: mate.id, agents: [{ provider: input.provider, billing: input.billing }] });
16743
+ if (budget.over !== null)
16744
+ return { ok: false, why: "A budget holds this provider attempt." };
16745
+ const row = this.db.prepare("INSERT INTO subagent_turn (subagent, card, card_entry, model, provider, billing, backup_of, pending, counted_attempt, authority_generation, ok, ms, at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, 1, ?, 0, 0, ?)")
16746
+ .run(mate.id, input.card, input.cardEntry, input.model, input.provider, input.billing, input.backupOf ?? null, mate.authorityGeneration, now.toISOString());
16747
+ this.spendCache = null;
16748
+ return { ok: true, id: Number(row.lastInsertRowid) };
16749
+ });
16750
+ }
16751
+ settleSubagentAttempt(id, result) {
16752
+ this.db.prepare("UPDATE subagent_turn SET pending = 0, ok = ?, ms = ?, model_reported = ?, failure_kind = ?, cost_usd = ?, tokens_in = ?, tokens_out = ? WHERE id = ? AND pending = 1")
16753
+ .run(result.ok ? 1 : 0, Math.round(result.ms), result.modelReported ?? null, result.failureKind ?? null, result.costUsd ?? null, result.tokensIn ?? null, result.tokensOut ?? null, id);
16754
+ this.spendCache = null;
16755
+ }
16756
+ workspaceIdentity() {
16757
+ const problem = workspaceIdentityShapeProblem(this.db);
16758
+ if (problem !== null)
16759
+ throw new Error(problem);
16760
+ const row = this.db.prepare("SELECT workspace_id, recovery_generation, created_at FROM workspace_identity WHERE singleton = 1").get();
16761
+ return { id: String(row["workspace_id"]), recoveryGeneration: String(row["recovery_generation"]), createdAt: String(row["created_at"]) };
16762
+ }
16564
16763
  }
16565
16764
  function wholeNumber(value) {
16566
16765
  if (value === null || value === undefined)
@@ -18131,6 +18330,9 @@ export function taskFamilyRefs(store, taskId) {
18131
18330
  export function liveFamilyAttempt(store, refs, now) {
18132
18331
  if (refs.length === 0)
18133
18332
  return null;
18333
+ const recovery = unresolvedRecoveryCheckFamily(store, refs);
18334
+ if (recovery !== null)
18335
+ return recovery;
18134
18336
  const row = store.handle.prepare(`SELECT r.external_id FROM task_ref r JOIN task t ON t.id = r.external_id
18135
18337
  WHERE r.id IN (SELECT value FROM json_each(?)) AND (t.state = 'running'
18136
18338
  OR EXISTS (SELECT 1 FROM claim c WHERE c.task_ref = r.id AND c.released_at IS NULL AND c.expires_at > ?
@@ -18163,6 +18365,10 @@ export function archiveTaskFamily(store, taskId, by, now, options = {}) {
18163
18365
  if (options.expect !== undefined && [...options.expect].sort((a, b) => a - b).join(",") !== refs.join(",")) {
18164
18366
  return { ok: false, reason: "blocked", message: `${taskId}'s versions changed since the list was shown.` };
18165
18367
  }
18368
+ const recovery = unresolvedRecoveryCheckFamily(store, refs);
18369
+ if (recovery !== null)
18370
+ return { ok: false, reason: "recovery-held",
18371
+ message: "This task can't be put away while earlier check execution is unverified after recovery." };
18166
18372
  const remaining = refs.filter(ref => !refArchived(store, ref));
18167
18373
  if (remaining.length === 0)
18168
18374
  return { ok: false, reason: "archived", message: `${taskId} is already put away.` };
@@ -18172,11 +18378,15 @@ export function archiveTaskFamily(store, taskId, by, now, options = {}) {
18172
18378
  const blocked = options.guard?.(refs) ?? null;
18173
18379
  if (blocked !== null)
18174
18380
  return { ok: false, reason: "blocked", message: blocked };
18381
+ if (unresolvedRecoveryCheckFamily(store, refs) !== null)
18382
+ return { ok: false, reason: "recovery-held",
18383
+ message: "This task can't be put away while earlier check execution is unverified after recovery." };
18175
18384
  const reason = by.reason.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 300) || "Put away";
18176
18385
  const at = now.toISOString();
18177
18386
  const insert = store.handle.prepare("INSERT INTO task_archive (task_ref, by, by_kind, rule, reason, at) VALUES (?, ?, ?, ?, ?, ?)");
18178
18387
  for (const ref of remaining)
18179
18388
  insert.run(ref, by.by, by.byKind, by.rule, reason, at);
18389
+ store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref IN (SELECT value FROM json_each(?))").run(JSON.stringify(refs));
18180
18390
  store.handle.prepare("UPDATE notification SET resolved_at = ? WHERE resolved_at IS NULL AND task_ref IN (SELECT value FROM json_each(?))")
18181
18391
  .run(at, JSON.stringify(refs));
18182
18392
  store.handle.prepare(`UPDATE notification SET resolved_at = ? WHERE resolved_at IS NULL AND EXISTS (SELECT 1 FROM flow_card c
@@ -19124,3 +19334,334 @@ function flexibleEverydayShapeProblem(db) {
19124
19334
  }
19125
19335
  return null;
19126
19336
  }
19337
+ function flexibleInteractiveShapeProblem(db) {
19338
+ const statements = V175_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
19339
+ for (const [type, name] of V175_OBJECTS) {
19340
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
19341
+ if (row === undefined)
19342
+ return `the interactive agent threads ${type} ${name} is missing`;
19343
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
19344
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want.replace(/;$/, "")).trim())
19345
+ return `the interactive agent threads ${type} ${name} has an unknown shape`;
19346
+ }
19347
+ return null;
19348
+ }
19349
+ function subagentBackupShapeProblem(db) {
19350
+ for (const [table, columns] of Object.entries(V176_ADDED_COLUMNS)) {
19351
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
19352
+ for (const [column, { definition }] of Object.entries(columns)) {
19353
+ if (!hasColumn(db, table, column))
19354
+ return `the subagent backup column ${table}.${column} is missing`;
19355
+ if (row === undefined || !canonicalDdl(String(row["sql"])).includes(canonicalDdl(`, ${column} ${definition}`).trim()))
19356
+ return `the subagent backup column ${table}.${column} has an unknown shape`;
19357
+ }
19358
+ }
19359
+ const statements = V176_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(Boolean);
19360
+ for (const [type, name] of V176_OBJECTS) {
19361
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
19362
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
19363
+ if (row === undefined || want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")) !== canonicalDdl(want))
19364
+ return `the subagent backup ${type} ${name} has an unknown shape`;
19365
+ }
19366
+ return null;
19367
+ }
19368
+ function workspaceIdentityShapeProblem(db, requireRow = true) {
19369
+ const statements = V177_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(Boolean);
19370
+ for (const [type, name] of V177_OBJECTS) {
19371
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
19372
+ const want = statements.find(one => new RegExp(`^CREATE ${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
19373
+ if (row === undefined || want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")) !== canonicalDdl(want))
19374
+ return `the workspace identity ${type} ${name} is missing or has an unknown shape`;
19375
+ }
19376
+ const rows = db.prepare("SELECT singleton, workspace_id, recovery_generation, created_at FROM workspace_identity").all();
19377
+ if (rows.length === 0 && !requireRow)
19378
+ return null;
19379
+ if (rows.length !== 1)
19380
+ return "the workspace identity must have exactly one row";
19381
+ const row = rows[0], id = row["workspace_id"], recovery = row["recovery_generation"], at = row["created_at"];
19382
+ if (row["singleton"] !== 1 || typeof id !== "string" || !WORKSPACE_ID_PATTERN.test(id)
19383
+ || typeof recovery !== "string" || !RECOVERY_GENERATION_PATTERN.test(recovery)
19384
+ || typeof at !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(at)
19385
+ || !Number.isFinite(Date.parse(at)) || new Date(at).toISOString() !== at)
19386
+ return "the workspace identity row has invalid metadata";
19387
+ return null;
19388
+ }
19389
+ function checkRecoveryIndexShapeProblem(db, required = true) {
19390
+ const row = db.prepare("SELECT type,tbl_name,sql FROM sqlite_master WHERE name = ?").get(V178_INDEX);
19391
+ if (row === undefined && !required)
19392
+ return null;
19393
+ if (row === undefined || row["type"] !== "index" || row["tbl_name"] !== "action_ledger"
19394
+ || canonicalDdl(String(row["sql"]).replace(/;$/, "")) !== canonicalDdl(V178_SCHEMA.replace(/;$/, ""))) {
19395
+ return "the action ledger action index is missing or has an unknown shape";
19396
+ }
19397
+ const index = db.prepare("PRAGMA index_list('action_ledger')").all().find(one => one["name"] === V178_INDEX);
19398
+ const columns = db.prepare("PRAGMA index_xinfo('action_ledger_action')").all().filter(one => one["key"] === 1);
19399
+ if (index?.["partial"] !== 1 || index["unique"] !== 0 || index["origin"] !== "c" || columns.length !== 2
19400
+ || columns.some((one, i) => one["seqno"] !== i || one["name"] !== ["action", "id"][i] || one["desc"] !== 0 || one["coll"] !== "BINARY")) {
19401
+ return "the action ledger action index is missing or has an unknown shape";
19402
+ }
19403
+ return null;
19404
+ }
19405
+ function unresolvedRecoveryCheckFamily(store, refs) {
19406
+ if (store.handle.prepare("SELECT 1 FROM action_ledger WHERE action = ? LIMIT 1").get(CHECK_RECOVERY_HELD) === undefined)
19407
+ return null;
19408
+ const covered = new Set();
19409
+ for (const ref of refs) {
19410
+ if (covered.has(ref))
19411
+ continue;
19412
+ const evidence = readCheckRecoveryHoldsForTaskRef(store, ref);
19413
+ if (evidence.kind !== "no-evidence")
19414
+ return store.externalIdFor(ref) ?? "Unknown task";
19415
+ for (const member of evidence.familyRefs)
19416
+ covered.add(member);
19417
+ }
19418
+ return null;
19419
+ }
19420
+ export const MERGE_RECOVERY_HELD = "Checks are on hold after recovery. Earlier execution is unverified.";
19421
+ export function mergeIntentRecoveryHeld(store, publicationId) {
19422
+ try {
19423
+ if (store.handle.prepare("SELECT 1 FROM action_ledger WHERE action=? LIMIT 1").get(CHECK_RECOVERY_HELD) === undefined)
19424
+ return false;
19425
+ const p = store.handle.prepare("SELECT task_ref, run FROM publication WHERE id=?").get(publicationId);
19426
+ const run = p === undefined ? undefined : store.handle.prepare("SELECT task_ref FROM run WHERE id=?").get(p["run"]);
19427
+ if (p === undefined || run === undefined || run["task_ref"] !== p["task_ref"])
19428
+ return true;
19429
+ return readCheckRecoveryHoldsForTaskRef(store, Number(p["task_ref"])).kind !== "no-evidence";
19430
+ }
19431
+ catch {
19432
+ return true;
19433
+ }
19434
+ }
19435
+ function mergeIntentRecoveryHeldById(store, id) {
19436
+ const row = store.handle.prepare("SELECT publication FROM merge_intent WHERE id=?").get(id);
19437
+ return mergeIntentRecoveryHeld(store, Number(row?.["publication"]));
19438
+ }
19439
+ const mergeObservationReservations = new WeakMap();
19440
+ const activeMergeObservations = new WeakMap();
19441
+ export function settleObservedMergeIntent(store, publication, facts, now, rollup) {
19442
+ const key = `${facts.githubRepo}:${facts.prNumber}`;
19443
+ const eligibility = mergeObservationReservations.get(store)?.get(key);
19444
+ mergeObservationReservations.get(store)?.delete(key);
19445
+ if (!Number.isSafeInteger(facts.generation) || facts.generation <= 0 || !Number.isSafeInteger(facts.prNumber) || facts.prNumber <= 0 || (facts.state !== "MERGED" && facts.state !== "CLOSED") || store.handle.isTransaction !== false || eligibility === undefined || eligibility.generation !== facts.generation
19446
+ || eligibility.dataVersion !== store.handle.prepare("PRAGMA data_version").get()?.["data_version"])
19447
+ return { won: false, settled: false, resolved: 0 };
19448
+ try {
19449
+ return store.transact(() => {
19450
+ if (eligibility.dataVersion !== store.handle.prepare("PRAGMA data_version").get()?.["data_version"] || eligibility.writeStamp === null || eligibility.writeStamp !== mergeObservationWriteStamp(store) || eligibility.scope === null || eligibility.scope !== mergeObservationScope(store, facts.githubRepo, facts.prNumber))
19451
+ return { won: false, settled: false, resolved: 0 };
19452
+ const p = store.handle.prepare("SELECT github_repo,pr_number FROM publication WHERE id=?").get(publication);
19453
+ if (p?.["github_repo"] !== facts.githubRepo || p["pr_number"] !== facts.prNumber || facts.number !== facts.prNumber || facts.url !== `https://github.com/${facts.githubRepo}/pull/${facts.prNumber}`)
19454
+ return { won: false, settled: false, resolved: 0 };
19455
+ if (!store.settleObservation({ githubRepo: facts.githubRepo, prNumber: facts.prNumber, generation: facts.generation, headSha: facts.head, state: "none" }, now).won)
19456
+ return { won: false, settled: false, resolved: 0 };
19457
+ if (rollup !== undefined)
19458
+ recordCiChecks(store, facts.githubRepo, facts.prNumber, facts.head, parseCiRollup(rollup), now);
19459
+ if (facts.state === "MERGED" || facts.state === "CLOSED")
19460
+ store.recordPublicationRemoteState(publication, facts.state, now);
19461
+ const row = store.handle.prepare("SELECT id,generation,state FROM merge_intent WHERE publication=?").get(publication);
19462
+ let settled = false;
19463
+ if (row !== undefined) {
19464
+ if (facts.state === "MERGED" && exactMergeObservation(store, Number(row["id"]), facts))
19465
+ activeMergeObservations.set(store, { id: Number(row["id"]), generation: Number(row["generation"]), state: String(row["state"]), facts: { ...facts } });
19466
+ settled = store.settleMergeIntent(Number(row["id"]), Number(row["generation"]), facts.state === "MERGED" ? "merged" : "superseded", now, { receipt: `observed ${facts.state.toLowerCase()} remotely`, bumpGeneration: true });
19467
+ }
19468
+ const canResolve = settled || (row === undefined && !mergeIntentRecoveryHeld(store, publication));
19469
+ let resolved = 0;
19470
+ if (canResolve) {
19471
+ store.liftMergeBlocker(publication, "the-remote", now);
19472
+ store.resolveEpisodes(`merge-attn:${publication}`, now);
19473
+ resolved = store.resolveCiEpisodes(facts.githubRepo, facts.prNumber, null, now);
19474
+ }
19475
+ return { won: true, settled, resolved };
19476
+ });
19477
+ }
19478
+ finally {
19479
+ activeMergeObservations.delete(store);
19480
+ }
19481
+ }
19482
+ function validMergeIntentObservation(store, id, generation) {
19483
+ const proof = activeMergeObservations.get(store);
19484
+ activeMergeObservations.delete(store);
19485
+ return proof !== undefined && proof.id === id && proof.generation === generation
19486
+ && proof.state === store.handle.prepare("SELECT state FROM merge_intent WHERE id=?").get(id)?.["state"] && exactMergeObservation(store, id, proof.facts);
19487
+ }
19488
+ function exactMergeObservation(store, id, facts) {
19489
+ const row = store.handle.prepare("SELECT i.*,p.github_repo,p.base,p.head,p.head_sha AS publication_head,p.remote,p.pr_number,p.task_ref,p.run FROM merge_intent i JOIN publication p ON p.id=i.publication WHERE i.id=?").get(id);
19490
+ if (row === undefined || !/^[0-9a-f]{40}$/.test(facts.head) || facts.state !== "MERGED" || facts.githubRepo !== row["github_repo"] || facts.prNumber !== row["pr_number"] || facts.number !== row["pr_number"] || facts.head !== row["head_sha"] || facts.head !== row["publication_head"] || facts.base !== row["base"] || facts.url !== `https://github.com/${facts.githubRepo}/pull/${facts.number}`)
19491
+ return false;
19492
+ const ref = store.handle.prepare("SELECT repo FROM task_ref WHERE id=?").get(row["task_ref"]);
19493
+ const run = store.handle.prepare("SELECT task_ref FROM run WHERE id=?").get(row["run"]);
19494
+ if (ref === undefined || run?.["task_ref"] !== row["task_ref"] || typeof ref["repo"] !== "string")
19495
+ return false;
19496
+ const observed = store.handle.prepare("SELECT generation,head_sha,observed_at FROM ci_observation WHERE github_repo=? AND pr_number=?").get(facts.githubRepo, facts.prNumber);
19497
+ if (observed?.["generation"] !== facts.generation || observed["head_sha"] !== facts.head || observed["observed_at"] === "")
19498
+ return false;
19499
+ if (row["state"] !== "firing")
19500
+ return false;
19501
+ const scope = mergeAdmissionScope(store, id, Number(row["generation"]), null, true);
19502
+ if (scope === null)
19503
+ return false;
19504
+ const capsules = readMergeAdmissionCandidates(store, scope);
19505
+ return capsules !== null && capsules.filter(c => c.g === scope.g).length === 1;
19506
+ }
19507
+ function mergeObservationScope(store, githubRepo, prNumber) {
19508
+ const rows = store.handle.prepare("SELECT i.id,i.generation,i.state,i.grant_terms_hash,i.head_sha,p.id AS publication,p.run,p.task_ref,p.github_repo,p.remote,p.base,p.head,p.head_sha AS publication_head,p.pr_number FROM publication p LEFT JOIN merge_intent i ON i.publication=p.id WHERE p.github_repo=? AND p.pr_number=?").all(githubRepo, prNumber);
19509
+ return rows.length === 1 ? JSON.stringify(rows[0]) : null;
19510
+ }
19511
+ function mergeObservationWriteStamp(store) {
19512
+ const changes = store.handle.prepare("SELECT total_changes() AS changes").get()?.["changes"];
19513
+ const schema = store.handle.prepare("PRAGMA schema_version").get()?.["schema_version"];
19514
+ return typeof changes === "number" && Number.isSafeInteger(changes) && changes >= 0 && typeof schema === "number" && Number.isSafeInteger(schema) && schema >= 0 ? JSON.stringify([changes, schema]) : null;
19515
+ }
19516
+ const MERGE_FIRING_ADMITTED = "merge firing admitted";
19517
+ function mergeAdmissionScope(store, id, generation, grantId, observing = false, historical = false) {
19518
+ const row = store.handle.prepare("SELECT i.*,p.id AS pid,p.task_ref,p.run,p.github_repo,p.remote,p.base,p.head,p.head_sha AS publication_head,t.repo,t.external_id,t.backend,r.task_ref AS run_ref FROM merge_intent i JOIN publication p ON p.id=i.publication JOIN task_ref t ON t.id=p.task_ref JOIN run r ON r.id=p.run WHERE i.id=?").get(id);
19519
+ const whole = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
19520
+ if (row === undefined || !whole(id) || !whole(generation) || (!historical && row["generation"] !== generation) || row["run_ref"] !== row["task_ref"] || row["backend"] !== "built-in"
19521
+ || !(historical ? ["pending", "claimed", "waiting-human", "firing", "merged", "refused", "superseded"] : ["claimed", "firing"]).includes(String(row["state"])) || [row["pid"], row["task_ref"], row["run"]].some(v => !whole(v))
19522
+ || [row["repo"], row["external_id"], row["github_repo"], row["remote"], row["base"], row["head"]].some(v => typeof v !== "string" || v.length === 0)
19523
+ || !/^[0-9a-f]{40}$/.test(String(row["head_sha"])) || row["head_sha"] !== row["publication_head"] || !["grant", "human", "mode"].includes(String(row["authority_basis"]))
19524
+ || (row["mode_digest"] !== null && typeof row["mode_digest"] !== "string") || ![0, 1].includes(Number(row["delete_branch"])))
19525
+ return null;
19526
+ if (observing && grantId === null) {
19527
+ const raw = mergeAdmissionRows(store, id, generation, Number(row["run"]), String(row["external_id"]), String(row["repo"]));
19528
+ const candidates = raw.map(r => parseMergeAdmission(r["detail"]));
19529
+ if (candidates.some(c => c === null))
19530
+ return null;
19531
+ const current = candidates.filter(c => c !== null && c.i === id && c.g === generation);
19532
+ if (current.length !== 1)
19533
+ return null;
19534
+ grantId = current[0].j;
19535
+ }
19536
+ const rawGrant = grantId === null ? store.handle.prepare("SELECT * FROM publication_grant WHERE repo=? AND revoked_at IS NULL").get(row["repo"]) : store.handle.prepare("SELECT * FROM publication_grant WHERE id=?").get(grantId);
19537
+ if (rawGrant === undefined || !whole(rawGrant["id"]))
19538
+ return null;
19539
+ let grant;
19540
+ try {
19541
+ grant = readPublicationGrant(rawGrant);
19542
+ }
19543
+ catch {
19544
+ return null;
19545
+ }
19546
+ const grantHash = createHash("sha256").update("merge-terms/v1 " + grant.githubRepo + " " + grant.base + " " + grant.headPrefix + " " + (grant.mergeMethod ?? "") + " " + (grant.mergeDeleteBranch === true ? 1 : 0)).digest("hex");
19547
+ if (grant.repo !== row["repo"] || grant.merge !== true || grant.githubRepo !== row["github_repo"] || grant.remote !== row["remote"] || grant.base !== row["base"] || !headWithin(String(row["head"]), grant.headPrefix)
19548
+ || grantHash !== row["grant_terms_hash"] || grant.mergeMethod !== row["method"] || (grant.mergeDeleteBranch === true ? 1 : 0) !== row["delete_branch"])
19549
+ return null;
19550
+ const tuple = [1, id, generation, row["pid"], row["task_ref"], row["run"], row["repo"], row["external_id"], row["github_repo"], row["remote"], row["base"], row["head"], row["head_sha"], row["method"], Number(row["delete_branch"]) === 1, grant.id, grantHash, row["authority_basis"], row["mode_digest"]];
19551
+ return { v: 1, i: id, g: generation, p: Number(row["pid"]), r: Number(row["task_ref"]), u: Number(row["run"]), j: grant.id, s: createHash("sha256").update(JSON.stringify(tuple)).digest("hex"), repo: grant.repo, taskId: String(row["external_id"]), head: String(row["head_sha"]), grantHash };
19552
+ }
19553
+ function mergeAdmissionDetail(scope) { return { v: 1, i: scope.i, g: scope.g, p: scope.p, r: scope.r, u: scope.u, j: scope.j, s: scope.s }; }
19554
+ function parseMergeAdmission(raw) {
19555
+ if (typeof raw !== "string" || raw.length > 204 || !/^[\x20-\x7e]*$/.test(raw))
19556
+ return null;
19557
+ try {
19558
+ const c = JSON.parse(raw);
19559
+ if (c === null || Array.isArray(c) || Object.keys(c).join(",") !== "v,i,g,p,r,u,j,s" || c.v !== 1 || [c.i, c.g, c.p, c.r, c.u, c.j].some(v => typeof v !== "number" || !Number.isSafeInteger(v) || v <= 0) || typeof c.s !== "string" || !/^[0-9a-f]{64}$/.test(c.s))
19560
+ return null;
19561
+ return JSON.stringify(mergeAdmissionDetail(c)) === raw ? c : null;
19562
+ }
19563
+ catch {
19564
+ return null;
19565
+ }
19566
+ }
19567
+ function mergeAdmissionRows(store, id, generation, run, task, repo) {
19568
+ return store.handle.prepare("SELECT * FROM action_ledger WHERE action=? AND (outcome=? OR run_id=? OR (task_id=? AND repo=?) OR (CASE WHEN json_valid(detail) THEN CAST(json_extract(detail,'$.i') AS TEXT) ELSE NULL END)=?) ORDER BY id")
19569
+ .all(MERGE_FIRING_ADMITTED, `${id}:${generation}`, run, task, repo, String(id));
19570
+ }
19571
+ function readMergeAdmissionCandidates(store, scope) {
19572
+ const found = [], seen = new Set();
19573
+ for (const raw of mergeAdmissionRows(store, scope.i, scope.g, scope.u, scope.taskId, scope.repo)) {
19574
+ const c = parseMergeAdmission(raw["detail"]);
19575
+ if (c === null || raw["actor"] !== "toolroll" || raw["source"] !== "work" || raw["outcome"] !== `${c.i}:${c.g}`)
19576
+ return null;
19577
+ const key = `${c.i}:${c.g}`;
19578
+ if (seen.has(key))
19579
+ return null;
19580
+ seen.add(key);
19581
+ const protectedScope = mergeAdmissionScope(store, c.i, c.g, c.j, false, c.i !== scope.i || c.g !== scope.g);
19582
+ if (protectedScope === null || c.p !== protectedScope.p || c.r !== protectedScope.r || c.u !== protectedScope.u || c.s !== protectedScope.s
19583
+ || raw["repo"] !== protectedScope.repo || raw["task_id"] !== protectedScope.taskId || raw["run_id"] !== protectedScope.u)
19584
+ return null;
19585
+ if (c.i !== scope.i)
19586
+ continue;
19587
+ if (c.p !== scope.p || c.r !== scope.r || c.u !== scope.u || c.g > scope.g || found.some(other => other.g === c.g))
19588
+ return null;
19589
+ found.push(c);
19590
+ }
19591
+ return found;
19592
+ }
19593
+ function writeMergeAdmission(store, scope, now) {
19594
+ const detail = mergeAdmissionDetail(scope), raw = JSON.stringify(detail);
19595
+ if (parseMergeAdmission(raw) === null || raw.length > 204 || Buffer.byteLength(raw, "ascii") !== raw.length)
19596
+ throw new Error("Merge firing admission detail cannot be represented exactly");
19597
+ recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo: scope.repo, taskId: scope.taskId, runId: scope.u, action: MERGE_FIRING_ADMITTED, outcome: `${scope.i}:${scope.g}`, source: "work" }, detail);
19598
+ }
19599
+ function widenTableCheck(db, table, before, after, already = [after]) {
19600
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
19601
+ if (row === undefined)
19602
+ return;
19603
+ const stored = String(row["sql"]);
19604
+ if (already.some(one => stored.includes(one)))
19605
+ return;
19606
+ if (stored.split(before).length !== 2)
19607
+ throw new Error(`the ${table} table's DDL is not a shape this migration knows — refusing to widen it`);
19608
+ const named = (sql) => (name) => sql.replace(new RegExp(`^CREATE TABLE (?:IF NOT EXISTS )?"?${table}"?`), `CREATE TABLE ${name}`);
19609
+ const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(one => String(one["name"]));
19610
+ rebuildExact(db, table, named(stored), named(stored.replace(before, after)), columns);
19611
+ }
19612
+ function widenForAntigravity(db) {
19613
+ for (const table of ["phase_config", "phase_tier_config", "phase_tier_alternate", "provider_readiness"]) {
19614
+ widenTableCheck(db, table, PROVIDERS_WITH_ACP, PROVIDERS_WITH_ANTIGRAVITY);
19615
+ }
19616
+ for (const table of ["acp_attestation", "acp_check_request", "acp_billing"]) {
19617
+ widenTableCheck(db, table, ACP_PROVIDERS_BEFORE_ANTIGRAVITY, ACP_PROVIDERS_WITH_ANTIGRAVITY);
19618
+ }
19619
+ }
19620
+ function pendingAgentChangeShapeProblem(db) {
19621
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'pending_agent_change'").get();
19622
+ if (row === undefined)
19623
+ return "the pending model change table is missing";
19624
+ if (canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(V180_SCHEMA.trim().replace(/;$/, "")).trim())
19625
+ return "the pending model change table has an unknown shape";
19626
+ return null;
19627
+ }
19628
+ function directChatShapeProblem(db) {
19629
+ for (const name of V181_TABLES) {
19630
+ if (!tableExists(db, name))
19631
+ return `the direct chat table ${name} is missing`;
19632
+ for (const col of V181_REQUIRED_COLUMNS[name]) {
19633
+ if (!hasColumn(db, name, col))
19634
+ return `the direct chat table ${name} has an unknown shape`;
19635
+ }
19636
+ }
19637
+ return null;
19638
+ }
19639
+ function directChatPhase1bShapeProblem(db) {
19640
+ for (const name of V182_TABLES) {
19641
+ if (!tableExists(db, name))
19642
+ return `the direct chat table ${name} is missing`;
19643
+ for (const col of V182_REQUIRED_COLUMNS[name]) {
19644
+ if (!hasColumn(db, name, col))
19645
+ return `the direct chat table ${name} has an unknown shape`;
19646
+ }
19647
+ }
19648
+ return null;
19649
+ }
19650
+ function directChatHardeningShapeProblem(db) {
19651
+ for (const [table, columns] of Object.entries(V183_ADDED_COLUMNS)) {
19652
+ for (const column of Object.keys(columns)) {
19653
+ if (!hasColumn(db, table, column))
19654
+ return `the direct chat table ${table} is missing column ${column}`;
19655
+ }
19656
+ }
19657
+ return null;
19658
+ }
19659
+ function directChatEffortUsageShapeProblem(db) {
19660
+ for (const [table, columns] of Object.entries(V184_ADDED_COLUMNS)) {
19661
+ for (const column of Object.keys(columns)) {
19662
+ if (!hasColumn(db, table, column))
19663
+ return `the direct chat table ${table} is missing column ${column}`;
19664
+ }
19665
+ }
19666
+ return null;
19667
+ }