@futurelastic/colab-handbook 1.13.0-rc.2 → 1.13.0-rc.21

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.
@@ -95,6 +95,43 @@ function isIntentSession(s) {
95
95
  return /^intent:\S/.test(String(s == null ? '' : s).trim());
96
96
  }
97
97
 
98
+ /**
99
+ * Should a blank session be DERIVED for a person at a plain terminal (#528)? Only when nothing was
100
+ * said at all: `COLAB_SESSION` is UNSET (an explicit `COLAB_SESSION=''` is a deliberate "present no
101
+ * identity" and is honoured as one), and the shell is not an agent's (`CLAUDECODE=1` / `AI_AGENT`,
102
+ * the same signal `place.resolveAnchor` reads). An agent keeps #242's refusal: two concurrent agent
103
+ * sessions on one machine would derive the SAME person id, and `place.conflict`'s same-holder
104
+ * exemption would then read one session's hold as the other's — the collision #242 exists to stop.
105
+ * A person running several units at once from separate shells has the same problem, which is why
106
+ * the README tells them to give each shell its own `COLAB_SESSION`.
107
+ */
108
+ function shouldDerivePersonSession(env) {
109
+ const e = env || {};
110
+ if (Object.prototype.hasOwnProperty.call(e, 'COLAB_SESSION')) return false;
111
+ if (e.CLAUDECODE === '1' || e.AI_AGENT) return false;
112
+ return true;
113
+ }
114
+
115
+ /**
116
+ * The derived identity for a person (#528): `person:<who>/<hostToken>`, where `<who>` is git's
117
+ * `user.email`, else the OS user. The host is the opaque `h:` token (`machine.hostToken`), never
118
+ * the raw name: this value is written verbatim into claim comments, and a public tracker must not
119
+ * learn a machine's name from it (#369). Stable across invocations — the same person on the same
120
+ * machine always derives the same value, which is what a re-acquire needs. '' when no `<who>` or
121
+ * no host is available: then nothing is derived and the blank-session paths apply unchanged.
122
+ */
123
+ function derivePersonSession({ email, user, hostToken } = {}) {
124
+ const who = String(email || '').trim() || String(user || '').trim();
125
+ const host = String(hostToken || '').trim();
126
+ if (!who || !host || /\s/.test(who)) return '';
127
+ return `person:${who}/${host}`;
128
+ }
129
+
130
+ /** Is `s` a derived person identity (#528)? */
131
+ function isPersonSession(s) {
132
+ return /^person:\S+$/.test(String(s == null ? '' : s).trim());
133
+ }
134
+
98
135
  /**
99
136
  * Are `a` and `b` on the SAME machine (#327)? Both carry a `machine` → compare those (a raw id or
100
137
  * the `m:` digest a claim comment carries — `machineToken` makes the two comparable); raw ids of
@@ -189,4 +226,5 @@ module.exports = {
189
226
  DEFAULT_COMPONENTS, FINE_COMPONENTS,
190
227
  claimIdentityProblem, components, identityString, sameClaimant, mergeClaimRecord,
191
228
  looksLikeSessionId, isIntentSession, sameHost,
229
+ shouldDerivePersonSession, derivePersonSession, isPersonSession,
192
230
  };
@@ -35,13 +35,18 @@ const MACHINE_RE = /· machine `(m:[0-9a-f]{12})`/;
35
35
  const YIELD_RE = /^✅ Released \(yielded — earlier claim by (.+?) wins\)/;
36
36
 
37
37
  /**
38
- * Does `v` look like a session URL / `session_…` id rather than a display name? A SHAPE heuristic
39
- * (#306), not a gate — claim-identity.js re-exports this one copy of it.
38
+ * Does `v` look like a session id — a URL, a `session_…` token, a bare uuid — rather than a display
39
+ * name? A SHAPE heuristic (#306), not a gate — claim-identity.js re-exports this one copy of it.
40
+ * The uuid shape is #531: `--session` takes any stable id, and an engine whose session id is a bare
41
+ * uuid must not have it read back from a claim comment as a session NAME.
40
42
  */
41
43
  function looksLikeSessionId(v) {
42
44
  const s = String(v == null ? '' : v).trim();
43
45
  if (!s) return false;
44
- return /^https?:\/\//.test(s) || /session_[\w-]+/.test(s);
46
+ // #528: a derived person identity (`claim-identity.js` `derivePersonSession`) is a session id
47
+ // too — a stable join key, not a display name — so it reads back as one from a claim comment.
48
+ return /^https?:\/\//.test(s) || /session_[\w-]+/.test(s) || /^person:\S+$/.test(s)
49
+ || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
45
50
  }
46
51
 
47
52
  /**
@@ -169,6 +169,11 @@
169
169
  * this entry, plus the matching `code-triage` verdict, is what makes those readings
170
170
  * reconcilable instead of silently contradictory.
171
171
  *
172
+ * `priority:now` / `priority:high` joined the set in #537: the upward rank beside `low-priority`
173
+ * (CONVENTIONS.md §5, *Priority*). Fixed values, not a prefix kind — they decode as plain
174
+ * `convention` labels. Same malignant-absence reason: a rank only the owner may set must be
175
+ * appliable the moment the owner says so, which a label the repo never created is not.
176
+ *
172
177
  * `deferred:date` / `deferred:measurement` / `deferred:external-party` joined the set in
173
178
  * #279: `deps-checked` was being asked to carry two orthogonal facts at once — "has a
174
179
  * reasoning session evaluated this?" (process state, monotonic — the label's own
@@ -222,6 +227,8 @@ const CONVENTION_LABELS = [
222
227
  { name: 'needs-migration-grant', color: 'D4C5F9', description: 'Agent-flagged: deliverable is a schema migration; surfaces the grant request for a human to Accept' },
223
228
  { name: 'ci-granted', color: 'D73A4A', description: "A human granted this branch a one-shot exemption from ship's trunk-CI-green gate" },
224
229
  { name: 'low-priority', color: 'C2E0C6', description: 'Throttle, not a veto — startable, but code-triage ranks it behind every other ready group' },
230
+ { name: 'priority:now', color: 'B60205', description: "Rank first among ready work — the owner's order; never skips a gate or overrides a file hold" },
231
+ { name: 'priority:high', color: 'D93F0B', description: 'Rank ahead of default among ready work — owner or coordinator; never skips a gate' },
225
232
  { name: 'delivery:code', color: '1D76DB', description: 'Delivery is a code commit — the ordinary code pipeline applies' },
226
233
  { name: 'delivery:content', color: 'FEF2C0', description: 'Delivery is a content push, not a code commit — route, do not start in the code pipeline' },
227
234
  { name: 'delivery:ops', color: 'D4C5F9', description: 'Delivery is an ops/production check, not a code commit — route, do not start in the code pipeline' },
@@ -81,6 +81,22 @@
81
81
  "known": true
82
82
  }
83
83
  },
84
+ {
85
+ "wire": "priority:now",
86
+ "decoded": {
87
+ "kind": "convention",
88
+ "value": "priority:now",
89
+ "known": true
90
+ }
91
+ },
92
+ {
93
+ "wire": "priority:high",
94
+ "decoded": {
95
+ "kind": "convention",
96
+ "value": "priority:high",
97
+ "known": true
98
+ }
99
+ },
84
100
  {
85
101
  "wire": "release-hold",
86
102
  "decoded": {
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+ /**
3
+ * engines/<id>.conf — one data file per coding agent the skills can be installed for (#530).
4
+ *
5
+ * The format is deliberately trivial (`key: value` lines, `#` comments, `note:`/`caveat:`
6
+ * repeatable) so install.sh can read it with sed, without node — a skills-only install must not
7
+ * need the CLI's runtime. This module is the JS reader for `install.sh --check`; the two readers
8
+ * must agree, and install-sh.test.js holds them to it. engines/README.md is the format's doc.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ const REPEATABLE = new Set(['note', 'caveat']);
15
+
16
+ /** Parse one conf file's text. First occurrence of a single-valued key wins, as `sed …;q` does. */
17
+ function parseConf(text) {
18
+ const out = { note: [], caveat: [] };
19
+ for (const raw of String(text).split(/\r?\n/)) {
20
+ if (/^\s*#/.test(raw)) continue;
21
+ const m = /^([a-z_]+):[ \t]*(.*)$/.exec(raw);
22
+ if (!m) continue;
23
+ const [, key, value] = m;
24
+ if (REPEATABLE.has(key)) out[key].push(value);
25
+ else if (!(key in out)) out[key] = value;
26
+ }
27
+ return out;
28
+ }
29
+
30
+ /** `~/x` → <home>/x. Same rule as install.sh's expand_home for the values a conf file can hold. */
31
+ function expandHome(p, home) {
32
+ if (p === '~') return home;
33
+ if (p.startsWith('~/')) return path.join(home, p.slice(2));
34
+ return p;
35
+ }
36
+
37
+ /** Every engine in <root>/engines, in file order (the order install.sh's prompt numbers them). */
38
+ function listEngines(root) {
39
+ const dir = path.join(root, 'engines');
40
+ let files = [];
41
+ try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.conf')).sort(); } catch (_) { return []; }
42
+ return files.map((f) => ({ id: f.slice(0, -'.conf'.length), ...parseConf(fs.readFileSync(path.join(dir, f), 'utf8')) }));
43
+ }
44
+
45
+ /** Folders given with --skills-dir on an earlier install, one per line in <COLAB_HOME>/skills-dirs. */
46
+ function rememberedDirs(colabHome) {
47
+ let text = '';
48
+ try { text = fs.readFileSync(path.join(colabHome, 'skills-dirs'), 'utf8'); } catch (_) { return []; }
49
+ return text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));
50
+ }
51
+
52
+ module.exports = { parseConf, expandHome, listEngines, rememberedDirs };
@@ -27,6 +27,7 @@ const path = require('path');
27
27
  const { execFileSync } = require('child_process');
28
28
  const stamp = require('./stamp');
29
29
  const notifyEndpoint = require('./notify-endpoint');
30
+ const engines = require('./engines');
30
31
 
31
32
  const OK = 'ok';
32
33
  const WARN = 'warn';
@@ -141,6 +142,75 @@ function checkFrozen({ root, colabHome }) {
141
142
  return rows;
142
143
  }
143
144
 
145
+ /**
146
+ * The skills, per engine (#530). For every engine in engines/ with a folder of its own, plus every
147
+ * folder an earlier --skills-dir remembered: how many of this clone's skills are linked there, which
148
+ * are missing (a skill added since the install — re-run it), which links are broken (they point into
149
+ * this clone's skills/ at a folder that no longer exists — ✗, installed and now unusable), and which
150
+ * names something else holds (⚠, possibly a deliberate local variant; install.sh never clobbers it).
151
+ *
152
+ * An engine with nothing linked is "not installed for it" — one ✓ line naming them, because a
153
+ * Claude-only machine is a correct machine. Only when NO engine has the skills is that a ⚠.
154
+ * The engine's own `caveat:` lines become ⚠ rows while it is installed: they are what the user must
155
+ * do there for the skills to work (a sandbox with no network, say), and they stay true until done.
156
+ */
157
+ function checkSkills({ root, home, colabHome }) {
158
+ const src = path.join(root, 'skills');
159
+ let skills = [];
160
+ try { skills = fs.readdirSync(src, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort(); } catch (_) { /* none */ }
161
+ const all = engines.listEngines(root);
162
+ const byId = Object.fromEntries(all.map((e) => [e.id, e]));
163
+ const targets = all.filter((e) => e.skills_dir).map((e) => ({ e, dir: engines.expandHome(e.skills_dir, home) }));
164
+ for (const dir of engines.rememberedDirs(colabHome)) {
165
+ if (!targets.some((t) => t.dir === dir)) targets.push({ e: byId.generic || { id: 'generic', label: 'another engine', note: [], caveat: [] }, dir });
166
+ }
167
+
168
+ const rows = [];
169
+ const notInstalled = [];
170
+ for (const { e, dir } of targets) {
171
+ const linked = []; const missing = []; const broken = []; const foreign = [];
172
+ for (const name of skills) {
173
+ const dest = path.join(dir, name);
174
+ let st;
175
+ try { st = fs.lstatSync(dest); } catch (_) { missing.push(name); continue; }
176
+ if (!st.isSymbolicLink()) { foreign.push(name); continue; }
177
+ const to = path.resolve(dir, fs.readlinkSync(dest));
178
+ if (to === path.join(src, name)) linked.push(name);
179
+ else foreign.push(name);
180
+ }
181
+ // Links into this clone's skills/ whose target is gone: a skill removed or renamed upstream.
182
+ let entries = [];
183
+ try { entries = fs.readdirSync(dir); } catch (_) { /* folder absent */ }
184
+ for (const n of entries) {
185
+ const p = path.join(dir, n);
186
+ try {
187
+ if (!fs.lstatSync(p).isSymbolicLink()) continue;
188
+ const to = path.resolve(dir, fs.readlinkSync(p));
189
+ if (to.startsWith(src + path.sep) && !fs.existsSync(to)) broken.push(n);
190
+ } catch (_) { /* unreadable entry — not ours to judge */ }
191
+ }
192
+ const who = `${e.id} (${e.label || e.id}) ${dir}`;
193
+ if (!linked.length && !broken.length) { notInstalled.push(e.id === 'generic' ? dir : `${e.id} (${e.label || e.id})`); continue; }
194
+ const parts = [`${linked.length}/${skills.length} linked`];
195
+ if (missing.length) parts.push(`missing ${missing.join(', ')} — re-run ./install.sh${e.id === 'generic' ? '' : ` --engine ${e.id}`}`);
196
+ if (foreign.length) parts.push(`held by something else (left as is): ${foreign.join(', ')}`);
197
+ if (broken.length) parts.push(`BROKEN links to skills that no longer exist: ${broken.join(', ')} — remove them: ${broken.map((b) => `rm '${path.join(dir, b)}'`).join('; ')}`);
198
+ rows.push({
199
+ area: 'skills',
200
+ severity: broken.length ? FAIL : (missing.length || foreign.length) ? WARN : OK,
201
+ text: `${who}: ${parts.join('; ')}`,
202
+ });
203
+ for (const c of e.caveat || []) rows.push({ area: 'skills', severity: WARN, text: `${e.id}: ${c}` });
204
+ if (e.verified && /^no\b/.test(e.verified)) rows.push({ area: 'skills', severity: WARN, text: `${e.id}: engine file not verified by a run yet — ${e.verified.replace(/^no\s*[—-]?\s*/, '')}` });
205
+ }
206
+ if (!rows.length) {
207
+ rows.push({ area: 'skills', severity: WARN, text: `not linked for any engine — ./install.sh asks which (or --engine <id> / --skills-dir <path>)` });
208
+ } else if (notInstalled.length) {
209
+ rows.push({ area: 'skills', severity: OK, text: `not installed for: ${notInstalled.join(', ')} — fine if deliberate; ./install.sh --engine <id> adds one` });
210
+ }
211
+ return rows;
212
+ }
213
+
144
214
  /** The state file. The CLI creates it lazily, so a consumer reading it early saw an error, not an empty fleet. */
145
215
  function checkState({ root, colabHome, home }) {
146
216
  const file = path.join(colabHome, 'state.json');
@@ -236,15 +306,17 @@ function checkNotify({ colabHome }) {
236
306
  try { cfg = JSON.parse(readText(path.join(colabHome, 'config.json')) || '{}'); } catch (_) { /* reported by colab itself */ }
237
307
  const st = notifyEndpoint.status(cfg, colabHome);
238
308
  if (st.state === 'unset') return [];
239
- if (st.state === 'set' && !st.declared) {
240
- return [{ area: 'notify', severity: OK, text: `notifyUrl = ${st.url}` }];
241
- }
242
- return [{ area: 'notify', severity: WARN, text: notifyEndpoint.healthLine(st) }];
309
+ // One ⚠ row per problem — each declared URL the key lacks is its own row (#546), so a machine
310
+ // running two observers sees which one is going without, not a single blended line.
311
+ const problems = notifyEndpoint.healthLines(st);
312
+ if (problems.length) return problems.map((text) => ({ area: 'notify', severity: WARN, text }));
313
+ return [{ area: 'notify', severity: OK, text: `notifyUrl = ${st.urls.join(', ')}` }];
243
314
  }
244
315
 
245
316
  function runChecks(opts) {
246
317
  const o = { env: process.env, ...opts };
247
318
  return [
319
+ ...checkSkills(o),
248
320
  checkLink(o),
249
321
  ...checkFrozen(o),
250
322
  checkState(o),
@@ -280,5 +352,5 @@ if (require.main === module) {
280
352
 
281
353
  module.exports = {
282
354
  OK, WARN, FAIL,
283
- dispatchedCommands, checkLink, checkFrozen, checkState, checkFleet, checkHooks, checkNotify, runChecks, render,
355
+ dispatchedCommands, checkSkills, checkLink, checkFrozen, checkState, checkFleet, checkHooks, checkNotify, runChecks, render,
284
356
  };
@@ -392,6 +392,9 @@ function repoRootOf(dir) {
392
392
  function safeArgv(argv) {
393
393
  const a = (argv || []).map(String);
394
394
  if (a[0] === 'config' && a[1] === 'set' && a.length > 3) return [...a.slice(0, 3), '<redacted>'];
395
+ // add-notify-url / rm-notify-url carry the same kind of value as `set notifyUrl` — a URL that can
396
+ // hold a token (#546) — so it is redacted the same way.
397
+ if (a[0] === 'config' && (a[1] === 'add-notify-url' || a[1] === 'rm-notify-url') && a.length > 2) return [...a.slice(0, 2), '<redacted>'];
395
398
  return a;
396
399
  }
397
400
 
@@ -15,17 +15,20 @@
15
15
  *
16
16
  * 1. an explicit URL a human passes to `install.sh --notify-url <url>`;
17
17
  * 2. the DECLARED ENDPOINT FILE, `<COLAB_HOME>/notify-endpoint` — the convention by which a local
18
- * observer announces itself. The observer writes its own events URL there (one http(s) URL on
19
- * the first non-comment line); colab only reads it. No port is probed and no well-known URL is
20
- * hard-coded: an observer's address is the observer's fact, not the handbook's.
18
+ * observer announces itself. Each observer writes its own events URL there on its OWN line (one
19
+ * http(s) URL per non-comment line, #546 — a machine may run two observers side by side, and
20
+ * neither may overwrite the other's line); colab only reads it. A one-line file is the
21
+ * one-observer case and stays valid. No port is probed and no well-known URL is hard-coded: an
22
+ * observer's address is the observer's fact, not the handbook's.
21
23
  *
22
24
  * What reads this:
23
- * - install.sh seeds `notifyUrl` from (1), else (2), ONLY when the key is absent — an existing
24
- * value is someone's deliberate choice and is never overwritten. When nothing seeds it, install
25
- * says plainly that the key is unset and what that costs.
25
+ * - install.sh ADDS to `notifyUrl` every URL from (1) and (2) that the key lacks, and never
26
+ * removes or rewrites an entry already there — an existing value is someone's deliberate choice.
27
+ * With one URL the key is written as a plain string, exactly as before the list form (#546).
28
+ * When nothing seeds it, install says plainly that the key is unset and what that costs.
26
29
  * - `install.sh --check` and `colab doctor` report `notifyUrl: unset` when (2) exists and the key
27
- * does not. No declared endpoint → nothing is reported: silence stays right for a machine with
28
- * no observer.
30
+ * does not, and name EACH declared URL the key lacks when it is set. No declared endpoint →
31
+ * nothing is reported: silence stays right for a machine with no observer.
29
32
  *
30
33
  * CommonJS, zero dependencies. Runnable as a script (install.sh's entry):
31
34
  * node tools/lib/notify-endpoint.js seed --colab-home <dir> [--url <url>] [--dry]
@@ -36,6 +39,7 @@
36
39
 
37
40
  const fs = require('fs');
38
41
  const path = require('path');
42
+ const { configuredUrls, storedNotifyUrl } = require('./notify');
39
43
 
40
44
  const ENDPOINT_FILE = 'notify-endpoint';
41
45
  const HTTP_RE = /^https?:\/\//i;
@@ -48,84 +52,113 @@ function endpointFile(colabHome) {
48
52
  }
49
53
 
50
54
  /**
51
- * Read the declared endpoint. Returns null when no file exists (the common, silent case), else
52
- * `{ file, url }` for a usable URL or `{ file, invalid }` naming what is wrong with it — a declared
53
- * endpoint that cannot be used is reported, never silently treated as absent.
55
+ * Read the declared endpoints. Returns null when no file exists (the common, silent case), else
56
+ * `{ file, urls, bad }`: every usable URL in file order (deduplicated), and every non-comment line
57
+ * that is not one. When no line is usable it also carries `invalid`, naming what is wrong — a
58
+ * declared endpoint that cannot be used is reported, never silently treated as absent. `url` is the
59
+ * first usable URL, kept for readers that predate the list form.
54
60
  */
55
61
  function readDeclared(colabHome) {
56
62
  const file = endpointFile(colabHome);
57
63
  let raw;
58
64
  try { raw = fs.readFileSync(file, 'utf8'); } catch (_) { return null; }
59
- const line = raw.split(/\r?\n/).map((l) => l.replace(/#.*$/, '').trim()).find(Boolean);
60
- if (!line) return { file, invalid: 'empty — no URL on any non-comment line' };
61
- if (!HTTP_RE.test(line)) return { file, invalid: `not an http(s) URL: ${line}` };
62
- return { file, url: line };
63
- }
64
-
65
- function configuredUrl(cfg) {
66
- return cfg && typeof cfg.notifyUrl === 'string' ? cfg.notifyUrl.trim() : '';
65
+ const lines = raw.split(/\r?\n/).map((l) => l.replace(/#.*$/, '').trim()).filter(Boolean);
66
+ const urls = [];
67
+ const bad = [];
68
+ for (const l of lines) {
69
+ if (!HTTP_RE.test(l)) bad.push(l);
70
+ else if (!urls.includes(l)) urls.push(l);
71
+ }
72
+ if (urls.length === 0) {
73
+ const invalid = lines.length === 0 ? 'empty — no URL on any non-comment line' : `not an http(s) URL: ${bad[0]}`;
74
+ return { file, urls, bad, invalid };
75
+ }
76
+ return { file, urls, bad, url: urls[0] };
67
77
  }
68
78
 
69
79
  /**
70
80
  * The read-only verdict both health checks print. `state`:
71
- * 'set' notifyUrl is configured (payload: url; `declared` when the file names another)
81
+ * 'set' notifyUrl is configured (payload: url, urls; `missing` lists each declared URL
82
+ * the key lacks — the observers that receive nothing — empty when none)
72
83
  * 'unset-declared' notifyUrl absent while an observer declared an endpoint — the outage case
73
84
  * 'declared-invalid' notifyUrl absent and the declared file is unusable
74
85
  * 'unset' neither — a machine with no observer; callers stay silent
86
+ * `declared` rides along whenever the file exists.
75
87
  */
76
88
  function status(cfg, colabHome) {
77
- const url = configuredUrl(cfg);
89
+ const urls = configuredUrls(cfg);
78
90
  const declared = readDeclared(colabHome);
79
- if (url) {
80
- return declared && declared.url && declared.url !== url
81
- ? { state: 'set', url, declared }
82
- : { state: 'set', url };
91
+ if (urls.length) {
92
+ const st = { state: 'set', url: urls[0], urls, missing: declared ? declared.urls.filter((u) => !urls.includes(u)) : [] };
93
+ if (declared) st.declared = declared;
94
+ return st;
83
95
  }
84
96
  if (!declared) return { state: 'unset' };
85
97
  if (declared.invalid) return { state: 'declared-invalid', declared };
86
98
  return { state: 'unset-declared', declared };
87
99
  }
88
100
 
89
- /** One human line for a status, or null when the right output is silence. */
90
- function healthLine(st) {
101
+ /** The fix command for one or several URLs a key lacks. One URL on an unset key: the same `set` as ever. */
102
+ function fixFor(urls, keyIsSet) {
103
+ if (!keyIsSet && urls.length === 1) return `colab config set notifyUrl ${urls[0]}`;
104
+ return urls.map((u) => `colab config add-notify-url ${u}`).join(' && ');
105
+ }
106
+
107
+ /** Human lines for a status — one per problem — or [] when the right output is silence. */
108
+ function healthLines(st) {
109
+ const out = [];
110
+ const d = st.declared;
91
111
  if (st.state === 'unset-declared') {
92
- return `notifyUrl: unset — ${st.declared.file} declares a local observer at ${st.declared.url}, ` +
93
- `which receives no events (${PUSH_ONLY_KINDS.join(', ')}). Fix: colab config set notifyUrl ${st.declared.url}`;
94
- }
95
- if (st.state === 'declared-invalid') {
96
- return `notifyUrl: unset — ${st.declared.file} is ${st.declared.invalid}, so nothing could be seeded from it`;
97
- }
98
- if (st.state === 'set' && st.declared) {
99
- return `notifyUrl: ${st.url} — differs from the endpoint declared in ${st.declared.file} (${st.declared.url}); ` +
100
- 'left as configured, check which one the local observer listens on';
112
+ const where = d.urls.length === 1 ? `a local observer at ${d.urls[0]}, which receives` : `${d.urls.length} local observers (${d.urls.join(', ')}), which receive`;
113
+ out.push(`notifyUrl: unset — ${d.file} declares ${where} no events (${PUSH_ONLY_KINDS.join(', ')}). ` +
114
+ `Fix: ${fixFor(d.urls, false)}`);
115
+ } else if (st.state === 'declared-invalid') {
116
+ out.push(`notifyUrl: unset — ${d.file} is ${d.invalid}, so nothing could be seeded from it`);
117
+ return out;
118
+ } else if (st.state === 'set') {
119
+ for (const u of st.missing || []) {
120
+ out.push(`notifyUrl: lacks ${u} — declared in ${d.file} by a local observer, which receives no events ` +
121
+ `(${PUSH_ONLY_KINDS.join(', ')}). Fix: ${fixFor([u], true)}`);
122
+ }
101
123
  }
102
- return null;
124
+ for (const b of (d && d.bad) || []) out.push(`notifyUrl: ${d.file} has a line that is not an http(s) URL — ignored: ${b}`);
125
+ return out;
126
+ }
127
+
128
+ /** The lines above joined, or null when the right output is silence. Kept for one-string readers. */
129
+ function healthLine(st) {
130
+ const lines = healthLines(st);
131
+ return lines.length ? lines.join('\n') : null;
103
132
  }
104
133
 
105
134
  /**
106
- * Decide what install.sh does. Pure: returns `{ action, url?, source?, lines[] }` and writes nothing.
107
- * action 'keep' the key is already set — never overwritten
108
- * action 'seed' write `url` (from the flag, else the declared file)
135
+ * Decide what install.sh does. Pure: returns `{ action, add?, lines[] }` and writes nothing.
136
+ * action 'keep' the key already holds every URL there is to add — left exactly as it is
137
+ * action 'seed' add each `{ url, source }` in `add` (from the flag and the declared file) that the
138
+ * key lacks; existing entries are never removed or rewritten
109
139
  * action 'none' nothing to seed — the lines say plainly the key is unset and what it costs
140
+ * action 'error' a non-http --notify-url
141
+ * The flag is one more "an observer lives here" source, added beside the declared ones rather than
142
+ * winning over them: since #546 a second receiver is an addition, never a replacement.
110
143
  */
111
144
  function plan({ cfg, colabHome, flagUrl }) {
112
- const current = configuredUrl(cfg);
145
+ const current = configuredUrls(cfg);
113
146
  const declared = readDeclared(colabHome);
114
147
  if (flagUrl && !HTTP_RE.test(flagUrl)) {
115
148
  return { action: 'error', lines: [`--notify-url must be an http(s) URL, got: ${flagUrl}`] };
116
149
  }
117
- if (current) {
118
- const lines = [`✓ notifyUrl = ${current} (already set → left untouched)`];
119
- if (flagUrl && flagUrl !== current) {
120
- lines.push(`⚠ --notify-url ${flagUrl} NOT applied: an existing value is never overwritten. ` +
121
- `To change it: colab config set notifyUrl ${flagUrl}`);
122
- }
123
- const hl = healthLine(status(cfg, colabHome));
124
- if (hl) lines.push(`⚠ ${hl}`);
125
- return { action: 'keep', lines };
150
+ const candidates = [];
151
+ if (flagUrl) candidates.push({ url: flagUrl, source: '--notify-url' });
152
+ for (const u of (declared && declared.urls) || []) candidates.push({ url: u, source: declared.file });
153
+ const add = [];
154
+ for (const c of candidates) {
155
+ if (!current.includes(c.url) && !add.some((a) => a.url === c.url)) add.push(c);
156
+ }
157
+ const badLines = ((declared && declared.bad) || []).map((b) => `⚠ ${declared.file} has a line that is not an http(s) URL — ignored: ${b}`);
158
+ if (add.length) return { action: 'seed', add, lines: badLines };
159
+ if (current.length) {
160
+ return { action: 'keep', lines: [`✓ notifyUrl = ${current.join(', ')} (already set → left untouched)`, ...badLines] };
126
161
  }
127
- if (flagUrl) return { action: 'seed', url: flagUrl, source: '--notify-url', lines: [] };
128
- if (declared && declared.url) return { action: 'seed', url: declared.url, source: declared.file, lines: [] };
129
162
  const lines = [];
130
163
  if (declared && declared.invalid) lines.push(`⚠ ${declared.file} is ${declared.invalid} — ignored.`);
131
164
  lines.push(
@@ -137,6 +170,16 @@ function plan({ cfg, colabHome, flagUrl }) {
137
170
  return { action: 'none', lines };
138
171
  }
139
172
 
173
+ /**
174
+ * The config value after adding `add` to `cfg`'s current list — existing entries first, untouched and
175
+ * in order, new ones appended. Pure; used by the seed entry right before it writes.
176
+ */
177
+ function merged(cfg, add) {
178
+ const urls = configuredUrls(cfg);
179
+ for (const a of add) if (!urls.includes(a.url)) urls.push(a.url);
180
+ return storedNotifyUrl(urls);
181
+ }
182
+
140
183
  function main(argv) {
141
184
  const sub = argv[0];
142
185
  const val = (flag) => {
@@ -154,17 +197,29 @@ function main(argv) {
154
197
  const p = plan({ cfg, colabHome, flagUrl: val('--url') });
155
198
  const out = (l) => process.stdout.write(` ${l}\n`);
156
199
  if (p.action === 'error') { process.stderr.write(` ✗ ${p.lines[0]}\n`); return 2; }
157
- if (p.action !== 'seed') { p.lines.forEach(out); return 0; }
158
- if (argv.includes('--dry')) { out(`[dry] seed notifyUrl = ${p.url} (from ${p.source})`); return 0; }
159
- // Re-read inside the write: a key set between plan and write is still never overwritten.
200
+ p.lines.forEach(out);
201
+ if (p.action !== 'seed') return 0;
202
+ const hadAny = configuredUrls(cfg).length > 0;
203
+ if (argv.includes('--dry')) {
204
+ for (const a of p.add) out(`[dry] ${hadAny ? 'add to' : 'seed'} notifyUrl ${a.url} (from ${a.source})`);
205
+ return 0;
206
+ }
207
+ // Re-read inside the write: an entry added between plan and write is kept, never rewritten or
208
+ // removed, and a URL someone else just added is not added twice.
160
209
  const fresh = state.loadConfig();
161
- if (configuredUrl(fresh)) { out(`✓ notifyUrl = ${configuredUrl(fresh)} (already set → left untouched)`); return 0; }
162
- fresh.notifyUrl = p.url;
210
+ const before = configuredUrls(fresh);
211
+ const add = p.add.filter((a) => !before.includes(a.url));
212
+ if (!add.length) { out(`✓ notifyUrl = ${before.join(', ')} (already set → left untouched)`); return 0; }
213
+ fresh.notifyUrl = merged(fresh, add);
163
214
  state.saveConfig(fresh);
164
- out(`📡 notifyUrl seeded: ${p.url} (from ${p.source}) — colab now pushes its events there`);
215
+ for (const a of add) {
216
+ out(before.length
217
+ ? `📡 notifyUrl: added ${a.url} (from ${a.source}) — existing entries left untouched`
218
+ : `📡 notifyUrl seeded: ${a.url} (from ${a.source}) — colab now pushes its events there`);
219
+ }
165
220
  return 0;
166
221
  }
167
222
 
168
223
  if (require.main === module) process.exitCode = main(process.argv.slice(2));
169
224
 
170
- module.exports = { ENDPOINT_FILE, PUSH_ONLY_KINDS, endpointFile, readDeclared, status, healthLine, plan, main };
225
+ module.exports = { ENDPOINT_FILE, PUSH_ONLY_KINDS, endpointFile, readDeclared, status, healthLines, healthLine, plan, merged, main };