agl 42.2.2 → 43.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 (179) hide show
  1. package/changelog.md +24 -0
  2. package/dist_serve/bundle.js +6697 -5287
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +29 -29
  5. package/dist_serve/bundle.js.third-party-notices.txt +29 -29
  6. package/dist_serve/third-party-notices.md +597 -8
  7. package/dist_ts/00_commitinfo_data.js +1 -1
  8. package/dist_ts/aglapi/aglapisurface.document.js +114 -16
  9. package/dist_ts/aglapi/interfaces.d.ts +30 -0
  10. package/dist_ts/aglapi/interfaces.js +7 -1
  11. package/dist_ts/classes.authstore.d.ts +7 -0
  12. package/dist_ts/classes.authstore.js +12 -1
  13. package/dist_ts/classes.browserpainttransport.d.ts +2 -2
  14. package/dist_ts/classes.browserpainttransport.js +9 -8
  15. package/dist_ts/classes.browserresourcehost.js +30 -20
  16. package/dist_ts/classes.cli.js +10 -1
  17. package/dist_ts/classes.controller.d.ts +41 -11
  18. package/dist_ts/classes.controller.js +232 -52
  19. package/dist_ts/classes.harnessoperationmanager.d.ts +44 -0
  20. package/dist_ts/classes.harnessoperationmanager.js +15 -10
  21. package/dist_ts/classes.mcpclient.d.ts +5 -0
  22. package/dist_ts/classes.mcpclient.js +15 -3
  23. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
  24. package/dist_ts/classes.mcpcontrollerhost.js +17 -3
  25. package/dist_ts/classes.mcptools.d.ts +4 -3
  26. package/dist_ts/classes.mcptools.js +20 -1
  27. package/dist_ts/classes.mcpvalidation.js +4 -1
  28. package/dist_ts/classes.ticketstore.d.ts +71 -3
  29. package/dist_ts/classes.ticketstore.js +299 -12
  30. package/dist_ts/classes.validation.d.ts +2 -0
  31. package/dist_ts/classes.validation.js +27 -5
  32. package/dist_ts/driver/classes.directreports.d.ts +23 -3
  33. package/dist_ts/driver/classes.directreports.js +59 -2
  34. package/dist_ts/driver/classes.drivereventrelay.js +3 -2
  35. package/dist_ts/driver/functions.driverinstructions.d.ts +1 -1
  36. package/dist_ts/driver/functions.driverinstructions.js +12 -3
  37. package/dist_ts/driver/functions.drivertools.d.ts +4 -0
  38. package/dist_ts/driver/functions.drivertools.js +8 -2
  39. package/dist_ts/fleet/classes.boardpump.d.ts +53 -3
  40. package/dist_ts/fleet/classes.boardpump.js +237 -32
  41. package/dist_ts/fleet/classes.claudeworkers.d.ts +10 -3
  42. package/dist_ts/fleet/classes.claudeworkers.js +43 -19
  43. package/dist_ts/fleet/classes.codexworkers.d.ts +5 -3
  44. package/dist_ts/fleet/classes.codexworkers.js +26 -9
  45. package/dist_ts/fleet/classes.deploymonitor.d.ts +253 -0
  46. package/dist_ts/fleet/classes.deploymonitor.js +821 -0
  47. package/dist_ts/fleet/classes.gitfacts.d.ts +61 -0
  48. package/dist_ts/fleet/classes.gitfacts.js +125 -0
  49. package/dist_ts/fleet/classes.releasereconciler.d.ts +51 -0
  50. package/dist_ts/fleet/classes.releasereconciler.js +101 -0
  51. package/dist_ts/fleet/classes.service.d.ts +13 -1
  52. package/dist_ts/fleet/classes.service.js +76 -7
  53. package/dist_ts/fleet/classes.ticketeffects.d.ts +13 -0
  54. package/dist_ts/fleet/classes.ticketeffects.js +42 -8
  55. package/dist_ts/fleet/classes.workers.d.ts +10 -3
  56. package/dist_ts/fleet/classes.workers.js +18 -3
  57. package/dist_ts/fleet/functions.controllerbuild.d.ts +23 -0
  58. package/dist_ts/fleet/functions.controllerbuild.js +75 -0
  59. package/dist_ts/fleet/functions.deployprobes.d.ts +39 -0
  60. package/dist_ts/fleet/functions.deployprobes.js +82 -0
  61. package/dist_ts/fleet/functions.deployvalidation.d.ts +27 -0
  62. package/dist_ts/fleet/functions.deployvalidation.js +43 -0
  63. package/dist_ts/fleet/functions.release.d.ts +2 -1
  64. package/dist_ts/fleet/functions.release.js +32 -5
  65. package/dist_ts/fleet/functions.releasefacts.d.ts +42 -0
  66. package/dist_ts/fleet/functions.releasefacts.js +46 -0
  67. package/dist_ts/fleet/functions.validation.d.ts +3 -3
  68. package/dist_ts/fleet/functions.validation.js +4 -7
  69. package/dist_ts/fleet/functions.watchprobes.js +7 -9
  70. package/dist_ts/fleet/functions.workervalidation.js +4 -3
  71. package/dist_ts/fleet/interfaces.workers.d.ts +30 -3
  72. package/dist_ts/fleet/interfaces.workers.js +14 -1
  73. package/dist_ts/functions.deploycli.d.ts +36 -0
  74. package/dist_ts/functions.deploycli.js +157 -0
  75. package/dist_ts/functions.mcpdeploytools.d.ts +13 -0
  76. package/dist_ts/functions.mcpdeploytools.js +16 -0
  77. package/dist_ts/functions.mcptickettools.d.ts +54 -0
  78. package/dist_ts/functions.mcptickettools.js +8 -7
  79. package/dist_ts/functions.ticketautolabels.d.ts +2 -0
  80. package/dist_ts/functions.ticketautolabels.js +9 -3
  81. package/dist_ts/functions.ticketcli.d.ts +16 -2
  82. package/dist_ts/functions.ticketcli.js +105 -27
  83. package/dist_ts/functions.ticketvalidation.d.ts +55 -0
  84. package/dist_ts/functions.ticketvalidation.js +26 -8
  85. package/dist_ts_interfaces/deployments.d.ts +241 -0
  86. package/dist_ts_interfaces/deployments.js +5 -6
  87. package/dist_ts_interfaces/fleet.d.ts +12 -0
  88. package/dist_ts_interfaces/fleetworkers.d.ts +21 -1
  89. package/dist_ts_interfaces/functions.fleetversion.d.ts +4 -0
  90. package/dist_ts_interfaces/functions.fleetversion.js +25 -0
  91. package/dist_ts_interfaces/interfaces.d.ts +4 -2
  92. package/dist_ts_interfaces/interfaces.js +4 -2
  93. package/dist_ts_interfaces/mcprequests.d.ts +3 -2
  94. package/dist_ts_interfaces/mcprequests.js +3 -1
  95. package/dist_ts_interfaces/requests.d.ts +3 -2
  96. package/dist_ts_interfaces/requests.directreports.d.ts +58 -6
  97. package/dist_ts_interfaces/requests.js +1 -1
  98. package/dist_ts_interfaces/requests.tickets.d.ts +25 -5
  99. package/dist_ts_interfaces/requests.tickets.js +2 -2
  100. package/dist_ts_interfaces/tickets.d.ts +71 -6
  101. package/dist_ts_interfaces/tickets.js +34 -6
  102. package/dist_ts_migration/classes.documentmigrationrunner.d.ts +7 -0
  103. package/dist_ts_migration/classes.documentmigrationrunner.js +14 -1
  104. package/dist_ts_migration/index.d.ts +2 -0
  105. package/dist_ts_migration/index.js +3 -1
  106. package/dist_ts_migration/v41_ticketclosedcolumn.d.ts +20 -0
  107. package/dist_ts_migration/v41_ticketclosedcolumn.js +118 -0
  108. package/dist_ts_migration/v41_ticketlinkrepos.d.ts +24 -0
  109. package/dist_ts_migration/v41_ticketlinkrepos.js +101 -0
  110. package/package.json +6 -2
  111. package/readme.md +308 -36
  112. package/third-party-notices.md +597 -8
  113. package/ts/00_commitinfo_data.ts +1 -1
  114. package/ts/aglapi/aglapisurface.document.ts +113 -15
  115. package/ts/aglapi/interfaces.ts +6 -0
  116. package/ts/classes.authstore.ts +13 -0
  117. package/ts/classes.browserpainttransport.ts +8 -7
  118. package/ts/classes.browserresourcehost.ts +38 -14
  119. package/ts/classes.cli.ts +9 -0
  120. package/ts/classes.controller.ts +244 -61
  121. package/ts/classes.harnessoperationmanager.ts +20 -14
  122. package/ts/classes.mcpclient.ts +17 -2
  123. package/ts/classes.mcpcontrollerhost.ts +18 -2
  124. package/ts/classes.mcptools.ts +21 -2
  125. package/ts/classes.mcpvalidation.ts +2 -0
  126. package/ts/classes.ticketstore.ts +312 -13
  127. package/ts/classes.validation.ts +28 -4
  128. package/ts/driver/classes.directreports.ts +58 -3
  129. package/ts/driver/classes.drivereventrelay.ts +2 -1
  130. package/ts/driver/functions.driverinstructions.ts +11 -2
  131. package/ts/driver/functions.drivertools.ts +10 -2
  132. package/ts/fleet/classes.boardpump.ts +235 -28
  133. package/ts/fleet/classes.claudeworkers.ts +36 -15
  134. package/ts/fleet/classes.codexworkers.ts +24 -7
  135. package/ts/fleet/classes.deploymonitor.ts +854 -0
  136. package/ts/fleet/classes.gitfacts.ts +135 -0
  137. package/ts/fleet/classes.releasereconciler.ts +103 -0
  138. package/ts/fleet/classes.service.ts +81 -8
  139. package/ts/fleet/classes.ticketeffects.ts +38 -6
  140. package/ts/fleet/classes.workers.ts +19 -5
  141. package/ts/fleet/functions.controllerbuild.ts +84 -0
  142. package/ts/fleet/functions.deployprobes.ts +84 -0
  143. package/ts/fleet/functions.deployvalidation.ts +50 -0
  144. package/ts/fleet/functions.release.ts +32 -3
  145. package/ts/fleet/functions.releasefacts.ts +74 -0
  146. package/ts/fleet/functions.validation.ts +3 -6
  147. package/ts/fleet/functions.watchprobes.ts +6 -8
  148. package/ts/fleet/functions.workervalidation.ts +3 -2
  149. package/ts/fleet/interfaces.workers.ts +23 -3
  150. package/ts/functions.deploycli.ts +156 -0
  151. package/ts/functions.mcpdeploytools.ts +18 -0
  152. package/ts/functions.mcptickettools.ts +7 -6
  153. package/ts/functions.ticketautolabels.ts +10 -2
  154. package/ts/functions.ticketcli.ts +100 -24
  155. package/ts/functions.ticketvalidation.ts +26 -7
  156. package/ts_interfaces/deployments.ts +194 -0
  157. package/ts_interfaces/fleet.ts +17 -2
  158. package/ts_interfaces/fleetworkers.ts +20 -0
  159. package/ts_interfaces/functions.fleetversion.ts +20 -0
  160. package/ts_interfaces/interfaces.ts +3 -1
  161. package/ts_interfaces/mcprequests.ts +3 -0
  162. package/ts_interfaces/requests.directreports.ts +52 -8
  163. package/ts_interfaces/requests.tickets.ts +20 -4
  164. package/ts_interfaces/requests.ts +6 -1
  165. package/ts_interfaces/tickets.ts +53 -6
  166. package/ts_migration/classes.documentmigrationrunner.ts +15 -0
  167. package/ts_migration/index.ts +2 -0
  168. package/ts_migration/v41_ticketclosedcolumn.ts +106 -0
  169. package/ts_migration/v41_ticketlinkrepos.ts +91 -0
  170. package/ts_web/00_commitinfo_data.ts +1 -1
  171. package/ts_web/elements.deployments.ts +1066 -0
  172. package/ts_web/elements.directreport.ts +2 -2
  173. package/ts_web/elements.directreportsession.ts +5 -5
  174. package/ts_web/elements.harnesscontrollerapp.ts +179 -13
  175. package/ts_web/elements.makedirectreport.ts +444 -0
  176. package/ts_web/elements.nativesession.ts +29 -1
  177. package/ts_web/elements.ticketboard.ts +74 -18
  178. package/ts_web/functions.deployments.ts +231 -0
  179. package/ts_web/functions.sessionchat.ts +2 -0
@@ -0,0 +1,135 @@
1
+ import * as plugins from '../plugins.js';
2
+ import type { IFleetRepository } from '../../ts_interfaces/fleet.js';
3
+ import type { IFleetDeployRelease } from '../../ts_interfaces/deployments.js';
4
+ import type { TTicketData } from '../../ts_interfaces/tickets.js';
5
+ import { compareFleetVersions, fleetRepositoryMatches, fleetVersion, type TFleetGitRunner } from './functions.releasefacts.js';
6
+
7
+ /**
8
+ * Where fleet mirrors a remote's release tags: refs of its own, pruned to what the remote holds, so a tag that exists
9
+ * only in a checkout is never a release, and the checkout's own tags are left as they are.
10
+ */
11
+ export const fleetRemoteTagRefs = 'refs/agl/remote-tags';
12
+ /**
13
+ * Where fleet's deploy monitor mirrors remote main: a ref of its own, so its fetch never takes the lock of the
14
+ * `refs/remotes/<remote>/main` that a fleet land or release pushes and checks; racing one, it would fail its pass.
15
+ */
16
+ export const fleetRemoteMainRef = 'refs/agl/remote-main';
17
+ /** The columns whose tickets have landed; a ticket elsewhere has no landed commit, whatever it links. */
18
+ export const fleetLandedColumns: readonly TTicketData['columnId'][] = ['landed', 'released', 'closed'];
19
+
20
+ /** What fleet knows of a repository's remote, as its last fetch left it. */
21
+ export interface IFleetRemoteState {
22
+ /** Remote main's commit. */
23
+ main?: string;
24
+ /** The remote's release tags `v<version>`, newest version first, each with the commit it names. */
25
+ releases: IFleetDeployRelease[];
26
+ }
27
+
28
+ const fullSha = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;
29
+ const ancestryCacheSize = 50_000;
30
+
31
+ /**
32
+ * What git says about the fleet's repositories (AGL-909), always outside a ticket transaction. A release is a tag on
33
+ * the remote: `fetch` mirrors remote main and the remote's `v*` tags into refs of the checkout fleet's own operations
34
+ * never touch (`refs/agl/remote-main`, `refs/agl/remote-tags`, pruned), and every read takes them from there without
35
+ * touching the network. Whether one commit
36
+ * holds another never changes, so it is cached.
37
+ */
38
+ export class FleetGitFacts {
39
+ private readonly ancestry = new Map<string, boolean>();
40
+ private readonly firstReleases = new Map<string, IFleetDeployRelease | undefined>();
41
+ private readonly digests = new WeakMap<IFleetDeployRelease[], string>();
42
+
43
+ constructor(private readonly git: TFleetGitRunner) {}
44
+
45
+ /**
46
+ * Mirrors the remote's main and release tags; resolves to the failure's text, or undefined. A failed fetch leaves the
47
+ * last mirrored refs as they were.
48
+ */
49
+ public async fetch(repoArg: IFleetRepository): Promise<string | undefined> {
50
+ // `--refmap=` keeps git from also updating the remote-tracking branch, and no FETCH_HEAD is written.
51
+ const result = await this.git('git', ['fetch', '--quiet', '--no-tags', '--prune', '--no-write-fetch-head', '--refmap=', repoArg.remote,
52
+ `+refs/heads/main:${fleetRemoteMainRef}`, `+refs/tags/v*:${fleetRemoteTagRefs}/v*`], repoArg.path);
53
+ return result.code === 0 ? undefined : (result.stderr.trim() || `git fetch exited with ${result.code}`).slice(0, 512);
54
+ }
55
+
56
+ /** Remote main and the remote's release tags as the last fetch mirrored them. */
57
+ public async remote(repoArg: IFleetRepository): Promise<IFleetRemoteState> {
58
+ const main = await this.git('git', ['rev-parse', '--verify', '--quiet', `${fleetRemoteMainRef}^{commit}`], repoArg.path);
59
+ const tags = await this.git('git', ['for-each-ref', '--format=%(refname:lstrip=3)%09%(objectname)%09%(*objectname)%09%(creatordate:iso-strict)',
60
+ `${fleetRemoteTagRefs}/v*`], repoArg.path);
61
+ const releases: IFleetDeployRelease[] = [];
62
+ if (tags.code === 0) {
63
+ for (const line of tags.stdout.split('\n')) {
64
+ const [name = '', object = '', peeled = '', taggedAt = ''] = line.split('\t');
65
+ const version = fleetVersion(name);
66
+ if (!version || !name.startsWith('v')) continue;
67
+ releases.push({ version, sha: peeled || object, ...(taggedAt ? { taggedAt: new Date(taggedAt).toISOString() } : {}) });
68
+ }
69
+ }
70
+ const sha = main.code === 0 ? main.stdout.trim() : '';
71
+ return { ...(fullSha.test(sha) ? { main: sha } : {}), releases: releases.sort((leftArg, rightArg) => compareFleetVersions(rightArg.version, leftArg.version)) };
72
+ }
73
+
74
+ /** Whether `ancestorArg` is `descendantArg` or one of its ancestors; a commit the checkout lacks is none. */
75
+ public async isAncestor(repoArg: Pick<IFleetRepository, 'path'>, ancestorArg: string, descendantArg: string): Promise<boolean> {
76
+ const key = `${repoArg.path}\0${ancestorArg}\0${descendantArg}`;
77
+ const known = this.ancestry.get(key);
78
+ if (known !== undefined) return known;
79
+ const result = await this.git('git', ['merge-base', '--is-ancestor', ancestorArg, descendantArg], repoArg.path);
80
+ // 0 and 1 are answers; anything else (an unknown commit) is no answer to keep.
81
+ if (result.code === 1 || result.code === 0) {
82
+ if (fullSha.test(ancestorArg) && fullSha.test(descendantArg)) {
83
+ if (this.ancestry.size >= ancestryCacheSize) this.ancestry.clear();
84
+ this.ancestry.set(key, result.code === 0);
85
+ }
86
+ }
87
+ return result.code === 0;
88
+ }
89
+
90
+ /**
91
+ * The commit a ticket landed as in a repository (AGL-909): the newest branch or commit link there whose commit remote
92
+ * main holds, for a ticket in landed, released or closed. A review branch's commit before its rebase, the commit that
93
+ * brought a bug in, a revert on another branch: none of them is a landing, and a ticket elsewhere on the board has
94
+ * none. `mainArg` is remote main's commit, or the commit a release is cut from.
95
+ */
96
+ public async landedSha(ticketArg: Pick<TTicketData, 'columnId' | 'links'>, repoArg: IFleetRepository, mainArg: string | undefined): Promise<string | undefined> {
97
+ if (!mainArg || !fleetLandedColumns.includes(ticketArg.columnId)) return undefined;
98
+ return await this.newestOnMain(ticketArg, repoArg, mainArg);
99
+ }
100
+
101
+ /** The newest branch or commit link of the repository whose commit `mainArg` holds, whatever the ticket's column. */
102
+ public async newestOnMain(ticketArg: Pick<TTicketData, 'links'>, repoArg: IFleetRepository, mainArg: string): Promise<string | undefined> {
103
+ for (let index = ticketArg.links.length - 1; index >= 0; index--) {
104
+ const link = ticketArg.links[index]!;
105
+ if ((link.kind === 'branch' || link.kind === 'commit') && fleetRepositoryMatches(repoArg, link.repo)
106
+ && await this.isAncestor(repoArg, link.sha, mainArg)) return link.sha;
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ /**
112
+ * The first release, by version, whose commit holds `shaArg`: where a commit was released ("fixed in"). One git call
113
+ * lists the mirrored tags that hold it; the answer is kept while the remote's tags stay the same.
114
+ */
115
+ public async firstReleaseContaining(repoArg: IFleetRepository, releasesArg: IFleetDeployRelease[], shaArg: string): Promise<IFleetDeployRelease | undefined> {
116
+ const key = `${repoArg.path}\0${shaArg}\0${this.digest(releasesArg)}`;
117
+ if (this.firstReleases.has(key)) return this.firstReleases.get(key);
118
+ const result = await this.git('git', ['for-each-ref', '--contains', shaArg, '--format=%(refname:lstrip=3)', `${fleetRemoteTagRefs}/v*`], repoArg.path);
119
+ if (result.code !== 0) return undefined;
120
+ const containing = new Set(result.stdout.split('\n').map((lineArg) => fleetVersion(lineArg)).filter((valueArg): valueArg is string => valueArg !== undefined));
121
+ const first = [...releasesArg].reverse().find((releaseArg) => containing.has(releaseArg.version));
122
+ if (this.firstReleases.size >= ancestryCacheSize) this.firstReleases.clear();
123
+ this.firstReleases.set(key, first);
124
+ return first;
125
+ }
126
+
127
+ private digest(releasesArg: IFleetDeployRelease[]): string {
128
+ let digest = this.digests.get(releasesArg);
129
+ if (digest === undefined) {
130
+ digest = plugins.crypto.createHash('sha256').update(JSON.stringify(releasesArg.map((releaseArg) => [releaseArg.version, releaseArg.sha]))).digest('hex');
131
+ this.digests.set(releasesArg, digest);
132
+ }
133
+ return digest;
134
+ }
135
+ }
@@ -0,0 +1,103 @@
1
+ import type { IFleetRepository } from '../../ts_interfaces/fleet.js';
2
+ import type { IFleetDeployRelease } from '../../ts_interfaces/deployments.js';
3
+ import type { ITicket, ITicketActor, TTicketFleetEvent } from '../../ts_interfaces/tickets.js';
4
+ import type { FleetTicketEffects } from './classes.ticketeffects.js';
5
+ import type { FleetGitFacts, IFleetRemoteState } from './classes.gitfacts.js';
6
+ import { findFleetRepository, fleetReleaseLinkMatches, fleetRepositorySlug } from './functions.releasefacts.js';
7
+
8
+ /** Who the reconciler's release links and moves name. */
9
+ export const releaseReconcilerActor: ITicketActor = { id: 'agl:release-reconciler', name: 'AGL release reconciler', role: 'driver' };
10
+
11
+ /**
12
+ * The `released` events of one release for one ticket, the only way AGL writes "released" (AGL-909): one per package the
13
+ * release is known to have published, or one without a package, each under the reconciler's actor and a key built from the facts
14
+ * (`release:<org/name>:<version>:<ticket>:<package|->`). The same release with the same packages gives the same events,
15
+ * so each applies once whoever applies it. The packages are what is known: a reconciler pass that runs between the tag
16
+ * reaching the remote and `fleet release` recording what it published writes the event without a package, so that
17
+ * release's own ticket can hold both links, each true.
18
+ */
19
+ export const releasedEvents = (ticketKeyArg: string, repoArg: string, releaseArg: IFleetDeployRelease, packagesArg: readonly string[]): TTicketFleetEvent[] => {
20
+ const packages = [...new Set(packagesArg)].sort();
21
+ return (packages.length ? packages : [undefined]).map((packageName): TTicketFleetEvent => ({
22
+ ticketKey: ticketKeyArg, actor: releaseReconcilerActor, kind: 'released', version: releaseArg.version, repo: repoArg, sha: releaseArg.sha,
23
+ ...(packageName === undefined ? {} : { package: packageName }),
24
+ idempotencyKey: `release:${repoArg}:${releaseArg.version}:${ticketKeyArg}:${packageName ?? '-'}`.slice(0, 256),
25
+ }));
26
+ };
27
+
28
+ /** A ticket the reconciler released: its key, and the repository and version it shipped in. */
29
+ export interface IReleaseReconcilerOutcome {
30
+ ticketKey: string;
31
+ repo: string;
32
+ version: string;
33
+ }
34
+
35
+ /**
36
+ * The one writer of "released" for work that landed (AGL-909, Linus #2). For every repository a landed or released
37
+ * ticket's code landed in whose release the ticket does not link yet, it finds the first tag on the remote that holds
38
+ * the ticket's landed commit there, whoever cut the tag (fleet, gitzone by hand, CI), and links it with `releasedEvents`.
39
+ * A ticket moves to released on its first tag; every other repository's release is linked as its tag appears, so each
40
+ * repository's deploy targets count it. Each event's key is built from the facts, so whichever pass or controller
41
+ * applies it, it applies once.
42
+ */
43
+ export class ReleaseReconciler {
44
+ constructor(private readonly facts: FleetGitFacts, private readonly effects: FleetTicketEffects) {}
45
+
46
+ /**
47
+ * The tickets the reconciler would release, in board order: each landed or released ticket with the repositories its
48
+ * code links name whose release it does not link yet.
49
+ */
50
+ public static candidates(ticketsArg: ITicket[], repositoriesArg: IFleetRepository[]): { ticket: ITicket; repos: IFleetRepository[] }[] {
51
+ return ticketsArg.flatMap((ticketArg) => {
52
+ if (ticketArg.columnId !== 'landed' && ticketArg.columnId !== 'released') return [];
53
+ const repos = new Map<string, IFleetRepository>();
54
+ for (const link of ticketArg.links) {
55
+ if (link.kind !== 'branch' && link.kind !== 'commit') continue;
56
+ const repo = findFleetRepository(repositoriesArg, link.repo);
57
+ if (repo && !ticketArg.links.some((linkArg) => linkArg.kind === 'release' && fleetReleaseLinkMatches(linkArg, repo))) repos.set(repo.path, repo);
58
+ }
59
+ return repos.size ? [{ ticket: ticketArg, repos: [...repos.values()] }] : [];
60
+ });
61
+ }
62
+
63
+ /**
64
+ * One pass: `remotesArg` holds each repository's remote as the pass fetched it. Resolves with the tickets it released;
65
+ * one ticket's failure is logged and leaves it to the next pass.
66
+ */
67
+ public async reconcile(ownerArg: string, candidatesArg: { ticket: ITicket; repos: IFleetRepository[] }[],
68
+ remotesArg: Map<string, IFleetRemoteState>, signalArg: AbortSignal): Promise<IReleaseReconcilerOutcome[]> {
69
+ const outcomes: IReleaseReconcilerOutcome[] = [];
70
+ // What a release published is known only where a fleet release said so; the repository's packages today are not.
71
+ const published = new Map<string, Promise<string[]>>();
72
+ const packagesOf = (slugArg: string, versionArg: string): Promise<string[]> => {
73
+ const key = `${slugArg}@${versionArg}`;
74
+ if (!published.has(key)) published.set(key, this.effects.publishedPackages(ownerArg, slugArg, versionArg));
75
+ return published.get(key)!;
76
+ };
77
+ for (const { ticket, repos } of candidatesArg) {
78
+ signalArg.throwIfAborted();
79
+ for (const repo of repos) {
80
+ const remote = remotesArg.get(repo.path);
81
+ if (!remote?.main) continue;
82
+ try {
83
+ const landed = await this.facts.landedSha(ticket, repo, remote.main);
84
+ const release = landed ? await this.facts.firstReleaseContaining(repo, remote.releases, landed) : undefined;
85
+ if (!release) continue;
86
+ const slug = fleetRepositorySlug(repo);
87
+ const events = releasedEvents(ticket.key, slug, release, await packagesOf(slug, release.version));
88
+ let applied = true;
89
+ for (const event of events) {
90
+ const prepared = await this.effects.prepare(ownerArg, event);
91
+ const { effect } = prepared.state === 'applied' ? { effect: { state: 'applied' } } : await this.effects.dispatch(prepared, signalArg);
92
+ if (effect.state !== 'applied') applied = false;
93
+ }
94
+ if (applied) outcomes.push({ ticketKey: ticket.key, repo: slug, version: release.version });
95
+ } catch (errorArg) {
96
+ if (signalArg.aborted) throw errorArg;
97
+ console.error(`Releasing ${ticket.key} from the tags of ${repo.id} failed.`, errorArg);
98
+ }
99
+ }
100
+ }
101
+ return outcomes;
102
+ }
103
+ }
@@ -5,8 +5,10 @@ import { assertFleetRequest, validateFleetScope } from './functions.validation.j
5
5
  import { fleetBackupCreatedAt, fleetBackupNamespace, fleetBackupRetentionMs, legacyFleetBackupPattern, rebaseFleetBranch } from './functions.rebase.js';
6
6
  import { releaseFleetRepository, toolingFleetRepository } from './functions.release.js';
7
7
  import type { IFleetRuntime } from './interfaces.js';
8
- import type { ITicketActor } from '../../ts_interfaces/tickets.js';
8
+ import type { ITicket, ITicketActor } from '../../ts_interfaces/tickets.js';
9
+ import { findFleetRepository, fleetRepositoryMatches, fleetRepositorySlug, type IFleetReleaseGuard } from './functions.releasefacts.js';
9
10
  import type { FleetTicketEffects } from './classes.ticketeffects.js';
11
+ import { ticketDeployPlanRefusesLink } from '../classes.ticketstore.js';
10
12
 
11
13
  export interface IFleetServiceOptions {
12
14
  runner?: TFleetRunner;
@@ -16,6 +18,10 @@ export interface IFleetServiceOptions {
16
18
  reconcileSessions?: (owner: string) => Promise<unknown>;
17
19
  /** The Claude Code background jobs that look like drivers and that no worker binds; an audit lists them. */
18
20
  unboundDrivers?: (signal: AbortSignal) => Promise<{ drivers: IFleetUnboundDriver[]; errors: string[] }>;
21
+ /** The board's tickets: a release checks their release plans and names the landed ones it ships. */
22
+ tickets?: (signal: AbortSignal) => Promise<ITicket[]>;
23
+ /** A release went out: the release reconciler links and releases the landed tickets its tag holds, now rather than at its next pass. */
24
+ released?: (repo: IFleetRepository) => void;
19
25
  }
20
26
  interface IFleetOwnedOperation { owner: string; snapshot: IFleetOperation; completion: Promise<void> }
21
27
  const queues = new Map<string, Promise<unknown>>();
@@ -79,7 +85,8 @@ export class FleetService {
79
85
  public async close(): Promise<void> {
80
86
  this.abort.abort(); await Promise.allSettled([...this.operations.values()].map((item) => item.completion));
81
87
  }
82
- public async execute<T extends TFleetOperation>(operation: T, request: TFleetRequest<T>, scope: IFleetScope, running: () => void = () => {}, owner?: string): Promise<TFleetResult<T>> {
88
+ public async execute<T extends TFleetOperation>(operation: T, request: TFleetRequest<T>, scope: IFleetScope, running: () => void = () => {},
89
+ owner?: string): Promise<TFleetResult<T>> {
83
90
  const input = assertFleetRequest(operation, request), configuration = validateFleetScope(scope);
84
91
  const runtime = new FleetRuntime(this.abort.signal, this.options.runner);
85
92
  if (operation === 'reconcile') {
@@ -92,8 +99,9 @@ export class FleetService {
92
99
  }
93
100
  const repoId = 'repo' in input ? input.repo : undefined;
94
101
  const target = repoId !== undefined && plugins.path.isAbsolute(repoId) ? await plugins.fs.promises.realpath(repoId).catch(() => plugins.path.resolve(repoId)) : undefined;
95
- const repositories = repoId === undefined ? configuration.repositories
96
- : configuration.repositories.filter((repo) => repo.id === repoId || repo.path === repoId || repo.path === target);
102
+ // The one resolver every caller uses: a fleet id, `org/name` or a checkout path through its symlinks.
103
+ const found = repoId === undefined ? undefined : findFleetRepository(configuration.repositories, repoId);
104
+ const repositories = repoId === undefined ? configuration.repositories : found ? [found] : [];
97
105
  if (repoId !== undefined && repositories.length !== 1) {
98
106
  const skipped = configuration.skipped?.find((entry) => entry.path === target || plugins.path.basename(entry.path) === repoId);
99
107
  throw new Error(skipped ? `Repository ${repoId} is not in the fleet: ${skipped.reason}`
@@ -123,11 +131,71 @@ export class FleetService {
123
131
  const repo = withHostEnvironment(repositories[0]!, configuration.environment);
124
132
  return this.exclusive(runtime, repo, async () => {
125
133
  running();
126
- return (operation === 'land' ? await this.land(runtime, repo, input as IFleetLandRequest)
127
- : operation === 'tooling' ? await toolingFleetRepository(runtime, repo, input as TFleetRequest<'tooling'>)
128
- : await releaseFleetRepository(runtime, repo, input as TFleetRequest<'release'>)) as TFleetResult<T>;
134
+ if (operation === 'land') return await this.land(runtime, repo, input as IFleetLandRequest) as TFleetResult<T>;
135
+ if (operation === 'tooling') return await toolingFleetRepository(runtime, repo, input as TFleetRequest<'tooling'>) as TFleetResult<T>;
136
+ const release = await releaseFleetRepository(runtime, repo, input as TFleetRequest<'release'>, {},
137
+ await this.releaseGuard(runtime, repo, input as TFleetRequest<'release'>));
138
+ this.options.released?.(repo);
139
+ return release as TFleetResult<T>;
129
140
  });
130
141
  }
142
+ /**
143
+ * The checks a release makes against the board (AGL-909): its own ticket is no deploy ticket, its release plan must
144
+ * name this repository and the version gitzone plans, and its newest code link here must be on the commit the release
145
+ * is cut from (a review branch that never landed is not released); every landed ticket the release holds is named
146
+ * before it publishes, and one whose plan names another version of this repository stops it. Nothing is read from the
147
+ * board after it publishes.
148
+ */
149
+ private async releaseGuard(runtime: IFleetRuntime, repo: IFleetRepository, request: TFleetRequest<'release'>): Promise<IFleetReleaseGuard> {
150
+ const tickets = this.options.tickets ? await this.options.tickets(runtime.signal) : [];
151
+ const own = tickets.find((ticket) => ticket.key === request.ticketKey);
152
+ if (own && ticketDeployPlanRefusesLink(own, 'release')) {
153
+ throw new Error(`${own.key} plans a deploy, and a deploy ticket holds no release: release for the code ticket. Nothing was published.`);
154
+ }
155
+ const slug = fleetRepositorySlug(repo);
156
+ const plannedHere = (ticket: ITicket) => ticket.releasePlan && fleetRepositoryMatches(repo, ticket.releasePlan.repo) ? ticket.releasePlan : undefined;
157
+ if (own?.releasePlan && !plannedHere(own)) {
158
+ throw new Error(`${own.key} plans a release of ${own.releasePlan.repo}, not of ${slug}; release ${own.releasePlan.repo} for it, or change its release plan first.`);
159
+ }
160
+ const ownVersion = own && plannedHere(own)?.version;
161
+ const requested = request.plan?.split('->').at(-1)?.trim();
162
+ if (ownVersion !== undefined && requested !== undefined && requested !== ownVersion) {
163
+ throw new Error(`${own!.key} plans ${slug} ${ownVersion}, but the release was asked for ${request.plan}; ask the owner which version to release and update the plan.`);
164
+ }
165
+ const isAncestor = async (ancestor: string, descendant: string) => (
166
+ (await runtime.run('git', ['merge-base', '--is-ancestor', ancestor, descendant], repo.path)).code === 0);
167
+ const newestCode = (ticket: ITicket) => ticket.links.findLast((link): link is Extract<ITicket['links'][number], { kind: 'branch' | 'commit' }> => (
168
+ (link.kind === 'branch' || link.kind === 'commit') && fleetRepositoryMatches(repo, link.repo)));
169
+ return {
170
+ plan: (plan) => {
171
+ if (ownVersion !== undefined && ownVersion !== plan.version) {
172
+ throw new Error(`Release plan mismatch: ${own!.key} plans ${ownVersion}, gitzone plans ${plan.from} -> ${plan.version}. Nothing was published; ask the owner which version to release and update the ticket's release plan.`);
173
+ }
174
+ },
175
+ ship: async (releaseBase, plan) => {
176
+ const ownCode = own && newestCode(own);
177
+ if (ownCode && !await isAncestor(ownCode.sha, releaseBase)) {
178
+ throw new Error(`${own!.key}'s newest commit in ${slug}, ${ownCode.sha.slice(0, 12)}, is not on main: this release would not hold its work. Land it first. Nothing was published.`);
179
+ }
180
+ const contained: string[] = [];
181
+ for (const ticket of tickets) {
182
+ if (ticket.key === own?.key || ticket.columnId !== 'landed') continue;
183
+ let landed = false;
184
+ for (let index = ticket.links.length - 1; index >= 0 && !landed; index--) {
185
+ const link = ticket.links[index]!;
186
+ landed = (link.kind === 'branch' || link.kind === 'commit') && fleetRepositoryMatches(repo, link.repo) && await isAncestor(link.sha, releaseBase);
187
+ }
188
+ if (!landed) continue;
189
+ const version = plannedHere(ticket)?.version;
190
+ if (version !== undefined && version !== plan.version) {
191
+ throw new Error(`Release plan mismatch: ${ticket.key} ships in this release and plans ${slug} ${version}, gitzone plans ${plan.from} -> ${plan.version}. Nothing was published; ask the owner which version to release and update the plans.`);
192
+ }
193
+ contained.push(ticket.key);
194
+ }
195
+ return contained;
196
+ },
197
+ };
198
+ }
131
199
  private async exclusive<T>(runtime: FleetRuntime, repo: IFleetRepository, action: () => Promise<T>): Promise<T> {
132
200
  const common = await runtime.git(repo.path, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
133
201
  const key = await plugins.fs.promises.realpath(common);
@@ -152,6 +220,11 @@ export class FleetService {
152
220
  try { return await operation; } finally { if (queues.get(key) === operation) queues.delete(key); }
153
221
  }
154
222
  private async land(runtime: IFleetRuntime, repo: IFleetRepository, input: IFleetLandRequest): Promise<IFleetLandResult> {
223
+ // A deploy ticket holds no code: the store would refuse the landing's link after the push (AGL-909).
224
+ const own = this.options.tickets ? (await this.options.tickets(runtime.signal)).find((ticket) => ticket.key === input.ticketKey) : undefined;
225
+ if (own && ticketDeployPlanRefusesLink(own, 'branch')) {
226
+ throw new Error(`${own.key} plans a deploy, and a deploy ticket holds no code: land the branch for the code ticket. Nothing was pushed.`);
227
+ }
155
228
  await runtime.checked('git', ['check-ref-format', '--branch', input.branch], repo.path);
156
229
  await runtime.fetch(repo); const base = await runtime.assertMain(repo);
157
230
  const worktrees = parseFleetWorktrees(await runtime.git(repo.path, ['worktree', 'list', '--porcelain', '-z']));
@@ -239,7 +312,7 @@ export class FleetService {
239
312
  await runtime.git(repo.path, ['worktree', 'prune']);
240
313
  // The landing holds everything the pre-rebase tip had; compare-and-delete keeps a backup another process moved.
241
314
  if (backup) { await runtime.git(repo.path, ['update-ref', '-d', backup, original]); resolutions.push(`backup removed: ${backup}`); }
242
- return { operation: 'land', repo: repo.id, branch: input.branch, sha, checks, archive, resolutions };
315
+ return { operation: 'land', repo: repo.id, repository: fleetRepositorySlug(repo), branch: input.branch, sha, checks, archive, resolutions };
243
316
  }
244
317
  private async assertAttribution(runtime: IFleetRuntime, repo: IFleetRepository, base: string, branch: string): Promise<void> {
245
318
  const messages = await runtime.git(repo.path, ['log', '--format=%B', `${base}..${branch}`]);
@@ -4,6 +4,10 @@ import { ticketActorSchema, ticketFleetEventSchema, ticketIdentifierSchema } fro
4
4
  import type { ITicketActor, TTicketFleetEvent, ITicketFleetEventResult } from '../../ts_interfaces/tickets.js';
5
5
  import type { IFleetLandResult, IFleetReleaseResult, IFleetTicketEffect, IFleetTicketSync, IFleetToolingResult } from '../../ts_interfaces/fleet.js';
6
6
  import type { IFleetWorker } from '../../ts_interfaces/fleetworkers.js';
7
+ import { releasedEvents } from './classes.releasereconciler.js';
8
+
9
+ /** How often an effect whose ticket transaction met a concurrent change is tried again before it is marked failed. */
10
+ export const fleetTicketEffectRetries = 4;
7
11
 
8
12
  export interface IFleetTicketEffectDocument {
9
13
  id: string; owner: string; request: TTicketFleetEvent; state: IFleetTicketEffect['state']; updateId: string;
@@ -61,6 +65,17 @@ export class FleetTicketEffects {
61
65
  const current = await FleetTicketEffectModel.exact.findStoredOne({ id: eventKey });
62
66
  return current ? structuredClone(FleetTicketEffectModel.exact.toPersisted(current)) : undefined;
63
67
  }
68
+ /**
69
+ * The packages a release of `repoArg` (`org/name`) at `versionArg` is known to have published: those its `released`
70
+ * events name. Only a fleet release names packages, after it saw each one at every registry; a tag cut elsewhere
71
+ * names none, so its tickets link the repository and version alone.
72
+ */
73
+ public async publishedPackages(owner: string, repoArg: string, versionArg: string): Promise<string[]> {
74
+ const records = await FleetTicketEffectModel.exact.findStored({ filter: { owner, 'request.kind': 'released', 'request.repo': repoArg,
75
+ 'request.version': versionArg }, limit: 512 });
76
+ return [...new Set(records.flatMap((recordArg) => recordArg.request.kind === 'released' && recordArg.request.package !== undefined
77
+ ? [recordArg.request.package] : []))].sort();
78
+ }
64
79
  public async prepare(owner: string, input: TTicketFleetEvent, origin?: string): Promise<IFleetTicketEffectDocument> {
65
80
  const request = ticketFleetEventSchema.parse(input);
66
81
  const current = await FleetTicketEffectModel.exact.findStoredOne({ id: request.idempotencyKey });
@@ -106,8 +121,16 @@ export class FleetTicketEffects {
106
121
  let commentId: string | undefined;
107
122
  const named = (effect: IFleetTicketEffect): IFleetTicketDispatch => ({ effect, ...(commentId ? { commentId } : {}) });
108
123
  try {
109
- // Even confirmed replays use the durable board receipt, never a local dedupe cache.
110
- const result = await this.apply(structuredClone(doc.request), signal, doc.origin);
124
+ // Even confirmed replays use the durable board receipt, never a local dedupe cache. A board that changed under the
125
+ // transaction is tried again, a few times, before the effect is marked failed.
126
+ let result: Awaited<ReturnType<typeof this.apply>> | undefined;
127
+ for (let attempt = 0; !result; attempt++) {
128
+ try { result = await this.apply(structuredClone(doc.request), signal, doc.origin); }
129
+ catch (error) {
130
+ if (!(error instanceof TicketError) || error.code !== 'concurrent_change' || attempt >= fleetTicketEffectRetries) throw error;
131
+ await plugins.timersPromises.setTimeout(50 * 2 ** attempt, undefined, signal ? { signal } : undefined);
132
+ }
133
+ }
111
134
  commentId = result.comment?.id;
112
135
  return named(await this.mark(doc, 'applied', result.revision));
113
136
  } catch (error) {
@@ -135,12 +158,10 @@ export class FleetTicketEffects {
135
158
  public async operation(owner: string, ticketKey: string, actor: ITicketActor, operationId: string, result: IFleetLandResult | IFleetReleaseResult | IFleetToolingResult, signal?: AbortSignal): Promise<IFleetTicketSync> {
136
159
  const base = { ticketKey, actor: this.actor(actor) };
137
160
  const events: TTicketFleetEvent[] = result.operation === 'land'
138
- ? [{ ...base, kind: 'landed', repo: result.repo, branch: result.branch, sha: result.sha, idempotencyKey: `fleet:${operationId}:landed` }]
161
+ ? [{ ...base, kind: 'landed', repo: result.repository, branch: result.branch, sha: result.sha, idempotencyKey: `fleet:${operationId}:landed` }]
139
162
  : result.operation === 'tooling'
140
163
  ? [{ ...base, kind: 'comment', body: `Tooling currency committed to ${result.repo} main as ${result.sha}: ${result.updated.join(', ') || 'lockfile integrity'}.`, idempotencyKey: `fleet:${operationId}:tooling` }]
141
- : [...new Set(result.packages)].map(packageName => ({ ...base, kind: 'released', package: packageName, version: result.version,
142
- idempotencyKey: `fleet:${operationId}:released:${plugins.crypto.createHash('sha256').update(packageName).digest('hex')}` }));
143
- if (!events.length) return { state: 'failed', effects: [], error: 'Release published no package evidence for this ticket.' };
164
+ : this.releaseEvents(base, operationId, result);
144
165
  const prepared: IFleetTicketEffectDocument[] = [];
145
166
  // Save the entire release set before any ticket application.
146
167
  for (const event of events) prepared.push(await this.prepare(owner, event));
@@ -148,6 +169,17 @@ export class FleetTicketEffects {
148
169
  for (const event of prepared) effects.push((await this.dispatch(event, signal)).effect);
149
170
  return this.summary(effects);
150
171
  }
172
+ /**
173
+ * The release's own ticket is released as the release reconciler releases a ticket, with the same events, once the
174
+ * remote holds the tag; until then it is told why it stays. The landed tickets the release holds are the reconciler's.
175
+ */
176
+ private releaseEvents(base: { ticketKey: string; actor: ITicketActor }, operationId: string, result: IFleetReleaseResult): TTicketFleetEvent[] {
177
+ if (result.tagged) return releasedEvents(base.ticketKey, result.repository, { version: result.version, sha: result.sha }, result.packages);
178
+ return [{ ...base, kind: 'comment', idempotencyKey: `fleet:${operationId}:untagged`,
179
+ body: `Released ${result.repository} ${result.version} at ${result.sha}, but the remote holds no tag v${result.version} at that commit, so `
180
+ + `${base.ticketKey} is not released: a release is the remote's tag. Once the tag is there, the release reconciler releases the landed `
181
+ + 'tickets it holds.' }];
182
+ }
151
183
  /** Comments a worker's report on its ticket; the result names the comment that holds it. */
152
184
  public async report(owner: string, ticketKey: string, actor: ITicketActor, worker: { name: string; harness: string; nativeId?: string }, report: { reportId?: string; text: string; truncated: boolean }, signal?: AbortSignal): Promise<IFleetTicketReport> {
153
185
  if (!worker.nativeId || !report.reportId || !report.text.trim()) throw new Error('A report comment requires proven native session and report identities.');
@@ -1,6 +1,6 @@
1
1
  import * as plugins from '../plugins.js';
2
2
  import { controllerRuntimeIdKey, type IWorkerClaudeJobRequest, type TWorkerClaudeJobObservation } from '../../ts_interfaces/index.js';
3
- import type { IFleetEvent, IFleetWorker, IFleetWorkerProfile, IFleetWorkerJob, IFleetNativeMessageReceipt, TFleetEventKind, TFleetWorkerAction, TFleetWorkerRequest, TFleetWorkerResponse, TFleetWorkerJobAction, IFleetWorkerReport, IFleetWorkerDispatchHolder } from '../../ts_interfaces/fleetworkers.js';
3
+ import type { IFleetEvent, IFleetWorker, IFleetWorkerProfile, IFleetWorkerJob, IFleetNativeMessageReceipt, TFleetEventKind, TFleetWorkerAction, TFleetWorkerRequest, TFleetWorkerResponse, TFleetWorkerJobAction, IFleetWorkerReport, IFleetRelaunchBlocker, IFleetWorkerDispatchHolder } from '../../ts_interfaces/fleetworkers.js';
4
4
  import type { IFleetConfiguration, IFleetOperation, IFleetTicketSync } from '../../ts_interfaces/fleet.js';
5
5
  import type { ITicketActor } from '../../ts_interfaces/tickets.js';
6
6
  import type { FleetTicketEffects, IFleetTicketReport } from './classes.ticketeffects.js';
@@ -10,7 +10,7 @@ import { FleetEvents } from './classes.events.js';
10
10
  import { FleetClaudeWorkers } from './classes.claudeworkers.js';
11
11
  import { FleetCodexWorkers } from './classes.codexworkers.js';
12
12
  import type { FleetWorkerLaunches } from './classes.workerlaunches.js';
13
- import { FleetDispatchError, fleetMessageDigest, fleetReportMarker, type IFleetWorkerBackend, type IFleetNativeAgent, type IFleetNativeThread, type IFleetNativeSession, type IFleetNativePage } from './interfaces.workers.js';
13
+ import { FleetDispatchError, fleetMessageDigest, fleetReportMarker, type IFleetWorkerBackend, type IFleetNativeAgent, type IFleetNativeThread, type IFleetNativeSession, type IFleetNativePage, type IFleetNativeSendTurn, type IFleetNativeSendReceipt } from './interfaces.workers.js';
14
14
  import { assertFleetWorkerRequest, validateFleetWorkerProfiles } from './functions.workervalidation.js';
15
15
  import { readControllerProcessIdentity, controllerProcessIdentityIsLive } from '../classes.processinspection.js';
16
16
  import { ticketActorSchema } from '../functions.ticketvalidation.js';
@@ -273,7 +273,7 @@ export class FleetWorkers {
273
273
  public async boundView(owner: string, harness: IFleetWorker['harness'], nativeId: string): Promise<IControllerFleetWorkerView | undefined> {
274
274
  return (await this.views(owner)).find((view) => view.worker.harness === harness && view.worker.nativeId === nativeId);
275
275
  }
276
- private nativeBackend<K extends 'nativeHistory' | 'nativeSend' | 'nativeAttention' | 'nativeReply'>(harness: IFleetWorker['harness'], method: K): NonNullable<IFleetWorkerBackend[K]> {
276
+ private nativeBackend<K extends 'nativeHistory' | 'nativeSend' | 'nativeTurn' | 'nativeAttention' | 'nativeReply'>(harness: IFleetWorker['harness'], method: K): NonNullable<IFleetWorkerBackend[K]> {
277
277
  this.abort.signal.throwIfAborted();
278
278
  const backend = this.backends[harness], operation = backend[method];
279
279
  if (!operation) throw new Error(`The ${harness} backend does not serve native sessions.`);
@@ -284,8 +284,22 @@ export class FleetWorkers {
284
284
  return await this.nativeBackend(harness, 'nativeHistory')(session, limit, before);
285
285
  }
286
286
  /** Sends to a listed native session through the server that owns it; see `IFleetWorkerBackend.nativeSend`. */
287
- public async nativeSend(harness: IFleetWorker['harness'], session: IFleetNativeSession, text: string, settled: () => void): Promise<void> {
288
- await this.nativeBackend(harness, 'nativeSend')(session, text, settled);
287
+ public async nativeSend(harness: IFleetWorker['harness'], session: IFleetNativeSession, text: string, settled: () => void, turn?: IFleetNativeSendTurn): Promise<IFleetNativeSendReceipt> {
288
+ return await this.nativeBackend(harness, 'nativeSend')(session, text, settled, turn);
289
+ }
290
+ /** The turn a listed native session runs now; see `IFleetWorkerBackend.nativeTurn`. */
291
+ public async nativeTurn(harness: IFleetWorker['harness'], session: IFleetNativeSession): Promise<string | undefined> {
292
+ return await this.nativeBackend(harness, 'nativeTurn')(session);
293
+ }
294
+ /**
295
+ * Why an adopt with a relaunch of the native session `nativeId` under the profile `profileId` in `cwd` would be
296
+ * refused now, by the checks the relaunch itself runs, read-only; `undefined` when none does.
297
+ */
298
+ public async relaunchBlocker(configuration: IFleetConfiguration, profileId: string, nativeId: string, cwd: string): Promise<IFleetRelaunchBlocker | undefined> {
299
+ this.abort.signal.throwIfAborted();
300
+ const profile = this.profile(validateFleetWorkerProfiles(configuration.workerProfiles ?? []), profileId), backend = this.backends[profile.harness];
301
+ if (!backend.relaunchBlocker) throw new Error('Only a Claude Code session is relaunched.');
302
+ return await backend.relaunchBlocker(cwd, profile, nativeId);
289
303
  }
290
304
  public async nativeAttention(harness: IFleetWorker['harness'], session: IFleetNativeSession): Promise<{ permissions: IControllerPermission[]; questions: IControllerQuestion[] }> {
291
305
  return await this.nativeBackend(harness, 'nativeAttention')(session);
@@ -0,0 +1,84 @@
1
+ import * as plugins from '../plugins.js';
2
+ import type { TSha256Digest } from '../../ts_interfaces/deployments.js';
3
+ import type { TFleetGitRunner } from './functions.releasefacts.js';
4
+
5
+ /** What the running controller was built from (AGL-909), as it reports itself to its own deploy target. */
6
+ export interface IFleetControllerBuild {
7
+ /** The commit a development checkout runs; an installed package names none and runs its version's tag. */
8
+ sha?: string;
9
+ /** SHA-256 of every `name@version` its dependencies install, once each and sorted. */
10
+ treeDigest: TSha256Digest;
11
+ /** How many packages that is. */
12
+ packages: number;
13
+ }
14
+
15
+ interface IFleetManifest {
16
+ name?: unknown;
17
+ version?: unknown;
18
+ repository?: unknown;
19
+ dependencies?: Record<string, string>;
20
+ optionalDependencies?: Record<string, string>;
21
+ }
22
+
23
+ const readManifest = (dirArg: string): IFleetManifest | undefined => {
24
+ try { return JSON.parse(plugins.fs.readFileSync(plugins.path.join(dirArg, 'package.json'), 'utf8')) as IFleetManifest; }
25
+ catch { return undefined; }
26
+ };
27
+
28
+ /**
29
+ * The repository a package is released from, as `org/name`, from its package.json `repository` (a URL whose path ends
30
+ * in `org/name`, with or without `.git`). Undefined when the manifest names none.
31
+ */
32
+ export const packageRepositorySlug = (packageRootArg: string): string | undefined => {
33
+ const repository = readManifest(packageRootArg)?.repository;
34
+ const url = typeof repository === 'string' ? repository
35
+ : repository && typeof repository === 'object' && typeof (repository as { url?: unknown }).url === 'string' ? (repository as { url: string }).url : undefined;
36
+ const match = url ? /([^/:]+)\/([^/]+?)(?:\.git)?\/?$/u.exec(url) : null;
37
+ return match ? `${match[1]}/${match[2]}` : undefined;
38
+ };
39
+
40
+ /** The directory Node resolves `nameArg` to from `fromArg`: the nearest `node_modules/<name>` up the tree, through symlinks. */
41
+ const packageDirectory = (nameArg: string, fromArg: string): string | undefined => {
42
+ for (let dir = fromArg; ; dir = plugins.path.dirname(dir)) {
43
+ const candidate = plugins.path.join(dir, 'node_modules', nameArg);
44
+ if (plugins.fs.existsSync(plugins.path.join(candidate, 'package.json'))) {
45
+ try { return plugins.fs.realpathSync(candidate); } catch { return candidate; }
46
+ }
47
+ if (plugins.path.dirname(dir) === dir) return undefined;
48
+ }
49
+ };
50
+
51
+ /**
52
+ * Every package a package's dependencies install, as `name@version`, once each and sorted: what a reinstall that
53
+ * resolved other versions changes. Development dependencies are not installed with a published package and not counted.
54
+ */
55
+ export const installedDependencyTree = (packageRootArg: string): string[] => {
56
+ const installed = new Set<string>();
57
+ const visited = new Set<string>();
58
+ const pending: string[] = [packageRootArg];
59
+ while (pending.length) {
60
+ const dir = pending.pop()!;
61
+ if (visited.has(dir)) continue;
62
+ visited.add(dir);
63
+ const manifest = readManifest(dir);
64
+ if (!manifest) continue;
65
+ if (dir !== packageRootArg && typeof manifest.name === 'string' && typeof manifest.version === 'string') installed.add(`${manifest.name}@${manifest.version}`);
66
+ for (const name of Object.keys({ ...manifest.dependencies, ...manifest.optionalDependencies })) {
67
+ const found = packageDirectory(name, dir);
68
+ if (found) pending.push(found);
69
+ }
70
+ }
71
+ return [...installed].sort();
72
+ };
73
+
74
+ /** What the controller in `packageRootArg` was built from; the commit only for a development checkout. */
75
+ export const readControllerBuild = async (packageRootArg: string, gitArg: TFleetGitRunner): Promise<IFleetControllerBuild> => {
76
+ const tree = installedDependencyTree(packageRootArg);
77
+ const digest = plugins.crypto.createHash('sha256').update(tree.join('\n')).digest('hex');
78
+ let sha: string | undefined;
79
+ if (plugins.fs.existsSync(plugins.path.join(packageRootArg, '.git'))) {
80
+ const head = await gitArg('git', ['rev-parse', 'HEAD'], packageRootArg);
81
+ if (head.code === 0 && /^[a-f0-9]{40,64}$/u.test(head.stdout.trim())) sha = head.stdout.trim();
82
+ }
83
+ return { ...(sha ? { sha } : {}), treeDigest: `sha256:${digest}`, packages: tree.length };
84
+ };