agl 43.11.0 → 43.12.0

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 (34) hide show
  1. package/changelog.md +12 -0
  2. package/dist_serve/bundle.js +1 -1
  3. package/dist_serve/bundle.js.map +1 -1
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/fleet/classes.deploymonitor.d.ts +7 -8
  6. package/dist_ts/fleet/classes.deploymonitor.js +16 -14
  7. package/dist_ts/fleet/classes.releasereconciler.d.ts +2 -1
  8. package/dist_ts/fleet/classes.releasereconciler.js +3 -2
  9. package/dist_ts/fleet/classes.runtime.js +9 -5
  10. package/dist_ts/fleet/classes.service.d.ts +12 -2
  11. package/dist_ts/fleet/classes.service.js +55 -17
  12. package/dist_ts/fleet/functions.discovery.d.ts +11 -2
  13. package/dist_ts/fleet/functions.discovery.js +55 -12
  14. package/dist_ts/fleet/functions.rebase.js +5 -2
  15. package/dist_ts/fleet/functions.toolchain.d.ts +20 -0
  16. package/dist_ts/fleet/functions.toolchain.js +50 -0
  17. package/dist_ts/fleet/functions.validation.d.ts +2 -0
  18. package/dist_ts/fleet/functions.validation.js +11 -3
  19. package/dist_ts/functions.mcpfleettools.js +2 -2
  20. package/dist_ts_interfaces/fleet.d.ts +23 -0
  21. package/package.json +1 -1
  22. package/readme.md +25 -5
  23. package/ts/00_commitinfo_data.ts +1 -1
  24. package/ts/fleet/classes.deploymonitor.ts +19 -16
  25. package/ts/fleet/classes.releasereconciler.ts +2 -1
  26. package/ts/fleet/classes.runtime.ts +8 -4
  27. package/ts/fleet/classes.service.ts +50 -17
  28. package/ts/fleet/functions.discovery.ts +54 -12
  29. package/ts/fleet/functions.rebase.ts +4 -1
  30. package/ts/fleet/functions.toolchain.ts +56 -0
  31. package/ts/fleet/functions.validation.ts +7 -2
  32. package/ts/functions.mcpfleettools.ts +1 -1
  33. package/ts_interfaces/fleet.ts +15 -0
  34. package/ts_web/00_commitinfo_data.ts +1 -1
package/readme.md CHANGED
@@ -1302,8 +1302,10 @@ Fleet operations run on the controller's host. There is no central repository li
1302
1302
  discovers every canonical checkout (a directory whose `.git` is a directory, not a linked
1303
1303
  worktree) up to three levels below the controller's standard project directories, plus each
1304
1304
  registered project that is itself a canonical checkout. A checkout belongs to the fleet when
1305
- its `.smartconfig.json` declares a `@git.zone/cli` release or a fleet section; `"fleet": false`
1306
- opts it out. Each setting is read from the repository itself:
1305
+ its `.smartconfig.json` declares a `@git.zone/cli` release or a fleet section and its `main` has
1306
+ a commit; `"fleet": false` opts it out. The fleet lands and releases on `main` only: a checkout
1307
+ whose default branch is another (`master`) or whose `main` is unborn is skipped with that reason,
1308
+ never followed onto its own branch. Each setting is read from the repository itself:
1307
1309
 
1308
1310
  - `id`: the directory name, or `parent/name` while two checkouts share a name;
1309
1311
  - `remote`: `git config branch.main.remote`, else `origin`;
@@ -1331,8 +1333,19 @@ opts it out. Each setting is read from the repository itself:
1331
1333
 
1332
1334
  `agl fleet audit` lists each discovered repository with the file and key of every setting in
1333
1335
  `sources`, and each skipped checkout with its reason (opted out, an invalid section, an
1334
- unreadable file or an ambiguous id). A repository name that matches no discovered checkout
1335
- refuses with that reason. `remote` names the remote that canonical main tracks, such as
1336
+ unreadable file, an ambiguous id, no commit on `main`, or a remote or registry the fleet cannot
1337
+ use). A repository name that matches no discovered checkout refuses with that reason, in a
1338
+ fleet operation as in a release plan or an `affects` link. A repository whose audit fails is
1339
+ listed under `unaudited` with its reason and the audit goes on with the others; `entries` may
1340
+ still hold what was read of it before the failure, and with `--cleanup` `removed` holds the refs
1341
+ already deleted. `--repo` fails with it, and its error names the refs its cleanup removed before
1342
+ the failure. `landedOutsideFleet` names each landed ticket whose
1343
+ branch or commit link names a repository the fleet does not hold, with why: the reason its
1344
+ checkout was skipped, a checkout without a release or fleet section, a name several fleet
1345
+ repositories match, or no canonical checkout below the roots or among the registered projects.
1346
+ The release reconciler releases a ticket only from fleet repositories, so such a ticket stays in
1347
+ landed until its repository joins the fleet; `landedOutsideFleetError` says why the board could
1348
+ not be read. `remote` names the remote that canonical main tracks, such as
1336
1349
  `lossless`; fleet fetches, bases and pushes through it alone. List every build step CI requires
1337
1350
  in `ciBuildSteps`, including auxiliary builds. Test and guard paths support globs under `test/`;
1338
1351
  every matching file runs separately and must report a non-empty passing count. Configure a
@@ -1384,7 +1397,14 @@ lockfile conflicts, and regenerates admitted generated files. It runs production
1384
1397
  typechecks, the build, named tests and configured guards before fast-forwarding and
1385
1398
  pushing, so a test that loads the built bundle sees the branch's own build. A repository
1386
1399
  that declares a `test:before` script runs it in place of the early build, and the build
1387
- follows the tests. Named tests are resolved in the branch worktree after the rebase, so a test the
1400
+ follows the tests. Each check runs with the repository's own tooling, never a binary found on
1401
+ `PATH`: the production typecheck is its `typecheck` script, else `tsrepo build tsfolders`; the
1402
+ test typecheck its `check:test` script, else `tsrepo check 'test/**/*'`; each named test or
1403
+ guard `tsrepo test <file> --timeout 120 --logfile`; a regenerated file `tsrepo run <generator>`.
1404
+ `tsrepo` is used when the repository's `package.json` pins `@git.zone/tsrepo`; a repository
1405
+ still on the deprecated single tools runs the `tsbuild`, `tstest` or `tsrun` it pins instead. A
1406
+ pinned tool must be installed in the repository's own `node_modules/.bin`. A step with neither a
1407
+ script nor a pinned tool refuses the landing or release and names what to add. Named tests are resolved in the branch worktree after the rebase, so a test the
1388
1408
  branch adds, or one main received through another landing, can qualify it; a name that matches
1389
1409
  no file there refuses the landing before verification. The released-changelog guard compares released sections by
1390
1410
  position, so repeated headings stay distinct. Canonical main must be clean and equal to its
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: 'agl',
6
- version: '43.11.0',
6
+ version: '43.12.0',
7
7
  description: 'Agent Gateway Layer for OpenCode, FlexHarness, and Codex sessions'
8
8
  }
@@ -1,5 +1,5 @@
1
1
  import * as plugins from '../plugins.js';
2
- import type { IFleetConfiguration, IFleetDiscoverySkip, IFleetRepository } from '../../ts_interfaces/fleet.js';
2
+ import type { IFleetConfiguration, IFleetDiscoverySkip, IFleetRepository, IFleetScope } from '../../ts_interfaces/fleet.js';
3
3
  import type { IFleetEvent } from '../../ts_interfaces/fleetworkers.js';
4
4
  import { ticketDeployPlanOptions, ticketDoneColumns, ticketWindowOptions, type ITicket, type ITicketActor, type ITicketQuestion } from '../../ts_interfaces/tickets.js';
5
5
  import {
@@ -25,6 +25,7 @@ import { TicketError, type TicketStore } from '../classes.ticketstore.js';
25
25
  import type { FleetTicketEffects } from './classes.ticketeffects.js';
26
26
  import type { IFleetControllerBuild } from './functions.controllerbuild.js';
27
27
  import { FleetRuntime } from './classes.runtime.js';
28
+ import { fleetRepositoryGap } from './functions.discovery.js';
28
29
 
29
30
  export const deployMonitorDefaults = {
30
31
  intervalMinutes: 5, timeoutMs: 10_000, discoveryTtlMs: 60_000, gitTimeoutMs: 120_000, fetchConcurrency: 4,
@@ -73,8 +74,8 @@ export interface IDeployMonitorHost {
73
74
  controllerId(): string;
74
75
  /** The fleet owner and configuration; undefined while the configuration authority is unavailable. */
75
76
  scope(): Promise<{ owner: string; configuration: IFleetConfiguration } | undefined>;
76
- /** The repositories fleet discovery finds; a target's repository is one of them. */
77
- discover(): Promise<{ repositories: IFleetRepository[]; skipped?: IFleetDiscoverySkip[] }>;
77
+ /** The repositories fleet discovery finds, and the checkouts it did not admit; a target's repository is one of them. */
78
+ discover(): Promise<Pick<IFleetScope, 'repositories' | 'skipped' | 'unconfigured'>>;
78
79
  /** Every ticket of the board, with its AutoLabels. */
79
80
  tickets(signalArg?: AbortSignal): Promise<ITicket[]>;
80
81
  /** The board's revision, which every ticket change moves: the monitor reads the board again only when it moved. */
@@ -218,6 +219,7 @@ interface IDeployDiscovery {
218
219
  workspace: number;
219
220
  repositories: IFleetRepository[];
220
221
  skipped: IFleetDiscoverySkip[];
222
+ unconfigured: string[];
221
223
  }
222
224
 
223
225
  /** What the monitor holds about a target's probe, beyond what the views show: the failures in a row. */
@@ -474,7 +476,8 @@ export class DeployMonitor {
474
476
 
475
477
  /**
476
478
  * A pass's network work: fetch the remotes the board and the targets name, release what their tags hold and probe
477
- * every target. Answers the remotes as fetched, which the computation that follows reads.
479
+ * every target. Answers the remotes as fetched, which the computation that follows reads. A remote whose fetched refs
480
+ * cannot be read holds back no other repository's release or probe; the pass fails after them, naming it.
478
481
  */
479
482
  private async passFetchAndProbe(scopeArg: { owner: string; configuration: IFleetConfiguration }): Promise<Map<string, IFleetRemoteState>> {
480
483
  const targets = this.targets(scopeArg.configuration);
@@ -484,7 +487,7 @@ export class DeployMonitor {
484
487
  const repos = new Map<string, IFleetRepository>();
485
488
  for (const repo of [...targets.flatMap((targetArg) => findFleetRepository(repositories, targetArg.repo) ?? []),
486
489
  ...candidates.flatMap((candidateArg) => candidateArg.repos), ...this.namedRepositories(tickets, repositories)]) repos.set(repo.path, repo);
487
- const remotes = await this.fetchRemotes([...repos.values()]);
490
+ const { remotes, unread } = await this.fetchRemotes([...repos.values()]);
488
491
  try {
489
492
  await this.reconciler.reconcile(scopeArg.owner, candidates.filter((candidateArg) => candidateArg.repos.some((repoArg) => remotes.has(repoArg.path))),
490
493
  remotes, this.abort.signal);
@@ -500,6 +503,7 @@ export class DeployMonitor {
500
503
  console.error(`The deploy probe of ${target.id} failed.`, errorArg);
501
504
  }
502
505
  }
506
+ if (unread) throw unread;
503
507
  return remotes;
504
508
  }
505
509
 
@@ -516,14 +520,15 @@ export class DeployMonitor {
516
520
 
517
521
  /**
518
522
  * Fetches each repository's remote, a few at a time; a failed fetch keeps the last mirrored refs and is logged once.
519
- * A remote whose mirrored refs cannot be read fails the pass, naming the repository, and starts no further fetch.
523
+ * Answers the remotes it read and, when one's mirrored refs cannot be read, the failure naming the first such
524
+ * repository; the others are still fetched and read.
520
525
  */
521
- private async fetchRemotes(reposArg: IFleetRepository[]): Promise<Map<string, IFleetRemoteState>> {
526
+ private async fetchRemotes(reposArg: IFleetRepository[]): Promise<{ remotes: Map<string, IFleetRemoteState>; unread?: DeployStatusError }> {
522
527
  const remotes = new Map<string, IFleetRemoteState>();
523
528
  const pending = [...reposArg];
524
529
  let unread: DeployStatusError | undefined;
525
530
  const worker = async () => {
526
- for (let repo = pending.shift(); repo && !unread; repo = pending.shift()) {
531
+ for (let repo = pending.shift(); repo; repo = pending.shift()) {
527
532
  this.abort.signal.throwIfAborted();
528
533
  const failure = await this.facts.fetch(repo).catch((errorArg: unknown) => errorArg instanceof Error ? errorArg.message : 'git fetch failed');
529
534
  if (failure) {
@@ -538,8 +543,7 @@ export class DeployMonitor {
538
543
  }
539
544
  };
540
545
  await Promise.all(Array.from({ length: Math.min(deployMonitorDefaults.fetchConcurrency, pending.length) }, worker));
541
- if (unread) throw unread;
542
- return remotes;
546
+ return { remotes, ...(unread ? { unread } : {}) };
543
547
  }
544
548
 
545
549
  /** A remote whose mirrored refs could not be read: the computation fails, naming the repository, and never takes it as one without releases. */
@@ -846,7 +850,8 @@ export class DeployMonitor {
846
850
  const scope = await this.requireScope();
847
851
  const context = await this.context();
848
852
  const repo = await this.findRepository(context, repoArg);
849
- if (!repo) throw new DeployError('deploy_repository_unknown', `No single fleet repository is named ${repoArg}.`);
853
+ // findRepository walked again for a name the last walk did not know: the walk it cached says why none or several match.
854
+ if (!repo) throw new DeployError('deploy_repository_unknown', `${repoArg} is not in the fleet: ${fleetRepositoryGap(await this.discovery(), repoArg)}`);
850
855
  return { checkedAt: new Date(this.now()).toISOString(), repositories: [await this.repositoryRelease(context, repo, this.targets(scope.configuration))] };
851
856
  }
852
857
 
@@ -923,8 +928,8 @@ export class DeployMonitor {
923
928
  walking = next;
924
929
  }
925
930
  const workspace = this.workspace;
926
- const walk = this.host.discover().then(({ repositories, skipped }) => {
927
- this.discovered = { at: this.now(), workspace, repositories, skipped: skipped ?? [] };
931
+ const walk = this.host.discover().then(({ repositories, skipped, unconfigured }) => {
932
+ this.discovered = { at: this.now(), workspace, repositories, skipped: skipped ?? [], unconfigured: unconfigured ?? [] };
928
933
  return this.discovered;
929
934
  });
930
935
  const entry = { walk, workspace };
@@ -945,9 +950,7 @@ export class DeployMonitor {
945
950
  repo = findFleetRepository(discovery.repositories, nameArg);
946
951
  }
947
952
  if (repo) return repo;
948
- const skipped = discovery.skipped.find((entryArg) => entryArg.path === nameArg || entryArg.path.endsWith(`/${nameArg}`));
949
- throw new Error(skipped ? `${nameArg} is not in the fleet: ${skipped.reason}`
950
- : `No single fleet repository is named ${nameArg}; name it as org/name, its fleet id or its checkout path.`);
953
+ throw new Error(`${nameArg} is not in the fleet: ${fleetRepositoryGap(discovery, nameArg)}`);
951
954
  }
952
955
 
953
956
  /** The board, read again only when its revision moved since the last read. */
@@ -45,7 +45,8 @@ export class ReleaseReconciler {
45
45
 
46
46
  /**
47
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.
48
+ * code links name whose release it does not link yet. A link to a repository outside the fleet has none to release it;
49
+ * `fleet audit` names each landed ticket with such a link and why (`landedOutsideFleet`).
49
50
  */
50
51
  public static candidates(ticketsArg: ITicket[], repositoriesArg: IFleetRepository[]): { ticket: ITicket; repos: IFleetRepository[] }[] {
51
52
  return ticketsArg.flatMap((ticketArg) => {
@@ -1,6 +1,7 @@
1
1
  import * as plugins from '../plugins.js';
2
2
  import type { IFleetRepository, IFleetCheck } from '../../ts_interfaces/fleet.js';
3
3
  import type { IFleetRuntime, IFleetCommandResult } from './interfaces.js';
4
+ import { fleetToolArgs, fleetToolStep, readFleetToolchainManifest } from './functions.toolchain.js';
4
5
 
5
6
  export type TFleetRunner = IFleetRuntime['run'];
6
7
  export const isFleetReleaseCommand = (command: string): boolean => {
@@ -145,10 +146,13 @@ export class FleetRuntime implements IFleetRuntime {
145
146
  checks.push(parseFleetTestCount(await this.checked('deno', ['task', 'test'], cwd, environment), 'deno task test'));
146
147
  return checks;
147
148
  }
148
- const pkg = JSON.parse(await plugins.fs.promises.readFile(plugins.path.join(cwd, 'package.json'), 'utf8')) as { scripts?: Record<string, string> };
149
+ const pkg = await readFleetToolchainManifest(cwd);
150
+ // Every tool step is chosen from the repository's own manifest before anything runs: its script, else its pinned toolchain.
151
+ const typecheck = fleetToolStep(pkg, 'typecheck'), testTypecheck = fleetToolStep(pkg, 'test typecheck');
152
+ const testTool = fullSuite || ![...tests, ...repo.guards].length ? undefined : fleetToolStep(pkg, 'test');
149
153
  await check('install', 'pnpm', ['install', '--frozen-lockfile']);
150
- await check('typecheck', 'pnpm', pkg.scripts?.typecheck ? ['run', 'typecheck'] : ['exec', 'tsbuild', 'tsfolders']);
151
- await check('test typecheck', 'pnpm', pkg.scripts?.['check:test'] ? ['run', 'check:test'] : ['exec', 'tsbuild', 'check', 'test/**/*']);
154
+ await check('typecheck', 'pnpm', await fleetToolArgs(cwd, typecheck));
155
+ await check('test typecheck', 'pnpm', await fleetToolArgs(cwd, testTypecheck));
152
156
  // Tests may load the built bundle or a native binary: the repository's test preparation, else its build, runs first.
153
157
  const preparation = pkg.scripts?.['test:before'] ? 'test:before' : build ? 'build' : undefined;
154
158
  if (preparation) await check(preparation, 'pnpm', ['run', preparation]);
@@ -163,7 +167,7 @@ export class FleetRuntime implements IFleetRuntime {
163
167
  }
164
168
  }
165
169
  for (const file of selected) {
166
- const output = await this.checked('pnpm', ['exec', 'tstest', file, '--timeout', '120', '--logfile'], cwd, environment);
170
+ const output = await this.checked('pnpm', await fleetToolArgs(cwd, testTool!, [file, '--timeout', '120', '--logfile']), cwd, environment);
167
171
  checks.push(parseFleetTestCount(output, file));
168
172
  }
169
173
  if (build && preparation !== 'build') await check('build', 'pnpm', ['run', 'build']);
@@ -1,5 +1,5 @@
1
1
  import * as plugins from '../plugins.js';
2
- import type { IFleetScope, IFleetRepository, IFleetOperation, TFleetOperation, TFleetRequest, TFleetResult, IFleetAuditResult, IFleetAuditEntry, IFleetLandRequest, IFleetLandResult, IFleetUnboundDriver } from '../../ts_interfaces/fleet.js';
2
+ import type { IFleetScope, IFleetRepository, IFleetOperation, TFleetOperation, TFleetRequest, TFleetResult, IFleetAuditEntry, IFleetLandRequest, IFleetLandResult, IFleetUnboundDriver, IFleetUnauditedRepository, IFleetLandedOutsideFleet } from '../../ts_interfaces/fleet.js';
3
3
  import { FleetRuntime, type TFleetRunner } from './classes.runtime.js';
4
4
  import { assertFleetRequest, validateFleetScope } from './functions.validation.js';
5
5
  import { fleetBackupCreatedAt, fleetBackupNamespace, fleetBackupRetentionMs, legacyFleetBackupPattern, rebaseFleetBranch } from './functions.rebase.js';
@@ -9,6 +9,7 @@ import type { ITicket, ITicketActor } from '../../ts_interfaces/tickets.js';
9
9
  import { findFleetRepository, fleetRepositoryMatches, fleetRepositorySlug, type IFleetReleaseGuard } from './functions.releasefacts.js';
10
10
  import type { FleetTicketEffects } from './classes.ticketeffects.js';
11
11
  import { ticketDeployPlanRefusesLink } from '../classes.ticketstore.js';
12
+ import { fleetRepositoryGap } from './functions.discovery.js';
12
13
 
13
14
  export interface IFleetServiceOptions {
14
15
  runner?: TFleetRunner;
@@ -18,7 +19,10 @@ export interface IFleetServiceOptions {
18
19
  reconcileSessions?: (owner: string) => Promise<unknown>;
19
20
  /** The Claude Code background jobs that look like drivers and that no worker binds; an audit lists them. */
20
21
  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
+ /**
23
+ * The board's tickets: a release checks their release plans and names the landed ones it ships; an audit names the
24
+ * landed ones whose code links name a repository outside the fleet.
25
+ */
22
26
  tickets?: (signal: AbortSignal) => Promise<ITicket[]>;
23
27
  /** A release went out: the release reconciler links and releases the landed tickets its tag holds, now rather than at its next pass. */
24
28
  released?: (repo: IFleetRepository) => void;
@@ -100,25 +104,36 @@ export class FleetService {
100
104
  return { operation: 'reconcile', ticketSync: await this.options.ticketEffects.reconcile(owner, args.ticketKey, args.eventKey, this.abort.signal) } as TFleetResult<T>;
101
105
  }
102
106
  const repoId = 'repo' in input ? input.repo : undefined;
103
- const target = repoId !== undefined && plugins.path.isAbsolute(repoId) ? await plugins.fs.promises.realpath(repoId).catch(() => plugins.path.resolve(repoId)) : undefined;
104
107
  // The one resolver every caller uses: a fleet id, `org/name` or a checkout path through its symlinks.
105
108
  const found = repoId === undefined ? undefined : findFleetRepository(configuration.repositories, repoId);
106
109
  const repositories = repoId === undefined ? configuration.repositories : found ? [found] : [];
107
- if (repoId !== undefined && repositories.length !== 1) {
108
- const skipped = configuration.skipped?.find((entry) => entry.path === target || plugins.path.basename(entry.path) === repoId);
109
- throw new Error(skipped ? `Repository ${repoId} is not in the fleet: ${skipped.reason}`
110
- : `Repository ${repoId} is not in the fleet: no canonical checkout below the workspace roots declares a release or a fleet section.`);
111
- }
110
+ if (repoId !== undefined && repositories.length !== 1) throw new Error(`${repoId} is not in the fleet: ${fleetRepositoryGap(configuration, repoId)}`);
112
111
  if (operation === 'audit') {
113
112
  running();
114
- const entries: IFleetAuditEntry[] = [], removed: string[] = [];
113
+ const entries: IFleetAuditEntry[] = [], removed: string[] = [], unaudited: IFleetUnauditedRepository[] = [];
115
114
  for (const repo of repositories) {
116
- const result = 'cleanup' in input && input.cleanup
117
- ? await this.exclusive(runtime, repo, () => this.auditRepository(runtime, repo, true))
118
- : await this.auditRepository(runtime, repo, false);
119
- entries.push(...result.entries); removed.push(...result.removed);
115
+ // One repository's failure is its own result; the audit goes on with the others and keeps what it read and removed.
116
+ try {
117
+ if ('cleanup' in input && input.cleanup) await this.exclusive(runtime, repo, () => this.auditRepository(runtime, repo, true, entries, removed));
118
+ else await this.auditRepository(runtime, repo, false, entries, removed);
119
+ } catch (error) {
120
+ if (this.abort.signal.aborted) throw error;
121
+ // A named repository's failure is the audit's error, which names the refs its cleanup removed before it.
122
+ if (repoId !== undefined) {
123
+ throw removed.length ? new Error(`${error instanceof Error ? error.message : 'Fleet audit failed.'} Removed before the failure: ${removed.join(', ')}.`, { cause: error }) : error;
124
+ }
125
+ unaudited.push({ repo: repo.id, path: repo.path, reason: (error instanceof Error ? error.message : 'unknown failure').slice(0, 1024) });
126
+ }
120
127
  }
121
128
  const skipped = repoId === undefined ? configuration.skipped ?? [] : [];
129
+ let outside: { tickets: IFleetLandedOutsideFleet[] } | { error: string } | undefined;
130
+ if (repoId === undefined && this.options.tickets) {
131
+ try { outside = { tickets: landedOutsideFleet(await this.options.tickets(this.abort.signal), configuration) }; }
132
+ catch (error) {
133
+ if (this.abort.signal.aborted) throw error;
134
+ outside = { error: `Board read: ${(error instanceof Error ? error.message : 'unknown failure').slice(0, 1024)}` };
135
+ }
136
+ }
122
137
  let unbound: { drivers: IFleetUnboundDriver[]; errors: string[] } | undefined;
123
138
  if (this.options.unboundDrivers) {
124
139
  try { unbound = await this.options.unboundDrivers(this.abort.signal); }
@@ -127,7 +142,8 @@ export class FleetService {
127
142
  unbound = { drivers: [], errors: [`Unbound driver search: ${(error instanceof Error ? error.message : 'unknown failure').slice(0, 1024)}`] };
128
143
  }
129
144
  }
130
- return { operation: 'audit', entries, removed, repositories, ...(skipped.length ? { skipped } : {}),
145
+ return { operation: 'audit', entries, removed, repositories, ...(skipped.length ? { skipped } : {}), ...(unaudited.length ? { unaudited } : {}),
146
+ ...(outside && 'tickets' in outside ? { landedOutsideFleet: outside.tickets } : outside ? { landedOutsideFleetError: outside.error } : {}),
131
147
  ...(unbound ? { unboundDrivers: unbound.drivers, ...(unbound.errors.length ? { unboundDriverErrors: unbound.errors } : {}) } : {}) } as TFleetResult<T>;
132
148
  }
133
149
  const repo = withHostEnvironment(repositories[0]!, configuration.environment);
@@ -332,9 +348,9 @@ export class FleetService {
332
348
  const first = /@\{(\d+)\}$/u.exec(reflog.stdout.trim().split('\n').at(-1) ?? '');
333
349
  return Number(first ? first[1] : await runtime.git(repo.path, ['log', '-1', '--format=%ct', sha])) * 1000;
334
350
  }
335
- private async auditRepository(runtime: IFleetRuntime, repo: IFleetRepository, cleanup: boolean): Promise<IFleetAuditResult> {
351
+ /** Adds the repository's entries and the refs its cleanup removed as it goes, so a failure keeps what was done before it. */
352
+ private async auditRepository(runtime: IFleetRuntime, repo: IFleetRepository, cleanup: boolean, entries: IFleetAuditEntry[], removed: string[]): Promise<void> {
336
353
  // Audit uses the local main snapshot and never fetches or prunes in read-only mode.
337
- const entries: IFleetAuditEntry[] = [], removed: string[] = [];
338
354
  const canonicalDirty = Boolean(await runtime.git(repo.path, ['status', '--porcelain']));
339
355
  const canonicalBranch = await runtime.git(repo.path, ['branch', '--show-current']);
340
356
  const main = await runtime.git(repo.path, ['rev-parse', 'main']);
@@ -385,10 +401,27 @@ export class FleetService {
385
401
  status: !exists ? 'stale' : tree.locked ? 'locked' : !tree.branch ? 'detached' : dirty ? 'dirty' : entry?.provenOnMain ? 'superseded' : 'unlanded',
386
402
  provenOnMain: entry?.provenOnMain ?? false });
387
403
  }
388
- return { operation: 'audit', entries, removed };
389
404
  }
390
405
  }
391
406
 
407
+ /**
408
+ * The landed tickets whose branch or commit links name a repository the scope does not hold as exactly one fleet
409
+ * repository (AGL-1974): the release reconciler releases a ticket only from discovered repositories, so each such link
410
+ * is named once per ticket with the reason discovery gives, in board order.
411
+ */
412
+ export const landedOutsideFleet = (ticketsArg: ITicket[], scopeArg: Pick<IFleetScope, 'repositories' | 'skipped' | 'unconfigured'>): IFleetLandedOutsideFleet[] => {
413
+ const gaps = new Map<string, string | undefined>();
414
+ return ticketsArg.flatMap((ticketArg) => {
415
+ if (ticketArg.columnId !== 'landed') return [];
416
+ const names = new Set(ticketArg.links.flatMap((linkArg) => linkArg.kind === 'branch' || linkArg.kind === 'commit' ? [linkArg.repo] : []));
417
+ return [...names].flatMap((nameArg) => {
418
+ if (!gaps.has(nameArg)) gaps.set(nameArg, fleetRepositoryGap(scopeArg, nameArg));
419
+ const reason = gaps.get(nameArg);
420
+ return reason === undefined ? [] : [{ ticketKey: ticketArg.key, repo: nameArg, reason }];
421
+ });
422
+ });
423
+ };
424
+
392
425
  export interface IFleetWorktree { path: string; branch?: string; head?: string; locked?: boolean }
393
426
  export const parseFleetWorktrees = (output: string): IFleetWorktree[] => {
394
427
  const results: IFleetWorktree[] = []; let current: IFleetWorktree | undefined;
@@ -1,7 +1,8 @@
1
1
  import * as plugins from '../plugins.js';
2
- import type { IFleetDiscoverySkip, IFleetRepository, IFleetRepositorySection } from '../../ts_interfaces/fleet.js';
2
+ import type { IFleetDiscoverySkip, IFleetRepository, IFleetRepositorySection, IFleetScope } from '../../ts_interfaces/fleet.js';
3
3
  import { runFleetCommand, type TFleetRunner } from './classes.runtime.js';
4
- import { fleetRepositoryIdPattern, validateFleetSection } from './functions.validation.js';
4
+ import { fleetRepositoryIdPattern, validateFleetRepository, validateFleetSection } from './functions.validation.js';
5
+ import { fleetRepositoryMatches } from './functions.releasefacts.js';
5
6
 
6
7
  /** The `.smartconfig.json` key holding a repository's fleet settings: `{ "@modelprofile.com/agl": { "fleet": { … } | false } }`. */
7
8
  export const fleetSectionKey = '@modelprofile.com/agl';
@@ -13,7 +14,13 @@ const maximumDepth = 3;
13
14
  const maximumDirectories = 20_000;
14
15
  const sectionDefaults: Required<Pick<IFleetRepositorySection, 'tests' | 'guards' | 'ciBuildSteps'>> = { tests: [], guards: [], ciBuildSteps: [] };
15
16
 
16
- export interface IFleetDiscovery { repositories: IFleetRepository[]; skipped: IFleetDiscoverySkip[] }
17
+ export interface IFleetDiscovery {
18
+ repositories: IFleetRepository[];
19
+ skipped: IFleetDiscoverySkip[];
20
+ /** The canonical checkouts that declare neither a release nor a fleet section: not skipped, just not fleet repositories. */
21
+ unconfigured: string[];
22
+ }
23
+ /** A checkout with neither `repository` nor `skip` declares no section. */
17
24
  interface ICandidate { path: string; repository?: Omit<IFleetRepository, 'id'>; skip?: string }
18
25
 
19
26
  const readJson = async (file: string): Promise<Record<string, unknown> | undefined> => {
@@ -52,17 +59,31 @@ const canonicalCheckouts = async (roots: string[], checkouts: string[]): Promise
52
59
  return [...found].sort();
53
60
  };
54
61
 
55
- const inspect = async (path: string, runner: TFleetRunner): Promise<ICandidate | undefined> => {
62
+ /**
63
+ * Why a checkout with a section has no `main` to land and release on, or undefined when it has one. The fleet lands
64
+ * and releases on `main` alone: a checkout on another default branch is reported, never followed onto that branch.
65
+ */
66
+ const missingMain = async (path: string, runner: TFleetRunner): Promise<string | undefined> => {
67
+ if ((await runner('git', ['rev-parse', '--verify', '--quiet', 'refs/heads/main^{commit}'], path)).code === 0) return undefined;
68
+ const head = await runner('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], path);
69
+ const branch = head.code === 0 ? head.stdout.trim() : '';
70
+ return branch === 'main' ? 'main has no commit yet; the fleet lands and releases on main only'
71
+ : `no main branch (${branch ? `${branch} is checked out` : 'HEAD is detached'}); the fleet lands and releases on main only`;
72
+ };
73
+
74
+ const inspect = async (path: string, runner: TFleetRunner): Promise<ICandidate> => {
56
75
  let config: Record<string, unknown> | undefined;
57
76
  try { config = await readJson(plugins.path.join(path, smartconfig)); }
58
77
  catch (error) { return { path, skip: `${smartconfig} is unreadable: ${error instanceof Error ? error.message : String(error)}` }; }
59
78
  const release = record(record(config?.['@git.zone/cli'])?.release);
60
79
  const declared = record(config?.[fleetSectionKey])?.fleet;
61
80
  if (declared === false) return { path, skip: `opted out by ${sectionPath} = false` };
62
- if (!release && declared === undefined) return undefined;
81
+ if (!release && declared === undefined) return { path };
63
82
  let section: IFleetRepositorySection;
64
83
  try { section = declared === undefined ? {} : validateFleetSection(declared); }
65
84
  catch (error) { return { path, skip: `${sectionPath} is invalid: ${error instanceof Error ? error.message : String(error)}` }; }
85
+ const noMain = await missingMain(path, runner);
86
+ if (noMain) return { path, skip: noMain };
66
87
  const sources: Record<string, string> = {};
67
88
  const configured = (await runner('git', ['config', '--get', 'branch.main.remote'], path)).stdout.trim();
68
89
  const remote = configured || 'origin';
@@ -95,16 +116,15 @@ const inspect = async (path: string, runner: TFleetRunner): Promise<ICandidate |
95
116
 
96
117
  /**
97
118
  * Finds every canonical Git checkout below the workspace roots (and each of `checkouts` that is one itself) whose `.smartconfig.json` declares a `@git.zone/cli`
98
- * release or a fleet section, and reads its fleet settings from the repository itself; there is no central list.
119
+ * release or a fleet section, and reads its fleet settings from the repository itself; there is no central list. A checkout
120
+ * without a commit on `main`, or one a fleet scope would refuse, is skipped with the reason.
99
121
  * Ids are directory names, prefixed with the parent directory while two repositories share a name.
100
122
  */
101
123
  export const discoverFleetRepositories = async (roots: string[], checkouts: string[] = [], runner: TFleetRunner = runFleetCommand): Promise<IFleetDiscovery> => {
102
124
  const candidates: ICandidate[] = [];
103
- for (const path of await canonicalCheckouts(roots, checkouts)) {
104
- const candidate = await inspect(path, runner);
105
- if (candidate) candidates.push(candidate);
106
- }
125
+ for (const path of await canonicalCheckouts(roots, checkouts)) candidates.push(await inspect(path, runner));
107
126
  const skipped = candidates.filter((candidate) => candidate.skip).map((candidate) => ({ path: candidate.path, reason: candidate.skip! }));
127
+ const unconfigured = candidates.filter((candidate) => !candidate.skip && !candidate.repository).map((candidate) => candidate.path);
108
128
  const admitted = candidates.filter((candidate) => candidate.repository);
109
129
  const names = new Map<string, number>();
110
130
  for (const { path } of admitted) names.set(plugins.path.basename(path), (names.get(plugins.path.basename(path)) ?? 0) + 1);
@@ -119,7 +139,29 @@ export const discoverFleetRepositories = async (roots: string[], checkouts: stri
119
139
  for (const repository of named) {
120
140
  if (!fleetRepositoryIdPattern.test(repository.id)) skipped.push({ path: repository.path, reason: `${repository.id} is not a valid fleet repository id (lowercase letters, digits, ., _ and -).` });
121
141
  else if (ids.get(repository.id)! > 1) skipped.push({ path: repository.path, reason: `${repository.id} names more than one checkout; rename one or opt one out.` });
122
- else repositories.push(repository);
142
+ else {
143
+ // A scope refuses as a whole what it cannot hold, so a checkout it would refuse is skipped here, with the reason.
144
+ try { validateFleetRepository(repository); repositories.push(repository); }
145
+ catch (error) { skipped.push({ path: repository.path, reason: `not a valid fleet repository: ${error instanceof Error ? error.message : String(error)}` }); }
146
+ }
147
+ }
148
+ return { repositories, skipped, unconfigured };
149
+ };
150
+
151
+ /**
152
+ * Why a repository name (fleet id, `org/name` or checkout path, as a ticket link holds it) resolves to no single
153
+ * repository of the scope, or undefined when it resolves to one: the reason discovery skipped its checkout, a checkout
154
+ * without a release or fleet section, several matching repositories, or no checkout below the roots at all.
155
+ */
156
+ export const fleetRepositoryGap = (scopeArg: Pick<IFleetScope, 'repositories' | 'skipped' | 'unconfigured'>, nameArg: string): string | undefined => {
157
+ const admitted = scopeArg.repositories.filter((repoArg) => fleetRepositoryMatches(repoArg, nameArg));
158
+ if (admitted.length === 1) return undefined;
159
+ if (admitted.length > 1) return `it names ${admitted.length} fleet repositories (${admitted.map((repoArg) => repoArg.id).join(', ')}); name it by its checkout path`;
160
+ const checkout = (pathArg: string) => ({ id: plugins.path.basename(pathArg), path: pathArg });
161
+ const reasons = [...new Set((scopeArg.skipped ?? []).filter((entryArg) => fleetRepositoryMatches(checkout(entryArg.path), nameArg)).map((entryArg) => entryArg.reason))];
162
+ if (reasons.length) return reasons.join('; ');
163
+ if ((scopeArg.unconfigured ?? []).some((pathArg) => fleetRepositoryMatches(checkout(pathArg), nameArg))) {
164
+ return `its ${smartconfig} declares no @git.zone/cli release and no ${fleetSectionKey} fleet section`;
123
165
  }
124
- return { repositories, skipped };
166
+ return 'no canonical checkout below the fleet discovery roots or among the registered projects matches it';
125
167
  };
@@ -12,6 +12,7 @@ import {
12
12
  fleetPendingChanges,
13
13
  fleetUnionNotes,
14
14
  } from './functions.conflicts.js';
15
+ import { fleetToolArgs, fleetToolStep, readFleetToolchainManifest } from './functions.toolchain.js';
15
16
 
16
17
  const optionalGitFile = async (runtime: IFleetRuntime, cwd: string, ref: string, file: string): Promise<string | undefined> => {
17
18
  const result = await runtime.run('git', ['show', `${ref}:${file}`], cwd);
@@ -214,7 +215,9 @@ export const rebaseFleetBranch = async (
214
215
  }
215
216
  if (generators.size) {
216
217
  const generated = new Set([...generators.values()].flatMap((files) => [...files]));
217
- for (const generator of generators.keys()) await runtime.checked('pnpm', ['exec', 'tsrun', generator], worktree, repo.environment);
218
+ // Generators run through the rebased branch's own pinned runner: tsrepo run, else the tsrun it still pins.
219
+ const runner = fleetToolStep(await readFleetToolchainManifest(worktree), 'run');
220
+ for (const generator of generators.keys()) await runtime.checked('pnpm', await fleetToolArgs(worktree, runner, [generator]), worktree, repo.environment);
218
221
  const changed = (await runtime.git(worktree, ['diff', '--name-only', '-z'])).split('\0').filter(Boolean);
219
222
  const unexpected = changed.filter((file) => !generated.has(file));
220
223
  const untracked = (await runtime.git(worktree, ['ls-files', '--others', '--exclude-standard', '-z'])).split('\0').filter(Boolean);
@@ -0,0 +1,56 @@
1
+ import * as plugins from '../plugins.js';
2
+
3
+ /** The manifest fields that name a repository's own checks and its pinned git.zone toolchain. */
4
+ export interface IFleetToolchainManifest {
5
+ scripts?: Record<string, string>;
6
+ dependencies?: Record<string, string>;
7
+ devDependencies?: Record<string, string>;
8
+ }
9
+ /** A fleet step that runs repository tooling: production typecheck, test typecheck, one test file, one TypeScript file. */
10
+ export type TFleetToolStep = 'typecheck' | 'test typecheck' | 'test' | 'run';
11
+ /** `pnpm run <script>`, or `pnpm exec <bin> <args>` for a binary the repository pins itself. */
12
+ export type TFleetToolCommand = { script: string } | { bin: string; args: string[] };
13
+
14
+ /**
15
+ * Each step prefers the repository's own script, then `@git.zone/tsrepo`, then the single tool it still pins.
16
+ * The single tools are npm-deprecated in favour of tsrepo; a binary the manifest does not pin is never run.
17
+ */
18
+ const fleetToolSteps: Record<TFleetToolStep, { script?: string; tsrepo: string[]; single: { name: string; bin: string; args: string[] } }> = {
19
+ typecheck: { script: 'typecheck', tsrepo: ['build', 'tsfolders'], single: { name: '@git.zone/tsbuild', bin: 'tsbuild', args: ['tsfolders'] } },
20
+ 'test typecheck': { script: 'check:test', tsrepo: ['check', 'test/**/*'], single: { name: '@git.zone/tsbuild', bin: 'tsbuild', args: ['check', 'test/**/*'] } },
21
+ test: { tsrepo: ['test'], single: { name: '@git.zone/tstest', bin: 'tstest', args: [] } },
22
+ run: { tsrepo: ['run'], single: { name: '@git.zone/tsrun', bin: 'tsrun', args: [] } },
23
+ };
24
+
25
+ export const readFleetToolchainManifest = async (cwd: string): Promise<IFleetToolchainManifest> => {
26
+ const file = plugins.path.join(cwd, 'package.json');
27
+ let text: string;
28
+ try { text = await plugins.fs.promises.readFile(file, 'utf8'); }
29
+ catch (error) {
30
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new Error(`Fleet tooling refused: ${file} is missing, so the repository pins no toolchain.`);
31
+ throw error;
32
+ }
33
+ return JSON.parse(text) as IFleetToolchainManifest;
34
+ };
35
+
36
+ /** Chooses a step's command from the manifest alone, so a repository without its own tooling is refused before anything runs. */
37
+ export const fleetToolStep = (manifest: IFleetToolchainManifest, step: TFleetToolStep): TFleetToolCommand => {
38
+ const entry = fleetToolSteps[step];
39
+ if (entry.script && manifest.scripts?.[entry.script]) return { script: entry.script };
40
+ const pinned = (name: string) => typeof manifest.devDependencies?.[name] === 'string' || typeof manifest.dependencies?.[name] === 'string';
41
+ if (pinned('@git.zone/tsrepo')) return { bin: 'tsrepo', args: entry.tsrepo };
42
+ if (pinned(entry.single.name)) return { bin: entry.single.bin, args: entry.single.args };
43
+ const script = entry.script ? `has no "${entry.script}" script and ` : '';
44
+ throw new Error(`Fleet ${step} refused: the repository ${script}pins neither @git.zone/tsrepo nor ${entry.single.name} in package.json. `
45
+ + `Add ${entry.script ? `a "${entry.script}" script or ` : ''}@git.zone/tsrepo to its devDependencies; the fleet never runs a ${entry.single.bin} or tsrepo from PATH.`);
46
+ };
47
+
48
+ /** The pnpm arguments of a chosen command; a pinned binary must be installed in the repository's own `node_modules/.bin`. */
49
+ export const fleetToolArgs = async (cwd: string, command: TFleetToolCommand, args: string[] = []): Promise<string[]> => {
50
+ if ('script' in command) return ['run', command.script, ...args];
51
+ const local = plugins.path.join(cwd, 'node_modules', '.bin', command.bin);
52
+ const installed = await plugins.fs.promises.stat(local).then((stats) => stats.isFile(), () => false);
53
+ if (!installed) throw new Error(`Fleet tooling refused: package.json pins ${command.bin} but ${local} is not installed; run pnpm install there. A ${command.bin} from PATH is never used.`);
54
+ // `pnpm exec` puts the repository's own node_modules/.bin first on PATH, so the installed binary is the one that runs.
55
+ return ['exec', command.bin, ...command.args, ...args];
56
+ };
@@ -76,7 +76,8 @@ export const validateFleetSection = (input: unknown): IFleetRepositorySection =>
76
76
  return structuredClone(section) as IFleetRepositorySection;
77
77
  };
78
78
  export const fleetRepositoryIdPattern = /^[a-z0-9][a-z0-9._-]{0,127}(?:\/[a-z0-9][a-z0-9._-]{0,127})?$/u;
79
- const validateFleetRepository = (input: unknown): void => {
79
+ /** One repository as a fleet scope holds it; discovery admits none this refuses, so one checkout never fails a whole scope. */
80
+ export const validateFleetRepository = (input: unknown): void => {
80
81
  const repo = object(input);
81
82
  keys(repo, ['id', 'path', 'remote', 'tests', 'guards', 'ciBuildSteps'],
82
83
  ['environment', 'environmentFrom', 'registries', 'publishedPackages', 'toolchain', 'fullSuitePaths', 'sources']);
@@ -154,7 +155,7 @@ export const validateFleetConfiguration = (input: unknown, _optionsArg: { save?:
154
155
  };
155
156
  /** Validates one operation's configuration with its discovered repositories. */
156
157
  export const validateFleetScope = (input: unknown): IFleetScope => {
157
- const { repositories, skipped, ...configuration } = object(input);
158
+ const { repositories, skipped, unconfigured, ...configuration } = object(input);
158
159
  validateFleetConfiguration(configuration);
159
160
  if (!Array.isArray(repositories) || repositories.length > 4096) throw new Error('Invalid fleet repository list.');
160
161
  const ids = new Set<string>(), paths = new Set<string>();
@@ -168,6 +169,10 @@ export const validateFleetScope = (input: unknown): IFleetScope => {
168
169
  if (!Array.isArray(skipped) || skipped.length > 4096) throw new Error('Invalid fleet discovery list.');
169
170
  for (const entry of skipped) { const item = object(entry); keys(item, ['path', 'reason']); string(item.path); string(item.reason); }
170
171
  }
172
+ if (unconfigured !== undefined) {
173
+ if (!Array.isArray(unconfigured) || unconfigured.length > 20_000) throw new Error('Invalid fleet discovery list.');
174
+ for (const path of unconfigured) if (!plugins.path.isAbsolute(string(path))) throw new Error('Invalid fleet discovery list.');
175
+ }
171
176
  return structuredClone(input) as IFleetScope;
172
177
  };
173
178
 
@@ -10,7 +10,7 @@ export const fleetToolDefinitions = [
10
10
  inputSchema: plugins.z.object({ repo: text(), ticketKey, pnpm: text().optional(), specs: plugins.z.array(text()).min(1).max(512).optional() }).strict(), readOnly: false },
11
11
  { name: 'fleet_reconcile', operation: 'reconcile' as const, description: 'Reconcile ticket effects using their exact saved attributed requests and keys. Never reruns landing or release. Omit eventKey to reconcile this ticket\'s pending, failed and unknown effects.',
12
12
  inputSchema: plugins.z.object({ ticketKey, eventKey: text().max(256).optional() }).strict(), readOnly: false },
13
- { name: 'fleet_audit', operation: 'audit' as const, description: 'Audit the discovered fleet repositories, with the source of each setting and every skipped checkout, for unlanded branches, superseded patches, stale/detached worktrees and dirty canonical checkouts. Read-only unless cleanup is true; cleanup only deletes unused local refs proven on main and pre-rebase backups proven on main or older than seven days.',
13
+ { name: 'fleet_audit', operation: 'audit' as const, description: 'Audit the discovered fleet repositories, with the source of each setting and every skipped checkout, for unlanded branches, superseded patches, stale/detached worktrees and dirty canonical checkouts; a repository whose audit fails is listed under unaudited with its reason, and the landed tickets whose code links name a repository outside the fleet under landedOutsideFleet with why. Read-only unless cleanup is true; cleanup only deletes unused local refs proven on main and pre-rebase backups proven on main or older than seven days.',
14
14
  inputSchema: plugins.z.object({ repo: text().optional(), ticketKey: ticketKey.optional(), cleanup: plugins.z.boolean().optional() }).strict(), readOnly: false },
15
15
  { name: 'fleet_status', operation: 'status' as const, description: 'Resume observation of a transient controller-owned fleet operation by its id. It remains queued or running after its original client disconnects. A controller restart loses operation observations; inspect the repository and gitzone journal before retrying.',
16
16
  inputSchema: plugins.z.object({ id: text(), ticketKey: ticketKey.optional() }).strict(), readOnly: true },