11import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session' ;
2- import { sql , type Transaction } from 'kysely' ;
2+ import { sql , type Kysely , type Transaction } from 'kysely' ;
33import {
44 type AgentRecord ,
55 type CreateAgentInput ,
99 type ListAgentsInput ,
1010 type UpdateAgentInput ,
1111} from '../db/agentStore' ;
12+ import { PostgresAgentStore } from '../db/postgres/agent-store/PostgresAgentStore' ;
1213import type { Database } from '../db/postgres/types' ;
1314import {
1415 TrueFoundryServiceFoundryServerClient ,
@@ -34,57 +35,79 @@ function toPutRemoteAgentPayload({
3435 } ;
3536}
3637
37- type TrueFoundryAgentInner < TTransaction > = IAgentStore < TTransaction > & {
38- withTransaction < T > ( fn : ( transaction : TTransaction ) => Promise < T > ) : Promise < T > ;
39- } ;
40-
4138/**
42- * create: createDB(null) → putRemote → updateDB(external_id) | on put/update fail → deleteDB (+ deleteRemote if put ok)
43- * update: lock → get → putRemote(new) → updateDB | on DB fail → putRemote(old) | both fail → AggregateError
44- * delete: lock → get → deleteRemote(404 ok) → deleteDB
39+ * Postgres agent store that keeps a matching ServiceFoundry remote agent in sync.
40+ *
41+ * DB and ServiceFoundry are not one atomic transaction. Cleanup on failure is
42+ * best-effort: a delete/restore step can itself fail, leaving temporary SF↔DB skew
43+ * (orphan remote, orphan local row, or mismatched manifest). create / update /
44+ * delete stay retryable — a later successful call is expected to recover.
45+ *
46+ * create
47+ * Happy path: insert local row (external_id null) → put remote → set external_id.
48+ * Name clash on insert: throw; no remote call.
49+ * putRemote fails: delete local row; rethrow.
50+ * update(external_id) fails after put: delete remote (if put returned an id), then
51+ * delete local; if cleanup also fails, AggregateError (primary + cleanup errors).
52+ *
53+ * update (manifest)
54+ * Happy path: lock → load row → put remote (new manifest) → write local.
55+ * Missing row: return undefined (no remote call).
56+ * putRemote fails: leave local unchanged; rethrow.
57+ * local write fails after put: best-effort putRemote(old manifest); if restore fails,
58+ * AggregateError; if restore ok, rethrow the DB error (local still old, remote restored).
59+ * external_id-only patches skip ServiceFoundry and go straight to the inner store.
60+ *
61+ * delete
62+ * Happy path: lock → load row → delete remote when external_id is set → delete local.
63+ * Missing row or null external_id: skip remote; still delete local (idempotent).
64+ * remote delete fails: do not delete local; rethrow (local kept so retry can finish).
4565 */
46- export class TrueFoundryAgentStore <
47- TTransaction extends Transaction < Database > = Transaction < Database > ,
48- > implements IAgentStore < TTransaction > {
49- readonly #inner: TrueFoundryAgentInner < TTransaction > ;
66+ export class TrueFoundryAgentStore implements IAgentStore < Transaction < Database > > {
67+ readonly #inner: PostgresAgentStore ;
5068 readonly #client: TrueFoundryServiceFoundryServerClient ;
5169 readonly #accessToken: string ;
70+ readonly #db: Kysely < Database > ;
5271
5372 constructor ( input : {
54- inner : TrueFoundryAgentInner < TTransaction > ;
73+ inner : PostgresAgentStore ;
5574 client : TrueFoundryServiceFoundryServerClient ;
5675 accessToken : string ;
76+ db : Kysely < Database > ;
5777 } ) {
5878 this . #inner = input . inner ;
5979 this . #client = input . client ;
6080 this . #accessToken = input . accessToken ;
81+ this . #db = input . db ;
6182 }
6283
63- listAgents ( input : ListAgentsInput , transaction ?: TTransaction ) : Promise < AgentRecord [ ] > {
84+ listAgents ( input : ListAgentsInput , transaction ?: Transaction < Database > ) : Promise < AgentRecord [ ] > {
6485 return this . #inner. listAgents ( input , transaction ) ;
6586 }
6687
67- getAgent ( input : GetAgentInput , transaction ?: TTransaction ) : Promise < AgentRecord | undefined > {
88+ getAgent ( input : GetAgentInput , transaction ?: Transaction < Database > ) : Promise < AgentRecord | undefined > {
6889 return this . #inner. getAgent ( input , transaction ) ;
6990 }
7091
71- // Serializes updates for this tenant ID and agent id.
72- // Prevents concurrent MCP writes from desyncing the remote agent.
92+ // Takes a Postgres transaction advisory lock for this tenant + agent id so concurrent
93+ // update/delete cannot desync ServiceFoundry MCP grants. The lock only lasts for the
94+ // lifetime of a DB transaction: if the caller passed one, use it; otherwise open a
95+ // short transaction on db just for this critical section.
7396 #withUpdateLock< T > (
7497 input : { tenant_id : string ; id : string } ,
75- transaction : TTransaction | undefined ,
76- fn : ( transaction : TTransaction ) => Promise < T > ,
98+ transaction : Transaction < Database > | undefined ,
99+ fn : ( transaction : Transaction < Database > ) => Promise < T > ,
77100 ) : Promise < T > {
78- const run = async ( txn : TTransaction ) => {
101+ const run = async ( txn : Transaction < Database > ) => {
79102 const key = `tf:agent:${ input . tenant_id } :${ input . id } ` ;
80103 await sql `SELECT pg_advisory_xact_lock(hashtext(${ key } ))` . execute ( txn ) ;
81104 return fn ( txn ) ;
82105 } ;
83- return transaction !== undefined ? run ( transaction ) : this . #inner . withTransaction ( run ) ;
106+ return transaction !== undefined ? run ( transaction ) : this . #db . transaction ( ) . execute ( run ) ;
84107 }
85108
86- async createAgent ( input : CreateAgentInput , transaction ?: TTransaction ) : Promise < AgentRecord > {
87- // Lets the DB unique constraint pick one winner for this tenant ID and name .
109+ async createAgent ( input : CreateAgentInput , transaction ?: Transaction < Database > ) : Promise < AgentRecord > {
110+ // Unique (tenant_id, name) picks one winner even when transaction is omitted (auto-commit inserts) .
88111 // Prevents concurrent requests from both creating the same remote agent.
89112 const created = await this . #inner. createAgent ( { ...input , external_id : null } , transaction ) ;
90113
@@ -123,7 +146,7 @@ export class TrueFoundryAgentStore<
123146 }
124147 }
125148
126- async updateAgent ( input : UpdateAgentInput , transaction ?: TTransaction ) : Promise < AgentRecord | undefined > {
149+ async updateAgent ( input : UpdateAgentInput , transaction ?: Transaction < Database > ) : Promise < AgentRecord | undefined > {
127150 const nextManifest = input . manifest ;
128151 if ( nextManifest === undefined ) {
129152 // No manifest means only `external_id` changed; pass through to the inner store.
@@ -169,7 +192,7 @@ export class TrueFoundryAgentStore<
169192 } ) ;
170193 }
171194
172- async deleteAgent ( input : DeleteAgentInput , transaction ?: TTransaction ) : Promise < void > {
195+ async deleteAgent ( input : DeleteAgentInput , transaction ?: Transaction < Database > ) : Promise < void > {
173196 return this . #withUpdateLock( input , transaction , async txn => {
174197 const previous = await this . #inner. getAgent ( { tenant_id : input . tenant_id , id : input . id } , txn ) ;
175198 if ( previous ?. external_id ) {
0 commit comments