@gaia-ai/core 0.0.1

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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -0
  3. package/dist/src/core/conductor-id.d.ts +1 -0
  4. package/dist/src/core/conductor-id.js +8 -0
  5. package/dist/src/core/exec.d.ts +41 -0
  6. package/dist/src/core/exec.js +75 -0
  7. package/dist/src/core/logger.d.ts +31 -0
  8. package/dist/src/core/logger.js +36 -0
  9. package/dist/src/core/shell.d.ts +21 -0
  10. package/dist/src/core/shell.js +46 -0
  11. package/dist/src/core/slug.d.ts +9 -0
  12. package/dist/src/core/slug.js +18 -0
  13. package/dist/src/index.d.ts +12 -0
  14. package/dist/src/index.js +7 -0
  15. package/dist/src/plugins/agent/agent.d.ts +52 -0
  16. package/dist/src/plugins/agent/agent.js +10 -0
  17. package/dist/src/plugins/auth/basic.d.ts +11 -0
  18. package/dist/src/plugins/auth/basic.js +35 -0
  19. package/dist/src/plugins/executor/executor.d.ts +92 -0
  20. package/dist/src/plugins/executor/executor.js +1 -0
  21. package/dist/src/plugins/plugins.d.ts +44 -0
  22. package/dist/src/plugins/plugins.js +16 -0
  23. package/dist/src/plugins/registry-exports.d.ts +6 -0
  24. package/dist/src/plugins/registry-exports.js +6 -0
  25. package/dist/src/plugins/remote/drupal.d.ts +34 -0
  26. package/dist/src/plugins/remote/drupal.js +334 -0
  27. package/dist/src/plugins/remote/fake.d.ts +95 -0
  28. package/dist/src/plugins/remote/fake.js +227 -0
  29. package/dist/src/plugins/remote/remote.d.ts +175 -0
  30. package/dist/src/plugins/remote/remote.js +1 -0
  31. package/dist/src/plugins/workspace/fake.d.ts +6 -0
  32. package/dist/src/plugins/workspace/fake.js +16 -0
  33. package/dist/src/plugins/workspace/git.d.ts +37 -0
  34. package/dist/src/plugins/workspace/git.js +89 -0
  35. package/dist/src/plugins/workspace/instructions.d.ts +6 -0
  36. package/dist/src/plugins/workspace/instructions.js +16 -0
  37. package/dist/src/plugins/workspace/workspace.d.ts +35 -0
  38. package/dist/src/plugins/workspace/workspace.js +1 -0
  39. package/dist/src/plugins-index.d.ts +1 -0
  40. package/dist/src/plugins-index.js +1 -0
  41. package/dist/src/types.d.ts +51 -0
  42. package/dist/src/types.js +1 -0
  43. package/package.json +33 -0
@@ -0,0 +1,34 @@
1
+ import type { JsonApiClient } from 'dropsh/plugin';
2
+ import type { RemotePlugin } from '../plugins.js';
3
+ import type { ActiveRun, ClaimedRun, ClaimOptions, ConductorRegistration, ConductorStatus, FinalizableRun, GaiaRemote, RunMetrics, RunWriteAttributes, Ticket, UncleanTicket } from './remote.js';
4
+ export declare class DrupalGaiaRemote implements GaiaRemote {
5
+ private readonly api;
6
+ constructor(api: JsonApiClient);
7
+ fetchActiveRuns(id: string): Promise<ActiveRun[]>;
8
+ activeRunCount(id: string): Promise<number>;
9
+ claimNext(c: ClaimOptions): Promise<ClaimedRun | null>;
10
+ getTicket(uuid: string): Promise<Ticket>;
11
+ getRunWorktree(uuid: string): Promise<string>;
12
+ getRunTicketIdentifier(uuid: string): Promise<string>;
13
+ getRunTicketBranchName(uuid: string): Promise<string>;
14
+ registerConductor(reg: ConductorRegistration): Promise<string>;
15
+ heartbeat(reg: ConductorRegistration, load: number, lease?: number): Promise<string>;
16
+ getConductorStatus(id: string): Promise<string | null>;
17
+ setConductorStatus(id: string, status: string): Promise<void>;
18
+ listConductors(owner?: 'me'): Promise<ConductorStatus[]>;
19
+ markRunning(uuid: string, attrs?: RunWriteAttributes): Promise<void>;
20
+ fetchFinalizableRuns(id: string): Promise<FinalizableRun[]>;
21
+ finalizeRun(uuid: string, log: string, metrics?: RunMetrics): Promise<void>;
22
+ fetchUncleanedTickets(id: string): Promise<UncleanTicket[]>;
23
+ closeTicket(uuid: string): Promise<void>;
24
+ markTicketCleanedUp(uuid: string): Promise<void>;
25
+ /**
26
+ * Absolute worktree path of the ticket's latest run (highest run id with a
27
+ * non-empty worktree_path), or '' when none — the cwd the cleanup command
28
+ * runs in. The conductor persists worktree_path on markRunning, so a done
29
+ * ticket's run carries the path even after the run closed.
30
+ */
31
+ private latestRunWorktree;
32
+ private projectUuid;
33
+ }
34
+ export declare function drupalRemote(): RemotePlugin;
@@ -0,0 +1,334 @@
1
+ import { resolveAuth } from 'dropsh';
2
+ import { createHttpClient, createJsonApiClient } from 'dropsh/plugin';
3
+ const ACTIVE = ['claimed', 'running'];
4
+ export class DrupalGaiaRemote {
5
+ api;
6
+ constructor(api) {
7
+ this.api = api;
8
+ }
9
+ async fetchActiveRuns(id) {
10
+ // The conductor identity `id` is the machine_id (hash of hostname+path).
11
+ // gaia_run links to its owning conductor via the `conductor_id` entity-ref;
12
+ // filter on the related conductor's `machine_id` (nested relationship filter).
13
+ const rows = await this.api
14
+ .collection('gaia_run')
15
+ .where('conductor_id.machine_id', '=', id)
16
+ .whereIn('state', ACTIVE)
17
+ .fields(['state', 'state_at_start', 'worktree_path'])
18
+ .page(100)
19
+ .list();
20
+ return Promise.all(rows.map(async (r) => ({
21
+ runUuid: r.id,
22
+ ticketUuid: r.rel('ticket_id') ?? '',
23
+ ticketIdentifier: await this.getRunTicketIdentifier(r.id),
24
+ branchName: await this.getRunTicketBranchName(r.id),
25
+ state: r.attr('state') ?? '',
26
+ stateAtStart: r.attr('state_at_start') ?? '',
27
+ worktreePath: r.attr('worktree_path') ?? '',
28
+ })));
29
+ }
30
+ async activeRunCount(id) {
31
+ // Filter on the related conductor's `machine_id` (nested relationship filter).
32
+ return this.api
33
+ .collection('gaia_run')
34
+ .where('conductor_id.machine_id', '=', id)
35
+ .whereIn('state', ACTIVE)
36
+ .fields(['drupal_internal__id'])
37
+ .page(100)
38
+ .count();
39
+ }
40
+ async claimNext(c) {
41
+ const res = (await this.api.post('gaia/claim-next', {
42
+ data: {
43
+ attributes: {
44
+ lease_seconds: c.leaseSeconds,
45
+ // Server (`ConductorResolverTrait`) narrows to the caller's conductor
46
+ // by the `machine_id` attribute; `c.conductorId` IS the machine_id.
47
+ machine_id: c.conductorId,
48
+ },
49
+ },
50
+ }));
51
+ if (!res?.data) {
52
+ return null;
53
+ }
54
+ const d = res.data;
55
+ const rawId = d.attributes?.drupal_internal__id;
56
+ if (rawId === undefined || rawId === null) {
57
+ throw new Error(`claimNext: missing drupal_internal__id on run ${d.id}`);
58
+ }
59
+ return {
60
+ runUuid: d.id,
61
+ runId: Number(rawId),
62
+ ticketUuid: d.relationships?.ticket_id?.data?.id ?? '',
63
+ stateAtStart: String(d.attributes?.state_at_start ?? ''),
64
+ // handler_id was dropped; the handler is the work the run does, i.e. the
65
+ // ticket state the run started in.
66
+ handler: String(d.attributes?.state_at_start ?? ''),
67
+ };
68
+ }
69
+ async getTicket(uuid) {
70
+ // The agent self-reads the ticket + its comments at run start (GAIA-112),
71
+ // so getTicket only needs the ticket's own attributes for dispatch — no
72
+ // ?include=comments sideload.
73
+ const doc = (await this.api.get(`gaia_ticket/gaia_ticket/${uuid}`));
74
+ const attrs = doc.data?.attributes ?? {};
75
+ const issueUrl = typeof attrs.origin === 'string' ? attrs.origin : undefined;
76
+ return {
77
+ uuid: doc.data?.id ?? uuid,
78
+ identifier: typeof attrs.identifier === 'string' ? attrs.identifier : uuid,
79
+ title: typeof attrs.title === 'string' ? attrs.title : '',
80
+ state: typeof attrs.state === 'string' ? attrs.state : '',
81
+ branchName: typeof attrs.branch_name === 'string' ? attrs.branch_name : '',
82
+ ...(typeof attrs.base_branch === 'string' && attrs.base_branch !== ''
83
+ ? { baseBranch: attrs.base_branch }
84
+ : {}),
85
+ ...(typeof attrs.effective_env_vars === 'string' &&
86
+ attrs.effective_env_vars !== ''
87
+ ? { effectiveEnvVars: attrs.effective_env_vars }
88
+ : {}),
89
+ ...(issueUrl ? { issueUrl } : {}),
90
+ };
91
+ }
92
+ async getRunWorktree(uuid) {
93
+ const r = await this.api.resource('gaia_run', uuid);
94
+ return r.attr('worktree_path') ?? '';
95
+ }
96
+ async getRunTicketIdentifier(uuid) {
97
+ const run = await this.api.resource('gaia_run', uuid);
98
+ const ticketUuid = run.rel('ticket_id');
99
+ if (!ticketUuid) {
100
+ return '';
101
+ }
102
+ const ticket = await this.api.resource('gaia_ticket', ticketUuid);
103
+ return ticket.attr('identifier') ?? '';
104
+ }
105
+ async getRunTicketBranchName(uuid) {
106
+ const run = await this.api.resource('gaia_run', uuid);
107
+ const ticketUuid = run.rel('ticket_id');
108
+ if (!ticketUuid) {
109
+ return '';
110
+ }
111
+ const ticket = await this.api.resource('gaia_ticket', ticketUuid);
112
+ return ticket.attr('branch_name') ?? '';
113
+ }
114
+ async registerConductor(reg) {
115
+ const r = await this.api.upsert('gaia_conductor', { path: 'machine_id', value: reg.id }, {
116
+ attributes: {
117
+ machine_id: reg.id,
118
+ status: 'online',
119
+ workspace_root: reg.workspace,
120
+ label: reg.label,
121
+ states: reg.states,
122
+ max_parallel: reg.max_parallel,
123
+ },
124
+ relationships: {
125
+ owner_user_id: {
126
+ data: { type: 'user--user', id: await this.api.me() },
127
+ },
128
+ project_id: {
129
+ data: {
130
+ type: 'gaia_project--gaia_project',
131
+ id: await this.projectUuid(reg.project),
132
+ },
133
+ },
134
+ },
135
+ });
136
+ return r.id; // drupal uuid
137
+ }
138
+ async heartbeat(reg, load, lease = 300) {
139
+ // Server-side upsert by machine_id (see HeartbeatResource): never 404s,
140
+ // heals a vanished registration, and returns the resulting status. Sending
141
+ // the full registration lets the server recreate the entity when missing.
142
+ const res = (await this.api.post('gaia/heartbeat', {
143
+ data: {
144
+ attributes: {
145
+ machine_id: reg.id,
146
+ project: reg.project,
147
+ states: reg.states,
148
+ workspace_root: reg.workspace,
149
+ label: reg.label,
150
+ max_parallel: reg.max_parallel,
151
+ current_load: load,
152
+ lease_seconds: lease,
153
+ },
154
+ },
155
+ }));
156
+ const status = res?.data?.attributes?.status;
157
+ return typeof status === 'string' ? status : 'online';
158
+ }
159
+ async getConductorStatus(id) {
160
+ const c = await this.api
161
+ .collection('gaia_conductor')
162
+ .where('machine_id', '=', id)
163
+ .fields(['status'])
164
+ .first();
165
+ return c ? (c.attr('status') ?? null) : null;
166
+ }
167
+ async setConductorStatus(id, status) {
168
+ const c = await this.api
169
+ .collection('gaia_conductor')
170
+ .where('machine_id', '=', id)
171
+ .first();
172
+ if (c) {
173
+ await this.api.update('gaia_conductor', c.id, { attributes: { status } });
174
+ }
175
+ }
176
+ async listConductors(owner) {
177
+ let col = this.api.collection('gaia_conductor');
178
+ if (owner === 'me') {
179
+ col = col.where('owner_user_id.id', '=', await this.api.me());
180
+ }
181
+ const rows = await col.page(200).list();
182
+ return rows.map((r) => ({
183
+ id: r.attr('machine_id') ?? r.id,
184
+ project: '',
185
+ label: r.attr('label') ?? '',
186
+ status: r.attr('status') ?? '',
187
+ lastSeen: r.attr('last_seen') ?? 0,
188
+ load: r.attr('current_load') ?? 0,
189
+ }));
190
+ }
191
+ async markRunning(uuid, attrs) {
192
+ const t = Math.floor(Date.now() / 1000);
193
+ await this.api.update('gaia_run', uuid, {
194
+ attributes: {
195
+ state: 'running',
196
+ heartbeat: t,
197
+ ...(attrs?.worktree_path ? { worktree_path: attrs.worktree_path } : {}),
198
+ },
199
+ });
200
+ }
201
+ async fetchFinalizableRuns(id) {
202
+ const rows = await this.api
203
+ .collection('gaia_run')
204
+ .where('conductor_id.machine_id', '=', id)
205
+ .where('state', '=', 'done')
206
+ .where('closed', '=', '0')
207
+ .fields(['worktree_path', 'started_at'])
208
+ .page(100)
209
+ .list();
210
+ return rows.map((r) => {
211
+ const startedAt = r.attr('started_at');
212
+ return {
213
+ runUuid: r.id,
214
+ worktreePath: r.attr('worktree_path') ?? '',
215
+ ...(typeof startedAt === 'number' ? { startedAt } : {}),
216
+ };
217
+ });
218
+ }
219
+ async finalizeRun(uuid, log, metrics) {
220
+ const t = Math.floor(Date.now() / 1000);
221
+ await this.api.update('gaia_run', uuid, {
222
+ attributes: {
223
+ closed: true,
224
+ closed_date: t,
225
+ ...(log ? { log } : {}),
226
+ ...(metrics ?? {}),
227
+ },
228
+ }); // NO state — the run is already done.
229
+ }
230
+ async fetchUncleanedTickets(id) {
231
+ // Finished tickets whose worktree is not yet torn down (cleaned_up=0),
232
+ // driven by the durable `cleaned_up` flag (GAIA-89) AND scoped to this
233
+ // conductor (GAIA-121): only tickets assigned to `id` are loaded, so a
234
+ // ticket owned by another conductor never reaches the reaper loop. "Finished"
235
+ // = reached `done` OR already `closed`; the collection builder has no OR, so
236
+ // this is two AND-queries merged + de-duped by uuid. The `conductor_id`
237
+ // relationship carries the assigned conductor's `machine_id` — the same
238
+ // nested filter the sibling reaper queries (`fetchFinalizableRuns` etc.) use.
239
+ const fields = ['branch_name', 'state', 'closed'];
240
+ const done = await this.api
241
+ .collection('gaia_ticket')
242
+ .where('conductor_id.machine_id', '=', id)
243
+ .where('state', '=', 'done')
244
+ .where('cleaned_up', '=', '0')
245
+ .fields(fields)
246
+ .page(100)
247
+ .list();
248
+ const closed = await this.api
249
+ .collection('gaia_ticket')
250
+ .where('conductor_id.machine_id', '=', id)
251
+ .where('closed', '=', '1')
252
+ .where('cleaned_up', '=', '0')
253
+ .fields(fields)
254
+ .page(100)
255
+ .list();
256
+ const byUuid = new Map();
257
+ for (const r of [...done, ...closed]) {
258
+ byUuid.set(r.id, r);
259
+ }
260
+ return Promise.all([...byUuid.values()].map(async (r) => ({
261
+ ticketUuid: r.id,
262
+ branchName: r.attr('branch_name') ?? '',
263
+ state: r.attr('state') ?? '',
264
+ closed: r.attr('closed') ?? false,
265
+ worktreePath: await this.latestRunWorktree(r.id),
266
+ })));
267
+ }
268
+ async closeTicket(uuid) {
269
+ const t = Math.floor(Date.now() / 1000);
270
+ await this.api.update('gaia_ticket', uuid, {
271
+ attributes: { closed: true, closed_date: t },
272
+ }); // NO state — the ticket is already done.
273
+ }
274
+ async markTicketCleanedUp(uuid) {
275
+ await this.api.update('gaia_ticket', uuid, {
276
+ attributes: { cleaned_up: true },
277
+ }); // NO state/closed — teardown flag only, decoupled from the lifecycle.
278
+ }
279
+ /**
280
+ * Absolute worktree path of the ticket's latest run (highest run id with a
281
+ * non-empty worktree_path), or '' when none — the cwd the cleanup command
282
+ * runs in. The conductor persists worktree_path on markRunning, so a done
283
+ * ticket's run carries the path even after the run closed.
284
+ */
285
+ async latestRunWorktree(ticketUuid) {
286
+ const rows = await this.api
287
+ .collection('gaia_run')
288
+ .where('ticket_id.id', '=', ticketUuid)
289
+ .fields(['worktree_path', 'drupal_internal__id'])
290
+ .sort('-drupal_internal__id')
291
+ .page(100)
292
+ .list();
293
+ for (const r of rows) {
294
+ const path = r.attr('worktree_path');
295
+ if (path) {
296
+ return path;
297
+ }
298
+ }
299
+ return '';
300
+ }
301
+ async projectUuid(name) {
302
+ const p = await this.api
303
+ .collection('gaia_project')
304
+ .where('name', '=', name)
305
+ .first();
306
+ if (!p) {
307
+ throw new Error(`gaia project "${name}" not found`);
308
+ }
309
+ return p.id;
310
+ }
311
+ }
312
+ export function drupalRemote() {
313
+ return {
314
+ kind: 'remote',
315
+ id: 'drupal',
316
+ requiredModules: [],
317
+ async createRemote(config) {
318
+ const http = createHttpClient();
319
+ const auth = await resolveAuth({
320
+ baseUrl: config.site.base_url,
321
+ plugins: config.plugins ?? [],
322
+ http,
323
+ now: Date.now,
324
+ // stateDir omitted → dropsh defaultStateDir() (~/.config/dropsh)
325
+ });
326
+ return new DrupalGaiaRemote(createJsonApiClient({
327
+ baseUrl: config.site.base_url,
328
+ prefix: config.site.jsonapi_prefix,
329
+ http,
330
+ auth: auth,
331
+ }));
332
+ },
333
+ };
334
+ }
@@ -0,0 +1,95 @@
1
+ import type { RemotePlugin } from '../plugins.js';
2
+ import type { ActiveRun, ClaimedRun, ClaimOptions, ConductorRegistration, ConductorStatus, FinalizableRun, GaiaRemote, RunMetrics, RunWriteAttributes, Ticket, UncleanTicket } from './remote.js';
3
+ export interface FakeSeedRun {
4
+ runUuid: string;
5
+ /** Numeric (drupal_internal__id) run id. Defaults to a stable 1-based counter when omitted. */
6
+ id?: number;
7
+ ticketUuid: string;
8
+ stateAtStart: string;
9
+ /** Override the initial state (defaults to stateAtStart). */
10
+ state?: string;
11
+ handler?: string;
12
+ worktreePath?: string;
13
+ closed?: boolean;
14
+ /** Unix timestamp (seconds) the run started — drives footprint duration_s. */
15
+ startedAt?: number;
16
+ }
17
+ export interface FakeSeedTicket {
18
+ identifier: string;
19
+ title: string;
20
+ state: string;
21
+ branchName?: string;
22
+ /** Computed base branch (parent branch / project default / 'main'). */
23
+ baseBranch?: string;
24
+ /** Effective env vars (parent-chain resolved) as `.env`-style lines. */
25
+ effectiveEnvVars?: string;
26
+ url?: string;
27
+ workflow?: string;
28
+ /** Whether the ticket is already closed (its lifecycle wound up). */
29
+ closed?: boolean;
30
+ /** Whether the ticket's worktree is already torn down (cleaned_up flag). */
31
+ cleanedUp?: boolean;
32
+ /**
33
+ * machine_id of the conductor this ticket is assigned to (GAIA-121). Omit to
34
+ * mean "belongs to the querying conductor" (the common case for reaper tests);
35
+ * set an explicit value to test conductor-scoping, or `''` for unassigned.
36
+ */
37
+ conductorId?: string;
38
+ }
39
+ export interface FakeRemoteSeed {
40
+ runs?: FakeSeedRun[];
41
+ tickets?: Record<string, FakeSeedTicket>;
42
+ }
43
+ export interface MarkRunningCall {
44
+ runUuid: string;
45
+ attrs?: {
46
+ worktree_path?: string;
47
+ };
48
+ }
49
+ export interface FinalizeRunCall {
50
+ runUuid: string;
51
+ log: string;
52
+ metrics?: RunMetrics;
53
+ }
54
+ export declare class FakeGaiaRemote implements GaiaRemote {
55
+ readonly calls: {
56
+ markRunning: MarkRunningCall[];
57
+ finalizeRun: FinalizeRunCall[];
58
+ closeTicket: string[];
59
+ markCleanedUp: string[];
60
+ };
61
+ /**
62
+ * Override for reconcile tests: when set, `fetchActiveRuns` returns this
63
+ * list verbatim instead of deriving it from the internal runs map.
64
+ */
65
+ activeRuns: ActiveRun[] | null;
66
+ private readonly runs;
67
+ private readonly queue;
68
+ private readonly tickets;
69
+ private conductorStatus;
70
+ /** Stable counter for assigning numeric ids to unseeded runs. */
71
+ private runIdCounter;
72
+ constructor(seed?: FakeRemoteSeed);
73
+ registerConductor(_reg: ConductorRegistration): Promise<string>;
74
+ heartbeat(): Promise<string>;
75
+ getConductorStatus(_conductorId: string): Promise<string | null>;
76
+ setConductorStatus(_conductorId: string, status: 'offline' | 'online'): Promise<void>;
77
+ listConductors(_owner?: 'me'): Promise<ConductorStatus[]>;
78
+ activeRunCount(_conductorId: string): Promise<number>;
79
+ fetchActiveRuns(_conductorId: string): Promise<ActiveRun[]>;
80
+ claimNext(_claim: ClaimOptions): Promise<ClaimedRun | null>;
81
+ getTicket(ticketUuid: string): Promise<Ticket>;
82
+ getRunWorktree(runUuid: string): Promise<string>;
83
+ getRunTicketIdentifier(runUuid: string): Promise<string>;
84
+ getRunTicketBranchName(runUuid: string): Promise<string>;
85
+ markRunning(runUuid: string, attrs?: RunWriteAttributes): Promise<void>;
86
+ fetchFinalizableRuns(_conductorId: string): Promise<FinalizableRun[]>;
87
+ finalizeRun(runUuid: string, log: string, metrics?: RunMetrics): Promise<void>;
88
+ fetchUncleanedTickets(conductorId: string): Promise<UncleanTicket[]>;
89
+ closeTicket(uuid: string): Promise<void>;
90
+ markTicketCleanedUp(uuid: string): Promise<void>;
91
+ /** Worktree path of the ticket's most recently seeded run, or '' when none. */
92
+ private latestRunWorktree;
93
+ private internalActiveRuns;
94
+ }
95
+ export declare function fakeRemote(seed?: FakeRemoteSeed): RemotePlugin;
@@ -0,0 +1,227 @@
1
+ const ACTIVE = ['claimed', 'running'];
2
+ export class FakeGaiaRemote {
3
+ calls = {
4
+ markRunning: [],
5
+ finalizeRun: [],
6
+ closeTicket: [],
7
+ markCleanedUp: [],
8
+ };
9
+ /**
10
+ * Override for reconcile tests: when set, `fetchActiveRuns` returns this
11
+ * list verbatim instead of deriving it from the internal runs map.
12
+ */
13
+ activeRuns = null;
14
+ runs = new Map();
15
+ queue = [];
16
+ tickets;
17
+ conductorStatus = 'online';
18
+ /** Stable counter for assigning numeric ids to unseeded runs. */
19
+ runIdCounter = 0;
20
+ constructor(seed = {}) {
21
+ this.tickets = seed.tickets ?? {};
22
+ for (const r of seed.runs ?? []) {
23
+ const handler = r.handler ?? 'code';
24
+ // Use the seeded id when provided; otherwise assign a deterministic counter.
25
+ const runId = r.id ?? ++this.runIdCounter;
26
+ this.runs.set(r.runUuid, {
27
+ runUuid: r.runUuid,
28
+ runId,
29
+ ticketUuid: r.ticketUuid,
30
+ handler,
31
+ state: r.state ?? r.stateAtStart,
32
+ stateAtStart: r.stateAtStart,
33
+ ...(r.worktreePath !== undefined
34
+ ? { worktreePath: r.worktreePath }
35
+ : {}),
36
+ ...(r.startedAt !== undefined ? { startedAt: r.startedAt } : {}),
37
+ ...(r.closed !== undefined ? { closed: r.closed } : {}),
38
+ });
39
+ this.queue.push({
40
+ runUuid: r.runUuid,
41
+ runId,
42
+ ticketUuid: r.ticketUuid,
43
+ stateAtStart: r.stateAtStart,
44
+ handler,
45
+ });
46
+ }
47
+ }
48
+ async registerConductor(_reg) {
49
+ this.conductorStatus = 'online';
50
+ return 'fake-conductor-uuid';
51
+ }
52
+ async heartbeat() {
53
+ // Mirrors the server: a heartbeat always brings the conductor online.
54
+ this.conductorStatus = 'online';
55
+ return this.conductorStatus;
56
+ }
57
+ async getConductorStatus(_conductorId) {
58
+ return this.conductorStatus;
59
+ }
60
+ async setConductorStatus(_conductorId, status) {
61
+ this.conductorStatus = status;
62
+ }
63
+ async listConductors(_owner) {
64
+ return [];
65
+ }
66
+ async activeRunCount(_conductorId) {
67
+ return this.internalActiveRuns().length;
68
+ }
69
+ async fetchActiveRuns(_conductorId) {
70
+ if (this.activeRuns !== null) {
71
+ return this.activeRuns;
72
+ }
73
+ return this.internalActiveRuns().map((r) => {
74
+ const ticket = this.tickets[r.ticketUuid];
75
+ const identifier = ticket?.identifier ?? '';
76
+ const branchName = ticket?.branchName ??
77
+ (identifier ? `gaia/${identifier.toLowerCase()}` : '');
78
+ return {
79
+ runUuid: r.runUuid,
80
+ ticketUuid: r.ticketUuid,
81
+ ticketIdentifier: identifier,
82
+ branchName,
83
+ state: r.state,
84
+ stateAtStart: r.stateAtStart,
85
+ worktreePath: r.worktreePath ?? '',
86
+ };
87
+ });
88
+ }
89
+ async claimNext(_claim) {
90
+ return this.queue.shift() ?? null;
91
+ }
92
+ async getTicket(ticketUuid) {
93
+ const t = this.tickets[ticketUuid];
94
+ if (!t) {
95
+ throw new Error(`fake remote: ticket ${ticketUuid} not seeded`);
96
+ }
97
+ const branchName = t.branchName ?? `gaia/${t.identifier.toLowerCase()}`;
98
+ return {
99
+ uuid: ticketUuid,
100
+ identifier: t.identifier,
101
+ title: t.title,
102
+ state: t.state,
103
+ branchName,
104
+ ...(t.baseBranch ? { baseBranch: t.baseBranch } : {}),
105
+ ...(t.effectiveEnvVars ? { effectiveEnvVars: t.effectiveEnvVars } : {}),
106
+ ...(t.url ? { issueUrl: t.url } : {}),
107
+ };
108
+ }
109
+ async getRunWorktree(runUuid) {
110
+ return this.runs.get(runUuid)?.worktreePath ?? '';
111
+ }
112
+ async getRunTicketIdentifier(runUuid) {
113
+ const ticketUuid = this.runs.get(runUuid)?.ticketUuid;
114
+ if (!ticketUuid) {
115
+ return '';
116
+ }
117
+ return this.tickets[ticketUuid]?.identifier ?? '';
118
+ }
119
+ async getRunTicketBranchName(runUuid) {
120
+ const ticketUuid = this.runs.get(runUuid)?.ticketUuid;
121
+ if (!ticketUuid) {
122
+ return '';
123
+ }
124
+ const ticket = this.tickets[ticketUuid];
125
+ if (!ticket) {
126
+ return '';
127
+ }
128
+ return ticket.branchName ?? `gaia/${ticket.identifier.toLowerCase()}`;
129
+ }
130
+ async markRunning(runUuid, attrs) {
131
+ this.calls.markRunning.push({
132
+ runUuid,
133
+ ...(attrs
134
+ ? {
135
+ attrs: {
136
+ ...(attrs.worktree_path
137
+ ? { worktree_path: attrs.worktree_path }
138
+ : {}),
139
+ },
140
+ }
141
+ : {}),
142
+ });
143
+ const run = this.runs.get(runUuid);
144
+ if (run) {
145
+ run.state = 'running';
146
+ if (attrs?.worktree_path) {
147
+ run.worktreePath = attrs.worktree_path;
148
+ }
149
+ }
150
+ }
151
+ async fetchFinalizableRuns(_conductorId) {
152
+ return [...this.runs.values()]
153
+ .filter((r) => r.state === 'done' && !r.closed)
154
+ .map((r) => ({
155
+ runUuid: r.runUuid,
156
+ worktreePath: r.worktreePath ?? '',
157
+ ...(r.startedAt !== undefined ? { startedAt: r.startedAt } : {}),
158
+ }));
159
+ }
160
+ async finalizeRun(runUuid, log, metrics) {
161
+ this.calls.finalizeRun.push({
162
+ runUuid,
163
+ log,
164
+ ...(metrics ? { metrics } : {}),
165
+ });
166
+ const run = this.runs.get(runUuid);
167
+ if (run) {
168
+ run.closed = true;
169
+ if (log)
170
+ run.log = log;
171
+ }
172
+ }
173
+ async fetchUncleanedTickets(conductorId) {
174
+ // Scoped to the querying conductor (GAIA-121). A seed without an explicit
175
+ // `conductorId` defaults to the querying conductor (the common reaper-test
176
+ // case); an explicit value scopes it, and `''` models an unassigned ticket.
177
+ return Object.entries(this.tickets)
178
+ .filter(([, t]) => (t.state === 'done' || t.closed) &&
179
+ !t.cleanedUp &&
180
+ (t.conductorId ?? conductorId) === conductorId)
181
+ .map(([ticketUuid, t]) => ({
182
+ ticketUuid,
183
+ branchName: t.branchName ?? `gaia/${t.identifier.toLowerCase()}`,
184
+ worktreePath: this.latestRunWorktree(ticketUuid),
185
+ state: t.state,
186
+ closed: t.closed ?? false,
187
+ }));
188
+ }
189
+ async closeTicket(uuid) {
190
+ this.calls.closeTicket.push(uuid);
191
+ const t = this.tickets[uuid];
192
+ if (t) {
193
+ t.closed = true;
194
+ }
195
+ }
196
+ async markTicketCleanedUp(uuid) {
197
+ this.calls.markCleanedUp.push(uuid);
198
+ const t = this.tickets[uuid];
199
+ if (t) {
200
+ t.cleanedUp = true;
201
+ }
202
+ }
203
+ /** Worktree path of the ticket's most recently seeded run, or '' when none. */
204
+ latestRunWorktree(ticketUuid) {
205
+ let worktree = '';
206
+ for (const r of this.runs.values()) {
207
+ if (r.ticketUuid === ticketUuid && r.worktreePath) {
208
+ worktree = r.worktreePath;
209
+ }
210
+ }
211
+ return worktree;
212
+ }
213
+ internalActiveRuns() {
214
+ return [...this.runs.values()].filter((r) => ACTIVE.includes(r.state));
215
+ }
216
+ }
217
+ export function fakeRemote(seed = {}) {
218
+ const remote = new FakeGaiaRemote(seed);
219
+ return {
220
+ kind: 'remote',
221
+ id: 'fake',
222
+ requiredModules: [],
223
+ async createRemote(_config) {
224
+ return remote;
225
+ },
226
+ };
227
+ }