@cleocode/core 2026.4.11 → 2026.4.12

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 (169) hide show
  1. package/dist/codebase-map/analyzers/architecture.d.ts.map +1 -1
  2. package/dist/codebase-map/analyzers/architecture.js +0 -1
  3. package/dist/codebase-map/analyzers/architecture.js.map +1 -1
  4. package/dist/conduit/local-transport.d.ts +18 -8
  5. package/dist/conduit/local-transport.d.ts.map +1 -1
  6. package/dist/conduit/local-transport.js +23 -13
  7. package/dist/conduit/local-transport.js.map +1 -1
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/config.js +0 -1
  10. package/dist/config.js.map +1 -1
  11. package/dist/errors.d.ts +19 -0
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +6 -0
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.js +175 -68950
  16. package/dist/index.js.map +1 -7
  17. package/dist/init.d.ts +1 -2
  18. package/dist/init.d.ts.map +1 -1
  19. package/dist/init.js +1 -2
  20. package/dist/init.js.map +1 -1
  21. package/dist/internal.d.ts +8 -3
  22. package/dist/internal.d.ts.map +1 -1
  23. package/dist/internal.js +13 -6
  24. package/dist/internal.js.map +1 -1
  25. package/dist/memory/learnings.d.ts +2 -2
  26. package/dist/memory/patterns.d.ts +6 -6
  27. package/dist/output.d.ts +32 -11
  28. package/dist/output.d.ts.map +1 -1
  29. package/dist/output.js +67 -67
  30. package/dist/output.js.map +1 -1
  31. package/dist/paths.js +80 -14
  32. package/dist/paths.js.map +1 -1
  33. package/dist/skills/dynamic-skill-generator.d.ts +0 -2
  34. package/dist/skills/dynamic-skill-generator.d.ts.map +1 -1
  35. package/dist/skills/dynamic-skill-generator.js.map +1 -1
  36. package/dist/store/agent-registry-accessor.d.ts +203 -12
  37. package/dist/store/agent-registry-accessor.d.ts.map +1 -1
  38. package/dist/store/agent-registry-accessor.js +618 -100
  39. package/dist/store/agent-registry-accessor.js.map +1 -1
  40. package/dist/store/api-key-kdf.d.ts +73 -0
  41. package/dist/store/api-key-kdf.d.ts.map +1 -0
  42. package/dist/store/api-key-kdf.js +84 -0
  43. package/dist/store/api-key-kdf.js.map +1 -0
  44. package/dist/store/cleanup-legacy.js +171 -0
  45. package/dist/store/cleanup-legacy.js.map +1 -0
  46. package/dist/store/conduit-sqlite.d.ts +184 -0
  47. package/dist/store/conduit-sqlite.d.ts.map +1 -0
  48. package/dist/store/conduit-sqlite.js +570 -0
  49. package/dist/store/conduit-sqlite.js.map +1 -0
  50. package/dist/store/global-salt.d.ts +78 -0
  51. package/dist/store/global-salt.d.ts.map +1 -0
  52. package/dist/store/global-salt.js +147 -0
  53. package/dist/store/global-salt.js.map +1 -0
  54. package/dist/store/migrate-signaldock-to-conduit.d.ts +81 -0
  55. package/dist/store/migrate-signaldock-to-conduit.d.ts.map +1 -0
  56. package/dist/store/migrate-signaldock-to-conduit.js +555 -0
  57. package/dist/store/migrate-signaldock-to-conduit.js.map +1 -0
  58. package/dist/store/nexus-sqlite.js +28 -3
  59. package/dist/store/nexus-sqlite.js.map +1 -1
  60. package/dist/store/signaldock-sqlite.d.ts +122 -19
  61. package/dist/store/signaldock-sqlite.d.ts.map +1 -1
  62. package/dist/store/signaldock-sqlite.js +401 -251
  63. package/dist/store/signaldock-sqlite.js.map +1 -1
  64. package/dist/store/sqlite-backup.js +122 -4
  65. package/dist/store/sqlite-backup.js.map +1 -1
  66. package/dist/system/backup.d.ts +0 -26
  67. package/dist/system/backup.d.ts.map +1 -1
  68. package/dist/system/runtime.d.ts +0 -2
  69. package/dist/system/runtime.d.ts.map +1 -1
  70. package/dist/system/runtime.js +3 -3
  71. package/dist/system/runtime.js.map +1 -1
  72. package/dist/tasks/add.d.ts +1 -1
  73. package/dist/tasks/add.d.ts.map +1 -1
  74. package/dist/tasks/add.js +98 -23
  75. package/dist/tasks/add.js.map +1 -1
  76. package/dist/tasks/complete.d.ts.map +1 -1
  77. package/dist/tasks/complete.js +4 -1
  78. package/dist/tasks/complete.js.map +1 -1
  79. package/dist/tasks/find.d.ts.map +1 -1
  80. package/dist/tasks/find.js +4 -1
  81. package/dist/tasks/find.js.map +1 -1
  82. package/dist/tasks/labels.d.ts.map +1 -1
  83. package/dist/tasks/labels.js +4 -1
  84. package/dist/tasks/labels.js.map +1 -1
  85. package/dist/tasks/relates.d.ts.map +1 -1
  86. package/dist/tasks/relates.js +16 -4
  87. package/dist/tasks/relates.js.map +1 -1
  88. package/dist/tasks/show.d.ts.map +1 -1
  89. package/dist/tasks/show.js +4 -1
  90. package/dist/tasks/show.js.map +1 -1
  91. package/dist/tasks/update.d.ts.map +1 -1
  92. package/dist/tasks/update.js +32 -6
  93. package/dist/tasks/update.js.map +1 -1
  94. package/dist/validation/engine.d.ts.map +1 -1
  95. package/dist/validation/engine.js +16 -4
  96. package/dist/validation/engine.js.map +1 -1
  97. package/dist/validation/param-utils.d.ts +5 -3
  98. package/dist/validation/param-utils.d.ts.map +1 -1
  99. package/dist/validation/param-utils.js +8 -6
  100. package/dist/validation/param-utils.js.map +1 -1
  101. package/dist/validation/protocols/_shared.d.ts.map +1 -1
  102. package/dist/validation/protocols/_shared.js +13 -6
  103. package/dist/validation/protocols/_shared.js.map +1 -1
  104. package/package.json +7 -7
  105. package/src/adapters/__tests__/manager.test.ts +0 -1
  106. package/src/codebase-map/analyzers/architecture.ts +0 -1
  107. package/src/conduit/__tests__/local-credential-flow.test.ts +20 -18
  108. package/src/conduit/__tests__/local-transport.test.ts +14 -12
  109. package/src/conduit/local-transport.ts +23 -13
  110. package/src/config.ts +0 -1
  111. package/src/errors.ts +24 -0
  112. package/src/hooks/handlers/__tests__/hook-automation-e2e.test.ts +2 -5
  113. package/src/init.ts +1 -2
  114. package/src/internal.ts +49 -2
  115. package/src/lifecycle/cant/lifecycle-rcasd.cant +133 -0
  116. package/src/memory/__tests__/engine-compat.test.ts +2 -2
  117. package/src/memory/__tests__/pipeline-manifest-sqlite.test.ts +4 -4
  118. package/src/observability/__tests__/index.test.ts +4 -4
  119. package/src/observability/__tests__/log-filter.test.ts +4 -4
  120. package/src/output.ts +73 -75
  121. package/src/sessions/__tests__/session-grade.integration.test.ts +1 -1
  122. package/src/sessions/__tests__/session-grade.test.ts +2 -2
  123. package/src/skills/__tests__/dynamic-skill-generator.test.ts +0 -2
  124. package/src/skills/dynamic-skill-generator.ts +0 -2
  125. package/src/store/__tests__/agent-registry-accessor.test.ts +807 -0
  126. package/src/store/__tests__/api-key-kdf.test.ts +113 -0
  127. package/src/store/__tests__/conduit-sqlite.test.ts +413 -0
  128. package/src/store/__tests__/global-salt.test.ts +195 -0
  129. package/src/store/__tests__/migrate-signaldock-to-conduit.test.ts +715 -0
  130. package/src/store/__tests__/signaldock-sqlite.test.ts +652 -0
  131. package/src/store/__tests__/sqlite-backup-global.test.ts +307 -3
  132. package/src/store/__tests__/sqlite-backup.test.ts +5 -1
  133. package/src/store/__tests__/t310-integration.test.ts +1150 -0
  134. package/src/store/agent-registry-accessor.ts +847 -140
  135. package/src/store/api-key-kdf.ts +104 -0
  136. package/src/store/conduit-sqlite.ts +655 -0
  137. package/src/store/global-salt.ts +175 -0
  138. package/src/store/migrate-signaldock-to-conduit.ts +669 -0
  139. package/src/store/signaldock-sqlite.ts +431 -254
  140. package/src/store/sqlite-backup.ts +185 -10
  141. package/src/system/backup.ts +2 -62
  142. package/src/system/runtime.ts +4 -6
  143. package/src/tasks/__tests__/error-hints.test.ts +256 -0
  144. package/src/tasks/add.ts +99 -9
  145. package/src/tasks/complete.ts +4 -1
  146. package/src/tasks/find.ts +4 -1
  147. package/src/tasks/labels.ts +4 -1
  148. package/src/tasks/relates.ts +16 -4
  149. package/src/tasks/show.ts +4 -1
  150. package/src/tasks/update.ts +32 -3
  151. package/src/validation/__tests__/error-hints.test.ts +97 -0
  152. package/src/validation/engine.ts +16 -1
  153. package/src/validation/param-utils.ts +10 -7
  154. package/src/validation/protocols/_shared.ts +14 -6
  155. package/src/validation/protocols/cant/architecture-decision.cant +80 -0
  156. package/src/validation/protocols/cant/artifact-publish.cant +95 -0
  157. package/src/validation/protocols/cant/consensus.cant +74 -0
  158. package/src/validation/protocols/cant/contribution.cant +82 -0
  159. package/src/validation/protocols/cant/decomposition.cant +92 -0
  160. package/src/validation/protocols/cant/implementation.cant +67 -0
  161. package/src/validation/protocols/cant/provenance.cant +88 -0
  162. package/src/validation/protocols/cant/release.cant +96 -0
  163. package/src/validation/protocols/cant/research.cant +66 -0
  164. package/src/validation/protocols/cant/specification.cant +67 -0
  165. package/src/validation/protocols/cant/testing.cant +88 -0
  166. package/src/validation/protocols/cant/validation.cant +65 -0
  167. package/src/validation/protocols/protocols-markdown/decomposition.md +0 -4
  168. package/templates/config.template.json +0 -1
  169. package/templates/global-config.template.json +0 -1
@@ -1,26 +1,118 @@
1
1
  /**
2
- * Agent Registry Accessor — CRUD operations for agent data in signaldock.db.
2
+ * Agent Registry Accessor — cross-DB CRUD for agent data.
3
3
  *
4
- * signaldock.db is the SSoT for ALL agent data: identity, credentials,
5
- * capabilities, skills, transport config. No agent data lives in tasks.db.
4
+ * Post-T310 (ADR-037), agent identity lives in the GLOBAL
5
+ * `$XDG_DATA_HOME/cleo/signaldock.db:agents` table; per-project
6
+ * visibility and overrides live in the PROJECT
7
+ * `.cleo/conduit.db:project_agent_refs` table.
6
8
  *
7
- * API keys are encrypted at rest using the crypto/credentials module.
9
+ * This module provides three module-level functions that perform the
10
+ * in-memory cross-DB join, plus the backward-compatible
11
+ * `AgentRegistryAccessor` class that wraps them.
8
12
  *
9
- * @see docs/specs/DATABASE-ARCHITECTURE.md
10
- * @task T234
13
+ * Architecture:
14
+ * global signaldock.db canonical identity (openGlobalDb)
15
+ * project conduit.db — project_agent_refs (openConduitDb)
16
+ * Join performed in Node (SQLite cannot cross-file-handle JOIN).
17
+ *
18
+ * @see .cleo/specs/T310-conduit-signaldock-spec.md §3.5
19
+ * @see .cleo/adrs/ADR-037-conduit-signaldock-separation.md
20
+ * @task T355
21
+ * @epic T310
11
22
  */
23
+ import { randomBytes } from 'node:crypto';
24
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
12
25
  import { createRequire } from 'node:module';
13
- import { decrypt, encrypt } from '../crypto/credentials.js';
14
- import { ensureSignaldockDb, getSignaldockDbPath } from './signaldock-sqlite.js';
26
+ import { join } from 'node:path';
27
+ import { getCleoHome } from '../paths.js';
28
+ import { deriveApiKey } from './api-key-kdf.js';
29
+ import { ensureConduitDb, getConduitDbPath } from './conduit-sqlite.js';
30
+ import { getGlobalSalt } from './global-salt.js';
31
+ import { ensureGlobalSignaldockDb, getGlobalSignaldockDbPath } from './signaldock-sqlite.js';
32
+ // ---------------------------------------------------------------------------
33
+ // node:sqlite interop (createRequire for ESM / Vitest compat)
34
+ // ---------------------------------------------------------------------------
15
35
  const _require = createRequire(import.meta.url);
16
- const { DatabaseSync: DatabaseSyncClass } = _require('node:sqlite');
17
- /** Convert a signaldock.db row to an AgentCredential, decrypting the API key. */
18
- async function rowToCredential(row, projectPath) {
19
- const apiKey = row.api_key_encrypted ? await decrypt(row.api_key_encrypted, projectPath) : '';
36
+ const { DatabaseSync } = _require('node:sqlite');
37
+ // ---------------------------------------------------------------------------
38
+ // Machine-key helper (internal — mirrors credentials.ts private getMachineKey)
39
+ // ---------------------------------------------------------------------------
40
+ /** Machine-key constants. */
41
+ const MACHINE_KEY_LENGTH = 32;
42
+ /**
43
+ * Read or auto-generate the machine key (32 bytes).
44
+ * Machine key lives at `getCleoHome()/machine-key` (same XDG root as the global salt).
45
+ *
46
+ * @returns A 32-byte Buffer.
47
+ * @task T355
48
+ * @epic T310
49
+ */
50
+ function readMachineKey() {
51
+ const keyPath = join(getCleoHome(), 'machine-key');
52
+ if (!existsSync(keyPath)) {
53
+ const cleoHome = getCleoHome();
54
+ if (!existsSync(cleoHome)) {
55
+ mkdirSync(cleoHome, { recursive: true });
56
+ }
57
+ const key = randomBytes(MACHINE_KEY_LENGTH);
58
+ writeFileSync(keyPath, key, { mode: 0o600 });
59
+ return key;
60
+ }
61
+ // Validate permissions on POSIX
62
+ if (process.platform !== 'win32') {
63
+ const stat = statSync(keyPath);
64
+ const mode = stat.mode & 0o777;
65
+ if (mode !== 0o600) {
66
+ throw new Error(`Machine key at ${keyPath} has wrong permissions: expected 0o600, got 0o${mode.toString(8)}. ` +
67
+ `Fix with: chmod 600 ${keyPath}`);
68
+ }
69
+ }
70
+ const key = readFileSync(keyPath);
71
+ if (key.length !== MACHINE_KEY_LENGTH) {
72
+ throw new Error(`Machine key at ${keyPath} has wrong length: expected ${MACHINE_KEY_LENGTH} bytes, got ${key.length}.`);
73
+ }
74
+ return key;
75
+ }
76
+ // ---------------------------------------------------------------------------
77
+ // Row-to-type converters
78
+ // ---------------------------------------------------------------------------
79
+ /**
80
+ * Convert a project_agent_refs row to a `ProjectAgentRef` contract object.
81
+ *
82
+ * @param row - Raw SQLite row from conduit.db:project_agent_refs.
83
+ * @returns Typed `ProjectAgentRef` object.
84
+ * @task T355
85
+ * @epic T310
86
+ */
87
+ function rowToProjectRef(row) {
88
+ return {
89
+ agentId: row.agent_id,
90
+ attachedAt: row.attached_at,
91
+ role: row.role,
92
+ capabilitiesOverride: row.capabilities_override,
93
+ lastUsedAt: row.last_used_at,
94
+ enabled: row.enabled,
95
+ };
96
+ }
97
+ /**
98
+ * Convert a global signaldock.db:agents row to an `AgentCredential`.
99
+ * API key is stored as binary (derived via KDF) — returned as hex string.
100
+ * Legacy encrypted values (pre-T310) are left as-is; the reauth flag handles
101
+ * forced re-authentication at the CLI layer.
102
+ *
103
+ * @param row - Raw SQLite row from global signaldock.db:agents.
104
+ * @returns Typed `AgentCredential` (apiKey is hex-encoded derived bytes or empty).
105
+ * @task T355
106
+ * @epic T310
107
+ */
108
+ function rowToCredential(row) {
20
109
  return {
21
110
  agentId: row.agent_id,
22
111
  displayName: row.name,
23
- apiKey,
112
+ // api_key_encrypted stores the KDF-derived key as binary or a legacy ciphertext.
113
+ // Return as hex-encoded bytes for callers that need the raw key.
114
+ // The reauth flow in `cleo agent auth` handles re-keying (T358).
115
+ apiKey: row.api_key_encrypted ? Buffer.from(row.api_key_encrypted).toString('hex') : '',
24
116
  apiBaseUrl: row.api_base_url,
25
117
  classification: row.classification ?? undefined,
26
118
  privacyTier: row.privacy_tier,
@@ -34,17 +126,67 @@ async function rowToCredential(row, projectPath) {
34
126
  updatedAt: new Date(row.updated_at * 1000).toISOString(),
35
127
  };
36
128
  }
37
- /** Open signaldock.db for read/write operations. Caller must close. */
38
- function openDb(projectPath) {
39
- const dbPath = getSignaldockDbPath(projectPath);
40
- const db = new DatabaseSyncClass(dbPath);
129
+ /**
130
+ * Merge a global agent row with an optional project_agent_refs row into an
131
+ * `AgentWithProjectOverride` object.
132
+ *
133
+ * @param agentRow - Row from global signaldock.db:agents.
134
+ * @param refRow - Row from conduit.db:project_agent_refs, or null.
135
+ * @returns Merged `AgentWithProjectOverride`.
136
+ * @task T355
137
+ * @epic T310
138
+ */
139
+ function mergeToAgentWithOverride(agentRow, refRow) {
140
+ return {
141
+ ...rowToCredential(agentRow),
142
+ projectRef: refRow ? rowToProjectRef(refRow) : null,
143
+ };
144
+ }
145
+ // ---------------------------------------------------------------------------
146
+ // Database handle helpers (short-lived, caller closes)
147
+ // ---------------------------------------------------------------------------
148
+ /**
149
+ * Open a short-lived read/write handle to the GLOBAL signaldock.db.
150
+ * Caller MUST call `db.close()` when done.
151
+ *
152
+ * @task T355
153
+ * @epic T310
154
+ */
155
+ function openGlobalDb() {
156
+ const dbPath = getGlobalSignaldockDbPath();
157
+ const db = new DatabaseSync(dbPath);
41
158
  db.exec('PRAGMA foreign_keys = ON');
42
159
  db.exec('PRAGMA journal_mode = WAL');
43
160
  return db;
44
161
  }
45
162
  /**
46
- * Sync capabilities/skills to junction tables in signaldock.db.
47
- * Junction tables are the SSoT — JSON columns are materialized cache.
163
+ * Open a short-lived read/write handle to the PROJECT conduit.db.
164
+ * Caller MUST call `db.close()` when done.
165
+ *
166
+ * @param projectRoot - Absolute path to the project root directory.
167
+ * @task T355
168
+ * @epic T310
169
+ */
170
+ function openConduitDb(projectRoot) {
171
+ const dbPath = getConduitDbPath(projectRoot);
172
+ const db = new DatabaseSync(dbPath);
173
+ db.exec('PRAGMA foreign_keys = ON');
174
+ db.exec('PRAGMA journal_mode = WAL');
175
+ return db;
176
+ }
177
+ // ---------------------------------------------------------------------------
178
+ // junction table sync (global signaldock.db only)
179
+ // ---------------------------------------------------------------------------
180
+ /**
181
+ * Sync capabilities/skills to junction tables in global signaldock.db.
182
+ * Junction tables are the SSoT — JSON columns are a materialized cache.
183
+ *
184
+ * @param db - Open handle to global signaldock.db.
185
+ * @param agentUuid - The `id` (UUID primary key) from the agents row.
186
+ * @param capabilities - Array of capability slugs.
187
+ * @param skills - Array of skill slugs.
188
+ * @task T355
189
+ * @epic T310
48
190
  */
49
191
  function syncJunctionTables(db, agentUuid, capabilities, skills) {
50
192
  db.prepare('DELETE FROM agent_capabilities WHERE agent_id = ?').run(agentUuid);
@@ -62,86 +204,336 @@ function syncJunctionTables(db, agentUuid, capabilities, skills) {
62
204
  }
63
205
  }
64
206
  }
65
- /** signaldock.db implementation of the AgentRegistryAPI. */
66
- export class AgentRegistryAccessor {
67
- projectPath;
68
- constructor(projectPath) {
69
- this.projectPath = projectPath;
207
+ // ---------------------------------------------------------------------------
208
+ // Module-level cross-DB functions (spec §3.5)
209
+ // ---------------------------------------------------------------------------
210
+ /**
211
+ * Cross-DB agent lookup. Opens both the global signaldock.db and the
212
+ * current project's conduit.db, joins project_agent_refs ⨝ agents by
213
+ * agentId, and returns the merged view.
214
+ *
215
+ * Default (includeGlobal=false): returns null if no project_agent_refs row
216
+ * exists, even if the agent exists globally. An enabled=0 row is also treated
217
+ * as absent.
218
+ *
219
+ * includeGlobal=true: returns the global agent with `projectRef: null` if no
220
+ * project attachment row exists.
221
+ *
222
+ * Dangling soft-FK detection: if a project_agent_refs row exists but the
223
+ * referenced global agent does not, logs a WARN and returns null.
224
+ *
225
+ * @param projectRoot - Absolute path to the project root directory.
226
+ * @param agentId - Agent business identifier.
227
+ * @param opts.includeGlobal - When true, returns global identity even without project ref.
228
+ * @returns Merged agent record or null if not found.
229
+ *
230
+ * @task T355
231
+ * @epic T310
232
+ */
233
+ export function lookupAgent(projectRoot, agentId, opts) {
234
+ const includeGlobal = opts?.includeGlobal ?? false;
235
+ const globalDb = openGlobalDb();
236
+ const conduitDb = openConduitDb(projectRoot);
237
+ try {
238
+ const agentRow = globalDb.prepare('SELECT * FROM agents WHERE agent_id = ?').get(agentId);
239
+ const refRow = conduitDb
240
+ .prepare('SELECT * FROM project_agent_refs WHERE agent_id = ?')
241
+ .get(agentId);
242
+ // Dangling soft-FK: ref exists in conduit but not in global
243
+ if (refRow && !agentRow) {
244
+ console.warn(`[agent-registry-accessor] WARN: dangling project_agent_refs row for agent_id="${agentId}". ` +
245
+ `No matching row in global signaldock.db:agents. Row will be ignored.`);
246
+ return null;
247
+ }
248
+ // Agent does not exist globally at all
249
+ if (!agentRow)
250
+ return null;
251
+ if (!includeGlobal) {
252
+ // INNER JOIN semantics: must have a project ref with enabled=1
253
+ if (!refRow || refRow.enabled === 0)
254
+ return null;
255
+ return mergeToAgentWithOverride(agentRow, refRow);
256
+ }
257
+ // includeGlobal=true: return global agent; populate projectRef only when enabled=1
258
+ const effectiveRef = refRow && refRow.enabled === 1 ? refRow : null;
259
+ return mergeToAgentWithOverride(agentRow, effectiveRef);
70
260
  }
71
- /** Ensure signaldock.db exists with full schema before any operation. */
72
- async ensureDb() {
73
- await ensureSignaldockDb(this.projectPath);
261
+ finally {
262
+ globalDb.close();
263
+ conduitDb.close();
74
264
  }
75
- async register(credential) {
76
- await this.ensureDb();
77
- const nowTs = Math.floor(Date.now() / 1000);
78
- const apiKeyEncrypted = credential.apiKey
79
- ? await encrypt(credential.apiKey, this.projectPath)
80
- : null;
81
- const db = openDb(this.projectPath);
82
- try {
83
- const existing = db
84
- .prepare('SELECT id FROM agents WHERE agent_id = ?')
85
- .get(credential.agentId);
86
- if (!existing) {
87
- const id = crypto.randomUUID();
88
- db.prepare(`INSERT INTO agents (id, agent_id, name, class, privacy_tier, capabilities, skills,
89
- transport_type, api_key_encrypted, api_base_url, classification, transport_config,
90
- is_active, last_used_at, status, created_at, updated_at)
91
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'online', ?, ?)`).run(id, credential.agentId, credential.displayName, credential.classification ?? 'custom', credential.privacyTier, JSON.stringify(credential.capabilities), JSON.stringify(credential.skills), credential.transportType ?? 'http', apiKeyEncrypted, credential.apiBaseUrl, credential.classification ?? null, JSON.stringify(credential.transportConfig), credential.isActive ? 1 : 0, credential.lastUsedAt
92
- ? Math.floor(new Date(credential.lastUsedAt).getTime() / 1000)
93
- : null, nowTs, nowTs);
94
- syncJunctionTables(db, id, credential.capabilities, credential.skills);
265
+ }
266
+ /**
267
+ * Lists agents visible in the current project.
268
+ *
269
+ * Default (includeGlobal=false): INNER JOIN on project_agent_refs (enabled=1)
270
+ * — only agents explicitly attached to this project are returned.
271
+ *
272
+ * includeGlobal=true: returns all global agents regardless of project
273
+ * attachment, with projectRef populated for attached ones and null for the rest.
274
+ *
275
+ * includeDisabled=true: also returns agents with enabled=0 in project_agent_refs.
276
+ * Ignored when includeGlobal=true (all global agents are returned regardless).
277
+ *
278
+ * @param projectRoot - Absolute path to the project root directory.
279
+ * @param opts.includeGlobal - Include all global agents (bypasses project filter).
280
+ * @param opts.includeDisabled - Include agents with enabled=0 in project_agent_refs.
281
+ * @returns Array of merged agent records.
282
+ *
283
+ * @task T355
284
+ * @epic T310
285
+ */
286
+ export function listAgentsForProject(projectRoot, opts) {
287
+ const includeGlobal = opts?.includeGlobal ?? false;
288
+ const includeDisabled = opts?.includeDisabled ?? false;
289
+ const globalDb = openGlobalDb();
290
+ const conduitDb = openConduitDb(projectRoot);
291
+ try {
292
+ const allAgents = globalDb
293
+ .prepare('SELECT * FROM agents ORDER BY name ASC')
294
+ .all();
295
+ const allRefs = conduitDb
296
+ .prepare('SELECT * FROM project_agent_refs')
297
+ .all();
298
+ // Build a map from agentId → ref row for O(1) lookup during join
299
+ const refMap = new Map();
300
+ for (const ref of allRefs) {
301
+ refMap.set(ref.agent_id, ref);
302
+ }
303
+ const result = [];
304
+ for (const agentRow of allAgents) {
305
+ const ref = refMap.get(agentRow.agent_id);
306
+ if (includeGlobal) {
307
+ // Return all global agents; populate projectRef only for attached ones
308
+ const effectiveRef = ref && ref.enabled === 1 ? ref : null;
309
+ result.push(mergeToAgentWithOverride(agentRow, effectiveRef));
95
310
  }
96
311
  else {
97
- db.prepare(`UPDATE agents SET name = ?, class = ?, privacy_tier = ?, capabilities = ?, skills = ?,
98
- transport_type = ?, api_key_encrypted = ?, api_base_url = ?, classification = ?,
99
- transport_config = ?, is_active = ?, updated_at = ? WHERE agent_id = ?`).run(credential.displayName, credential.classification ?? 'custom', credential.privacyTier, JSON.stringify(credential.capabilities), JSON.stringify(credential.skills), credential.transportType ?? 'http', apiKeyEncrypted, credential.apiBaseUrl, credential.classification ?? null, JSON.stringify(credential.transportConfig), credential.isActive ? 1 : 0, nowTs, credential.agentId);
100
- syncJunctionTables(db, existing.id, credential.capabilities, credential.skills);
312
+ // INNER JOIN: only agents with a project ref row
313
+ if (!ref)
314
+ continue;
315
+ if (!includeDisabled && ref.enabled === 0)
316
+ continue;
317
+ result.push(mergeToAgentWithOverride(agentRow, ref));
101
318
  }
102
319
  }
103
- finally {
104
- db.close();
105
- }
106
- const result = await this.get(credential.agentId);
107
- if (!result)
108
- throw new Error(`Failed to register agent: ${credential.agentId}`);
109
320
  return result;
110
321
  }
111
- async get(agentId) {
112
- await this.ensureDb();
113
- const db = openDb(this.projectPath);
114
- try {
115
- const row = db.prepare('SELECT * FROM agents WHERE agent_id = ?').get(agentId);
116
- if (!row)
117
- return null;
118
- return rowToCredential(row, this.projectPath);
322
+ finally {
323
+ globalDb.close();
324
+ conduitDb.close();
325
+ }
326
+ }
327
+ /**
328
+ * Creates a new agent: writes identity row to global signaldock.db AND attaches
329
+ * it to the current project via conduit.db:project_agent_refs.
330
+ *
331
+ * Write order: global first, then project ref. If the project ref write fails,
332
+ * the global row remains (recoverable via `cleo agent attach <id>`).
333
+ *
334
+ * API key derivation: HMAC-SHA256(machineKey || globalSalt, agentId) per ADR-037 §5.
335
+ *
336
+ * @param projectRoot - Absolute path to the project root directory.
337
+ * @param spec - Agent creation spec (without createdAt/updatedAt).
338
+ * @returns Merged agent record including the new project ref.
339
+ *
340
+ * @task T355
341
+ * @epic T310
342
+ */
343
+ export function createProjectAgent(projectRoot, spec) {
344
+ ensureGlobalSignaldockDb();
345
+ ensureConduitDb(projectRoot);
346
+ const nowTs = Math.floor(Date.now() / 1000);
347
+ const nowIso = new Date(nowTs * 1000).toISOString();
348
+ // Derive API key using the T310 KDF
349
+ const machineKey = readMachineKey();
350
+ const globalSalt = getGlobalSalt();
351
+ const derivedKey = deriveApiKey({
352
+ machineKey,
353
+ globalSalt,
354
+ agentId: spec.agentId,
355
+ });
356
+ // Store as hex string in the encrypted column
357
+ const apiKeyEncrypted = derivedKey.toString('hex');
358
+ const globalDb = openGlobalDb();
359
+ try {
360
+ const existing = globalDb
361
+ .prepare('SELECT id FROM agents WHERE agent_id = ?')
362
+ .get(spec.agentId);
363
+ let agentUuid;
364
+ if (!existing) {
365
+ agentUuid = crypto.randomUUID();
366
+ globalDb
367
+ .prepare(`INSERT INTO agents (id, agent_id, name, class, privacy_tier, capabilities, skills,
368
+ transport_type, api_key_encrypted, api_base_url, classification, transport_config,
369
+ is_active, last_used_at, status, created_at, updated_at, requires_reauth)
370
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'online', ?, ?, 0)`)
371
+ .run(agentUuid, spec.agentId, spec.displayName, spec.classification ?? 'custom', spec.privacyTier, JSON.stringify(spec.capabilities), JSON.stringify(spec.skills), spec.transportType ?? 'http', apiKeyEncrypted, spec.apiBaseUrl, spec.classification ?? null, JSON.stringify(spec.transportConfig), spec.isActive ? 1 : 0, spec.lastUsedAt ? Math.floor(new Date(spec.lastUsedAt).getTime() / 1000) : null, nowTs, nowTs);
372
+ syncJunctionTables(globalDb, agentUuid, spec.capabilities, spec.skills);
119
373
  }
120
- finally {
121
- db.close();
374
+ else {
375
+ agentUuid = existing.id;
376
+ // Update identity in global DB (idempotent re-register)
377
+ globalDb
378
+ .prepare(`UPDATE agents SET name = ?, class = ?, privacy_tier = ?, capabilities = ?, skills = ?,
379
+ transport_type = ?, api_key_encrypted = ?, api_base_url = ?, classification = ?,
380
+ transport_config = ?, is_active = ?, updated_at = ? WHERE agent_id = ?`)
381
+ .run(spec.displayName, spec.classification ?? 'custom', spec.privacyTier, JSON.stringify(spec.capabilities), JSON.stringify(spec.skills), spec.transportType ?? 'http', apiKeyEncrypted, spec.apiBaseUrl, spec.classification ?? null, JSON.stringify(spec.transportConfig), spec.isActive ? 1 : 0, nowTs, spec.agentId);
382
+ syncJunctionTables(globalDb, agentUuid, spec.capabilities, spec.skills);
383
+ }
384
+ }
385
+ finally {
386
+ globalDb.close();
387
+ }
388
+ // Attach to project via conduit.db:project_agent_refs
389
+ const conduitDb = openConduitDb(projectRoot);
390
+ try {
391
+ const existingRef = conduitDb
392
+ .prepare('SELECT agent_id, enabled FROM project_agent_refs WHERE agent_id = ?')
393
+ .get(spec.agentId);
394
+ if (!existingRef) {
395
+ conduitDb
396
+ .prepare(`INSERT INTO project_agent_refs (agent_id, attached_at, role, capabilities_override, last_used_at, enabled)
397
+ VALUES (?, ?, NULL, NULL, NULL, 1)`)
398
+ .run(spec.agentId, nowIso);
399
+ }
400
+ else if (existingRef.enabled === 0) {
401
+ // Re-enable a previously detached agent
402
+ conduitDb
403
+ .prepare(`UPDATE project_agent_refs SET enabled = 1, attached_at = ? WHERE agent_id = ?`)
404
+ .run(nowIso, spec.agentId);
122
405
  }
406
+ // If enabled=1 already, leave the existing ref intact
123
407
  }
408
+ finally {
409
+ conduitDb.close();
410
+ }
411
+ const result = lookupAgent(projectRoot, spec.agentId, { includeGlobal: false });
412
+ if (!result) {
413
+ throw new Error(`createProjectAgent: failed to retrieve agent after creation: ${spec.agentId}`);
414
+ }
415
+ return result;
416
+ }
417
+ // ---------------------------------------------------------------------------
418
+ // AgentRegistryAccessor class (backward-compatible wrapper)
419
+ // ---------------------------------------------------------------------------
420
+ /**
421
+ * AgentRegistryAccessor — backward-compatible CRUD wrapper around the
422
+ * cross-DB module-level functions.
423
+ *
424
+ * Post-T310 (ADR-037), the constructor accepts the project root (same
425
+ * semantics as `projectPath` in the pre-T310 version). All operations are
426
+ * routed through the cross-DB functions above.
427
+ *
428
+ * @task T355
429
+ * @epic T310
430
+ */
431
+ export class AgentRegistryAccessor {
432
+ projectPath;
433
+ /**
434
+ * @param projectPath - Absolute path to the project root directory.
435
+ * Used as the `projectRoot` argument for all cross-DB operations.
436
+ * @task T355
437
+ * @epic T310
438
+ */
439
+ constructor(projectPath) {
440
+ this.projectPath = projectPath;
441
+ }
442
+ /**
443
+ * Ensure both databases exist with their full schemas before any operation.
444
+ *
445
+ * @task T355
446
+ * @epic T310
447
+ */
448
+ ensureDbs() {
449
+ ensureGlobalSignaldockDb();
450
+ ensureConduitDb(this.projectPath);
451
+ }
452
+ /**
453
+ * Register (create or update) an agent in global signaldock.db and attach
454
+ * it to the current project via conduit.db:project_agent_refs.
455
+ *
456
+ * @param credential - Agent spec (without createdAt/updatedAt).
457
+ * @returns The registered agent credential.
458
+ * @task T355
459
+ * @epic T310
460
+ */
461
+ async register(credential) {
462
+ this.ensureDbs();
463
+ return createProjectAgent(this.projectPath, credential);
464
+ }
465
+ /**
466
+ * Get agent by agentId. Project-scoped by default (INNER JOIN).
467
+ *
468
+ * @param agentId - Agent business identifier.
469
+ * @param opts.includeGlobal - When true, returns global identity even without project ref.
470
+ * @returns The agent credential, or null if not found.
471
+ * @task T355
472
+ * @epic T310
473
+ */
474
+ async get(agentId, opts) {
475
+ this.ensureDbs();
476
+ return lookupAgent(this.projectPath, agentId, opts);
477
+ }
478
+ /**
479
+ * Lists project-scoped agents (INNER JOIN on project_agent_refs with enabled=1).
480
+ *
481
+ * @param filter - Optional filter (active field maps to is_active in global agents).
482
+ * @returns Array of agent credentials visible in this project.
483
+ * @task T355
484
+ * @epic T310
485
+ */
124
486
  async list(filter) {
125
- await this.ensureDb();
126
- const db = openDb(this.projectPath);
487
+ this.ensureDbs();
488
+ const results = listAgentsForProject(this.projectPath, { includeGlobal: false });
489
+ if (filter?.active !== undefined) {
490
+ return results.filter((a) => a.isActive === filter.active);
491
+ }
492
+ return results;
493
+ }
494
+ /**
495
+ * Lists all global agents (no project filter). Exposed for `--global` CLI flag.
496
+ *
497
+ * @param filter - Optional filter (active field maps to is_active in global agents).
498
+ * @returns Array of all globally registered agent credentials.
499
+ * @task T355
500
+ * @epic T310
501
+ */
502
+ async listGlobal(filter) {
503
+ this.ensureDbs();
504
+ const globalDb = openGlobalDb();
127
505
  try {
128
506
  const rows = filter?.active !== undefined
129
- ? db
130
- .prepare('SELECT * FROM agents WHERE is_active = ?')
507
+ ? globalDb
508
+ .prepare('SELECT * FROM agents WHERE is_active = ? ORDER BY name ASC')
131
509
  .all(filter.active ? 1 : 0)
132
- : db.prepare('SELECT * FROM agents').all();
133
- return Promise.all(rows.map((row) => rowToCredential(row, this.projectPath)));
510
+ : globalDb
511
+ .prepare('SELECT * FROM agents ORDER BY name ASC')
512
+ .all();
513
+ return rows.map(rowToCredential);
134
514
  }
135
515
  finally {
136
- db.close();
516
+ globalDb.close();
137
517
  }
138
518
  }
519
+ /**
520
+ * Update agent identity fields in global signaldock.db.
521
+ * Project-specific fields (role, capabilitiesOverride) require direct
522
+ * conduit.db manipulation (not yet exposed by this method).
523
+ *
524
+ * @param agentId - Agent business identifier.
525
+ * @param updates - Partial set of fields to update.
526
+ * @returns The updated agent credential (project-scoped lookup).
527
+ * @task T355
528
+ * @epic T310
529
+ */
139
530
  async update(agentId, updates) {
140
- const existing = await this.get(agentId);
531
+ this.ensureDbs();
532
+ const existing = await this.get(agentId, { includeGlobal: true });
141
533
  if (!existing)
142
534
  throw new Error(`Agent not found: ${agentId}`);
143
535
  const nowTs = Math.floor(Date.now() / 1000);
144
- const db = openDb(this.projectPath);
536
+ const globalDb = openGlobalDb();
145
537
  try {
146
538
  const sets = ['updated_at = ?'];
147
539
  const params = [nowTs];
@@ -182,40 +574,112 @@ export class AgentRegistryAccessor {
182
574
  params.push(updates.isActive ? 1 : 0);
183
575
  }
184
576
  if (updates.apiKey !== undefined) {
185
- const encrypted = await encrypt(updates.apiKey, this.projectPath);
577
+ // Re-derive using new T310 KDF
578
+ const machineKey = readMachineKey();
579
+ const globalSalt = getGlobalSalt();
580
+ const derivedKey = deriveApiKey({ machineKey, globalSalt, agentId });
186
581
  sets.push('api_key_encrypted = ?');
187
- params.push(encrypted);
582
+ params.push(derivedKey.toString('hex'));
188
583
  }
189
584
  params.push(agentId);
190
- db.prepare(`UPDATE agents SET ${sets.join(', ')} WHERE agent_id = ?`).run(...params);
585
+ globalDb
586
+ .prepare(`UPDATE agents SET ${sets.join(', ')} WHERE agent_id = ?`)
587
+ .run(...params);
191
588
  // Sync junction tables if capabilities or skills changed
192
589
  if (updates.capabilities !== undefined || updates.skills !== undefined) {
193
- const agentRow = db.prepare('SELECT id FROM agents WHERE agent_id = ?').get(agentId);
194
- syncJunctionTables(db, agentRow.id, updates.capabilities ?? existing.capabilities, updates.skills ?? existing.skills);
590
+ const agentRow = globalDb
591
+ .prepare('SELECT id FROM agents WHERE agent_id = ?')
592
+ .get(agentId);
593
+ if (agentRow) {
594
+ syncJunctionTables(globalDb, agentRow.id, updates.capabilities ?? existing.capabilities, updates.skills ?? existing.skills);
595
+ }
195
596
  }
196
597
  }
197
598
  finally {
198
- db.close();
599
+ globalDb.close();
199
600
  }
200
- const result = await this.get(agentId);
601
+ const result = await this.get(agentId, { includeGlobal: true });
201
602
  if (!result)
202
603
  throw new Error(`Agent not found after update: ${agentId}`);
203
604
  return result;
204
605
  }
606
+ /**
607
+ * Remove agent from current project (sets project_agent_refs.enabled=0).
608
+ * Does NOT delete from global signaldock.db (per ADR-037 §6 / Q4=C).
609
+ *
610
+ * @param agentId - Agent business identifier.
611
+ * @task T355
612
+ * @epic T310
613
+ */
205
614
  async remove(agentId) {
206
- const existing = await this.get(agentId);
207
- if (!existing)
208
- throw new Error(`Agent not found: ${agentId}`);
209
- const db = openDb(this.projectPath);
615
+ this.ensureDbs();
616
+ const conduitDb = openConduitDb(this.projectPath);
210
617
  try {
211
- db.prepare('DELETE FROM agents WHERE agent_id = ?').run(agentId);
618
+ const ref = conduitDb
619
+ .prepare('SELECT agent_id FROM project_agent_refs WHERE agent_id = ?')
620
+ .get(agentId);
621
+ if (!ref) {
622
+ throw new Error(`Agent not found in current project: ${agentId}`);
623
+ }
624
+ conduitDb
625
+ .prepare('UPDATE project_agent_refs SET enabled = 0 WHERE agent_id = ?')
626
+ .run(agentId);
212
627
  }
213
628
  finally {
214
- db.close();
629
+ conduitDb.close();
215
630
  }
216
631
  }
632
+ /**
633
+ * Remove agent from global signaldock.db.
634
+ * Requires explicit opt-in. Warns if cross-project refs may exist.
635
+ *
636
+ * @param agentId - Agent business identifier.
637
+ * @param opts.force - Skip the global-delete warning when refs exist.
638
+ * @task T355
639
+ * @epic T310
640
+ */
641
+ async removeGlobal(agentId, opts) {
642
+ this.ensureDbs();
643
+ const globalDb = openGlobalDb();
644
+ try {
645
+ const existing = globalDb.prepare('SELECT id FROM agents WHERE agent_id = ?').get(agentId);
646
+ if (!existing) {
647
+ throw new Error(`Agent not found globally: ${agentId}`);
648
+ }
649
+ if (!opts?.force) {
650
+ // Best-effort cross-project scan: check the current project's conduit.db
651
+ const conduitDb = openConduitDb(this.projectPath);
652
+ try {
653
+ const ref = conduitDb
654
+ .prepare('SELECT agent_id FROM project_agent_refs WHERE agent_id = ? AND enabled = 1')
655
+ .get(agentId);
656
+ if (ref) {
657
+ throw new Error(`Agent "${agentId}" still has project references in the current project. ` +
658
+ `Use removeGlobal(id, { force: true }) to skip this check.`);
659
+ }
660
+ }
661
+ finally {
662
+ conduitDb.close();
663
+ }
664
+ }
665
+ globalDb.prepare('DELETE FROM agents WHERE agent_id = ?').run(agentId);
666
+ }
667
+ finally {
668
+ globalDb.close();
669
+ }
670
+ }
671
+ /**
672
+ * Rotate API key via cloud endpoint and re-encrypt with the new T310 KDF
673
+ * in global signaldock.db.
674
+ *
675
+ * @param agentId - Agent business identifier.
676
+ * @returns Object with agentId and a redacted new API key string.
677
+ * @task T355
678
+ * @epic T310
679
+ */
217
680
  async rotateKey(agentId) {
218
- const credential = await this.get(agentId);
681
+ this.ensureDbs();
682
+ const credential = await this.get(agentId, { includeGlobal: true });
219
683
  if (!credential)
220
684
  throw new Error(`Agent not found: ${agentId}`);
221
685
  const response = await fetch(`${credential.apiBaseUrl}/agents/${agentId}/rotate-key`, {
@@ -232,33 +696,87 @@ export class AgentRegistryAccessor {
232
696
  const newApiKey = data.data?.apiKey;
233
697
  if (!newApiKey)
234
698
  throw new Error('Cloud API did not return a new API key');
235
- await this.update(agentId, { apiKey: newApiKey });
699
+ // Re-derive and store using T310 KDF
700
+ const machineKey = readMachineKey();
701
+ const globalSalt = getGlobalSalt();
702
+ const derivedKey = deriveApiKey({ machineKey, globalSalt, agentId });
703
+ const nowTs = Math.floor(Date.now() / 1000);
704
+ const globalDb = openGlobalDb();
705
+ try {
706
+ globalDb
707
+ .prepare('UPDATE agents SET api_key_encrypted = ?, updated_at = ?, requires_reauth = 0 WHERE agent_id = ?')
708
+ .run(derivedKey.toString('hex'), nowTs, agentId);
709
+ }
710
+ finally {
711
+ globalDb.close();
712
+ }
236
713
  return { agentId, newApiKey: `${newApiKey.substring(0, 8)}...rotated` };
237
714
  }
715
+ /**
716
+ * Get the most recently used active agent in the current project.
717
+ *
718
+ * @returns The most-recently-used active agent, or null if none found.
719
+ * @task T355
720
+ * @epic T310
721
+ */
238
722
  async getActive() {
239
- await this.ensureDb();
240
- const db = openDb(this.projectPath);
723
+ this.ensureDbs();
724
+ const globalDb = openGlobalDb();
725
+ const conduitDb = openConduitDb(this.projectPath);
241
726
  try {
242
- const row = db
727
+ // Get all project-attached, enabled agent IDs ordered by project last_used_at
728
+ const enabledRefs = conduitDb
729
+ .prepare('SELECT agent_id, last_used_at FROM project_agent_refs WHERE enabled = 1 ORDER BY last_used_at DESC')
730
+ .all();
731
+ for (const ref of enabledRefs) {
732
+ const agentRow = globalDb
733
+ .prepare('SELECT * FROM agents WHERE agent_id = ? AND is_active = 1')
734
+ .get(ref.agent_id);
735
+ if (agentRow)
736
+ return rowToCredential(agentRow);
737
+ }
738
+ // Fall back to global last_used_at if no project-local activity recorded
739
+ const row = globalDb
243
740
  .prepare('SELECT * FROM agents WHERE is_active = 1 ORDER BY last_used_at DESC, created_at DESC LIMIT 1')
244
741
  .get();
245
742
  if (!row)
246
743
  return null;
247
- return rowToCredential(row, this.projectPath);
744
+ return rowToCredential(row);
248
745
  }
249
746
  finally {
250
- db.close();
747
+ globalDb.close();
748
+ conduitDb.close();
251
749
  }
252
750
  }
751
+ /**
752
+ * Update last_used_at in both global signaldock.db:agents and
753
+ * conduit.db:project_agent_refs.
754
+ *
755
+ * @param agentId - Agent business identifier.
756
+ * @task T355
757
+ * @epic T310
758
+ */
253
759
  async markUsed(agentId) {
254
- await this.ensureDb();
760
+ this.ensureDbs();
255
761
  const nowTs = Math.floor(Date.now() / 1000);
256
- const db = openDb(this.projectPath);
762
+ const nowIso = new Date(nowTs * 1000).toISOString();
763
+ const globalDb = openGlobalDb();
764
+ try {
765
+ globalDb
766
+ .prepare('UPDATE agents SET last_used_at = ?, updated_at = ? WHERE agent_id = ?')
767
+ .run(nowTs, nowTs, agentId);
768
+ }
769
+ finally {
770
+ globalDb.close();
771
+ }
772
+ const conduitDb = openConduitDb(this.projectPath);
257
773
  try {
258
- db.prepare('UPDATE agents SET last_used_at = ?, updated_at = ? WHERE agent_id = ?').run(nowTs, nowTs, agentId);
774
+ conduitDb
775
+ .prepare('UPDATE project_agent_refs SET last_used_at = ? WHERE agent_id = ?')
776
+ .run(nowIso, agentId);
259
777
  }
260
778
  finally {
261
- db.close();
779
+ conduitDb.close();
262
780
  }
263
781
  }
264
782
  }