@cleocode/core 2026.4.11 → 2026.4.13
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.
- package/dist/codebase-map/analyzers/architecture.d.ts.map +1 -1
- package/dist/codebase-map/analyzers/architecture.js +0 -1
- package/dist/codebase-map/analyzers/architecture.js.map +1 -1
- package/dist/conduit/local-transport.d.ts +18 -8
- package/dist/conduit/local-transport.d.ts.map +1 -1
- package/dist/conduit/local-transport.js +23 -13
- package/dist/conduit/local-transport.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +0 -1
- package/dist/config.js.map +1 -1
- package/dist/errors.d.ts +19 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +6 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.js +175 -68950
- package/dist/index.js.map +1 -7
- package/dist/init.d.ts +1 -2
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +1 -2
- package/dist/init.js.map +1 -1
- package/dist/internal.d.ts +8 -3
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +13 -6
- package/dist/internal.js.map +1 -1
- package/dist/memory/learnings.d.ts +2 -2
- package/dist/memory/patterns.d.ts +6 -6
- package/dist/output.d.ts +32 -11
- package/dist/output.d.ts.map +1 -1
- package/dist/output.js +67 -67
- package/dist/output.js.map +1 -1
- package/dist/paths.js +80 -14
- package/dist/paths.js.map +1 -1
- package/dist/skills/dynamic-skill-generator.d.ts +0 -2
- package/dist/skills/dynamic-skill-generator.d.ts.map +1 -1
- package/dist/skills/dynamic-skill-generator.js.map +1 -1
- package/dist/store/agent-registry-accessor.d.ts +203 -12
- package/dist/store/agent-registry-accessor.d.ts.map +1 -1
- package/dist/store/agent-registry-accessor.js +618 -100
- package/dist/store/agent-registry-accessor.js.map +1 -1
- package/dist/store/api-key-kdf.d.ts +73 -0
- package/dist/store/api-key-kdf.d.ts.map +1 -0
- package/dist/store/api-key-kdf.js +84 -0
- package/dist/store/api-key-kdf.js.map +1 -0
- package/dist/store/cleanup-legacy.js +171 -0
- package/dist/store/cleanup-legacy.js.map +1 -0
- package/dist/store/conduit-sqlite.d.ts +184 -0
- package/dist/store/conduit-sqlite.d.ts.map +1 -0
- package/dist/store/conduit-sqlite.js +570 -0
- package/dist/store/conduit-sqlite.js.map +1 -0
- package/dist/store/global-salt.d.ts +78 -0
- package/dist/store/global-salt.d.ts.map +1 -0
- package/dist/store/global-salt.js +147 -0
- package/dist/store/global-salt.js.map +1 -0
- package/dist/store/migrate-signaldock-to-conduit.d.ts +81 -0
- package/dist/store/migrate-signaldock-to-conduit.d.ts.map +1 -0
- package/dist/store/migrate-signaldock-to-conduit.js +555 -0
- package/dist/store/migrate-signaldock-to-conduit.js.map +1 -0
- package/dist/store/nexus-sqlite.js +28 -3
- package/dist/store/nexus-sqlite.js.map +1 -1
- package/dist/store/signaldock-sqlite.d.ts +122 -19
- package/dist/store/signaldock-sqlite.d.ts.map +1 -1
- package/dist/store/signaldock-sqlite.js +401 -251
- package/dist/store/signaldock-sqlite.js.map +1 -1
- package/dist/store/sqlite-backup.js +122 -4
- package/dist/store/sqlite-backup.js.map +1 -1
- package/dist/system/backup.d.ts +0 -26
- package/dist/system/backup.d.ts.map +1 -1
- package/dist/system/runtime.d.ts +0 -2
- package/dist/system/runtime.d.ts.map +1 -1
- package/dist/system/runtime.js +3 -3
- package/dist/system/runtime.js.map +1 -1
- package/dist/tasks/add.d.ts +1 -1
- package/dist/tasks/add.d.ts.map +1 -1
- package/dist/tasks/add.js +98 -23
- package/dist/tasks/add.js.map +1 -1
- package/dist/tasks/complete.d.ts.map +1 -1
- package/dist/tasks/complete.js +4 -1
- package/dist/tasks/complete.js.map +1 -1
- package/dist/tasks/find.d.ts.map +1 -1
- package/dist/tasks/find.js +4 -1
- package/dist/tasks/find.js.map +1 -1
- package/dist/tasks/labels.d.ts.map +1 -1
- package/dist/tasks/labels.js +4 -1
- package/dist/tasks/labels.js.map +1 -1
- package/dist/tasks/relates.d.ts.map +1 -1
- package/dist/tasks/relates.js +16 -4
- package/dist/tasks/relates.js.map +1 -1
- package/dist/tasks/show.d.ts.map +1 -1
- package/dist/tasks/show.js +4 -1
- package/dist/tasks/show.js.map +1 -1
- package/dist/tasks/update.d.ts.map +1 -1
- package/dist/tasks/update.js +32 -6
- package/dist/tasks/update.js.map +1 -1
- package/dist/validation/engine.d.ts.map +1 -1
- package/dist/validation/engine.js +16 -4
- package/dist/validation/engine.js.map +1 -1
- package/dist/validation/param-utils.d.ts +5 -3
- package/dist/validation/param-utils.d.ts.map +1 -1
- package/dist/validation/param-utils.js +8 -6
- package/dist/validation/param-utils.js.map +1 -1
- package/dist/validation/protocols/_shared.d.ts.map +1 -1
- package/dist/validation/protocols/_shared.js +13 -6
- package/dist/validation/protocols/_shared.js.map +1 -1
- package/package.json +9 -7
- package/src/adapters/__tests__/manager.test.ts +0 -1
- package/src/codebase-map/analyzers/architecture.ts +0 -1
- package/src/conduit/__tests__/local-credential-flow.test.ts +20 -18
- package/src/conduit/__tests__/local-transport.test.ts +14 -12
- package/src/conduit/local-transport.ts +23 -13
- package/src/config.ts +0 -1
- package/src/errors.ts +24 -0
- package/src/hooks/handlers/__tests__/hook-automation-e2e.test.ts +2 -5
- package/src/init.ts +1 -2
- package/src/internal.ts +96 -2
- package/src/lifecycle/cant/lifecycle-rcasd.cant +133 -0
- package/src/memory/__tests__/engine-compat.test.ts +2 -2
- package/src/memory/__tests__/pipeline-manifest-sqlite.test.ts +4 -4
- package/src/observability/__tests__/index.test.ts +4 -4
- package/src/observability/__tests__/log-filter.test.ts +4 -4
- package/src/output.ts +73 -75
- package/src/sessions/__tests__/session-grade.integration.test.ts +1 -1
- package/src/sessions/__tests__/session-grade.test.ts +2 -2
- package/src/skills/__tests__/dynamic-skill-generator.test.ts +0 -2
- package/src/skills/dynamic-skill-generator.ts +0 -2
- package/src/store/__tests__/agent-registry-accessor.test.ts +807 -0
- package/src/store/__tests__/api-key-kdf.test.ts +113 -0
- package/src/store/__tests__/backup-crypto.test.ts +101 -0
- package/src/store/__tests__/backup-pack.test.ts +491 -0
- package/src/store/__tests__/backup-unpack.test.ts +298 -0
- package/src/store/__tests__/conduit-sqlite.test.ts +413 -0
- package/src/store/__tests__/global-salt.test.ts +195 -0
- package/src/store/__tests__/migrate-signaldock-to-conduit.test.ts +715 -0
- package/src/store/__tests__/regenerators.test.ts +234 -0
- package/src/store/__tests__/restore-conflict-report.test.ts +274 -0
- package/src/store/__tests__/restore-json-merge.test.ts +521 -0
- package/src/store/__tests__/signaldock-sqlite.test.ts +652 -0
- package/src/store/__tests__/sqlite-backup-global.test.ts +307 -3
- package/src/store/__tests__/sqlite-backup.test.ts +5 -1
- package/src/store/__tests__/t310-integration.test.ts +1150 -0
- package/src/store/__tests__/t310-readiness.test.ts +111 -0
- package/src/store/__tests__/t311-integration.test.ts +661 -0
- package/src/store/agent-registry-accessor.ts +847 -140
- package/src/store/api-key-kdf.ts +104 -0
- package/src/store/backup-crypto.ts +209 -0
- package/src/store/backup-pack.ts +739 -0
- package/src/store/backup-unpack.ts +583 -0
- package/src/store/conduit-sqlite.ts +655 -0
- package/src/store/global-salt.ts +175 -0
- package/src/store/migrate-signaldock-to-conduit.ts +669 -0
- package/src/store/regenerators.ts +243 -0
- package/src/store/restore-conflict-report.ts +317 -0
- package/src/store/restore-json-merge.ts +653 -0
- package/src/store/signaldock-sqlite.ts +431 -254
- package/src/store/sqlite-backup.ts +185 -10
- package/src/store/t310-readiness.ts +119 -0
- package/src/system/backup.ts +2 -62
- package/src/system/runtime.ts +4 -6
- package/src/tasks/__tests__/error-hints.test.ts +256 -0
- package/src/tasks/add.ts +99 -9
- package/src/tasks/complete.ts +4 -1
- package/src/tasks/find.ts +4 -1
- package/src/tasks/labels.ts +4 -1
- package/src/tasks/relates.ts +16 -4
- package/src/tasks/show.ts +4 -1
- package/src/tasks/update.ts +32 -3
- package/src/validation/__tests__/error-hints.test.ts +97 -0
- package/src/validation/engine.ts +16 -1
- package/src/validation/param-utils.ts +10 -7
- package/src/validation/protocols/_shared.ts +14 -6
- package/src/validation/protocols/cant/architecture-decision.cant +80 -0
- package/src/validation/protocols/cant/artifact-publish.cant +95 -0
- package/src/validation/protocols/cant/consensus.cant +74 -0
- package/src/validation/protocols/cant/contribution.cant +82 -0
- package/src/validation/protocols/cant/decomposition.cant +92 -0
- package/src/validation/protocols/cant/implementation.cant +67 -0
- package/src/validation/protocols/cant/provenance.cant +88 -0
- package/src/validation/protocols/cant/release.cant +96 -0
- package/src/validation/protocols/cant/research.cant +66 -0
- package/src/validation/protocols/cant/specification.cant +67 -0
- package/src/validation/protocols/cant/testing.cant +88 -0
- package/src/validation/protocols/cant/validation.cant +65 -0
- package/src/validation/protocols/protocols-markdown/decomposition.md +0 -4
- package/templates/config.template.json +0 -1
- package/templates/global-config.template.json +0 -1
|
@@ -1,32 +1,109 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Agent Registry Accessor — CRUD
|
|
2
|
+
* Agent Registry Accessor — cross-DB CRUD for agent data.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
10
|
-
*
|
|
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
|
*/
|
|
12
23
|
|
|
24
|
+
import { randomBytes } from 'node:crypto';
|
|
25
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
13
26
|
import { createRequire } from 'node:module';
|
|
14
|
-
import
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
import type { DatabaseSync as _DatabaseSyncType } from 'node:sqlite';
|
|
15
29
|
import type {
|
|
16
30
|
AgentCredential,
|
|
17
31
|
AgentListFilter,
|
|
18
32
|
AgentRegistryAPI,
|
|
33
|
+
AgentWithProjectOverride,
|
|
34
|
+
ProjectAgentRef,
|
|
19
35
|
TransportConfig,
|
|
20
36
|
} from '@cleocode/contracts';
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
37
|
+
import { getCleoHome } from '../paths.js';
|
|
38
|
+
import { deriveApiKey } from './api-key-kdf.js';
|
|
39
|
+
import { ensureConduitDb, getConduitDbPath } from './conduit-sqlite.js';
|
|
40
|
+
import { getGlobalSalt } from './global-salt.js';
|
|
41
|
+
import { ensureGlobalSignaldockDb, getGlobalSignaldockDbPath } from './signaldock-sqlite.js';
|
|
42
|
+
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// node:sqlite interop (createRequire for ESM / Vitest compat)
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
23
46
|
|
|
24
47
|
const _require = createRequire(import.meta.url);
|
|
25
|
-
|
|
26
|
-
|
|
48
|
+
type DatabaseSync = _DatabaseSyncType;
|
|
49
|
+
const { DatabaseSync } = _require('node:sqlite') as {
|
|
50
|
+
DatabaseSync: new (...args: ConstructorParameters<typeof _DatabaseSyncType>) => _DatabaseSyncType;
|
|
27
51
|
};
|
|
28
52
|
|
|
29
|
-
|
|
53
|
+
// ---------------------------------------------------------------------------
|
|
54
|
+
// Machine-key helper (internal — mirrors credentials.ts private getMachineKey)
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
/** Machine-key constants. */
|
|
58
|
+
const MACHINE_KEY_LENGTH = 32;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Read or auto-generate the machine key (32 bytes).
|
|
62
|
+
* Machine key lives at `getCleoHome()/machine-key` (same XDG root as the global salt).
|
|
63
|
+
*
|
|
64
|
+
* @returns A 32-byte Buffer.
|
|
65
|
+
* @task T355
|
|
66
|
+
* @epic T310
|
|
67
|
+
*/
|
|
68
|
+
function readMachineKey(): Buffer {
|
|
69
|
+
const keyPath = join(getCleoHome(), 'machine-key');
|
|
70
|
+
|
|
71
|
+
if (!existsSync(keyPath)) {
|
|
72
|
+
const cleoHome = getCleoHome();
|
|
73
|
+
if (!existsSync(cleoHome)) {
|
|
74
|
+
mkdirSync(cleoHome, { recursive: true });
|
|
75
|
+
}
|
|
76
|
+
const key = randomBytes(MACHINE_KEY_LENGTH);
|
|
77
|
+
writeFileSync(keyPath, key, { mode: 0o600 });
|
|
78
|
+
return key;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Validate permissions on POSIX
|
|
82
|
+
if (process.platform !== 'win32') {
|
|
83
|
+
const stat = statSync(keyPath);
|
|
84
|
+
const mode = stat.mode & 0o777;
|
|
85
|
+
if (mode !== 0o600) {
|
|
86
|
+
throw new Error(
|
|
87
|
+
`Machine key at ${keyPath} has wrong permissions: expected 0o600, got 0o${mode.toString(8)}. ` +
|
|
88
|
+
`Fix with: chmod 600 ${keyPath}`,
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const key = readFileSync(keyPath);
|
|
94
|
+
if (key.length !== MACHINE_KEY_LENGTH) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`Machine key at ${keyPath} has wrong length: expected ${MACHINE_KEY_LENGTH} bytes, got ${key.length}.`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return key;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
// Raw row shapes
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
/** Raw row shape from global signaldock.db:agents. */
|
|
30
107
|
interface AgentDbRow {
|
|
31
108
|
id: string;
|
|
32
109
|
agent_id: string;
|
|
@@ -47,13 +124,58 @@ interface AgentDbRow {
|
|
|
47
124
|
updated_at: number;
|
|
48
125
|
}
|
|
49
126
|
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
127
|
+
/** Raw row shape from conduit.db:project_agent_refs. */
|
|
128
|
+
interface ProjectAgentRefRow {
|
|
129
|
+
agent_id: string;
|
|
130
|
+
attached_at: string;
|
|
131
|
+
role: string | null;
|
|
132
|
+
capabilities_override: string | null;
|
|
133
|
+
last_used_at: string | null;
|
|
134
|
+
enabled: number;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
// Row-to-type converters
|
|
139
|
+
// ---------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Convert a project_agent_refs row to a `ProjectAgentRef` contract object.
|
|
143
|
+
*
|
|
144
|
+
* @param row - Raw SQLite row from conduit.db:project_agent_refs.
|
|
145
|
+
* @returns Typed `ProjectAgentRef` object.
|
|
146
|
+
* @task T355
|
|
147
|
+
* @epic T310
|
|
148
|
+
*/
|
|
149
|
+
function rowToProjectRef(row: ProjectAgentRefRow): ProjectAgentRef {
|
|
150
|
+
return {
|
|
151
|
+
agentId: row.agent_id,
|
|
152
|
+
attachedAt: row.attached_at,
|
|
153
|
+
role: row.role,
|
|
154
|
+
capabilitiesOverride: row.capabilities_override,
|
|
155
|
+
lastUsedAt: row.last_used_at,
|
|
156
|
+
enabled: row.enabled,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Convert a global signaldock.db:agents row to an `AgentCredential`.
|
|
162
|
+
* API key is stored as binary (derived via KDF) — returned as hex string.
|
|
163
|
+
* Legacy encrypted values (pre-T310) are left as-is; the reauth flag handles
|
|
164
|
+
* forced re-authentication at the CLI layer.
|
|
165
|
+
*
|
|
166
|
+
* @param row - Raw SQLite row from global signaldock.db:agents.
|
|
167
|
+
* @returns Typed `AgentCredential` (apiKey is hex-encoded derived bytes or empty).
|
|
168
|
+
* @task T355
|
|
169
|
+
* @epic T310
|
|
170
|
+
*/
|
|
171
|
+
function rowToCredential(row: AgentDbRow): AgentCredential {
|
|
53
172
|
return {
|
|
54
173
|
agentId: row.agent_id,
|
|
55
174
|
displayName: row.name,
|
|
56
|
-
|
|
175
|
+
// api_key_encrypted stores the KDF-derived key as binary or a legacy ciphertext.
|
|
176
|
+
// Return as hex-encoded bytes for callers that need the raw key.
|
|
177
|
+
// The reauth flow in `cleo agent auth` handles re-keying (T358).
|
|
178
|
+
apiKey: row.api_key_encrypted ? Buffer.from(row.api_key_encrypted).toString('hex') : '',
|
|
57
179
|
apiBaseUrl: row.api_base_url,
|
|
58
180
|
classification: row.classification ?? undefined,
|
|
59
181
|
privacyTier: row.privacy_tier as AgentCredential['privacyTier'],
|
|
@@ -68,18 +190,75 @@ async function rowToCredential(row: AgentDbRow, projectPath: string): Promise<Ag
|
|
|
68
190
|
};
|
|
69
191
|
}
|
|
70
192
|
|
|
71
|
-
/**
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
193
|
+
/**
|
|
194
|
+
* Merge a global agent row with an optional project_agent_refs row into an
|
|
195
|
+
* `AgentWithProjectOverride` object.
|
|
196
|
+
*
|
|
197
|
+
* @param agentRow - Row from global signaldock.db:agents.
|
|
198
|
+
* @param refRow - Row from conduit.db:project_agent_refs, or null.
|
|
199
|
+
* @returns Merged `AgentWithProjectOverride`.
|
|
200
|
+
* @task T355
|
|
201
|
+
* @epic T310
|
|
202
|
+
*/
|
|
203
|
+
function mergeToAgentWithOverride(
|
|
204
|
+
agentRow: AgentDbRow,
|
|
205
|
+
refRow: ProjectAgentRefRow | null,
|
|
206
|
+
): AgentWithProjectOverride {
|
|
207
|
+
return {
|
|
208
|
+
...rowToCredential(agentRow),
|
|
209
|
+
projectRef: refRow ? rowToProjectRef(refRow) : null,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---------------------------------------------------------------------------
|
|
214
|
+
// Database handle helpers (short-lived, caller closes)
|
|
215
|
+
// ---------------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Open a short-lived read/write handle to the GLOBAL signaldock.db.
|
|
219
|
+
* Caller MUST call `db.close()` when done.
|
|
220
|
+
*
|
|
221
|
+
* @task T355
|
|
222
|
+
* @epic T310
|
|
223
|
+
*/
|
|
224
|
+
function openGlobalDb(): DatabaseSync {
|
|
225
|
+
const dbPath = getGlobalSignaldockDbPath();
|
|
226
|
+
const db = new DatabaseSync(dbPath);
|
|
75
227
|
db.exec('PRAGMA foreign_keys = ON');
|
|
76
228
|
db.exec('PRAGMA journal_mode = WAL');
|
|
77
229
|
return db;
|
|
78
230
|
}
|
|
79
231
|
|
|
80
232
|
/**
|
|
81
|
-
*
|
|
82
|
-
*
|
|
233
|
+
* Open a short-lived read/write handle to the PROJECT conduit.db.
|
|
234
|
+
* Caller MUST call `db.close()` when done.
|
|
235
|
+
*
|
|
236
|
+
* @param projectRoot - Absolute path to the project root directory.
|
|
237
|
+
* @task T355
|
|
238
|
+
* @epic T310
|
|
239
|
+
*/
|
|
240
|
+
function openConduitDb(projectRoot: string): DatabaseSync {
|
|
241
|
+
const dbPath = getConduitDbPath(projectRoot);
|
|
242
|
+
const db = new DatabaseSync(dbPath);
|
|
243
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
244
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
245
|
+
return db;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ---------------------------------------------------------------------------
|
|
249
|
+
// junction table sync (global signaldock.db only)
|
|
250
|
+
// ---------------------------------------------------------------------------
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Sync capabilities/skills to junction tables in global signaldock.db.
|
|
254
|
+
* Junction tables are the SSoT — JSON columns are a materialized cache.
|
|
255
|
+
*
|
|
256
|
+
* @param db - Open handle to global signaldock.db.
|
|
257
|
+
* @param agentUuid - The `id` (UUID primary key) from the agents row.
|
|
258
|
+
* @param capabilities - Array of capability slugs.
|
|
259
|
+
* @param skills - Array of skill slugs.
|
|
260
|
+
* @task T355
|
|
261
|
+
* @epic T310
|
|
83
262
|
*/
|
|
84
263
|
function syncJunctionTables(
|
|
85
264
|
db: DatabaseSync,
|
|
@@ -112,128 +291,524 @@ function syncJunctionTables(
|
|
|
112
291
|
}
|
|
113
292
|
}
|
|
114
293
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
294
|
+
// ---------------------------------------------------------------------------
|
|
295
|
+
// Module-level cross-DB functions (spec §3.5)
|
|
296
|
+
// ---------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Cross-DB agent lookup. Opens both the global signaldock.db and the
|
|
300
|
+
* current project's conduit.db, joins project_agent_refs ⨝ agents by
|
|
301
|
+
* agentId, and returns the merged view.
|
|
302
|
+
*
|
|
303
|
+
* Default (includeGlobal=false): returns null if no project_agent_refs row
|
|
304
|
+
* exists, even if the agent exists globally. An enabled=0 row is also treated
|
|
305
|
+
* as absent.
|
|
306
|
+
*
|
|
307
|
+
* includeGlobal=true: returns the global agent with `projectRef: null` if no
|
|
308
|
+
* project attachment row exists.
|
|
309
|
+
*
|
|
310
|
+
* Dangling soft-FK detection: if a project_agent_refs row exists but the
|
|
311
|
+
* referenced global agent does not, logs a WARN and returns null.
|
|
312
|
+
*
|
|
313
|
+
* @param projectRoot - Absolute path to the project root directory.
|
|
314
|
+
* @param agentId - Agent business identifier.
|
|
315
|
+
* @param opts.includeGlobal - When true, returns global identity even without project ref.
|
|
316
|
+
* @returns Merged agent record or null if not found.
|
|
317
|
+
*
|
|
318
|
+
* @task T355
|
|
319
|
+
* @epic T310
|
|
320
|
+
*/
|
|
321
|
+
export function lookupAgent(
|
|
322
|
+
projectRoot: string,
|
|
323
|
+
agentId: string,
|
|
324
|
+
opts?: { includeGlobal?: boolean },
|
|
325
|
+
): AgentWithProjectOverride | null {
|
|
326
|
+
const includeGlobal = opts?.includeGlobal ?? false;
|
|
327
|
+
|
|
328
|
+
const globalDb = openGlobalDb();
|
|
329
|
+
const conduitDb = openConduitDb(projectRoot);
|
|
330
|
+
|
|
331
|
+
try {
|
|
332
|
+
const agentRow = globalDb.prepare('SELECT * FROM agents WHERE agent_id = ?').get(agentId) as
|
|
333
|
+
| AgentDbRow
|
|
334
|
+
| undefined;
|
|
335
|
+
|
|
336
|
+
const refRow = conduitDb
|
|
337
|
+
.prepare('SELECT * FROM project_agent_refs WHERE agent_id = ?')
|
|
338
|
+
.get(agentId) as ProjectAgentRefRow | undefined;
|
|
339
|
+
|
|
340
|
+
// Dangling soft-FK: ref exists in conduit but not in global
|
|
341
|
+
if (refRow && !agentRow) {
|
|
342
|
+
console.warn(
|
|
343
|
+
`[agent-registry-accessor] WARN: dangling project_agent_refs row for agent_id="${agentId}". ` +
|
|
344
|
+
`No matching row in global signaldock.db:agents. Row will be ignored.`,
|
|
345
|
+
);
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
118
348
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
349
|
+
// Agent does not exist globally at all
|
|
350
|
+
if (!agentRow) return null;
|
|
351
|
+
|
|
352
|
+
if (!includeGlobal) {
|
|
353
|
+
// INNER JOIN semantics: must have a project ref with enabled=1
|
|
354
|
+
if (!refRow || refRow.enabled === 0) return null;
|
|
355
|
+
return mergeToAgentWithOverride(agentRow, refRow);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// includeGlobal=true: return global agent; populate projectRef only when enabled=1
|
|
359
|
+
const effectiveRef = refRow && refRow.enabled === 1 ? refRow : null;
|
|
360
|
+
return mergeToAgentWithOverride(agentRow, effectiveRef);
|
|
361
|
+
} finally {
|
|
362
|
+
globalDb.close();
|
|
363
|
+
conduitDb.close();
|
|
122
364
|
}
|
|
365
|
+
}
|
|
123
366
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
367
|
+
/**
|
|
368
|
+
* Lists agents visible in the current project.
|
|
369
|
+
*
|
|
370
|
+
* Default (includeGlobal=false): INNER JOIN on project_agent_refs (enabled=1)
|
|
371
|
+
* — only agents explicitly attached to this project are returned.
|
|
372
|
+
*
|
|
373
|
+
* includeGlobal=true: returns all global agents regardless of project
|
|
374
|
+
* attachment, with projectRef populated for attached ones and null for the rest.
|
|
375
|
+
*
|
|
376
|
+
* includeDisabled=true: also returns agents with enabled=0 in project_agent_refs.
|
|
377
|
+
* Ignored when includeGlobal=true (all global agents are returned regardless).
|
|
378
|
+
*
|
|
379
|
+
* @param projectRoot - Absolute path to the project root directory.
|
|
380
|
+
* @param opts.includeGlobal - Include all global agents (bypasses project filter).
|
|
381
|
+
* @param opts.includeDisabled - Include agents with enabled=0 in project_agent_refs.
|
|
382
|
+
* @returns Array of merged agent records.
|
|
383
|
+
*
|
|
384
|
+
* @task T355
|
|
385
|
+
* @epic T310
|
|
386
|
+
*/
|
|
387
|
+
export function listAgentsForProject(
|
|
388
|
+
projectRoot: string,
|
|
389
|
+
opts?: { includeGlobal?: boolean; includeDisabled?: boolean },
|
|
390
|
+
): AgentWithProjectOverride[] {
|
|
391
|
+
const includeGlobal = opts?.includeGlobal ?? false;
|
|
392
|
+
const includeDisabled = opts?.includeDisabled ?? false;
|
|
132
393
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const existing = db
|
|
136
|
-
.prepare('SELECT id FROM agents WHERE agent_id = ?')
|
|
137
|
-
.get(credential.agentId) as { id: string } | undefined;
|
|
394
|
+
const globalDb = openGlobalDb();
|
|
395
|
+
const conduitDb = openConduitDb(projectRoot);
|
|
138
396
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
397
|
+
try {
|
|
398
|
+
const allAgents = globalDb
|
|
399
|
+
.prepare('SELECT * FROM agents ORDER BY name ASC')
|
|
400
|
+
.all() as unknown as AgentDbRow[];
|
|
401
|
+
|
|
402
|
+
const allRefs = conduitDb
|
|
403
|
+
.prepare('SELECT * FROM project_agent_refs')
|
|
404
|
+
.all() as unknown as ProjectAgentRefRow[];
|
|
405
|
+
|
|
406
|
+
// Build a map from agentId → ref row for O(1) lookup during join
|
|
407
|
+
const refMap = new Map<string, ProjectAgentRefRow>();
|
|
408
|
+
for (const ref of allRefs) {
|
|
409
|
+
refMap.set(ref.agent_id, ref);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const result: AgentWithProjectOverride[] = [];
|
|
413
|
+
|
|
414
|
+
for (const agentRow of allAgents) {
|
|
415
|
+
const ref = refMap.get(agentRow.agent_id);
|
|
416
|
+
|
|
417
|
+
if (includeGlobal) {
|
|
418
|
+
// Return all global agents; populate projectRef only for attached ones
|
|
419
|
+
const effectiveRef = ref && ref.enabled === 1 ? ref : null;
|
|
420
|
+
result.push(mergeToAgentWithOverride(agentRow, effectiveRef));
|
|
421
|
+
} else {
|
|
422
|
+
// INNER JOIN: only agents with a project ref row
|
|
423
|
+
if (!ref) continue;
|
|
424
|
+
if (!includeDisabled && ref.enabled === 0) continue;
|
|
425
|
+
result.push(mergeToAgentWithOverride(agentRow, ref));
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
return result;
|
|
430
|
+
} finally {
|
|
431
|
+
globalDb.close();
|
|
432
|
+
conduitDb.close();
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Creates a new agent: writes identity row to global signaldock.db AND attaches
|
|
438
|
+
* it to the current project via conduit.db:project_agent_refs.
|
|
439
|
+
*
|
|
440
|
+
* Write order: global first, then project ref. If the project ref write fails,
|
|
441
|
+
* the global row remains (recoverable via `cleo agent attach <id>`).
|
|
442
|
+
*
|
|
443
|
+
* API key derivation: HMAC-SHA256(machineKey || globalSalt, agentId) per ADR-037 §5.
|
|
444
|
+
*
|
|
445
|
+
* @param projectRoot - Absolute path to the project root directory.
|
|
446
|
+
* @param spec - Agent creation spec (without createdAt/updatedAt).
|
|
447
|
+
* @returns Merged agent record including the new project ref.
|
|
448
|
+
*
|
|
449
|
+
* @task T355
|
|
450
|
+
* @epic T310
|
|
451
|
+
*/
|
|
452
|
+
export function createProjectAgent(
|
|
453
|
+
projectRoot: string,
|
|
454
|
+
spec: Omit<AgentCredential, 'createdAt' | 'updatedAt'>,
|
|
455
|
+
): AgentWithProjectOverride {
|
|
456
|
+
ensureGlobalSignaldockDb();
|
|
457
|
+
ensureConduitDb(projectRoot);
|
|
458
|
+
|
|
459
|
+
const nowTs = Math.floor(Date.now() / 1000);
|
|
460
|
+
const nowIso = new Date(nowTs * 1000).toISOString();
|
|
461
|
+
|
|
462
|
+
// Derive API key using the T310 KDF
|
|
463
|
+
const machineKey = readMachineKey();
|
|
464
|
+
const globalSalt = getGlobalSalt();
|
|
465
|
+
const derivedKey = deriveApiKey({
|
|
466
|
+
machineKey,
|
|
467
|
+
globalSalt,
|
|
468
|
+
agentId: spec.agentId,
|
|
469
|
+
});
|
|
470
|
+
// Store as hex string in the encrypted column
|
|
471
|
+
const apiKeyEncrypted = derivedKey.toString('hex');
|
|
472
|
+
|
|
473
|
+
const globalDb = openGlobalDb();
|
|
474
|
+
try {
|
|
475
|
+
const existing = globalDb
|
|
476
|
+
.prepare('SELECT id FROM agents WHERE agent_id = ?')
|
|
477
|
+
.get(spec.agentId) as { id: string } | undefined;
|
|
478
|
+
|
|
479
|
+
let agentUuid: string;
|
|
480
|
+
|
|
481
|
+
if (!existing) {
|
|
482
|
+
agentUuid = crypto.randomUUID();
|
|
483
|
+
globalDb
|
|
484
|
+
.prepare(
|
|
142
485
|
`INSERT INTO agents (id, agent_id, name, class, privacy_tier, capabilities, skills,
|
|
143
486
|
transport_type, api_key_encrypted, api_base_url, classification, transport_config,
|
|
144
|
-
is_active, last_used_at, status, created_at, updated_at)
|
|
145
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'online', ?,
|
|
146
|
-
)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
JSON.stringify(
|
|
154
|
-
|
|
487
|
+
is_active, last_used_at, status, created_at, updated_at, requires_reauth)
|
|
488
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'online', ?, ?, 0)`,
|
|
489
|
+
)
|
|
490
|
+
.run(
|
|
491
|
+
agentUuid,
|
|
492
|
+
spec.agentId,
|
|
493
|
+
spec.displayName,
|
|
494
|
+
spec.classification ?? 'custom',
|
|
495
|
+
spec.privacyTier,
|
|
496
|
+
JSON.stringify(spec.capabilities),
|
|
497
|
+
JSON.stringify(spec.skills),
|
|
498
|
+
spec.transportType ?? 'http',
|
|
155
499
|
apiKeyEncrypted,
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
JSON.stringify(
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
? Math.floor(new Date(credential.lastUsedAt).getTime() / 1000)
|
|
162
|
-
: null,
|
|
500
|
+
spec.apiBaseUrl,
|
|
501
|
+
spec.classification ?? null,
|
|
502
|
+
JSON.stringify(spec.transportConfig),
|
|
503
|
+
spec.isActive ? 1 : 0,
|
|
504
|
+
spec.lastUsedAt ? Math.floor(new Date(spec.lastUsedAt).getTime() / 1000) : null,
|
|
163
505
|
nowTs,
|
|
164
506
|
nowTs,
|
|
165
507
|
);
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
508
|
+
syncJunctionTables(globalDb, agentUuid, spec.capabilities, spec.skills);
|
|
509
|
+
} else {
|
|
510
|
+
agentUuid = existing.id;
|
|
511
|
+
// Update identity in global DB (idempotent re-register)
|
|
512
|
+
globalDb
|
|
513
|
+
.prepare(
|
|
169
514
|
`UPDATE agents SET name = ?, class = ?, privacy_tier = ?, capabilities = ?, skills = ?,
|
|
170
515
|
transport_type = ?, api_key_encrypted = ?, api_base_url = ?, classification = ?,
|
|
171
516
|
transport_config = ?, is_active = ?, updated_at = ? WHERE agent_id = ?`,
|
|
172
|
-
)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
JSON.stringify(
|
|
178
|
-
|
|
517
|
+
)
|
|
518
|
+
.run(
|
|
519
|
+
spec.displayName,
|
|
520
|
+
spec.classification ?? 'custom',
|
|
521
|
+
spec.privacyTier,
|
|
522
|
+
JSON.stringify(spec.capabilities),
|
|
523
|
+
JSON.stringify(spec.skills),
|
|
524
|
+
spec.transportType ?? 'http',
|
|
179
525
|
apiKeyEncrypted,
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
JSON.stringify(
|
|
183
|
-
|
|
526
|
+
spec.apiBaseUrl,
|
|
527
|
+
spec.classification ?? null,
|
|
528
|
+
JSON.stringify(spec.transportConfig),
|
|
529
|
+
spec.isActive ? 1 : 0,
|
|
184
530
|
nowTs,
|
|
185
|
-
|
|
531
|
+
spec.agentId,
|
|
186
532
|
);
|
|
187
|
-
|
|
188
|
-
}
|
|
189
|
-
} finally {
|
|
190
|
-
db.close();
|
|
533
|
+
syncJunctionTables(globalDb, agentUuid, spec.capabilities, spec.skills);
|
|
191
534
|
}
|
|
535
|
+
} finally {
|
|
536
|
+
globalDb.close();
|
|
537
|
+
}
|
|
192
538
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
539
|
+
// Attach to project via conduit.db:project_agent_refs
|
|
540
|
+
const conduitDb = openConduitDb(projectRoot);
|
|
541
|
+
try {
|
|
542
|
+
const existingRef = conduitDb
|
|
543
|
+
.prepare('SELECT agent_id, enabled FROM project_agent_refs WHERE agent_id = ?')
|
|
544
|
+
.get(spec.agentId) as { agent_id: string; enabled: number } | undefined;
|
|
545
|
+
|
|
546
|
+
if (!existingRef) {
|
|
547
|
+
conduitDb
|
|
548
|
+
.prepare(
|
|
549
|
+
`INSERT INTO project_agent_refs (agent_id, attached_at, role, capabilities_override, last_used_at, enabled)
|
|
550
|
+
VALUES (?, ?, NULL, NULL, NULL, 1)`,
|
|
551
|
+
)
|
|
552
|
+
.run(spec.agentId, nowIso);
|
|
553
|
+
} else if (existingRef.enabled === 0) {
|
|
554
|
+
// Re-enable a previously detached agent
|
|
555
|
+
conduitDb
|
|
556
|
+
.prepare(`UPDATE project_agent_refs SET enabled = 1, attached_at = ? WHERE agent_id = ?`)
|
|
557
|
+
.run(nowIso, spec.agentId);
|
|
558
|
+
}
|
|
559
|
+
// If enabled=1 already, leave the existing ref intact
|
|
560
|
+
} finally {
|
|
561
|
+
conduitDb.close();
|
|
196
562
|
}
|
|
197
563
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
564
|
+
const result = lookupAgent(projectRoot, spec.agentId, { includeGlobal: false });
|
|
565
|
+
if (!result) {
|
|
566
|
+
throw new Error(`createProjectAgent: failed to retrieve agent after creation: ${spec.agentId}`);
|
|
567
|
+
}
|
|
568
|
+
return result;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// ---------------------------------------------------------------------------
|
|
572
|
+
// Standalone attach / detach helpers (T364)
|
|
573
|
+
// ---------------------------------------------------------------------------
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Attach a globally-registered agent to the current project.
|
|
577
|
+
*
|
|
578
|
+
* Creates a `project_agent_refs` row with `enabled=1`. If a row already exists
|
|
579
|
+
* with `enabled=0`, it is re-enabled (idempotent). If the row already has
|
|
580
|
+
* `enabled=1`, this is a no-op.
|
|
581
|
+
*
|
|
582
|
+
* The agent MUST already exist in the global `signaldock.db:agents` table.
|
|
583
|
+
* This function does NOT validate global existence — callers must check via
|
|
584
|
+
* `lookupAgent(..., { includeGlobal: true })` first.
|
|
585
|
+
*
|
|
586
|
+
* @param projectRoot - Absolute path to the project root directory.
|
|
587
|
+
* @param agentId - Agent business identifier.
|
|
588
|
+
* @param opts.role - Optional per-project role override (nullable).
|
|
589
|
+
* @param opts.capabilitiesOverride - Optional JSON blob of capability overrides (nullable).
|
|
590
|
+
*
|
|
591
|
+
* @task T364
|
|
592
|
+
* @epic T310
|
|
593
|
+
*/
|
|
594
|
+
export function attachAgentToProject(
|
|
595
|
+
projectRoot: string,
|
|
596
|
+
agentId: string,
|
|
597
|
+
opts?: { role?: string | null; capabilitiesOverride?: string | null },
|
|
598
|
+
): void {
|
|
599
|
+
const conduitDb = openConduitDb(projectRoot);
|
|
600
|
+
const nowIso = new Date().toISOString();
|
|
601
|
+
try {
|
|
602
|
+
const existingRef = conduitDb
|
|
603
|
+
.prepare('SELECT agent_id, enabled FROM project_agent_refs WHERE agent_id = ?')
|
|
604
|
+
.get(agentId) as { agent_id: string; enabled: number } | undefined;
|
|
605
|
+
|
|
606
|
+
if (!existingRef) {
|
|
607
|
+
conduitDb
|
|
608
|
+
.prepare(
|
|
609
|
+
`INSERT INTO project_agent_refs (agent_id, attached_at, role, capabilities_override, last_used_at, enabled)
|
|
610
|
+
VALUES (?, ?, ?, ?, NULL, 1)`,
|
|
611
|
+
)
|
|
612
|
+
.run(agentId, nowIso, opts?.role ?? null, opts?.capabilitiesOverride ?? null);
|
|
613
|
+
} else if (existingRef.enabled === 0) {
|
|
614
|
+
conduitDb
|
|
615
|
+
.prepare(
|
|
616
|
+
`UPDATE project_agent_refs SET enabled = 1, attached_at = ?, role = ?, capabilities_override = ? WHERE agent_id = ?`,
|
|
617
|
+
)
|
|
618
|
+
.run(nowIso, opts?.role ?? null, opts?.capabilitiesOverride ?? null, agentId);
|
|
209
619
|
}
|
|
620
|
+
// enabled=1 already — no-op
|
|
621
|
+
} finally {
|
|
622
|
+
conduitDb.close();
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Detach an agent from the current project by setting `project_agent_refs.enabled=0`.
|
|
628
|
+
*
|
|
629
|
+
* This is a soft-delete: the global `signaldock.db:agents` row is preserved.
|
|
630
|
+
* The agent can be re-attached later via `attachAgentToProject`.
|
|
631
|
+
*
|
|
632
|
+
* Returns `false` if no row exists in `project_agent_refs` for the given agentId
|
|
633
|
+
* (agent was never attached or was already fully removed).
|
|
634
|
+
*
|
|
635
|
+
* @param projectRoot - Absolute path to the project root directory.
|
|
636
|
+
* @param agentId - Agent business identifier.
|
|
637
|
+
* @returns `true` if a row was updated; `false` if no row existed.
|
|
638
|
+
*
|
|
639
|
+
* @task T364
|
|
640
|
+
* @epic T310
|
|
641
|
+
*/
|
|
642
|
+
export function detachAgentFromProject(projectRoot: string, agentId: string): boolean {
|
|
643
|
+
const conduitDb = openConduitDb(projectRoot);
|
|
644
|
+
try {
|
|
645
|
+
const ref = conduitDb
|
|
646
|
+
.prepare('SELECT agent_id FROM project_agent_refs WHERE agent_id = ?')
|
|
647
|
+
.get(agentId) as { agent_id: string } | undefined;
|
|
648
|
+
|
|
649
|
+
if (!ref) return false;
|
|
650
|
+
|
|
651
|
+
conduitDb.prepare('UPDATE project_agent_refs SET enabled = 0 WHERE agent_id = ?').run(agentId);
|
|
652
|
+
return true;
|
|
653
|
+
} finally {
|
|
654
|
+
conduitDb.close();
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* Get the raw `project_agent_refs` row for a given agentId in this project.
|
|
660
|
+
*
|
|
661
|
+
* Returns `null` if no row exists (agent not attached to this project).
|
|
662
|
+
*
|
|
663
|
+
* @param projectRoot - Absolute path to the project root directory.
|
|
664
|
+
* @param agentId - Agent business identifier.
|
|
665
|
+
* @returns Typed `ProjectAgentRef` object or `null`.
|
|
666
|
+
*
|
|
667
|
+
* @task T364
|
|
668
|
+
* @epic T310
|
|
669
|
+
*/
|
|
670
|
+
export function getProjectAgentRef(projectRoot: string, agentId: string): ProjectAgentRef | null {
|
|
671
|
+
const conduitDb = openConduitDb(projectRoot);
|
|
672
|
+
try {
|
|
673
|
+
const row = conduitDb
|
|
674
|
+
.prepare('SELECT * FROM project_agent_refs WHERE agent_id = ?')
|
|
675
|
+
.get(agentId) as ProjectAgentRefRow | undefined;
|
|
676
|
+
if (!row) return null;
|
|
677
|
+
return rowToProjectRef(row);
|
|
678
|
+
} finally {
|
|
679
|
+
conduitDb.close();
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// ---------------------------------------------------------------------------
|
|
684
|
+
// AgentRegistryAccessor class (backward-compatible wrapper)
|
|
685
|
+
// ---------------------------------------------------------------------------
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* AgentRegistryAccessor — backward-compatible CRUD wrapper around the
|
|
689
|
+
* cross-DB module-level functions.
|
|
690
|
+
*
|
|
691
|
+
* Post-T310 (ADR-037), the constructor accepts the project root (same
|
|
692
|
+
* semantics as `projectPath` in the pre-T310 version). All operations are
|
|
693
|
+
* routed through the cross-DB functions above.
|
|
694
|
+
*
|
|
695
|
+
* @task T355
|
|
696
|
+
* @epic T310
|
|
697
|
+
*/
|
|
698
|
+
export class AgentRegistryAccessor implements AgentRegistryAPI {
|
|
699
|
+
/**
|
|
700
|
+
* @param projectPath - Absolute path to the project root directory.
|
|
701
|
+
* Used as the `projectRoot` argument for all cross-DB operations.
|
|
702
|
+
* @task T355
|
|
703
|
+
* @epic T310
|
|
704
|
+
*/
|
|
705
|
+
constructor(private readonly projectPath: string) {}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Ensure both databases exist with their full schemas before any operation.
|
|
709
|
+
*
|
|
710
|
+
* @task T355
|
|
711
|
+
* @epic T310
|
|
712
|
+
*/
|
|
713
|
+
private ensureDbs(): void {
|
|
714
|
+
ensureGlobalSignaldockDb();
|
|
715
|
+
ensureConduitDb(this.projectPath);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Register (create or update) an agent in global signaldock.db and attach
|
|
720
|
+
* it to the current project via conduit.db:project_agent_refs.
|
|
721
|
+
*
|
|
722
|
+
* @param credential - Agent spec (without createdAt/updatedAt).
|
|
723
|
+
* @returns The registered agent credential.
|
|
724
|
+
* @task T355
|
|
725
|
+
* @epic T310
|
|
726
|
+
*/
|
|
727
|
+
async register(
|
|
728
|
+
credential: Omit<AgentCredential, 'createdAt' | 'updatedAt'>,
|
|
729
|
+
): Promise<AgentCredential> {
|
|
730
|
+
this.ensureDbs();
|
|
731
|
+
return createProjectAgent(this.projectPath, credential);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/**
|
|
735
|
+
* Get agent by agentId. Project-scoped by default (INNER JOIN).
|
|
736
|
+
*
|
|
737
|
+
* @param agentId - Agent business identifier.
|
|
738
|
+
* @param opts.includeGlobal - When true, returns global identity even without project ref.
|
|
739
|
+
* @returns The agent credential, or null if not found.
|
|
740
|
+
* @task T355
|
|
741
|
+
* @epic T310
|
|
742
|
+
*/
|
|
743
|
+
async get(agentId: string, opts?: { includeGlobal?: boolean }): Promise<AgentCredential | null> {
|
|
744
|
+
this.ensureDbs();
|
|
745
|
+
return lookupAgent(this.projectPath, agentId, opts);
|
|
210
746
|
}
|
|
211
747
|
|
|
748
|
+
/**
|
|
749
|
+
* Lists project-scoped agents (INNER JOIN on project_agent_refs with enabled=1).
|
|
750
|
+
*
|
|
751
|
+
* @param filter - Optional filter (active field maps to is_active in global agents).
|
|
752
|
+
* @returns Array of agent credentials visible in this project.
|
|
753
|
+
* @task T355
|
|
754
|
+
* @epic T310
|
|
755
|
+
*/
|
|
212
756
|
async list(filter?: AgentListFilter): Promise<AgentCredential[]> {
|
|
213
|
-
|
|
214
|
-
const
|
|
757
|
+
this.ensureDbs();
|
|
758
|
+
const results = listAgentsForProject(this.projectPath, { includeGlobal: false });
|
|
759
|
+
if (filter?.active !== undefined) {
|
|
760
|
+
return results.filter((a) => a.isActive === filter.active);
|
|
761
|
+
}
|
|
762
|
+
return results;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Lists all global agents (no project filter). Exposed for `--global` CLI flag.
|
|
767
|
+
*
|
|
768
|
+
* @param filter - Optional filter (active field maps to is_active in global agents).
|
|
769
|
+
* @returns Array of all globally registered agent credentials.
|
|
770
|
+
* @task T355
|
|
771
|
+
* @epic T310
|
|
772
|
+
*/
|
|
773
|
+
async listGlobal(filter?: AgentListFilter): Promise<AgentCredential[]> {
|
|
774
|
+
this.ensureDbs();
|
|
775
|
+
const globalDb = openGlobalDb();
|
|
215
776
|
try {
|
|
216
777
|
const rows =
|
|
217
778
|
filter?.active !== undefined
|
|
218
|
-
? (
|
|
219
|
-
.prepare('SELECT * FROM agents WHERE is_active = ?')
|
|
779
|
+
? (globalDb
|
|
780
|
+
.prepare('SELECT * FROM agents WHERE is_active = ? ORDER BY name ASC')
|
|
220
781
|
.all(filter.active ? 1 : 0) as unknown as AgentDbRow[])
|
|
221
|
-
: (
|
|
222
|
-
|
|
782
|
+
: (globalDb
|
|
783
|
+
.prepare('SELECT * FROM agents ORDER BY name ASC')
|
|
784
|
+
.all() as unknown as AgentDbRow[]);
|
|
785
|
+
return rows.map(rowToCredential);
|
|
223
786
|
} finally {
|
|
224
|
-
|
|
787
|
+
globalDb.close();
|
|
225
788
|
}
|
|
226
789
|
}
|
|
227
790
|
|
|
791
|
+
/**
|
|
792
|
+
* Update agent identity fields in global signaldock.db.
|
|
793
|
+
* Project-specific fields (role, capabilitiesOverride) require direct
|
|
794
|
+
* conduit.db manipulation (not yet exposed by this method).
|
|
795
|
+
*
|
|
796
|
+
* @param agentId - Agent business identifier.
|
|
797
|
+
* @param updates - Partial set of fields to update.
|
|
798
|
+
* @returns The updated agent credential (project-scoped lookup).
|
|
799
|
+
* @task T355
|
|
800
|
+
* @epic T310
|
|
801
|
+
*/
|
|
228
802
|
async update(
|
|
229
803
|
agentId: string,
|
|
230
804
|
updates: Partial<Omit<AgentCredential, 'agentId' | 'createdAt'>>,
|
|
231
805
|
): Promise<AgentCredential> {
|
|
232
|
-
|
|
806
|
+
this.ensureDbs();
|
|
807
|
+
const existing = await this.get(agentId, { includeGlobal: true });
|
|
233
808
|
if (!existing) throw new Error(`Agent not found: ${agentId}`);
|
|
234
809
|
|
|
235
810
|
const nowTs = Math.floor(Date.now() / 1000);
|
|
236
|
-
const
|
|
811
|
+
const globalDb = openGlobalDb();
|
|
237
812
|
try {
|
|
238
813
|
const sets: string[] = ['updated_at = ?'];
|
|
239
814
|
const params: unknown[] = [nowTs];
|
|
@@ -275,51 +850,125 @@ export class AgentRegistryAccessor implements AgentRegistryAPI {
|
|
|
275
850
|
params.push(updates.isActive ? 1 : 0);
|
|
276
851
|
}
|
|
277
852
|
if (updates.apiKey !== undefined) {
|
|
278
|
-
|
|
853
|
+
// Re-derive using new T310 KDF
|
|
854
|
+
const machineKey = readMachineKey();
|
|
855
|
+
const globalSalt = getGlobalSalt();
|
|
856
|
+
const derivedKey = deriveApiKey({ machineKey, globalSalt, agentId });
|
|
279
857
|
sets.push('api_key_encrypted = ?');
|
|
280
|
-
params.push(
|
|
858
|
+
params.push(derivedKey.toString('hex'));
|
|
281
859
|
}
|
|
282
860
|
|
|
283
861
|
params.push(agentId);
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
862
|
+
globalDb
|
|
863
|
+
.prepare(`UPDATE agents SET ${sets.join(', ')} WHERE agent_id = ?`)
|
|
864
|
+
.run(...(params as Array<string | number | null>));
|
|
287
865
|
|
|
288
866
|
// Sync junction tables if capabilities or skills changed
|
|
289
867
|
if (updates.capabilities !== undefined || updates.skills !== undefined) {
|
|
290
|
-
const agentRow =
|
|
291
|
-
id
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
868
|
+
const agentRow = globalDb
|
|
869
|
+
.prepare('SELECT id FROM agents WHERE agent_id = ?')
|
|
870
|
+
.get(agentId) as { id: string } | undefined;
|
|
871
|
+
if (agentRow) {
|
|
872
|
+
syncJunctionTables(
|
|
873
|
+
globalDb,
|
|
874
|
+
agentRow.id,
|
|
875
|
+
updates.capabilities ?? existing.capabilities,
|
|
876
|
+
updates.skills ?? existing.skills,
|
|
877
|
+
);
|
|
878
|
+
}
|
|
299
879
|
}
|
|
300
880
|
} finally {
|
|
301
|
-
|
|
881
|
+
globalDb.close();
|
|
302
882
|
}
|
|
303
883
|
|
|
304
|
-
const result = await this.get(agentId);
|
|
884
|
+
const result = await this.get(agentId, { includeGlobal: true });
|
|
305
885
|
if (!result) throw new Error(`Agent not found after update: ${agentId}`);
|
|
306
886
|
return result;
|
|
307
887
|
}
|
|
308
888
|
|
|
889
|
+
/**
|
|
890
|
+
* Remove agent from current project (sets project_agent_refs.enabled=0).
|
|
891
|
+
* Does NOT delete from global signaldock.db (per ADR-037 §6 / Q4=C).
|
|
892
|
+
*
|
|
893
|
+
* @param agentId - Agent business identifier.
|
|
894
|
+
* @task T355
|
|
895
|
+
* @epic T310
|
|
896
|
+
*/
|
|
309
897
|
async remove(agentId: string): Promise<void> {
|
|
310
|
-
|
|
311
|
-
if (!existing) throw new Error(`Agent not found: ${agentId}`);
|
|
898
|
+
this.ensureDbs();
|
|
312
899
|
|
|
313
|
-
const
|
|
900
|
+
const conduitDb = openConduitDb(this.projectPath);
|
|
314
901
|
try {
|
|
315
|
-
|
|
902
|
+
const ref = conduitDb
|
|
903
|
+
.prepare('SELECT agent_id FROM project_agent_refs WHERE agent_id = ?')
|
|
904
|
+
.get(agentId) as { agent_id: string } | undefined;
|
|
905
|
+
if (!ref) {
|
|
906
|
+
throw new Error(`Agent not found in current project: ${agentId}`);
|
|
907
|
+
}
|
|
908
|
+
conduitDb
|
|
909
|
+
.prepare('UPDATE project_agent_refs SET enabled = 0 WHERE agent_id = ?')
|
|
910
|
+
.run(agentId);
|
|
316
911
|
} finally {
|
|
317
|
-
|
|
912
|
+
conduitDb.close();
|
|
318
913
|
}
|
|
319
914
|
}
|
|
320
915
|
|
|
916
|
+
/**
|
|
917
|
+
* Remove agent from global signaldock.db.
|
|
918
|
+
* Requires explicit opt-in. Warns if cross-project refs may exist.
|
|
919
|
+
*
|
|
920
|
+
* @param agentId - Agent business identifier.
|
|
921
|
+
* @param opts.force - Skip the global-delete warning when refs exist.
|
|
922
|
+
* @task T355
|
|
923
|
+
* @epic T310
|
|
924
|
+
*/
|
|
925
|
+
async removeGlobal(agentId: string, opts?: { force?: boolean }): Promise<void> {
|
|
926
|
+
this.ensureDbs();
|
|
927
|
+
const globalDb = openGlobalDb();
|
|
928
|
+
try {
|
|
929
|
+
const existing = globalDb.prepare('SELECT id FROM agents WHERE agent_id = ?').get(agentId) as
|
|
930
|
+
| { id: string }
|
|
931
|
+
| undefined;
|
|
932
|
+
if (!existing) {
|
|
933
|
+
throw new Error(`Agent not found globally: ${agentId}`);
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
if (!opts?.force) {
|
|
937
|
+
// Best-effort cross-project scan: check the current project's conduit.db
|
|
938
|
+
const conduitDb = openConduitDb(this.projectPath);
|
|
939
|
+
try {
|
|
940
|
+
const ref = conduitDb
|
|
941
|
+
.prepare('SELECT agent_id FROM project_agent_refs WHERE agent_id = ? AND enabled = 1')
|
|
942
|
+
.get(agentId) as { agent_id: string } | undefined;
|
|
943
|
+
if (ref) {
|
|
944
|
+
throw new Error(
|
|
945
|
+
`Agent "${agentId}" still has project references in the current project. ` +
|
|
946
|
+
`Use removeGlobal(id, { force: true }) to skip this check.`,
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
} finally {
|
|
950
|
+
conduitDb.close();
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
globalDb.prepare('DELETE FROM agents WHERE agent_id = ?').run(agentId);
|
|
955
|
+
} finally {
|
|
956
|
+
globalDb.close();
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* Rotate API key via cloud endpoint and re-encrypt with the new T310 KDF
|
|
962
|
+
* in global signaldock.db.
|
|
963
|
+
*
|
|
964
|
+
* @param agentId - Agent business identifier.
|
|
965
|
+
* @returns Object with agentId and a redacted new API key string.
|
|
966
|
+
* @task T355
|
|
967
|
+
* @epic T310
|
|
968
|
+
*/
|
|
321
969
|
async rotateKey(agentId: string): Promise<{ agentId: string; newApiKey: string }> {
|
|
322
|
-
|
|
970
|
+
this.ensureDbs();
|
|
971
|
+
const credential = await this.get(agentId, { includeGlobal: true });
|
|
323
972
|
if (!credential) throw new Error(`Agent not found: ${agentId}`);
|
|
324
973
|
|
|
325
974
|
const response = await fetch(`${credential.apiBaseUrl}/agents/${agentId}/rotate-key`, {
|
|
@@ -338,38 +987,96 @@ export class AgentRegistryAccessor implements AgentRegistryAPI {
|
|
|
338
987
|
const newApiKey = data.data?.apiKey;
|
|
339
988
|
if (!newApiKey) throw new Error('Cloud API did not return a new API key');
|
|
340
989
|
|
|
341
|
-
|
|
990
|
+
// Re-derive and store using T310 KDF
|
|
991
|
+
const machineKey = readMachineKey();
|
|
992
|
+
const globalSalt = getGlobalSalt();
|
|
993
|
+
const derivedKey = deriveApiKey({ machineKey, globalSalt, agentId });
|
|
994
|
+
const nowTs = Math.floor(Date.now() / 1000);
|
|
995
|
+
|
|
996
|
+
const globalDb = openGlobalDb();
|
|
997
|
+
try {
|
|
998
|
+
globalDb
|
|
999
|
+
.prepare(
|
|
1000
|
+
'UPDATE agents SET api_key_encrypted = ?, updated_at = ?, requires_reauth = 0 WHERE agent_id = ?',
|
|
1001
|
+
)
|
|
1002
|
+
.run(derivedKey.toString('hex'), nowTs, agentId);
|
|
1003
|
+
} finally {
|
|
1004
|
+
globalDb.close();
|
|
1005
|
+
}
|
|
1006
|
+
|
|
342
1007
|
return { agentId, newApiKey: `${newApiKey.substring(0, 8)}...rotated` };
|
|
343
1008
|
}
|
|
344
1009
|
|
|
1010
|
+
/**
|
|
1011
|
+
* Get the most recently used active agent in the current project.
|
|
1012
|
+
*
|
|
1013
|
+
* @returns The most-recently-used active agent, or null if none found.
|
|
1014
|
+
* @task T355
|
|
1015
|
+
* @epic T310
|
|
1016
|
+
*/
|
|
345
1017
|
async getActive(): Promise<AgentCredential | null> {
|
|
346
|
-
|
|
347
|
-
|
|
1018
|
+
this.ensureDbs();
|
|
1019
|
+
|
|
1020
|
+
const globalDb = openGlobalDb();
|
|
1021
|
+
const conduitDb = openConduitDb(this.projectPath);
|
|
348
1022
|
try {
|
|
349
|
-
|
|
1023
|
+
// Get all project-attached, enabled agent IDs ordered by project last_used_at
|
|
1024
|
+
const enabledRefs = conduitDb
|
|
1025
|
+
.prepare(
|
|
1026
|
+
'SELECT agent_id, last_used_at FROM project_agent_refs WHERE enabled = 1 ORDER BY last_used_at DESC',
|
|
1027
|
+
)
|
|
1028
|
+
.all() as unknown as Array<{ agent_id: string; last_used_at: string | null }>;
|
|
1029
|
+
|
|
1030
|
+
for (const ref of enabledRefs) {
|
|
1031
|
+
const agentRow = globalDb
|
|
1032
|
+
.prepare('SELECT * FROM agents WHERE agent_id = ? AND is_active = 1')
|
|
1033
|
+
.get(ref.agent_id) as AgentDbRow | undefined;
|
|
1034
|
+
if (agentRow) return rowToCredential(agentRow);
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
// Fall back to global last_used_at if no project-local activity recorded
|
|
1038
|
+
const row = globalDb
|
|
350
1039
|
.prepare(
|
|
351
1040
|
'SELECT * FROM agents WHERE is_active = 1 ORDER BY last_used_at DESC, created_at DESC LIMIT 1',
|
|
352
1041
|
)
|
|
353
1042
|
.get() as AgentDbRow | undefined;
|
|
354
1043
|
if (!row) return null;
|
|
355
|
-
return rowToCredential(row
|
|
1044
|
+
return rowToCredential(row);
|
|
356
1045
|
} finally {
|
|
357
|
-
|
|
1046
|
+
globalDb.close();
|
|
1047
|
+
conduitDb.close();
|
|
358
1048
|
}
|
|
359
1049
|
}
|
|
360
1050
|
|
|
1051
|
+
/**
|
|
1052
|
+
* Update last_used_at in both global signaldock.db:agents and
|
|
1053
|
+
* conduit.db:project_agent_refs.
|
|
1054
|
+
*
|
|
1055
|
+
* @param agentId - Agent business identifier.
|
|
1056
|
+
* @task T355
|
|
1057
|
+
* @epic T310
|
|
1058
|
+
*/
|
|
361
1059
|
async markUsed(agentId: string): Promise<void> {
|
|
362
|
-
|
|
1060
|
+
this.ensureDbs();
|
|
363
1061
|
const nowTs = Math.floor(Date.now() / 1000);
|
|
364
|
-
const
|
|
1062
|
+
const nowIso = new Date(nowTs * 1000).toISOString();
|
|
1063
|
+
|
|
1064
|
+
const globalDb = openGlobalDb();
|
|
365
1065
|
try {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
nowTs,
|
|
369
|
-
|
|
370
|
-
);
|
|
1066
|
+
globalDb
|
|
1067
|
+
.prepare('UPDATE agents SET last_used_at = ?, updated_at = ? WHERE agent_id = ?')
|
|
1068
|
+
.run(nowTs, nowTs, agentId);
|
|
1069
|
+
} finally {
|
|
1070
|
+
globalDb.close();
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
const conduitDb = openConduitDb(this.projectPath);
|
|
1074
|
+
try {
|
|
1075
|
+
conduitDb
|
|
1076
|
+
.prepare('UPDATE project_agent_refs SET last_used_at = ? WHERE agent_id = ?')
|
|
1077
|
+
.run(nowIso, agentId);
|
|
371
1078
|
} finally {
|
|
372
|
-
|
|
1079
|
+
conduitDb.close();
|
|
373
1080
|
}
|
|
374
1081
|
}
|
|
375
1082
|
}
|