agentlane 0.5.1 → 0.6.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.
@@ -1,11 +1,134 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
- import { TOOL } from "../name.js";
3
+ import { envName, TOOL } from "../name.js";
3
4
  import { splitCommands } from "./shell.js";
5
+ /** The leading assignment, or variable in the hook's environment, that lets a container start through the guard. */
6
+ export const ALLOW_CONTAINER_ENV = envName('ALLOW_CONTAINER');
4
7
  const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
5
8
  const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish']);
6
9
  const RUNNERS = new Set(['npx', 'bunx', 'pnpx']);
7
10
  const PACKAGE_MANAGERS = new Set(['pnpm', 'npm', 'yarn', 'bun']);
8
- const PASS_THROUGH = new Set(['exec', 'nohup', 'builtin', 'noglob']);
11
+ const PASS_THROUGH = new Set(['exec', 'nohup', 'setsid', 'builtin', 'noglob']);
12
+ const PACKAGE_MANAGER_WITH_VALUE = new Set(['-C', '--dir', '--prefix', '--cwd', '--filter', '-F', '-w', '--workspace']);
13
+ const PACKAGE_MANAGER_CWD = new Set(['-C', '--dir', '--prefix', '--cwd']);
14
+ const LIFECYCLE_SCRIPTS = new Map([
15
+ ['start', 'start'],
16
+ ['test', 'test'],
17
+ ['t', 'test'],
18
+ ['restart', 'restart'],
19
+ ['stop', 'stop'],
20
+ ]);
21
+ const MAX_SCRIPT_DEPTH = 8;
22
+ const CONTAINER_GLOBAL_WITH_VALUE = new Set([
23
+ '-c',
24
+ '--config',
25
+ '--context',
26
+ '-H',
27
+ '--host',
28
+ '-l',
29
+ '--log-level',
30
+ '--tlscacert',
31
+ '--tlscert',
32
+ '--tlskey',
33
+ '--connection',
34
+ '--url',
35
+ '--identity',
36
+ '--root',
37
+ '--runroot',
38
+ '--storage-driver',
39
+ '--storage-opt',
40
+ '--cgroup-manager',
41
+ '--events-backend',
42
+ '--hooks-dir',
43
+ '--network-cmd-path',
44
+ '--network-config-dir',
45
+ '--runtime',
46
+ '--runtime-flag',
47
+ '--tmpdir',
48
+ '--module',
49
+ '--ssh',
50
+ '--conmon',
51
+ '--imagestore',
52
+ '--volumepath',
53
+ '--db-backend',
54
+ '--out',
55
+ '--cni-config-dir',
56
+ '--registries-conf',
57
+ '--cdi-spec-dir',
58
+ ]);
59
+ const COMPOSE_GLOBAL_WITH_VALUE = new Set([
60
+ '-f',
61
+ '--file',
62
+ '-p',
63
+ '--project-name',
64
+ '--profile',
65
+ '--env-file',
66
+ '--project-directory',
67
+ '--ansi',
68
+ '--parallel',
69
+ '--progress',
70
+ '--podman-path',
71
+ '--podman-args',
72
+ '--podman-pull-args',
73
+ '--podman-push-args',
74
+ '--podman-build-args',
75
+ '--podman-inspect-args',
76
+ '--podman-run-args',
77
+ '--podman-start-args',
78
+ '--podman-stop-args',
79
+ '--podman-rm-args',
80
+ '--podman-volume-args',
81
+ '--pod-args',
82
+ '--in-pod',
83
+ '--x-podman',
84
+ ]);
85
+ const CONTAINER_COMMANDS = new Set(('attach build builder buildx bake checkpoint commit compose config container context cp create debug ' +
86
+ 'desktop diff events exec export extension history image images import info init inspect kill load ' +
87
+ 'login logout logs ls manifest model network node pause plugin port prune ps pull push rename restart ' +
88
+ 'rm rmi run save sbom scout search secret service stack start stats stop swarm system tag top trust ' +
89
+ 'unpause update version volume wait help ai mcp offload auto-update artifact farm generate ' +
90
+ 'healthcheck kube machine mount play pod quadlet unmount umount unshare untag varlink').split(' '));
91
+ const COMPOSE_COMMANDS = new Set(('attach build commit config cp create down events exec export images kill logs ls pause port ps ' +
92
+ 'publish pull push restart rm run scale start stats stop top unpause up version volumes wait watch ' +
93
+ 'alpha bridge viz help systemd').split(' '));
94
+ /** The flags of `run` in docker, podman and compose that take no value; their parsers give every other flag the next word. */
95
+ const RUN_BOOLEAN_FLAGS = new Set([
96
+ '--detach',
97
+ '--disable-content-trust',
98
+ '--help',
99
+ '--init',
100
+ '--interactive',
101
+ '--no-healthcheck',
102
+ '--oom-kill-disable',
103
+ '--privileged',
104
+ '--publish-all',
105
+ '--quiet',
106
+ '--read-only',
107
+ '--rm',
108
+ '--sig-proxy',
109
+ '--tty',
110
+ '--use-api-socket',
111
+ '--env-host',
112
+ '--http-proxy',
113
+ '--no-hosts',
114
+ '--passwd',
115
+ '--read-only-tmpfs',
116
+ '--replace',
117
+ '--rmi',
118
+ '--rootfs',
119
+ '--tls-verify',
120
+ '--build',
121
+ '--no-deps',
122
+ '--remove-orphans',
123
+ '--service-ports',
124
+ '--use-aliases',
125
+ '--quiet-pull',
126
+ '--no-TTY',
127
+ '--quiet-build',
128
+ ]);
129
+ const RUN_BOOLEAN_SHORTS = /^[ditTPq]*/;
130
+ const UP_BOOLEAN_SHORTS = /^[dVwy]*/;
131
+ const TRUE = new Set(['1', 't', 'T', 'true', 'TRUE', 'True']);
9
132
  const ADB_READ_ONLY = new Set([
10
133
  'devices',
11
134
  'version',
@@ -69,22 +192,98 @@ function skipOptions(words, start, withValue) {
69
192
  }
70
193
  return i;
71
194
  }
195
+ /**
196
+ * The index of the subcommand: the first word that names one, past the options before it and any word that names none,
197
+ * such as the value of a global option this list doesn't know.
198
+ */
199
+ function subcommandAt(args, start, withValue, known, scope) {
200
+ let i = start;
201
+ while (i < args.length) {
202
+ const t = value(args[i], scope);
203
+ if (t !== null && known.has(t))
204
+ return i;
205
+ i += t !== null && withValue.has(t) ? 2 : 1;
206
+ }
207
+ return i;
208
+ }
209
+ /** Whether `run`'s options, up to the image or service, detach: `-d`, `--detach[=true]`, or `d` in a cluster like `-itd`. */
210
+ function runDetaches(args, scope) {
211
+ for (let i = 0; i < args.length; i++) {
212
+ const t = value(args[i], scope);
213
+ if (t === null || t === '--' || !t.startsWith('-') || t === '-')
214
+ return false;
215
+ if (t.startsWith('--')) {
216
+ const [flag = '', given] = t.split(/=(.*)/s);
217
+ if (flag === '--detach' && (given === undefined || TRUE.has(given)))
218
+ return true;
219
+ if (given === undefined && !RUN_BOOLEAN_FLAGS.has(flag))
220
+ i++;
221
+ continue;
222
+ }
223
+ const cluster = t.slice(1);
224
+ const flags = RUN_BOOLEAN_SHORTS.exec(cluster)?.[0] ?? '';
225
+ if (flags.includes('d'))
226
+ return true;
227
+ if (flags.length === cluster.length - 1)
228
+ i++;
229
+ }
230
+ return false;
231
+ }
232
+ /** Whether `compose up` detaches: `-d`, `--detach`, or `--wait`, which compose documents as implying detached mode. */
233
+ function upDetaches(args, scope) {
234
+ return args.some(word => {
235
+ const t = value(word, scope);
236
+ if (t === null || !t.startsWith('-') || t === '-')
237
+ return false;
238
+ const [flag = '', given] = t.split(/=(.*)/s);
239
+ if (flag === '--detach' || flag === '--wait')
240
+ return given === undefined || TRUE.has(given);
241
+ if (t.startsWith('--'))
242
+ return false;
243
+ return (UP_BOOLEAN_SHORTS.exec(t.slice(1))?.[0] ?? '').includes('d');
244
+ });
245
+ }
246
+ function nearestScripts(cwd) {
247
+ if (cwd === null)
248
+ return null;
249
+ for (let dir = cwd;; dir = path.dirname(dir)) {
250
+ let text;
251
+ try {
252
+ text = fs.readFileSync(path.join(dir, 'package.json'), 'utf8');
253
+ }
254
+ catch {
255
+ if (path.dirname(dir) === dir)
256
+ return null;
257
+ continue;
258
+ }
259
+ try {
260
+ const { scripts } = JSON.parse(text);
261
+ return typeof scripts === 'object' && scripts !== null ? { dir, scripts: scripts } : null;
262
+ }
263
+ catch {
264
+ return null;
265
+ }
266
+ }
267
+ }
72
268
  class Interpreter {
73
269
  aims = [];
74
270
  scope;
271
+ depth = 0;
75
272
  constructor(env, cwd) {
76
- this.scope = { env: new Map(Object.entries(env).map(([k, v]) => [k, v ?? null])), cwd };
273
+ this.scope = { env: new Map(Object.entries(env).map(([k, v]) => [k, v ?? null])), cwd, containersOnly: false };
77
274
  }
78
275
  script(text, scope = this.scope) {
79
276
  for (const command of splitCommands(text))
80
277
  this.command(command.words, scope);
81
278
  }
82
279
  aim(aim, words, scope) {
280
+ if (scope.containersOnly && aim.kind !== 'container')
281
+ return;
83
282
  this.aims.push({ aim, command: joined(words), cwd: scope.cwd });
84
283
  }
85
284
  command(words, outer) {
86
285
  let i = 0;
87
- const local = { env: new Map(outer.env), cwd: outer.cwd };
286
+ const local = { ...outer, env: new Map(outer.env) };
88
287
  for (; i < words.length; i++) {
89
288
  const word = words[i];
90
289
  const match = word?.literal ? ASSIGNMENT.exec(word.text) : null;
@@ -186,6 +385,14 @@ class Interpreter {
186
385
  case 'avdmanager':
187
386
  this.avdmanager(words, args, scope);
188
387
  return;
388
+ case 'docker':
389
+ case 'podman':
390
+ this.container(words, args, scope);
391
+ return;
392
+ case 'docker-compose':
393
+ case 'podman-compose':
394
+ this.compose(words, args, scope);
395
+ return;
189
396
  default:
190
397
  break;
191
398
  }
@@ -197,7 +404,7 @@ class Interpreter {
197
404
  const c = args.findIndex(w => w.literal && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(w.text));
198
405
  const script = c === -1 ? null : value(args[c + 1], scope);
199
406
  if (script !== null)
200
- this.script(script, { env: new Map(scope.env), cwd: scope.cwd });
407
+ this.script(script, { ...scope, env: new Map(scope.env) });
201
408
  return;
202
409
  }
203
410
  if (RUNNERS.has(head)) {
@@ -208,6 +415,10 @@ class Interpreter {
208
415
  this.command(args.slice(skipOptions(args, 1, new Set())), scope);
209
416
  return;
210
417
  }
418
+ if (PACKAGE_MANAGERS.has(head)) {
419
+ this.packageScript(head, args, scope);
420
+ return;
421
+ }
211
422
  if (head === TOOL && args[0]?.text === 'exec') {
212
423
  this.command(args.slice(skipOptions(args, 1, new Set())), scope);
213
424
  }
@@ -265,6 +476,93 @@ class Interpreter {
265
476
  if (session)
266
477
  this.aim({ kind: 'browser-session', driver, session }, words, scope);
267
478
  }
479
+ container(words, args, scope) {
480
+ const at = subcommandAt(args, 0, CONTAINER_GLOBAL_WITH_VALUE, CONTAINER_COMMANDS, scope);
481
+ let sub = value(args[at], scope);
482
+ let rest = args.slice(at + 1);
483
+ if (sub === 'container') {
484
+ const inner = subcommandAt(rest, 0, new Set(), CONTAINER_COMMANDS, scope);
485
+ sub = value(rest[inner], scope);
486
+ rest = rest.slice(inner + 1);
487
+ }
488
+ if (sub === 'compose') {
489
+ this.compose(words, rest, scope);
490
+ return;
491
+ }
492
+ const texts = rest.map(w => value(w, scope));
493
+ const starts = (sub === 'run' && runDetaches(rest, scope)) ||
494
+ ((sub === 'start' || sub === 'restart') && !texts.includes('--help')) ||
495
+ (sub === 'pod' && (texts[0] === 'start' || texts[0] === 'restart')) ||
496
+ (((sub === 'kube' && texts[0] === 'play') || (sub === 'play' && texts[0] === 'kube')) && !texts.includes('--down'));
497
+ if (starts)
498
+ this.startsContainer(words, scope);
499
+ }
500
+ compose(words, args, scope) {
501
+ const at = subcommandAt(args, 0, COMPOSE_GLOBAL_WITH_VALUE, COMPOSE_COMMANDS, scope);
502
+ const sub = value(args[at], scope);
503
+ const rest = args.slice(at + 1);
504
+ const starts = (sub === 'up' && upDetaches(rest, scope)) ||
505
+ (sub === 'run' && runDetaches(rest, scope)) ||
506
+ sub === 'start' ||
507
+ sub === 'restart';
508
+ if (starts)
509
+ this.startsContainer(words, scope);
510
+ }
511
+ startsContainer(words, scope) {
512
+ if (scope.env.get(ALLOW_CONTAINER_ENV) === '1')
513
+ return;
514
+ this.aim({ kind: 'container' }, words, scope);
515
+ }
516
+ /**
517
+ * npm runs a script with `run`, `run-script` or a lifecycle command, along with its pre- and post-scripts; pnpm, yarn
518
+ * and bun also run one named as the command itself. Each runs the script through `sh -c` in the folder of the nearest
519
+ * package.json.
520
+ */
521
+ packageScript(manager, args, scope) {
522
+ if (this.depth >= MAX_SCRIPT_DEPTH)
523
+ return;
524
+ let cwd = scope.cwd;
525
+ let i = 0;
526
+ while (i < args.length) {
527
+ const t = args[i]?.literal ? (args[i]?.text ?? '') : '';
528
+ if (!t.startsWith('-') || t === '-')
529
+ break;
530
+ const [flag = '', given] = t.split(/=(.*)/s);
531
+ if (PACKAGE_MANAGER_CWD.has(flag)) {
532
+ const dir = given ?? value(args[i + 1], scope);
533
+ cwd = dir === null || (cwd === null && !path.isAbsolute(dir)) ? null : path.resolve(cwd ?? '/', dir);
534
+ }
535
+ i += given === undefined && PACKAGE_MANAGER_WITH_VALUE.has(flag) ? 2 : 1;
536
+ }
537
+ const sub = value(args[i], scope);
538
+ if (sub === null)
539
+ return;
540
+ let name;
541
+ if (sub === 'run' || sub === 'run-script')
542
+ name = value(args[skipOptions(args, i + 1, new Set())], scope);
543
+ else if (manager !== 'bun' && LIFECYCLE_SCRIPTS.has(sub))
544
+ name = LIFECYCLE_SCRIPTS.get(sub);
545
+ else if (manager !== 'npm')
546
+ name = sub;
547
+ if (!name)
548
+ return;
549
+ const found = nearestScripts(cwd);
550
+ if (found === null)
551
+ return;
552
+ const names = manager === 'npm' ? [`pre${name}`, name, `post${name}`] : [name];
553
+ const inner = { env: new Map(scope.env), cwd: found.dir, containersOnly: true };
554
+ this.depth++;
555
+ try {
556
+ for (const key of names) {
557
+ const body = found.scripts[key];
558
+ if (typeof body === 'string')
559
+ this.script(body, inner);
560
+ }
561
+ }
562
+ finally {
563
+ this.depth--;
564
+ }
565
+ }
268
566
  cd(args, scope) {
269
567
  const target = args.find(w => !(w.literal && w.text.startsWith('-') && w.text !== '-'));
270
568
  if (!target)
@@ -278,7 +576,7 @@ class Interpreter {
278
576
  return scope.cwd === null ? null : path.resolve(scope.cwd, expanded);
279
577
  }
280
578
  env(args, scope) {
281
- const local = { env: new Map(scope.env), cwd: scope.cwd };
579
+ const local = { ...scope, env: new Map(scope.env) };
282
580
  let i = 0;
283
581
  while (i < args.length) {
284
582
  const w = args[i];
@@ -1,7 +1,7 @@
1
- import { CLI, TOOL } from "../name.js";
1
+ import { CLI, CONFIG_FILE, TOOL } from "../name.js";
2
2
  import { formatAge, formatTime } from "../registry/format.js";
3
3
  import { describeOwner, isProven } from "../registry/owner.js";
4
- import { aimsOf } from "./aims.js";
4
+ import { aimsOf, ALLOW_CONTAINER_ENV } from "./aims.js";
5
5
  const KIND = { ios: 'simulator', android: 'emulator' };
6
6
  function deviceLabel(lane) {
7
7
  const device = lane.device;
@@ -72,6 +72,8 @@ class Judge {
72
72
  return this.browsers.filter(c => (c.browser?.debugPort === aim.port || c.browser?.streamPort === aim.port) && theirs(c));
73
73
  case 'every-browser':
74
74
  return this.browsers.filter(c => c.browser?.driver === aim.driver && theirs(c));
75
+ case 'container':
76
+ return [];
75
77
  }
76
78
  }
77
79
  /** The caller's own lanes the command aims at, here. */
@@ -93,6 +95,8 @@ class Judge {
93
95
  return own(this.browsers.filter(c => c.browser?.debugPort === aim.port || c.browser?.streamPort === aim.port));
94
96
  case 'every-browser':
95
97
  return own(this.browsers.filter(c => c.browser?.driver === aim.driver));
98
+ case 'container':
99
+ return [];
96
100
  }
97
101
  }
98
102
  holder(lane, aim) {
@@ -121,6 +125,8 @@ function summary(aimed, holders) {
121
125
  return `\`${quoted}\` attaches to port ${String(aimed.aim.port)}, another lane's browser`;
122
126
  case 'every-browser':
123
127
  return `\`${quoted}\` stops every Playwright browser on this Mac, and other lanes hold some`;
128
+ case 'container':
129
+ return `\`${quoted}\` starts a container that keeps running after the command ends, and no lane will stop it`;
124
130
  }
125
131
  }
126
132
  function browserRecovery(aimed, holders, judge, self) {
@@ -162,6 +168,23 @@ function recovery(aimed, holders, judge, self) {
162
168
  lines.push(`${CLI} status (every lane with its owner)`);
163
169
  return lines;
164
170
  }
171
+ /**
172
+ * The denial of the first command among `aims` that starts a container which outlives it, such as `docker run -d` or
173
+ * `docker compose up -d`. It needs no lane to judge, so it can be given before the registry is read.
174
+ */
175
+ export function containerBlock(aims) {
176
+ const aimed = aims.find(a => a.aim.kind === 'container');
177
+ if (!aimed)
178
+ return { allow: true };
179
+ const lines = [
180
+ `${TOOL}: blocked: ${summary(aimed, [])}.`,
181
+ 'to recover:',
182
+ ` declare the server under "shared" in ${CONFIG_FILE} (or its data as a resource), then ${CLI} up, or ${CLI} up --no-app for the data alone`,
183
+ ` ${CLI} exec -- <command> (runs the work with that lane's servers and data)`,
184
+ ` ${ALLOW_CONTAINER_ENV}=1 ${aimed.command} (only if the user has asked, in this conversation, for a container outside lanes; ${TOOL} won't track or stop it)`,
185
+ ];
186
+ return { allow: false, reason: lines.join('\n') };
187
+ }
165
188
  /** The caller's own lanes a command the guard allows aims at: the command is a call on each of them. */
166
189
  export function aimedOwnLanes(script, env, ctx) {
167
190
  const judge = new Judge(ctx);
@@ -175,6 +198,9 @@ export function guard(script, env, ctx) {
175
198
  const aims = aimsOf(script, env, ctx.cwd);
176
199
  if (aims.length === 0)
177
200
  return { allow: true };
201
+ const container = containerBlock(aims);
202
+ if (!container.allow)
203
+ return container;
178
204
  const judge = new Judge(ctx);
179
205
  for (const aimed of aims) {
180
206
  const holders = judge.others(aimed);
@@ -15,7 +15,7 @@ import { commandUsage, groupUsage } from "../usage.js";
15
15
  import { toolVersion } from "../agents/package.js";
16
16
  import { aimsOf } from "./aims.js";
17
17
  import { CONVENTIONS, readHookInput } from "./conventions.js";
18
- import { aimedOwnLanes, guard } from "./guard.js";
18
+ import { aimedOwnLanes, containerBlock, guard } from "./guard.js";
19
19
  import { HOOK_PROBE_ENV, writeHookMark } from "./hook-mark.js";
20
20
  import { claimOnce } from "./hook-once.js";
21
21
  import { claudeSessionName } from "./session-name.js";
@@ -25,7 +25,9 @@ export const HOOK_HELP = {
25
25
  entries: {
26
26
  hook: ` hook pre-tool-use Deny a simctl, adb, emulator or avdmanager command aimed at a device
27
27
  another session holds, and a playwright-cli or agent-browser command
28
- aimed at another session's browser, the way the agent's hooks block.
28
+ aimed at another session's browser, and a docker or podman command that
29
+ starts a container which outlives it (run -d, start, compose up -d),
30
+ the way the agent's hooks block.
29
31
  hook session-end Release every lane this session holds and stop their services, in a
30
32
  detached process (the session-end budget is short).
31
33
  Both take --agent ${AGENTS.join('|')} (default claude).
@@ -61,8 +63,14 @@ function guardReply(raw, agent, deps) {
61
63
  const input = readHookInput(raw);
62
64
  const { command } = input;
63
65
  const cwd = input.cwd ?? deps.cwd;
64
- if (command === null || aimsOf(command, deps.env, cwd).length === 0)
66
+ if (command === null)
65
67
  return convention.allow;
68
+ const aims = aimsOf(command, deps.env, cwd);
69
+ if (aims.length === 0)
70
+ return convention.allow;
71
+ const container = containerBlock(aims);
72
+ if (!container.allow)
73
+ return convention.deny(container.reason);
66
74
  const owner = selfOwner(deps);
67
75
  const report = readRegistryStatus({
68
76
  dir: stateDir(deps.env),
package/dist/processes.js CHANGED
@@ -121,6 +121,19 @@ export function environmentOf(pid) {
121
121
  });
122
122
  return result.status === 0 ? result.stdout : undefined;
123
123
  }
124
+ const systemSignaller = (pid, signal) => {
125
+ process.kill(pid, signal);
126
+ };
127
+ /** Sends SIGKILL to every process of group `pgid`; false when none was left, or none could be signalled. */
128
+ export function killGroup(pgid, signal = systemSignaller) {
129
+ try {
130
+ signal(-pgid, 'SIGKILL');
131
+ return true;
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ }
124
137
  export function identityOf(table, pid) {
125
138
  const start = table.startTimes([pid])?.get(pid);
126
139
  return start === undefined ? undefined : { pid, start };
@@ -6,11 +6,11 @@ import { AGENT_BROWSER_RELEASE } from "../browser/release.js";
6
6
  import { parseBuildCacheConfig } from "../cache/config.js";
7
7
  import { CLI, CONFIG_FILE, ENV_PREFIX, FORMER, SCHEMA_FILE, TOOL } from "../name.js";
8
8
  import { UsageError } from "../registry/refusal.js";
9
- import { BUILT_IN_SERVICE_TYPES, DEFAULT_DIAL_VALUE, DEFAULT_READY_HOST, DEFAULT_READY_SECONDS, DEFAULT_TEARDOWN_SECONDS, DEFAULT_VARIANT, DEFAULT_WEB_PATH, projectSchema, WEB_PLATFORM, } from "./schema.js";
9
+ import { BUILT_IN_SERVICE_TYPES, DEFAULT_DIAL_VALUE, DEFAULT_READY_HOST, DEFAULT_READY_SECONDS, DEFAULT_SHARED_SECONDS, DEFAULT_TEARDOWN_SECONDS, DEFAULT_VARIANT, DEFAULT_WEB_PATH, projectSchema, WEB_PLATFORM, } from "./schema.js";
10
10
  import { SchemaValidator } from "./validate.js";
11
11
  export function asMobile(config) {
12
12
  const { app, platform } = config;
13
- return app !== null && platform !== WEB_PLATFORM ? { ...config, app, platform } : null;
13
+ return app !== null && platform !== null && platform !== WEB_PLATFORM ? { ...config, app, platform } : null;
14
14
  }
15
15
  export class ProjectConfigError extends Error {
16
16
  file;
@@ -106,13 +106,29 @@ function resourceProblems(raw) {
106
106
  }
107
107
  return problems;
108
108
  }
109
+ function needsProblems(raw) {
110
+ const declared = Object.keys(raw.shared ?? {});
111
+ const users = [
112
+ ...Object.entries(raw.resources ?? {}).map(([name, r]) => [`/resources/${name}`, r]),
113
+ ...Object.entries(raw.services ?? {}).map(([name, s]) => [`/services/${name}`, s]),
114
+ ];
115
+ const problems = [];
116
+ for (const [at, user] of users) {
117
+ (user.needs ?? []).forEach((name, i) => {
118
+ if (declared.includes(name))
119
+ return;
120
+ problems.push(problem(`${at}/needs/${String(i)}`, `${name} is not a shared service; declare it under shared, or name one of: ${declared.join(', ') || 'none'}`));
121
+ });
122
+ }
123
+ return problems;
124
+ }
109
125
  function crossFieldProblems(raw) {
110
126
  const services = Object.entries(raw.services ?? {});
111
127
  const problems = [];
112
128
  if (!raw.app && !raw.web) {
113
129
  problems.push(problem('', 'declares no app: add app (a mobile app), web (a web app), or both'));
114
130
  }
115
- problems.push(...appProblems(raw, services), ...webProblems(raw, services), ...browserProblems(raw), ...resourceProblems(raw));
131
+ problems.push(...appProblems(raw, services), ...webProblems(raw, services), ...browserProblems(raw), ...resourceProblems(raw), ...needsProblems(raw));
116
132
  for (const [name, service] of services) {
117
133
  if (BROWSER_SERVICES.includes(name)) {
118
134
  problems.push(problem(`/services/${name}`, `${name} is the name of the lane's browser ports; name the service otherwise`));
@@ -146,6 +162,7 @@ function normalize(raw, file) {
146
162
  timeoutMs: (s.timeoutSeconds ?? DEFAULT_READY_SECONDS) * 1000,
147
163
  dial: s.dial ? { argument: s.dial.argument, value: s.dial.value ?? DEFAULT_DIAL_VALUE } : null,
148
164
  platforms: s.platforms ?? null,
165
+ needs: s.needs ?? [],
149
166
  };
150
167
  });
151
168
  const { app } = raw;
@@ -194,6 +211,15 @@ function normalize(raw, file) {
194
211
  teardown: r.teardown,
195
212
  cwd: path.resolve(dir, r.cwd ?? '.'),
196
213
  teardownTimeoutMs: (r.teardownTimeoutSeconds ?? DEFAULT_TEARDOWN_SECONDS) * 1000,
214
+ needs: r.needs ?? [],
215
+ })),
216
+ shared: Object.entries(raw.shared ?? {}).map(([name, s]) => ({
217
+ name,
218
+ start: s.start,
219
+ stop: s.stop,
220
+ ready: s.ready,
221
+ cwd: path.resolve(dir, s.cwd ?? '.'),
222
+ timeoutMs: (s.timeoutSeconds ?? DEFAULT_SHARED_SECONDS) * 1000,
197
223
  })),
198
224
  hooks: { ...raw.hooks },
199
225
  preconditions: (raw.preconditions ?? []).map(p => ({
@@ -256,9 +282,21 @@ export function forPlatform(config, platform) {
256
282
  }
257
283
  return { ...config, platform, app: resolveApp(config.baseApp, config.platformApps, platform), services };
258
284
  }
259
- /** The config a lane was brought up with: for its platform, while the config still declares that platform. */
285
+ /**
286
+ * The config as `up --no-app` sees it: the project's data alone, for no platform, with no app, web app or service to
287
+ * run. Its resources, shared services, hooks and preconditions stay.
288
+ */
289
+ export function withoutApp(config) {
290
+ return { ...config, platform: null, app: null, web: null, services: [] };
291
+ }
292
+ /**
293
+ * The config a lane was brought up with: for its platform, while the config still declares that platform, and the
294
+ * project's data alone for a lane `up --no-app` made (`platform` null).
295
+ */
260
296
  export function loadLaneConfig(file, platform) {
261
297
  const loaded = loadProjectConfig(file);
298
+ if (platform === null)
299
+ return withoutApp(loaded);
262
300
  return platform !== undefined && declaredPlatforms(loaded).includes(platform) ? forPlatform(loaded, platform) : loaded;
263
301
  }
264
302
  export function parseProjectConfig(raw, file) {
@@ -18,6 +18,7 @@ export const DEFAULT_VARIANT = 'Debug';
18
18
  export const DEFAULT_READY_HOST = '127.0.0.1';
19
19
  export const DEFAULT_READY_SECONDS = 60;
20
20
  export const DEFAULT_DIAL_VALUE = 'http://localhost:{port}';
21
+ export const DEFAULT_SHARED_SECONDS = 180;
21
22
  const port = { type: 'integer', minimum: 1024, maximum: 65535 };
22
23
  const bundleId = {
23
24
  type: 'string',
@@ -62,6 +63,12 @@ const host = {
62
63
  default: DEFAULT_READY_HOST,
63
64
  description: 'The host the readiness check connects to.',
64
65
  };
66
+ const needs = {
67
+ type: 'array',
68
+ items: { type: 'string', pattern: SERVICE_NAME_PATTERN },
69
+ uniqueItems: true,
70
+ description: 'The shared services this uses, by their names under `shared`.',
71
+ };
65
72
  const hook = (when) => ({ type: 'string', minLength: 1, description: `A shell command run with \`sh -c\` ${when}.` });
66
73
  export const projectSchema = {
67
74
  $schema: 'https://json-schema.org/draft/2020-12/schema',
@@ -85,6 +92,12 @@ export const projectSchema = {
85
92
  propertyNames: { pattern: SERVICE_NAME_PATTERN },
86
93
  additionalProperties: { $ref: '#/$defs/resource' },
87
94
  },
95
+ shared: {
96
+ type: 'object',
97
+ description: `The servers the lanes of this repository use together, such as the database server each lane's database lives in, by name. There is one of each per repository, used by the lanes of all its worktrees. A lane needs a shared service when one of its resources or services names it in \`needs\`. ${TOOL} starts a shared service when a lane needs it, and stops it 5 minutes after the last lane that needs it parks or ends; it never removes one. A shared service whose start failed may be partly up, so it counts as running and stops under the same rule. A stop runs the commands, with the PATH and the variables that choose a container tool's daemon and project, as they were at the shared service's last start, so a change to them counts from its next start.`,
98
+ propertyNames: { pattern: SERVICE_NAME_PATTERN },
99
+ additionalProperties: { $ref: '#/$defs/shared' },
100
+ },
88
101
  hooks: { $ref: '#/$defs/hooks' },
89
102
  preconditions: {
90
103
  type: 'array',
@@ -197,6 +210,36 @@ export const projectSchema = {
197
210
  default: DEFAULT_TEARDOWN_SECONDS,
198
211
  description: 'How long teardown may run before it is stopped and counted as failed.',
199
212
  },
213
+ needs,
214
+ },
215
+ },
216
+ shared: {
217
+ type: 'object',
218
+ additionalProperties: false,
219
+ required: ['start', 'stop', 'ready'],
220
+ properties: {
221
+ start: {
222
+ type: 'string',
223
+ minLength: 1,
224
+ description: 'A shell command that starts the server and exits, leaving it running. It must cope with running twice and with finding the server already running.',
225
+ },
226
+ stop: {
227
+ type: 'string',
228
+ minLength: 1,
229
+ description: 'A shell command that stops the server and keeps its data. It must cope with running twice and with finding the server already stopped, or only partly started.',
230
+ },
231
+ ready: {
232
+ type: 'string',
233
+ minLength: 1,
234
+ description: `A shell command that exits 0 when the server answers. ${TOOL} also runs it to tell whether the shared service is running.`,
235
+ },
236
+ cwd: { type: 'string', minLength: 1, description: 'The directory start, stop and ready run in, relative to this file.' },
237
+ timeoutSeconds: {
238
+ type: 'number',
239
+ exclusiveMinimum: 0,
240
+ default: DEFAULT_SHARED_SECONDS,
241
+ description: 'How long start may run, and then how long ready may take to pass, before the start counts as failed; and how long stop may run before it counts as failed.',
242
+ },
200
243
  },
201
244
  },
202
245
  service: {
@@ -251,6 +294,7 @@ export const projectSchema = {
251
294
  },
252
295
  },
253
296
  },
297
+ needs,
254
298
  },
255
299
  },
256
300
  httpReady: {