toolroll 0.9.116 → 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 (129) hide show
  1. package/CHANGELOG.md +36 -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 +14 -3
  33. package/dist/contracts/engine-api.js +331 -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-session.js +91 -47
  57. package/dist/flexible-ship.js +87 -7
  58. package/dist/flexible-start.js +4 -1
  59. package/dist/flexible-thread.js +2 -3
  60. package/dist/flexible-turns.js +26 -5
  61. package/dist/flow-triggers.js +13 -4
  62. package/dist/flows-ui.js +54 -20
  63. package/dist/handoff-cli.js +630 -0
  64. package/dist/invoke.js +55 -13
  65. package/dist/lead-contract.js +5 -4
  66. package/dist/lead-doors.js +80 -1
  67. package/dist/lead-progress.js +9 -0
  68. package/dist/lead-tools.js +681 -10
  69. package/dist/lead.js +37 -9
  70. package/dist/live-bus.js +11 -0
  71. package/dist/live-terminal.js +132 -12
  72. package/dist/local-handoff.js +363 -0
  73. package/dist/local-owner-acts.js +264 -2
  74. package/dist/local-owner.js +16 -1
  75. package/dist/multiplayer-handoff.js +528 -0
  76. package/dist/multiplayer-presence.js +471 -0
  77. package/dist/names.js +17 -4
  78. package/dist/needs-you.js +10 -0
  79. package/dist/operate.js +280 -19
  80. package/dist/policy.js +2 -2
  81. package/dist/project-delete-ui.js +18 -11
  82. package/dist/project-delete.js +65 -4
  83. package/dist/project-tools.js +1 -1
  84. package/dist/prompt.js +1 -1
  85. package/dist/provider-connection.js +2 -0
  86. package/dist/provider-home.js +251 -8
  87. package/dist/provider.js +3 -2
  88. package/dist/publish.js +119 -64
  89. package/dist/pull-request-flow.js +35 -14
  90. package/dist/read-executor-worker.js +1 -1
  91. package/dist/read-executor.js +95 -1
  92. package/dist/restore-retirement.js +152 -0
  93. package/dist/result-follow-ups.js +116 -37
  94. package/dist/route-change.js +44 -4
  95. package/dist/scope.js +62 -5
  96. package/dist/serve.js +49 -5
  97. package/dist/server/chat.js +94 -13
  98. package/dist/server/direct-chat.js +583 -0
  99. package/dist/server/engine-api.js +219 -21
  100. package/dist/server/flows.js +43 -10
  101. package/dist/server/found-repos.js +25 -0
  102. package/dist/server/guards.js +20 -6
  103. package/dist/server/live.js +81 -23
  104. package/dist/server/pages.js +67 -13
  105. package/dist/server/people-tokens.js +47 -6
  106. package/dist/server/remote.js +29 -0
  107. package/dist/server/render-results.js +6 -2
  108. package/dist/server/render-settings.js +4 -2
  109. package/dist/server/render-tasks.js +18 -17
  110. package/dist/server/route-table.js +69 -2
  111. package/dist/server/settings.js +22 -7
  112. package/dist/server/task-views.js +15 -3
  113. package/dist/server/tasks.js +39 -2
  114. package/dist/server/terminals.js +185 -11
  115. package/dist/settings-proofs.js +1 -1
  116. package/dist/store.js +499 -56
  117. package/dist/subscription-chat.js +33 -6
  118. package/dist/subscription-usage.js +233 -0
  119. package/dist/task-live.js +2 -1
  120. package/dist/teardown-git.js +34 -4
  121. package/dist/terminal-connection.js +159 -0
  122. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  123. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  124. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  125. package/dist/tui/linux-x64/toolroll-tui +0 -0
  126. package/dist/tui-contract.js +1 -1
  127. package/dist/tui-launch.js +32 -1
  128. package/dist/workspace-identity-schema.js +21 -0
  129. package/package.json +3 -1
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";
@@ -33,6 +34,10 @@ import { V172_ADDED_COLUMNS, V172_OBJECTS, V172_SCHEMA, V172_STEPS } from "./fle
33
34
  import { V173_ADDED_COLUMNS, V173_STEPS } from "./plan-problems-schema.js";
34
35
  import { V175_OBJECTS, V175_SCHEMA, V175_STEPS } from "./flexible-interactive-schema.js";
35
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";
36
41
  import { V174_OBJECTS, V174_SCHEMA, V174_STEPS } from "./flexible-everyday-schema.js";
37
42
  import { endThreadAuthorityFor } from "./flexible-authority-end.js";
38
43
  import { relayCancel } from "./flexible-relay-cancel.js";
@@ -103,7 +108,7 @@ import { BUILDER_SERVICE_SCHEMA, CHECK_ONLY_SCHEMA, FAST_PREVIEW_SCHEMA, ROUTE_C
103
108
  export { V153_ADDED_COLUMNS } from "./plain-schema.js";
104
109
  import { releasePolicyDigest, serializeReleaseCheckPurpose, storedReleaseCheckPurpose, storedReleaseTerms, readReleaseTerms, readReleasePolicy } from "./contracts/release-terms.js";
105
110
  import { accountReachesSql, normalizeProjectAccess, projectAccessAllows, readProjectAccess } from "./project-access.js";
106
- 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";
107
112
  import { PLAN_AUTO_SCHEMA } from "./plan-auto.js";
108
113
  import { CONSOLE_INSTANCE_SCHEMA } from "./console-instance.js";
109
114
  import { endUnattendedGrants, FLOW_UNATTENDED_SCHEMA, grantStandsSql } from "./flow-unattended.js";
@@ -120,7 +125,7 @@ import { CHECKOUT_CLEANUP_SCHEMA, LANDED_CLEANUP_SCHEMA, STORAGE_SWEEP_SCHEMA, D
120
125
  import { inReadOnlyRequest } from "./read-only-request.js";
121
126
  import { IN_RANGE, LEDGER_CHAIN_SCHEMA, safeWhole, sealLedger, verifyLedgerChain } from "./ledger-chain.js";
122
127
  import { NO_RULES, filerFor, isProtectedWork, protectedChanges, rulesWords } from "./approval-policy.js";
123
- import { configBase, envValue, namedPath } from "./names.js";
128
+ import { configBase, envValue, namedPath, headWithin } from "./names.js";
124
129
  import { PULL_REQUEST_SCHEMA } from "./pull-request-schema.js";
125
130
  import { chatTurnAmountOf, combineReportedModels, providerTurnsOf, reportedCostUsdOf, reportedModelOf, runAmountOf } from "./reported-usage.js";
126
131
  import { usageOf } from "./run-efficiency.js";
@@ -840,7 +845,8 @@ export function checkSuitesOf(value) {
840
845
  }
841
846
  }
842
847
  const REGISTERED_AT_FILING = "again, as it was filed";
843
- export const SCHEMA_VERSION = 176;
848
+ export const SCHEMA_VERSION = 184;
849
+ export const V179_STEPS = Object.freeze(["antigravity-provider"]);
844
850
  export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
845
851
  const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
846
852
  const V118_COORDINATOR_COLUMNS = [["task_ref", "coordinator_cid"], ["coordinator_event", "cid"], ["mcp_idempotency", "cid"], ["coordinator_proposal", "cid"]];
@@ -905,7 +911,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
905
911
  "fallback_config", "fallback_cycle", "fallback_transition",
906
912
  ]);
907
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;
908
- 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]);
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]);
909
915
  export const V119_ADDED_COLUMNS = Object.freeze({
910
916
  task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
911
917
  run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
@@ -1448,7 +1454,7 @@ export { V156_STEPS };
1448
1454
  export { V157_STEPS };
1449
1455
  export { V158_STEPS };
1450
1456
  export { V159_STEPS };
1451
- 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 };
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 };
1452
1458
  export const RELEASE_ONCE_SCHEMA = `
1453
1459
  CREATE TABLE IF NOT EXISTS release_authority (
1454
1460
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -2105,7 +2111,7 @@ CREATE TABLE IF NOT EXISTS mcp_idempotency (
2105
2111
  CREATE TABLE IF NOT EXISTS phase_config (
2106
2112
  scope TEXT NOT NULL,
2107
2113
  phase TEXT NOT NULL CHECK (phase IN ('plan','build','repair','review')),
2108
- 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')),
2109
2115
  model TEXT,
2110
2116
  updated_at TEXT NOT NULL,
2111
2117
  updated_by TEXT NOT NULL,
@@ -2121,7 +2127,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_config (
2121
2127
  scope TEXT NOT NULL,
2122
2128
  phase TEXT NOT NULL CHECK (phase IN ('plan','build','repair','review')),
2123
2129
  tier TEXT NOT NULL CHECK (tier IN ('light','strong')),
2124
- 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')),
2125
2131
  model TEXT,
2126
2132
  updated_at TEXT NOT NULL,
2127
2133
  updated_by TEXT NOT NULL,
@@ -2137,7 +2143,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_config (
2137
2143
  -- substitutes for it.
2138
2144
  CREATE TABLE IF NOT EXISTS provider_readiness (
2139
2145
  runner TEXT NOT NULL REFERENCES runner(name) ON DELETE CASCADE,
2140
- 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')),
2141
2147
  state TEXT NOT NULL CHECK (state IN ('ready','unavailable','unknown')),
2142
2148
  reason TEXT NOT NULL,
2143
2149
  probe TEXT NOT NULL,
@@ -4148,6 +4154,17 @@ function initializeStore(db, file, options = {}) {
4148
4154
  const read = schemaVersionPreflight(db, file);
4149
4155
  if (read !== null && Math.abs(read) < BASELINE_SCHEMA_VERSION)
4150
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
+ }
4151
4168
  const fresh = read === null;
4152
4169
  const preflight = fresh ? createBaseline(db, file, options.createdBy) : read;
4153
4170
  if (!tableExists(db, "service_cursor")) {
@@ -4226,7 +4243,7 @@ function initializeStore(db, file, options = {}) {
4226
4243
  throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
4227
4244
  }
4228
4245
  if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
4229
- 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);
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);
4230
4247
  if (missing !== null)
4231
4248
  throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
4232
4249
  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -4658,6 +4675,59 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
4658
4675
  if (backupDamaged !== null)
4659
4676
  throw new Error(`${file}: refusing to open — ${backupDamaged}`);
4660
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");
4661
4731
  if (!fresh)
4662
4732
  reclaimDatabase(db, "migration");
4663
4733
  const expectedMarker = preflight < 0 ? preflight : -preflight;
@@ -5397,7 +5467,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_alternate (
5397
5467
  scope TEXT NOT NULL,
5398
5468
  phase TEXT NOT NULL CHECK (phase IN ('plan','build')),
5399
5469
  tier TEXT NOT NULL CHECK (tier IN ('light','routine','strong')),
5400
- 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')),
5401
5471
  model TEXT NOT NULL,
5402
5472
  updated_at TEXT NOT NULL,
5403
5473
  updated_by TEXT NOT NULL,
@@ -5407,7 +5477,7 @@ CREATE TABLE IF NOT EXISTS phase_tier_alternate (
5407
5477
  export const ACP_ATTESTATION_SCHEMA = `
5408
5478
  CREATE TABLE IF NOT EXISTS acp_attestation (
5409
5479
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5410
- 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')),
5411
5481
  runner TEXT NOT NULL,
5412
5482
  conformance_version INTEGER NOT NULL,
5413
5483
  launch_json TEXT NOT NULL,
@@ -5426,7 +5496,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS acp_attestation_live ON acp_attestation (provi
5426
5496
  export const ACP_CHECK_SCHEMA = `
5427
5497
  CREATE TABLE IF NOT EXISTS acp_check_request (
5428
5498
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5429
- 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')),
5430
5500
  runner TEXT NOT NULL,
5431
5501
  model TEXT NOT NULL,
5432
5502
  conformance_version INTEGER NOT NULL,
@@ -5455,7 +5525,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS acp_check_running ON acp_check_request (runner
5455
5525
  export const ACP_BILLING_SCHEMA = `
5456
5526
  CREATE TABLE IF NOT EXISTS acp_billing (
5457
5527
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5458
- 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')),
5459
5529
  runner TEXT NOT NULL,
5460
5530
  model TEXT NOT NULL,
5461
5531
  kind TEXT NOT NULL CHECK (kind IN ('metered','plan')),
@@ -5466,26 +5536,17 @@ CREATE INDEX IF NOT EXISTS acp_billing_by ON acp_billing (provider, runner, mode
5466
5536
  `;
5467
5537
  const PROVIDERS_BEFORE_ACP = "CHECK (provider IN ('claude','codex','openrouter','gemini'))";
5468
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'))";
5469
5542
  const AUTH_MODES_BEFORE_ACP = "CHECK (auth_mode IN ('subscription', 'api-key'))";
5470
5543
  const AUTH_MODES_WITH_ACP = "CHECK (auth_mode IN ('subscription', 'api-key', 'agent-login'))";
5471
5544
  function widenForAcp(db) {
5472
- const widen = (table, before, after) => {
5473
- const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
5474
- if (row === undefined)
5475
- return;
5476
- const stored = String(row["sql"]);
5477
- if (stored.includes(after))
5478
- return;
5479
- if (stored.split(before).length !== 2)
5480
- throw new Error(`the ${table} table's DDL is not a shape this migration knows — refusing to widen it`);
5481
- const named = (sql) => (name) => sql.replace(new RegExp(`^CREATE TABLE (?:IF NOT EXISTS )?"?${table}"?`), `CREATE TABLE ${name}`);
5482
- const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(one => String(one["name"]));
5483
- rebuildExact(db, table, named(stored), named(stored.replace(before, after)), columns);
5484
- };
5485
- for (const table of ["phase_config", "phase_tier_config", "phase_tier_alternate", "provider_readiness"])
5486
- widen(table, PROVIDERS_BEFORE_ACP, PROVIDERS_WITH_ACP);
5487
- widen("provider_auth_pause", AUTH_MODES_BEFORE_ACP, AUTH_MODES_WITH_ACP);
5488
- 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'))");
5489
5550
  }
5490
5551
  function widenPhaseTierSchema(db) {
5491
5552
  const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'phase_tier_config'").get();
@@ -5497,7 +5558,7 @@ function widenPhaseTierSchema(db) {
5497
5558
  scope TEXT NOT NULL,
5498
5559
  phase TEXT NOT NULL CHECK (phase IN ('plan','build','repair','review')),
5499
5560
  tier TEXT NOT NULL CHECK (tier IN ('light','strong')),
5500
- 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')),
5501
5562
  model TEXT,
5502
5563
  updated_at TEXT NOT NULL,
5503
5564
  updated_by TEXT NOT NULL,
@@ -5662,6 +5723,14 @@ export class Store {
5662
5723
  const ref = this.db
5663
5724
  .prepare("SELECT id, coordinator_cid FROM task_ref WHERE backend = ? AND external_id = ?")
5664
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
+ }
5665
5734
  const coordinator = ref?.["coordinator_cid"] != null;
5666
5735
  if (reason.kind === "operator") {
5667
5736
  if (coordinator) {
@@ -5694,6 +5763,8 @@ export class Store {
5694
5763
  releaseTrialPlaces(this, Number(ref["id"]), now);
5695
5764
  if (ref !== undefined)
5696
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"]));
5697
5768
  if (ref !== undefined)
5698
5769
  this.closeQuestionsLocked(Number(ref["id"]), "cancelled", now);
5699
5770
  if (ref !== undefined && coordinator) {
@@ -7083,7 +7154,9 @@ export class Store {
7083
7154
  continue;
7084
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);
7085
7156
  }
7086
- 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 (
7087
7160
  SELECT publication.id FROM publication
7088
7161
  JOIN run ON run.id = publication.run
7089
7162
  JOIN task_ref ON task_ref.id = run.task_ref
@@ -7583,6 +7656,8 @@ export class Store {
7583
7656
  return this.ledgerHeadId();
7584
7657
  }
7585
7658
  recordAction(entry) {
7659
+ if (entry.action === MERGE_FIRING_ADMITTED)
7660
+ throw new Error("Merge firing admission is written only by the firing transaction");
7586
7661
  const detail = entry.detail == null ? null : entry.detail.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 300);
7587
7662
  const row = this.db.prepare("INSERT INTO action_ledger(at,actor,repo,task_id,run_id,action,outcome,source,detail) VALUES (?,?,?,?,?,?,?,?,?)")
7588
7663
  .run(entry.at, entry.actor, entry.repo, entry.taskId, entry.runId, entry.action, entry.outcome, entry.source, detail);
@@ -9698,6 +9773,10 @@ export class Store {
9698
9773
  .get(BUILT_IN, taskId);
9699
9774
  if (ref === undefined)
9700
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" };
9701
9780
  if (seen !== undefined) {
9702
9781
  const state = this.db.prepare("SELECT state FROM task WHERE id = ?").get(taskId)?.["state"];
9703
9782
  const last = this.db.prepare("SELECT MAX(id) AS id FROM run WHERE task_ref = ?").get(Number(ref["id"]))?.["id"];
@@ -9707,7 +9786,7 @@ export class Store {
9707
9786
  }
9708
9787
  if (this.hasLiveClaim(Number(ref["id"]), now))
9709
9788
  return { ok: false, reason: "claimed" };
9710
- 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);
9711
9790
  if (done.reason !== undefined)
9712
9791
  return { ok: false, reason: done.reason };
9713
9792
  if (!done.changed)
@@ -10709,8 +10788,8 @@ export class Store {
10709
10788
  sweepStaleChatTurns(now) {
10710
10789
  const swept = this.db
10711
10790
  .prepare(`UPDATE chat_turn SET state = 'failed', failure_reason = 'crashed', generation = generation + 1,
10712
- unknown_spend = CASE WHEN started_at IS NOT NULL THEN 1 ELSE 0 END,
10713
- 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,
10714
10793
  finished_at = ?
10715
10794
  WHERE state IN ('queued','running') AND deadline_at < ?`)
10716
10795
  .run(now.toISOString(), now.toISOString());
@@ -12957,7 +13036,10 @@ export class Store {
12957
13036
  });
12958
13037
  }
12959
13038
  reserveObservation(githubRepo, prNumber) {
12960
- 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(() => {
12961
13043
  const row = this.db
12962
13044
  .prepare("SELECT generation FROM ci_observation WHERE github_repo = ? AND pr_number = ?")
12963
13045
  .get(githubRepo, prNumber);
@@ -12974,6 +13056,18 @@ export class Store {
12974
13056
  }
12975
13057
  return generation;
12976
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;
12977
13071
  }
12978
13072
  settleObservation(observation, now) {
12979
13073
  const { changes } = this.db
@@ -13001,7 +13095,9 @@ export class Store {
13001
13095
  .run(now.toISOString(), by, publication).changes) > 0);
13002
13096
  }
13003
13097
  createMergeIntent(intent, now) {
13004
- this.transact(() => {
13098
+ return this.transact(() => {
13099
+ if (mergeIntentRecoveryHeld(this, intent.publication))
13100
+ return "recovery-held";
13005
13101
  if (nightlyPublication(this, intent.publication))
13006
13102
  throw new Error(NIGHTLY_CHECK_ONLY);
13007
13103
  if (releasePublication(this, intent.publication))
@@ -13035,8 +13131,8 @@ export class Store {
13035
13131
  }
13036
13132
  claimMergeIntent(id, by, leaseMs, now) {
13037
13133
  return this.transact(() => {
13038
- const row = this.db.prepare("SELECT state, claimed_until, generation FROM merge_intent WHERE id = ?").get(id);
13039
- 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"])))
13040
13136
  return null;
13041
13137
  const state = String(row["state"]);
13042
13138
  const expired = row["claimed_until"] !== null && String(row["claimed_until"]) <= now.toISOString();
@@ -13051,9 +13147,17 @@ export class Store {
13051
13147
  });
13052
13148
  }
13053
13149
  settleMergeIntent(id, generation, state, now, detail = {}) {
13054
- const from = detail.from ?? "nonterminal";
13055
- const { changes } = this.db
13056
- .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,
13057
13161
  firing_at = NULL, firing_deadline = NULL,
13058
13162
  authority_basis = CASE WHEN ? = 'waiting-human' THEN 'human' ELSE authority_basis END,
13059
13163
  mode_digest = CASE WHEN ? = 'waiting-human' THEN NULL ELSE mode_digest END,
@@ -13063,13 +13167,16 @@ export class Store {
13063
13167
  WHERE id = ? AND generation = ?
13064
13168
  AND state NOT IN ('merged','refused','superseded')
13065
13169
  AND (? = 'nonterminal' OR state = ?)`)
13066
- .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);
13067
- 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
+ });
13068
13173
  }
13069
13174
  authorizeMergeIntent(id, expectedHeadSha, by, now) {
13070
13175
  void by;
13071
13176
  void now;
13072
13177
  return this.transact(() => {
13178
+ if (mergeIntentRecoveryHeldById(this, id))
13179
+ return { ok: false, reason: "recovery-held" };
13073
13180
  const row = this.db.prepare("SELECT state, head_sha FROM merge_intent WHERE id = ?").get(id);
13074
13181
  if (row === undefined || String(row["state"]) !== "waiting-human")
13075
13182
  return { ok: false, reason: "not-waiting" };
@@ -13085,10 +13192,12 @@ export class Store {
13085
13192
  });
13086
13193
  }
13087
13194
  fireMergeIntent(id, generation, proof, now) {
13088
- return this.transact(() => {
13195
+ return this.transact(() => this.savepoint(() => {
13089
13196
  const row = this.db
13090
13197
  .prepare("SELECT state, generation, head_sha, grant_terms_hash, authority_basis, mode_digest, publication FROM merge_intent WHERE id = ?")
13091
13198
  .get(id);
13199
+ if (mergeIntentRecoveryHeldById(this, id))
13200
+ return { ok: false, outcome: "recovery-held", why: MERGE_RECOVERY_HELD };
13092
13201
  if (row !== undefined && nightlyPublication(this, Number(row["publication"]))) {
13093
13202
  this.settleMergeIntent(id, generation, "refused", now, { error: NIGHTLY_CHECK_ONLY, from: "claimed" });
13094
13203
  return { ok: false, outcome: "superseded", why: NIGHTLY_CHECK_ONLY };
@@ -13118,8 +13227,15 @@ export class Store {
13118
13227
  if (proof.liveGrantTermsHash === null || proof.liveGrantTermsHash !== String(row["grant_terms_hash"])) {
13119
13228
  return supersede("the grant was revoked or its merge terms changed since this intent was written");
13120
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" };
13121
13237
  const basis = String(row["authority_basis"]);
13122
- const mode = this.activeMode(proof.repo, now);
13238
+ const mode = this.activeMode(admission.repo, now);
13123
13239
  if (basis === "mode") {
13124
13240
  let publication;
13125
13241
  try {
@@ -13147,14 +13263,17 @@ export class Store {
13147
13263
  .prepare(`UPDATE merge_intent SET state = 'firing', firing_at = ?, firing_deadline = ?
13148
13264
  WHERE id = ? AND state = 'claimed' AND generation = ?`)
13149
13265
  .run(now.toISOString(), new Date(now.getTime() + proof.graceMs).toISOString(), id, generation);
13150
- return Number(changes) === 1
13151
- ? { ok: true }
13152
- : { ok: false, outcome: "raced", why: "the claim moved" };
13153
- });
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
+ }));
13154
13271
  }
13155
13272
  refireMergeIntent(id, by, now) {
13156
13273
  void by;
13157
13274
  return this.transact(() => {
13275
+ if (mergeIntentRecoveryHeldById(this, id))
13276
+ return { ok: false, reason: "recovery-held" };
13158
13277
  const row = this.db.prepare("SELECT state, firing_deadline FROM merge_intent WHERE id = ?").get(id);
13159
13278
  if (row === undefined || String(row["state"]) !== "firing")
13160
13279
  return { ok: false, reason: "not-firing" };
@@ -13169,10 +13288,14 @@ export class Store {
13169
13288
  });
13170
13289
  }
13171
13290
  rearmMergeIntent(publication) {
13172
- const { changes } = this.db
13173
- .prepare("UPDATE merge_intent SET state = 'pending', last_error = NULL WHERE publication = ? AND state = 'refused'")
13174
- .run(publication);
13175
- 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
+ });
13176
13299
  }
13177
13300
  mergeIntentFor(publication) {
13178
13301
  const row = this.db
@@ -13362,11 +13485,13 @@ export class Store {
13362
13485
  const projects = readProjectAccess(row["projects_json"]);
13363
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);
13364
13487
  }
13365
- activeLeadSession(approver) {
13488
+ activeLeadSession(approver, credentialKey) {
13366
13489
  const row = this.db
13367
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")
13368
13491
  .get(approver);
13369
- return row === undefined ? null : readLeadSession(row);
13492
+ if (row === undefined || (credentialKey !== undefined && row["credential_key"] !== credentialKey))
13493
+ return null;
13494
+ return readLeadSession(row);
13370
13495
  }
13371
13496
  getLeadSession(id) {
13372
13497
  const row = this.db.prepare("SELECT * FROM lead_session WHERE id = ?").get(id);
@@ -16628,6 +16753,13 @@ export class Store {
16628
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);
16629
16754
  this.spendCache = null;
16630
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
+ }
16631
16763
  }
16632
16764
  function wholeNumber(value) {
16633
16765
  if (value === null || value === undefined)
@@ -18198,6 +18330,9 @@ export function taskFamilyRefs(store, taskId) {
18198
18330
  export function liveFamilyAttempt(store, refs, now) {
18199
18331
  if (refs.length === 0)
18200
18332
  return null;
18333
+ const recovery = unresolvedRecoveryCheckFamily(store, refs);
18334
+ if (recovery !== null)
18335
+ return recovery;
18201
18336
  const row = store.handle.prepare(`SELECT r.external_id FROM task_ref r JOIN task t ON t.id = r.external_id
18202
18337
  WHERE r.id IN (SELECT value FROM json_each(?)) AND (t.state = 'running'
18203
18338
  OR EXISTS (SELECT 1 FROM claim c WHERE c.task_ref = r.id AND c.released_at IS NULL AND c.expires_at > ?
@@ -18230,6 +18365,10 @@ export function archiveTaskFamily(store, taskId, by, now, options = {}) {
18230
18365
  if (options.expect !== undefined && [...options.expect].sort((a, b) => a - b).join(",") !== refs.join(",")) {
18231
18366
  return { ok: false, reason: "blocked", message: `${taskId}'s versions changed since the list was shown.` };
18232
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." };
18233
18372
  const remaining = refs.filter(ref => !refArchived(store, ref));
18234
18373
  if (remaining.length === 0)
18235
18374
  return { ok: false, reason: "archived", message: `${taskId} is already put away.` };
@@ -18239,11 +18378,15 @@ export function archiveTaskFamily(store, taskId, by, now, options = {}) {
18239
18378
  const blocked = options.guard?.(refs) ?? null;
18240
18379
  if (blocked !== null)
18241
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." };
18242
18384
  const reason = by.reason.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 300) || "Put away";
18243
18385
  const at = now.toISOString();
18244
18386
  const insert = store.handle.prepare("INSERT INTO task_archive (task_ref, by, by_kind, rule, reason, at) VALUES (?, ?, ?, ?, ?, ?)");
18245
18387
  for (const ref of remaining)
18246
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));
18247
18390
  store.handle.prepare("UPDATE notification SET resolved_at = ? WHERE resolved_at IS NULL AND task_ref IN (SELECT value FROM json_each(?))")
18248
18391
  .run(at, JSON.stringify(refs));
18249
18392
  store.handle.prepare(`UPDATE notification SET resolved_at = ? WHERE resolved_at IS NULL AND EXISTS (SELECT 1 FROM flow_card c
@@ -19222,3 +19365,303 @@ function subagentBackupShapeProblem(db) {
19222
19365
  }
19223
19366
  return null;
19224
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
+ }