@nanocollective/roster 0.1.0-beta.13 → 0.1.0-beta.15

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 (49) hide show
  1. package/dist/agents-NMGVORU3.js +232 -0
  2. package/dist/chunk-E3EVPK4I.js +338 -0
  3. package/dist/chunk-QCKEGMXD.js +562 -0
  4. package/dist/cli.js +1731 -830
  5. package/dist/compose-56JIIIHA.js +15 -0
  6. package/dist/connectors-ZVEPXSAR.js +23 -0
  7. package/dist/worker/assets/assets/css/connectors.css +50 -0
  8. package/dist/worker/assets/assets/js/api.js +3 -0
  9. package/dist/worker/assets/assets/js/app.js +4 -1
  10. package/dist/worker/assets/assets/js/icons.js +2 -0
  11. package/dist/worker/assets/assets/js/state.js +11 -1
  12. package/dist/worker/assets/assets/js/views/connectors.js +290 -0
  13. package/dist/worker/assets/index.html +4 -0
  14. package/dist/worker/index.js +2786 -1028
  15. package/docs/README.md +1 -0
  16. package/docs/architecture.md +1 -1
  17. package/docs/commands.md +37 -1
  18. package/docs/connectors.md +157 -0
  19. package/docs/cost.md +1 -1
  20. package/docs/developing.md +2 -2
  21. package/docs/doctor-codes.md +6 -2
  22. package/docs/export.md +2 -2
  23. package/docs/extending.md +1 -1
  24. package/docs/hosting.md +14 -1
  25. package/docs/memory.md +1 -1
  26. package/docs/org-yaml.md +33 -1
  27. package/docs/portal.md +18 -1
  28. package/docs/prompts.md +3 -2
  29. package/docs/security.md +17 -1
  30. package/docs/session-workflow.md +23 -5
  31. package/docs/staff-yaml.md +1 -1
  32. package/docs/troubleshooting.md +1 -1
  33. package/docs/upgrading.md +1 -1
  34. package/docs/writing-a-charter.md +1 -1
  35. package/package.json +2 -1
  36. package/templates/brain/.github/workflows/%%STAFF%%-daily.yaml +8 -6
  37. package/templates/brain/.github/workflows/%%STAFF%%-mention.yaml +8 -6
  38. package/templates/ops/.github/workflows/session.yaml +52 -11
  39. package/templates/ops/agents.mjs +38 -11
  40. package/templates/ops/compose.mjs +20 -2
  41. package/templates/ops/connectors.mjs +722 -0
  42. package/templates/ops/prompts/_identity.md +20 -0
  43. package/templates/portal/css/connectors.css +50 -0
  44. package/templates/portal/index.html +4 -0
  45. package/templates/portal/js/api.js +3 -0
  46. package/templates/portal/js/app.js +4 -1
  47. package/templates/portal/js/icons.js +2 -0
  48. package/templates/portal/js/state.js +11 -1
  49. package/templates/portal/js/views/connectors.js +290 -0
package/dist/cli.js CHANGED
@@ -1,4 +1,14 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ compose,
4
+ parseYaml
5
+ } from "./chunk-E3EVPK4I.js";
6
+ import {
7
+ CATALOGUE,
8
+ declared,
9
+ secretName,
10
+ withConnectors
11
+ } from "./chunk-QCKEGMXD.js";
2
12
 
3
13
  // src/commands/app.ts
4
14
  import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
@@ -102,7 +112,7 @@ async function createApp(spec2, opts = {}) {
102
112
  const state = randomBytes(16).toString("hex");
103
113
  const redirectUrl = `http://localhost:${port}/callback`;
104
114
  const manifest = buildManifest(spec2, redirectUrl);
105
- return new Promise((resolve8, reject) => {
115
+ return new Promise((resolve7, reject) => {
106
116
  let settled = false;
107
117
  const finish = (fn) => {
108
118
  if (settled) return;
@@ -145,7 +155,7 @@ async function createApp(spec2, opts = {}) {
145
155
  "Its keys are saved in the repository's secrets. You can close this tab; the terminal has the next step."
146
156
  )
147
157
  );
148
- finish(() => resolve8(app));
158
+ finish(() => resolve7(app));
149
159
  }).catch((err) => {
150
160
  res.writeHead(502, { "content-type": "text/html" }).end(page("Exchange failed", esc(err.message)));
151
161
  finish(() => reject(err));
@@ -186,11 +196,11 @@ function setOrgSecret(org, name, repos, value) {
186
196
  );
187
197
  }
188
198
  function secretFromStdin(args, value) {
189
- return new Promise((resolve8, reject) => {
199
+ return new Promise((resolve7, reject) => {
190
200
  const child = execFile2(
191
201
  "gh",
192
202
  args,
193
- (err, _out, stderr) => err ? reject(new Error(`gh secret set ${args[2]}: ${String(stderr || err.message).trim()}`)) : resolve8()
203
+ (err, _out, stderr) => err ? reject(new Error(`gh secret set ${args[2]}: ${String(stderr || err.message).trim()}`)) : resolve7()
194
204
  );
195
205
  child.stdin?.end(value);
196
206
  });
@@ -370,8 +380,8 @@ function opsTemplateDir() {
370
380
  var NOTE = "%%TOKENS%%";
371
381
  var TOKEN = /%%([A-Z_]+)%%/g;
372
382
  function toolsOf(org) {
373
- const list = org?.defaults?.allowed_tools;
374
- const asked = Array.isArray(list) ? list.join(",") : typeof list === "string" ? list : "";
383
+ const list2 = org?.defaults?.allowed_tools;
384
+ const asked = Array.isArray(list2) ? list2.join(",") : typeof list2 === "string" ? list2 : "";
375
385
  return asked.replace(/\s+/g, "") || "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch";
376
386
  }
377
387
  function orgTokens(org) {
@@ -1215,13 +1225,24 @@ function readHumans(org) {
1215
1225
  github,
1216
1226
  name: name || github,
1217
1227
  marker: String(entry.marker ?? "").trim() || defaultMarker(name || github),
1218
- role: entry.role === void 0 || entry.role === null ? void 0 : String(entry.role)
1228
+ role: entry.role === void 0 || entry.role === null ? void 0 : String(entry.role),
1229
+ ...entry.view_only === true ? { viewOnly: true } : {}
1219
1230
  });
1220
1231
  }
1221
1232
  return out;
1222
1233
  }
1234
+ function staffHumans(org) {
1235
+ return readHumans(org).filter((h) => !h.viewOnly);
1236
+ }
1237
+ function isViewOnly(org, login) {
1238
+ const l = login.toLowerCase();
1239
+ return readHumans(org).some((h) => h.viewOnly && h.github.toLowerCase() === l);
1240
+ }
1241
+ function primaryHuman(org) {
1242
+ return staffHumans(org)[0] ?? null;
1243
+ }
1223
1244
  function humanLogins(org) {
1224
- return readHumans(org).map((h) => h.github).filter(Boolean);
1245
+ return staffHumans(org).map((h) => h.github).filter(Boolean);
1225
1246
  }
1226
1247
  function defaultMarker(name) {
1227
1248
  return String(name).trim().split(/[\s-]+/)[0].toLowerCase().replace(/[^a-z0-9]/g, "") || "human";
@@ -1377,19 +1398,21 @@ function validateOrgYaml(text2, parseYaml3) {
1377
1398
  return `that is not YAML compose.mjs can read: ${err.message}`;
1378
1399
  }
1379
1400
  if (!doc || typeof doc !== "object") return "org.yaml has to be a mapping";
1380
- for (const key of ["org", "name"]) {
1381
- if (!doc[key] || typeof doc[key] !== "string") {
1382
- return `org.yaml needs a "${key}", and every prompt is composed against it`;
1401
+ for (const key2 of ["org", "name"]) {
1402
+ if (!doc[key2] || typeof doc[key2] !== "string") {
1403
+ return `org.yaml needs a "${key2}", and every prompt is composed against it`;
1383
1404
  }
1384
1405
  }
1385
- for (const key of ["staff", "repos", "humans"]) {
1386
- if (doc[key] !== void 0 && !Array.isArray(doc[key])) return `"${key}" has to be a list`;
1406
+ for (const key2 of ["staff", "repos", "humans"]) {
1407
+ if (doc[key2] !== void 0 && !Array.isArray(doc[key2])) return `"${key2}" has to be a list`;
1387
1408
  }
1388
1409
  for (const s of doc.staff ?? []) {
1389
1410
  if (!s?.handle) return "every staff entry needs a handle";
1390
1411
  }
1391
1412
  for (const h of doc.humans ?? []) {
1392
1413
  if (!h?.github) return "every entry in humans needs a github login";
1414
+ if (h.view_only !== void 0 && typeof h.view_only !== "boolean")
1415
+ return "view_only is true or false";
1393
1416
  }
1394
1417
  return null;
1395
1418
  }
@@ -1496,7 +1519,7 @@ function staffTokens(ws, org, handle, parseYaml3) {
1496
1519
  return tokensFor(spec(org, ws), specFromManifest(manifest, dir));
1497
1520
  }
1498
1521
  function spec(org, ws) {
1499
- const humans = readHumans(org);
1522
+ const humans = staffHumans(org);
1500
1523
  const first = humans[0];
1501
1524
  return {
1502
1525
  org: org.org,
@@ -1556,6 +1579,575 @@ function parseFlags2(argv) {
1556
1579
  return out;
1557
1580
  }
1558
1581
 
1582
+ // src/commands/connector.ts
1583
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
1584
+ import { join as join15 } from "path";
1585
+
1586
+ // src/lib/commit.ts
1587
+ import { execFileSync as execFileSync2 } from "child_process";
1588
+ function commitAndPush(repoDir, paths, message2) {
1589
+ const git4 = (args) => execFileSync2("git", ["-C", repoDir, ...args], {
1590
+ encoding: "utf8",
1591
+ stdio: ["ignore", "pipe", "pipe"]
1592
+ });
1593
+ try {
1594
+ if (!git4(["status", "--porcelain", "--", ...paths]).trim()) {
1595
+ return { committed: false, pushed: false, note: "nothing to commit" };
1596
+ }
1597
+ git4(["add", "--", ...paths]);
1598
+ git4(["commit", "-q", "-m", message2, "--", ...paths]);
1599
+ } catch (err) {
1600
+ return { committed: false, pushed: false, note: short2(err) };
1601
+ }
1602
+ const sha = git4(["rev-parse", "--short", "HEAD"]).trim();
1603
+ try {
1604
+ git4(["push", "-q"]);
1605
+ } catch (err) {
1606
+ return { committed: true, pushed: false, sha, note: short2(err) };
1607
+ }
1608
+ return { committed: true, pushed: true, sha };
1609
+ }
1610
+ function short2(e) {
1611
+ const msg = e instanceof Error ? e.stderr?.toString() || e.message : String(e);
1612
+ const line = msg.split("\n").find((l) => l.trim()) ?? msg;
1613
+ return line.length > 200 ? line.slice(0, 199) + "\u2026" : line;
1614
+ }
1615
+
1616
+ // src/lib/sealedbox.ts
1617
+ function sealedBox(message2, recipientPublicKey) {
1618
+ if (recipientPublicKey.length !== 32) throw new Error("a sealed box needs a 32-byte public key");
1619
+ const esk = new Uint8Array(32);
1620
+ crypto.getRandomValues(esk);
1621
+ const epk = x25519(esk, BASE);
1622
+ const nonce = blake2b(concat(epk, recipientPublicKey), 24);
1623
+ const k = hsalsa20(x25519(esk, recipientPublicKey), new Uint8Array(16));
1624
+ return concat(epk, secretbox(message2, nonce, k));
1625
+ }
1626
+ function sealForGitHub(value, publicKeyBase64) {
1627
+ return toBase64(sealedBox(new TextEncoder().encode(value), fromBase64(publicKeyBase64)));
1628
+ }
1629
+ var P = 2n ** 255n - 19n;
1630
+ var A24 = 121665n;
1631
+ var BASE = (() => {
1632
+ const b = new Uint8Array(32);
1633
+ b[0] = 9;
1634
+ return b;
1635
+ })();
1636
+ var mod = (a) => (a % P + P) % P;
1637
+ function pow(b, e) {
1638
+ let r = 1n;
1639
+ let x = mod(b);
1640
+ while (e > 0n) {
1641
+ if (e & 1n) r = mod(r * x);
1642
+ x = mod(x * x);
1643
+ e >>= 1n;
1644
+ }
1645
+ return r;
1646
+ }
1647
+ var leToBig = (b) => {
1648
+ let n = 0n;
1649
+ for (let i = b.length - 1; i >= 0; i--) n = n << 8n | BigInt(b[i]);
1650
+ return n;
1651
+ };
1652
+ var bigToLe = (n, len) => {
1653
+ const out = new Uint8Array(len);
1654
+ for (let i = 0; i < len; i++) {
1655
+ out[i] = Number(n & 0xffn);
1656
+ n >>= 8n;
1657
+ }
1658
+ return out;
1659
+ };
1660
+ function x25519(scalar, u) {
1661
+ const k = scalar.slice();
1662
+ k[0] &= 248;
1663
+ k[31] &= 127;
1664
+ k[31] |= 64;
1665
+ const uc = u.slice();
1666
+ uc[31] &= 127;
1667
+ const x1 = leToBig(uc);
1668
+ const kn = leToBig(k);
1669
+ let x2 = 1n;
1670
+ let z2 = 0n;
1671
+ let x3 = x1;
1672
+ let z3 = 1n;
1673
+ let swap = 0n;
1674
+ for (let t = 254n; t >= 0n; t--) {
1675
+ const kt = kn >> t & 1n;
1676
+ swap ^= kt;
1677
+ if (swap) [x2, x3, z2, z3] = [x3, x2, z3, z2];
1678
+ swap = kt;
1679
+ const a = mod(x2 + z2);
1680
+ const aa = mod(a * a);
1681
+ const b = mod(x2 - z2);
1682
+ const bb = mod(b * b);
1683
+ const e = mod(aa - bb);
1684
+ const c = mod(x3 + z3);
1685
+ const d = mod(x3 - z3);
1686
+ const da = mod(d * a);
1687
+ const cb = mod(c * b);
1688
+ x3 = mod((da + cb) ** 2n);
1689
+ z3 = mod(x1 * mod((da - cb) ** 2n));
1690
+ x2 = mod(aa * bb);
1691
+ z2 = mod(e * mod(aa + A24 * e));
1692
+ }
1693
+ if (swap) [x2, z2] = [x3, z3];
1694
+ return bigToLe(mod(x2 * pow(z2, P - 2n)), 32);
1695
+ }
1696
+ var SIGMA = new TextEncoder().encode("expand 32-byte k");
1697
+ var rotl = (v, c) => (v << c | v >>> 32 - c) >>> 0;
1698
+ var u32 = (b, i) => (b[i] | b[i + 1] << 8 | b[i + 2] << 16 | b[i + 3] << 24) >>> 0;
1699
+ function salsaState(key2, input16) {
1700
+ return [
1701
+ u32(SIGMA, 0),
1702
+ u32(key2, 0),
1703
+ u32(key2, 4),
1704
+ u32(key2, 8),
1705
+ u32(key2, 12),
1706
+ u32(SIGMA, 4),
1707
+ u32(input16, 0),
1708
+ u32(input16, 4),
1709
+ u32(input16, 8),
1710
+ u32(input16, 12),
1711
+ u32(SIGMA, 8),
1712
+ u32(key2, 16),
1713
+ u32(key2, 20),
1714
+ u32(key2, 24),
1715
+ u32(key2, 28),
1716
+ u32(SIGMA, 12)
1717
+ ];
1718
+ }
1719
+ function rounds(x) {
1720
+ const qr = (a, b, c, d) => {
1721
+ x[b] = (x[b] ^ rotl(x[a] + x[d] >>> 0, 7)) >>> 0;
1722
+ x[c] = (x[c] ^ rotl(x[b] + x[a] >>> 0, 9)) >>> 0;
1723
+ x[d] = (x[d] ^ rotl(x[c] + x[b] >>> 0, 13)) >>> 0;
1724
+ x[a] = (x[a] ^ rotl(x[d] + x[c] >>> 0, 18)) >>> 0;
1725
+ };
1726
+ for (let i = 0; i < 10; i++) {
1727
+ qr(0, 4, 8, 12);
1728
+ qr(5, 9, 13, 1);
1729
+ qr(10, 14, 2, 6);
1730
+ qr(15, 3, 7, 11);
1731
+ qr(0, 1, 2, 3);
1732
+ qr(5, 6, 7, 4);
1733
+ qr(10, 11, 8, 9);
1734
+ qr(15, 12, 13, 14);
1735
+ }
1736
+ }
1737
+ function hsalsa20(key2, input16) {
1738
+ const x = salsaState(key2, input16);
1739
+ rounds(x);
1740
+ const out = new Uint8Array(32);
1741
+ [0, 5, 10, 15, 6, 7, 8, 9].forEach((w, i) => {
1742
+ out.set(le32(x[w]), i * 4);
1743
+ });
1744
+ return out;
1745
+ }
1746
+ var le32 = (v) => new Uint8Array([v & 255, v >>> 8 & 255, v >>> 16 & 255, v >>> 24 & 255]);
1747
+ function xsalsa20Stream(key2, nonce24, len) {
1748
+ const sub = hsalsa20(key2, nonce24.subarray(0, 16));
1749
+ const out = new Uint8Array(len);
1750
+ const input = new Uint8Array(16);
1751
+ input.set(nonce24.subarray(16, 24), 0);
1752
+ for (let block = 0, off = 0; off < len; block++, off += 64) {
1753
+ input.set(le32(block), 8);
1754
+ input.set(le32(Math.floor(block / 2 ** 32)), 12);
1755
+ const s = salsaState(sub, input);
1756
+ const x = s.slice();
1757
+ rounds(x);
1758
+ for (let i = 0; i < 16 && off + i * 4 < len; i++) {
1759
+ const w = le32(x[i] + s[i] >>> 0);
1760
+ for (let j = 0; j < 4 && off + i * 4 + j < len; j++) out[off + i * 4 + j] = w[j];
1761
+ }
1762
+ }
1763
+ return out;
1764
+ }
1765
+ function secretbox(m, nonce, k) {
1766
+ const stream = xsalsa20Stream(k, nonce, m.length + 32);
1767
+ const c = new Uint8Array(m.length);
1768
+ for (let i = 0; i < m.length; i++) c[i] = m[i] ^ stream[i + 32];
1769
+ return concat(poly1305(c, stream.subarray(0, 32)), c);
1770
+ }
1771
+ function poly1305(m, key2) {
1772
+ const p = 2n ** 130n - 5n;
1773
+ const r = leToBig(key2.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn;
1774
+ const s = leToBig(key2.subarray(16, 32));
1775
+ let acc = 0n;
1776
+ for (let i = 0; i < m.length; i += 16) {
1777
+ const chunk = m.subarray(i, i + 16);
1778
+ const n = leToBig(chunk) + (1n << BigInt(8 * chunk.length));
1779
+ acc = (acc + n) * r % p;
1780
+ }
1781
+ return bigToLe(acc + s & (1n << 128n) - 1n, 16);
1782
+ }
1783
+ var M64 = (1n << 64n) - 1n;
1784
+ var IV = [
1785
+ 0x6a09e667f3bcc908n,
1786
+ 0xbb67ae8584caa73bn,
1787
+ 0x3c6ef372fe94f82bn,
1788
+ 0xa54ff53a5f1d36f1n,
1789
+ 0x510e527fade682d1n,
1790
+ 0x9b05688c2b3e6c1fn,
1791
+ 0x1f83d9abfb41bd6bn,
1792
+ 0x5be0cd19137e2179n
1793
+ ];
1794
+ var SIG = [
1795
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
1796
+ [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
1797
+ [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
1798
+ [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
1799
+ [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
1800
+ [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
1801
+ [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
1802
+ [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
1803
+ [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
1804
+ [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0]
1805
+ ];
1806
+ var rotr = (v, n) => (v >> n | v << 64n - n) & M64;
1807
+ function blake2b(input, outLen) {
1808
+ const h = IV.slice();
1809
+ h[0] = h[0] ^ 0x01010000n ^ BigInt(outLen);
1810
+ const blocks = Math.max(1, Math.ceil(input.length / 128));
1811
+ for (let b = 0; b < blocks; b++) {
1812
+ const last = b === blocks - 1;
1813
+ const block = new Uint8Array(128);
1814
+ block.set(input.subarray(b * 128, b * 128 + 128));
1815
+ const m = Array.from({ length: 16 }, (_, i) => leToBig(block.subarray(i * 8, i * 8 + 8)));
1816
+ const t = BigInt(last ? input.length : (b + 1) * 128);
1817
+ const v = [...h, ...IV];
1818
+ v[12] = v[12] ^ t & M64;
1819
+ v[13] = v[13] ^ t >> 64n;
1820
+ if (last) v[14] = v[14] ^ M64;
1821
+ const g = (a, bb, c, d, x, y) => {
1822
+ v[a] = v[a] + v[bb] + x & M64;
1823
+ v[d] = rotr(v[d] ^ v[a], 32n);
1824
+ v[c] = v[c] + v[d] & M64;
1825
+ v[bb] = rotr(v[bb] ^ v[c], 24n);
1826
+ v[a] = v[a] + v[bb] + y & M64;
1827
+ v[d] = rotr(v[d] ^ v[a], 16n);
1828
+ v[c] = v[c] + v[d] & M64;
1829
+ v[bb] = rotr(v[bb] ^ v[c], 63n);
1830
+ };
1831
+ for (let r = 0; r < 12; r++) {
1832
+ const s = SIG[r % 10];
1833
+ g(0, 4, 8, 12, m[s[0]], m[s[1]]);
1834
+ g(1, 5, 9, 13, m[s[2]], m[s[3]]);
1835
+ g(2, 6, 10, 14, m[s[4]], m[s[5]]);
1836
+ g(3, 7, 11, 15, m[s[6]], m[s[7]]);
1837
+ g(0, 5, 10, 15, m[s[8]], m[s[9]]);
1838
+ g(1, 6, 11, 12, m[s[10]], m[s[11]]);
1839
+ g(2, 7, 8, 13, m[s[12]], m[s[13]]);
1840
+ g(3, 4, 9, 14, m[s[14]], m[s[15]]);
1841
+ }
1842
+ for (let i = 0; i < 8; i++) h[i] = h[i] ^ v[i] ^ v[i + 8];
1843
+ }
1844
+ const out = new Uint8Array(64);
1845
+ h.forEach((w, i) => {
1846
+ out.set(bigToLe(w, 8), i * 8);
1847
+ });
1848
+ return out.slice(0, outLen);
1849
+ }
1850
+ function concat(...parts) {
1851
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
1852
+ let off = 0;
1853
+ for (const p of parts) {
1854
+ out.set(p, off);
1855
+ off += p.length;
1856
+ }
1857
+ return out;
1858
+ }
1859
+ function toBase64(b) {
1860
+ let s = "";
1861
+ for (const x of b) s += String.fromCharCode(x);
1862
+ return btoa(s);
1863
+ }
1864
+ function fromBase64(s) {
1865
+ return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
1866
+ }
1867
+
1868
+ // src/lib/connectors.ts
1869
+ var CATALOGUE2 = CATALOGUE;
1870
+ var declared2 = declared;
1871
+ var secretName2 = secretName;
1872
+ var withConnectors2 = withConnectors;
1873
+ function catalogueView() {
1874
+ return Object.entries(CATALOGUE2).map(([id, e]) => ({
1875
+ id,
1876
+ name: e.name,
1877
+ summary: e.summary,
1878
+ suggest: e.suggest ?? [],
1879
+ link: e.link ?? "",
1880
+ steps: e.steps,
1881
+ auth: e.auth ?? "key",
1882
+ fields: e.fields.map((f) => ({
1883
+ id: f.id,
1884
+ label: f.label,
1885
+ secret: f.secret === true,
1886
+ pattern: f.pattern ?? "",
1887
+ required: f.required !== false
1888
+ })),
1889
+ readOnly: Boolean(e.readOnly?.server || e.readOnly?.tools),
1890
+ canCheck: typeof e.check === "function"
1891
+ }));
1892
+ }
1893
+ function wrongValue(id, values, opts = {}) {
1894
+ const e = CATALOGUE2[id];
1895
+ if (!e) return null;
1896
+ for (const f of e.fields) {
1897
+ const v = (values[f.id] ?? "").trim();
1898
+ if (!v) {
1899
+ if (f.required !== false && !(f.secret && opts.keepKeys)) return `${f.label} is empty`;
1900
+ continue;
1901
+ }
1902
+ if (f.pattern && !new RegExp(f.pattern).test(v)) {
1903
+ return `That does not look like a ${e.name} ${f.label.toLowerCase()}`;
1904
+ }
1905
+ }
1906
+ return null;
1907
+ }
1908
+ async function checkKey(id, values, doFetch = fetch) {
1909
+ const e = CATALOGUE2[id];
1910
+ if (!e?.check) return { state: "unknown", note: "This one cannot be checked before a run." };
1911
+ const req = e.check(values);
1912
+ let res;
1913
+ try {
1914
+ res = await doFetch(req.url, {
1915
+ method: req.method ?? "GET",
1916
+ headers: { "user-agent": "roster", ...req.headers ?? {} },
1917
+ body: req.body,
1918
+ signal: AbortSignal.timeout(1e4)
1919
+ });
1920
+ } catch (err) {
1921
+ return { state: "unknown", note: `Could not reach ${e.name}: ${err.message}` };
1922
+ }
1923
+ if (res.ok) return { state: "ok" };
1924
+ if (res.status === 401) return { state: "rejected", note: `${e.name} rejected this key.` };
1925
+ if (res.status === 403) {
1926
+ return { state: "limited", note: "The key works. It cannot read everything, which is fine." };
1927
+ }
1928
+ return { state: "unknown", note: `${e.name} answered ${res.status}, so the key is unchecked.` };
1929
+ }
1930
+ async function secretsOn(gh, brains) {
1931
+ const out = /* @__PURE__ */ new Map();
1932
+ await Promise.all(
1933
+ brains.map(async (repo) => {
1934
+ const [own, shared] = await Promise.all([
1935
+ gh.request(
1936
+ "GET",
1937
+ `repos/${repo}/actions/secrets?per_page=100`
1938
+ ),
1939
+ gh.request(
1940
+ "GET",
1941
+ `repos/${repo}/actions/organization-secrets?per_page=100`
1942
+ )
1943
+ ]);
1944
+ if (!own.ok) {
1945
+ out.set(repo, null);
1946
+ return;
1947
+ }
1948
+ out.set(
1949
+ repo,
1950
+ /* @__PURE__ */ new Set([
1951
+ ...own.data.secrets.map((s) => s.name),
1952
+ ...shared.ok ? shared.data.secrets.map((s) => s.name) : []
1953
+ ])
1954
+ );
1955
+ })
1956
+ );
1957
+ return out;
1958
+ }
1959
+ async function storeSecret(gh, org, name, value, brains) {
1960
+ if (!value.trim()) throw new Error("the value is empty");
1961
+ if (!brains.length) throw new Error("there are no brain repos yet. Hire someone first");
1962
+ let fellBack;
1963
+ const info = await gh.request("GET", `orgs/${org}`);
1964
+ const plan2 = info.ok ? info.data?.plan?.name : void 0;
1965
+ if (plan2 && plan2 !== "free") {
1966
+ try {
1967
+ const ids = await Promise.all(
1968
+ brains.map(async (repo) => {
1969
+ const r = await gh.request("GET", `repos/${repo}`);
1970
+ if (!r.ok) throw new Error(`could not read ${repo}: ${r.error}`);
1971
+ return r.data.id;
1972
+ })
1973
+ );
1974
+ const key2 = await publicKey(gh, `orgs/${org}`);
1975
+ const put = await gh.request("PUT", `orgs/${org}/actions/secrets/${name}`, {
1976
+ body: {
1977
+ encrypted_value: sealForGitHub(value.trim(), key2.key),
1978
+ key_id: key2.key_id,
1979
+ visibility: "selected",
1980
+ selected_repository_ids: ids
1981
+ }
1982
+ });
1983
+ if (!put.ok) throw new Error(put.error ?? "refused");
1984
+ return { mode: "org", repos: brains };
1985
+ } catch (err) {
1986
+ fellBack = err.message;
1987
+ }
1988
+ }
1989
+ for (const repo of brains) {
1990
+ const key2 = await publicKey(gh, `repos/${repo}`);
1991
+ const put = await gh.request("PUT", `repos/${repo}/actions/secrets/${name}`, {
1992
+ body: { encrypted_value: sealForGitHub(value.trim(), key2.key), key_id: key2.key_id }
1993
+ });
1994
+ if (!put.ok) throw new Error(`could not store ${name} on ${repo}: ${put.error}`);
1995
+ }
1996
+ return { mode: "repo", repos: brains, fellBack };
1997
+ }
1998
+ async function deleteSecret(gh, org, name, brains) {
1999
+ await gh.request("DELETE", `orgs/${org}/actions/secrets/${name}`);
2000
+ await Promise.all(
2001
+ brains.map((repo) => gh.request("DELETE", `repos/${repo}/actions/secrets/${name}`))
2002
+ );
2003
+ }
2004
+ async function publicKey(gh, scope) {
2005
+ const r = await gh.request(
2006
+ "GET",
2007
+ `${scope}/actions/secrets/public-key`
2008
+ );
2009
+ if (!r.ok) throw new Error(`could not read ${scope}'s secret key: ${r.error}`);
2010
+ return r.data;
2011
+ }
2012
+ function setConnector(text2, org, id, entry) {
2013
+ const current = { ...org.connectors ?? {} };
2014
+ if (entry === null) delete current[id];
2015
+ else current[id] = { ...current[id] ?? {}, ...entry };
2016
+ for (const [k, v] of Object.entries(current[id] ?? {})) {
2017
+ if (v === void 0 || v === null || v === "" || v === false) delete current[id][k];
2018
+ }
2019
+ return withConnectors2(text2, current);
2020
+ }
2021
+
2022
+ // src/lib/localtoken.ts
2023
+ import { execFile as execFile3 } from "child_process";
2024
+
2025
+ // src/lib/github.ts
2026
+ function githubClient(token, opts = {}) {
2027
+ const doFetch = opts.fetch ?? fetch;
2028
+ const base2 = (opts.base ?? "https://api.github.com").replace(/\/$/, "");
2029
+ const limit = opts.remember ?? 500;
2030
+ const seen = /* @__PURE__ */ new Map();
2031
+ const headers = (accept) => ({
2032
+ authorization: `Bearer ${token}`,
2033
+ accept,
2034
+ "user-agent": opts.userAgent ?? "roster-portal",
2035
+ "x-github-api-version": "2022-11-28"
2036
+ });
2037
+ const request = async (method, path, o = {}) => {
2038
+ const url = path.startsWith("https://") ? path : `${base2}/${path.replace(/^\//, "")}`;
2039
+ const accept = o.accept ?? "application/vnd.github+json";
2040
+ const as = o.as ?? "json";
2041
+ const h = headers(accept);
2042
+ const key2 = `${accept} ${url}`;
2043
+ const kept = method === "GET" ? seen.get(key2) : void 0;
2044
+ if (kept) h["if-none-match"] = kept.etag;
2045
+ let body2;
2046
+ if (o.body !== void 0) {
2047
+ body2 = JSON.stringify(o.body);
2048
+ h["content-type"] = "application/json";
2049
+ }
2050
+ const reads = method === "GET" || o.retry === true;
2051
+ let res;
2052
+ for (let attempt = 0; ; attempt++) {
2053
+ try {
2054
+ res = await doFetch(url, { method, headers: h, body: body2 });
2055
+ } catch (err) {
2056
+ if (reads && attempt === 0) continue;
2057
+ return { ok: false, error: `GitHub could not be reached: ${err.message}` };
2058
+ }
2059
+ if (reads && attempt === 0 && [502, 503, 504].includes(res.status)) {
2060
+ await res.body?.cancel().catch(() => {
2061
+ });
2062
+ await new Promise((r) => setTimeout(r, 400));
2063
+ continue;
2064
+ }
2065
+ break;
2066
+ }
2067
+ if (res.status === 304 && kept) {
2068
+ seen.delete(key2);
2069
+ seen.set(key2, kept);
2070
+ return { ok: true, status: 304, data: kept.data, cached: true };
2071
+ }
2072
+ if (!res.ok) {
2073
+ const text2 = await res.text().catch(() => "");
2074
+ return { ok: false, status: res.status, error: message(res, text2) };
2075
+ }
2076
+ let data;
2077
+ if (res.status === 204) data = void 0;
2078
+ else if (as === "bytes") data = new Uint8Array(await res.arrayBuffer());
2079
+ else if (as === "text") data = await res.text();
2080
+ else {
2081
+ const text2 = await res.text();
2082
+ data = text2 ? JSON.parse(text2) : void 0;
2083
+ }
2084
+ const etag = res.headers.get("etag");
2085
+ if (method === "GET" && etag && as !== "bytes") {
2086
+ seen.set(key2, { etag, data });
2087
+ if (seen.size > limit) seen.delete(seen.keys().next().value);
2088
+ }
2089
+ return { ok: true, status: res.status, data };
2090
+ };
2091
+ const graphql2 = async (query2, vars = {}) => {
2092
+ const res = await request(
2093
+ "POST",
2094
+ "graphql",
2095
+ // A query reads; a mutation writes, and is never asked twice.
2096
+ { body: { query: query2, variables: vars }, retry: !/^\s*mutation\b/.test(query2) }
2097
+ );
2098
+ if (!res.ok) return { ok: false, status: res.status, error: res.error };
2099
+ const errors = res.data?.errors ?? [];
2100
+ if (errors.length) return { ok: false, status: 200, error: errors[0].message };
2101
+ return { ok: true, status: 200, data: res.data?.data };
2102
+ };
2103
+ return { request, graphql: graphql2 };
2104
+ }
2105
+ function message(res, text2) {
2106
+ const remaining = res.headers.get("x-ratelimit-remaining");
2107
+ if ((res.status === 403 || res.status === 429) && remaining === "0") {
2108
+ return "GitHub's API limit for this hour is used up. It resets within the hour.";
2109
+ }
2110
+ try {
2111
+ const parsed = JSON.parse(text2);
2112
+ if (parsed.message) return parsed.message;
2113
+ } catch {
2114
+ }
2115
+ if (res.status === 401) return "GitHub did not accept the token. Sign in again.";
2116
+ if (res.status === 404) return "Not Found";
2117
+ return `GitHub answered ${res.status} ${res.statusText}`.trim();
2118
+ }
2119
+ function splitRepo(repo) {
2120
+ const [owner = "", name = ""] = repo.split("/");
2121
+ return { owner, name };
2122
+ }
2123
+
2124
+ // src/lib/localtoken.ts
2125
+ var pending = null;
2126
+ function localGitHub() {
2127
+ pending ??= find();
2128
+ return pending;
2129
+ }
2130
+ async function find() {
2131
+ const env = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
2132
+ if (env) return { ok: true, gh: githubClient(env), token: env };
2133
+ const token = await new Promise(
2134
+ (resolve7) => execFile3(
2135
+ "gh",
2136
+ ["auth", "token"],
2137
+ { encoding: "utf8" },
2138
+ (err, out) => resolve7(err ? "" : out.trim())
2139
+ )
2140
+ );
2141
+ if (!token) {
2142
+ pending = null;
2143
+ return {
2144
+ ok: false,
2145
+ error: "No GitHub token. Run `gh auth login`, or set GITHUB_TOKEN, and try again."
2146
+ };
2147
+ }
2148
+ return { ok: true, gh: githubClient(token), token };
2149
+ }
2150
+
1559
2151
  // src/lib/credential.ts
1560
2152
  async function planCredential(org, name, brains, opts = {}, gh = api) {
1561
2153
  const base2 = { name, org, brains };
@@ -1622,7 +2214,7 @@ function repoName(full) {
1622
2214
  }
1623
2215
 
1624
2216
  // src/lib/setup.ts
1625
- import { execFile as execFile3 } from "child_process";
2217
+ import { execFile as execFile4 } from "child_process";
1626
2218
  import { mkdirSync } from "fs";
1627
2219
  import { join as join12 } from "path";
1628
2220
  var AGENTS = [
@@ -1665,13 +2257,13 @@ async function setupStatus(startedIn) {
1665
2257
  const ready2 = await ghReady();
1666
2258
  let orgs = [];
1667
2259
  if (ready2.ok) {
1668
- const list = await ghJson([
2260
+ const list2 = await ghJson([
1669
2261
  "api",
1670
2262
  "user/orgs?per_page=100",
1671
2263
  "--jq",
1672
2264
  "[.[] | {login}]"
1673
2265
  ]);
1674
- if (list.ok) orgs = (list.data ?? []).map((o) => o.login).sort();
2266
+ if (list2.ok) orgs = (list2.data ?? []).map((o) => o.login).sort();
1675
2267
  }
1676
2268
  return {
1677
2269
  tenant: found ? {
@@ -1712,11 +2304,11 @@ function readProducts(opsDir) {
1712
2304
  }
1713
2305
  return out;
1714
2306
  }
1715
- function readBlockNames(opsDir, block, key) {
2307
+ function readBlockNames(opsDir, block, key2) {
1716
2308
  const path = join12(opsDir, "org.yaml");
1717
2309
  if (!existsSync2(path)) return [];
1718
2310
  const names = [];
1719
- const pattern = new RegExp(`\\b${key}:\\s*([\\w.-]+)`);
2311
+ const pattern = new RegExp(`\\b${key2}:\\s*([\\w.-]+)`);
1720
2312
  let inside = false;
1721
2313
  for (const line of readFileSync2(path, "utf8").split("\n")) {
1722
2314
  if (new RegExp(`^${block}:\\s*$`).test(line)) {
@@ -1774,7 +2366,7 @@ async function joinTenant(root2, org) {
1774
2366
  }
1775
2367
  function clone(url, into) {
1776
2368
  return new Promise((ok, fail) => {
1777
- execFile3("git", ["clone", "-q", url, into], (err) => err ? fail(err) : ok());
2369
+ execFile4("git", ["clone", "-q", url, into], (err) => err ? fail(err) : ok());
1778
2370
  });
1779
2371
  }
1780
2372
 
@@ -1791,36 +2383,6 @@ function askKinds(labels) {
1791
2383
  return labels.filter((l) => ASK_KINDS.includes(l));
1792
2384
  }
1793
2385
 
1794
- // src/lib/commit.ts
1795
- import { execFileSync as execFileSync2 } from "child_process";
1796
- function commitAndPush(repoDir, paths, message2) {
1797
- const git4 = (args) => execFileSync2("git", ["-C", repoDir, ...args], {
1798
- encoding: "utf8",
1799
- stdio: ["ignore", "pipe", "pipe"]
1800
- });
1801
- try {
1802
- if (!git4(["status", "--porcelain", "--", ...paths]).trim()) {
1803
- return { committed: false, pushed: false, note: "nothing to commit" };
1804
- }
1805
- git4(["add", "--", ...paths]);
1806
- git4(["commit", "-q", "-m", message2, "--", ...paths]);
1807
- } catch (err) {
1808
- return { committed: false, pushed: false, note: short2(err) };
1809
- }
1810
- const sha = git4(["rev-parse", "--short", "HEAD"]).trim();
1811
- try {
1812
- git4(["push", "-q"]);
1813
- } catch (err) {
1814
- return { committed: true, pushed: false, sha, note: short2(err) };
1815
- }
1816
- return { committed: true, pushed: true, sha };
1817
- }
1818
- function short2(e) {
1819
- const msg = e instanceof Error ? e.stderr?.toString() || e.message : String(e);
1820
- const line = msg.split("\n").find((l) => l.trim()) ?? msg;
1821
- return line.length > 200 ? line.slice(0, 199) + "\u2026" : line;
1822
- }
1823
-
1824
2386
  // src/lib/reviewgate.ts
1825
2387
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
1826
2388
  import { tmpdir } from "os";
@@ -2089,7 +2651,7 @@ function buildPlan(ws, org, handle, opts, parseYaml3) {
2089
2651
  "status_issue is 0 until --apply opens the pinned issue; prompts will not compose before then"
2090
2652
  );
2091
2653
  }
2092
- const humans = readHumans(org);
2654
+ const humans = staffHumans(org);
2093
2655
  const orgSpec2 = {
2094
2656
  org: org.org,
2095
2657
  name: org.name,
@@ -2104,7 +2666,7 @@ function buildPlan(ws, org, handle, opts, parseYaml3) {
2104
2666
  warnings.push("org.yaml has no human.github, so the mention gate will never match");
2105
2667
  if (humans.length > 1) {
2106
2668
  warnings.push(
2107
- `the mention gate accepts ${humans.map((h) => h.github).join(", ")} \u2014 everyone in org.yaml`
2669
+ `the mention gate accepts ${humans.map((h) => h.github).join(", ")} \u2014 everyone in org.yaml but the view-only`
2108
2670
  );
2109
2671
  }
2110
2672
  const tokens = tokensFor(orgSpec2, staff);
@@ -2347,6 +2909,20 @@ async function applyPlan(ws, plan2, opts) {
2347
2909
  process.stdout.write(` ${shared.note}
2348
2910
  `);
2349
2911
  }
2912
+ for (const c of declared2(plan2.org)) {
2913
+ for (const k of c.secrets) {
2914
+ if (await readOrgSecret(plan2.org.org, k.name)) {
2915
+ const shared = await shareOrgSecret(plan2.org.org, k.name, staff.brain);
2916
+ process.stdout.write(` ${shared.note}
2917
+ `);
2918
+ } else {
2919
+ process.stdout.write(
2920
+ ` ${c.name}'s key is on each repo, so ${staff.brain} has none yet. Add it again from Connectors to give it to ${staff.handle}.
2921
+ `
2922
+ );
2923
+ }
2924
+ }
2925
+ }
2350
2926
  git(root2, ["init", "-q", "-b", "main"]);
2351
2927
  git(root2, ["add", "-A"]);
2352
2928
  git(root2, ["commit", "-q", "-m", `roster: scaffold ${staff.name}`]);
@@ -2486,15 +3062,15 @@ function addToOrgYaml(ws, plan2) {
2486
3062
  const withStaff = insertUnder(text2, "staff", staffLine);
2487
3063
  writeFileSync3(path, insertUnder(withStaff, "repos", repoLine));
2488
3064
  }
2489
- function insertUnder(text2, key, line) {
2490
- const empty = new RegExp(`^${key}:\\s*\\[\\]\\s*$`, "m");
2491
- if (empty.test(text2)) return text2.replace(empty, `${key}:
3065
+ function insertUnder(text2, key2, line) {
3066
+ const empty = new RegExp(`^${key2}:\\s*\\[\\]\\s*$`, "m");
3067
+ if (empty.test(text2)) return text2.replace(empty, `${key2}:
2492
3068
  ${line.trimEnd()}`);
2493
- const heading = new RegExp(`^${key}:\\s*$`, "m");
3069
+ const heading = new RegExp(`^${key2}:\\s*$`, "m");
2494
3070
  const m = heading.exec(text2);
2495
3071
  if (!m) return `${text2.trimEnd()}
2496
3072
 
2497
- ${key}:
3073
+ ${key2}:
2498
3074
  ${line.trimEnd()}
2499
3075
  `;
2500
3076
  const lines = text2.split("\n");
@@ -2676,18 +3252,18 @@ function howTo(org) {
2676
3252
  function readSecret(prompt) {
2677
3253
  const stdin = process.stdin;
2678
3254
  if (!stdin.isTTY) {
2679
- return new Promise((resolve8, reject) => {
3255
+ return new Promise((resolve7, reject) => {
2680
3256
  let buf = "";
2681
3257
  stdin.setEncoding("utf8");
2682
3258
  stdin.on("data", (c) => {
2683
3259
  buf += c;
2684
3260
  });
2685
- stdin.on("end", () => resolve8(buf.trim()));
3261
+ stdin.on("end", () => resolve7(buf.trim()));
2686
3262
  stdin.on("error", reject);
2687
3263
  });
2688
3264
  }
2689
3265
  process.stdout.write(prompt);
2690
- return new Promise((resolve8, reject) => {
3266
+ return new Promise((resolve7, reject) => {
2691
3267
  let buf = "";
2692
3268
  stdin.setRawMode(true);
2693
3269
  stdin.setEncoding("utf8");
@@ -2698,7 +3274,7 @@ function readSecret(prompt) {
2698
3274
  stdin.off("data", onData);
2699
3275
  process.stdout.write("\n");
2700
3276
  if (err) reject(err);
2701
- else resolve8(buf.trim());
3277
+ else resolve7(buf.trim());
2702
3278
  };
2703
3279
  const onData = (chunk) => {
2704
3280
  for (const ch of chunk) {
@@ -2726,12 +3302,244 @@ function parseFlags4(argv) {
2726
3302
  return out;
2727
3303
  }
2728
3304
 
3305
+ // src/commands/connector.ts
3306
+ var connectorHelp = `
3307
+ roster connector [list]
3308
+ roster connector add <name> [--staff <handles>] [--read-only] [--set <field=value>] [--apply]
3309
+ roster connector remove <name> [--apply]
3310
+
3311
+ Give staff an outside service to use in their runs, such as Sentry, Linear or Stripe.
3312
+
3313
+ list the services roster knows, and the ones this org has, with whose they are and
3314
+ whether their keys are stored
3315
+ add add one, or change who has it. With --apply it asks for the key, checks it with the
3316
+ service, stores it as a GitHub secret every brain can read, and commits org.yaml
3317
+ remove take one away, and delete its keys
3318
+
3319
+ The key is typed at a prompt that does not echo, or read from standard input. It never goes
3320
+ on a command line or in org.yaml.
3321
+
3322
+ --staff <handles> who gets it, comma separated (default: the catalogue's suggestion)
3323
+ --read-only hold it to reading, for everybody who has it
3324
+ --set <field=value> a setting the service needs, such as --set project_ref=abc123
3325
+ --url <url> a service roster does not know: its MCP server's URL
3326
+ --command <line> or the command that starts it
3327
+ --secret <NAME> a key that service needs, by the name it is given (repeatable)
3328
+ --keep-key change who has it without asking for the key again
3329
+ --apply do it
3330
+ --ops <dir> ops repo directory (default: found by walking up)
3331
+ `;
3332
+ async function connectorCommand(argv) {
3333
+ const [sub = "list", id, ...rest] = argv[0]?.startsWith("-") ? ["list", ...argv] : argv;
3334
+ const opts = parseFlags5(id?.startsWith("-") ? [id, ...rest] : rest);
3335
+ const name = id?.startsWith("-") ? void 0 : id;
3336
+ try {
3337
+ if (sub === "list") return await list(opts);
3338
+ if (!name) throw new Error(`roster connector ${sub} needs a name. See roster connector list`);
3339
+ if (sub === "add") return await add(name, opts);
3340
+ if (sub === "remove") return await remove(name, opts);
3341
+ throw new Error(`unknown subcommand ${sub}. One of: list, add, remove`);
3342
+ } catch (err) {
3343
+ process.stderr.write(`roster: ${err.message}
3344
+ `);
3345
+ return 1;
3346
+ }
3347
+ }
3348
+ async function load(opts) {
3349
+ const ws = findWorkspace(opts.ops);
3350
+ const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
3351
+ const org = readOrg(ws.opsDir, parseYaml3);
3352
+ const file = join15(ws.opsDir, "org.yaml");
3353
+ const brains = (org.staff ?? []).map((s) => `${org.org}/${s.dir ?? s.handle}`);
3354
+ return { ws, org, file, text: readFileSync6(file, "utf8"), brains };
3355
+ }
3356
+ async function list(opts) {
3357
+ const { org, brains } = await load(opts);
3358
+ const have = declared2(org);
3359
+ const out = ["", " Connected"];
3360
+ if (!have.length) out.push(" none yet");
3361
+ const gh = await localGitHub();
3362
+ const stored = gh.ok ? await secretsOn(gh.gh, brains) : null;
3363
+ for (const c of have) {
3364
+ const keys = c.secrets.map((s) => s.name);
3365
+ let status = "";
3366
+ if (c.problem) status = c.problem;
3367
+ else if (c.auth === "oauth") status = `signs in through ${c.portal}`;
3368
+ else if (stored) {
3369
+ const where = [...stored.values()].filter((s) => s !== null);
3370
+ status = !where.length ? "keys unreadable with your token" : keys.every((k) => where.every((s) => s.has(k))) ? "key stored" : `key missing: ${keys.join(", ")}`;
3371
+ }
3372
+ out.push(
3373
+ ` ${c.name.padEnd(26)} ${(c.staff.join(", ") || "nobody").padEnd(16)} ${status}` + (c.readOnly ? " (read only)" : "")
3374
+ );
3375
+ }
3376
+ out.push("", " Available");
3377
+ for (const [cid, e] of Object.entries(CATALOGUE2)) {
3378
+ if (have.some((c) => c.catalogue === cid)) continue;
3379
+ out.push(` ${cid.padEnd(12)} ${e.name.padEnd(26)} ${e.summary}`);
3380
+ }
3381
+ out.push("", " roster connector add <name> to add one.", "");
3382
+ process.stdout.write(out.join("\n") + "\n");
3383
+ return 0;
3384
+ }
3385
+ async function add(id, opts) {
3386
+ const { ws, org, file, text: text2, brains } = await load(opts);
3387
+ const known = CATALOGUE2[id];
3388
+ const existing = org.connectors?.[id];
3389
+ if (!known && !existing && !opts.url && !opts.command) {
3390
+ throw new Error(
3391
+ `roster does not know "${id}". Pick one from roster connector list, or give --url or --command`
3392
+ );
3393
+ }
3394
+ if (known?.auth === "oauth") {
3395
+ throw new Error(
3396
+ `${known.name} signs in with a browser. Add it from the hosted portal's Connectors page`
3397
+ );
3398
+ }
3399
+ const handles = new Set((org.staff ?? []).map((s) => s.handle));
3400
+ const staff = opts.staff ?? existing?.staff ?? (known?.suggest ?? []).filter((h) => handles.has(h));
3401
+ const unknown = staff.filter((h) => !handles.has(h));
3402
+ if (unknown.length) throw new Error(`no staff member ${unknown.join(", ")} in org.yaml`);
3403
+ if (!staff.length) throw new Error("nobody would have it. Say who with --staff cto,cmo");
3404
+ const entry = { staff };
3405
+ if (opts.readOnly) entry.read_only = true;
3406
+ if (opts.url) entry.url = opts.url;
3407
+ if (opts.command) entry.command = opts.command;
3408
+ if (opts.secrets.length) entry.secrets = opts.secrets;
3409
+ Object.assign(entry, opts.set);
3410
+ const next = setConnector(text2, org, id, entry);
3411
+ const after = declared2({
3412
+ ...org,
3413
+ connectors: { ...org.connectors ?? {}, [id]: { ...existing ?? {}, ...entry } }
3414
+ }).find((c) => c.id === id);
3415
+ if (after.problem) throw new Error(after.problem);
3416
+ process.stdout.write(`
3417
+ roster connector add ${id}
3418
+
3419
+ `);
3420
+ process.stdout.write(
3421
+ ` ${after.name} for ${staff.join(", ")}${opts.readOnly ? ", read only" : ""}
3422
+ `
3423
+ );
3424
+ if (!opts.keepKey) {
3425
+ for (const s of after.secrets)
3426
+ process.stdout.write(` + secret ${s.name} on ${brains.length} brain repos
3427
+ `);
3428
+ }
3429
+ process.stdout.write(` ~ org.yaml, committed and pushed
3430
+
3431
+ `);
3432
+ if (known) {
3433
+ for (const step of known.steps) process.stdout.write(` ${step}
3434
+ `);
3435
+ if (known.link) process.stdout.write(` ${known.link}
3436
+ `);
3437
+ process.stdout.write("\n");
3438
+ }
3439
+ if (!opts.apply) {
3440
+ process.stdout.write(" Nothing was changed. Re-run with --apply.\n\n");
3441
+ return 0;
3442
+ }
3443
+ const gh = await localGitHub();
3444
+ if (!gh.ok) throw new Error(gh.error);
3445
+ if (!opts.keepKey && after.secrets.length) {
3446
+ const values = { ...after.settings };
3447
+ for (const s of after.secrets) {
3448
+ values[s.field] = await readSecret(` ${s.label} (it is not shown): `);
3449
+ }
3450
+ const wrong = wrongValue(after.catalogue ?? "", values);
3451
+ if (wrong) throw new Error(wrong);
3452
+ if (after.catalogue) {
3453
+ const checked = await checkKey(after.catalogue, values);
3454
+ if (checked.state === "rejected") throw new Error(`${checked.note} Nothing was stored.`);
3455
+ process.stdout.write(` ${checked.state === "ok" ? "The key works." : checked.note}
3456
+ `);
3457
+ }
3458
+ for (const s of after.secrets) {
3459
+ const done = await storeSecret(gh.gh, org.org, s.name, values[s.field], brains);
3460
+ if (done.fellBack) process.stdout.write(` the org secret was refused: ${done.fellBack}
3461
+ `);
3462
+ process.stdout.write(
3463
+ done.mode === "org" ? ` stored ${s.name} once for ${org.org}
3464
+ ` : ` stored ${s.name} on ${done.repos.join(", ")}
3465
+ `
3466
+ );
3467
+ }
3468
+ }
3469
+ writeFileSync4(file, next);
3470
+ report(commitAndPush(ws.opsDir, ["org.yaml"], `roster: connect ${after.name}`));
3471
+ return 0;
3472
+ }
3473
+ async function remove(id, opts) {
3474
+ const { ws, org, file, text: text2, brains } = await load(opts);
3475
+ const c = declared2(org).find((x) => x.id === id);
3476
+ if (!c) throw new Error(`org.yaml has no connector "${id}"`);
3477
+ process.stdout.write(`
3478
+ roster connector remove ${id}
3479
+
3480
+ `);
3481
+ process.stdout.write(` - ${c.name}, from ${c.staff.join(", ") || "nobody"}
3482
+ `);
3483
+ for (const s of c.secrets) process.stdout.write(` - secret ${s.name}
3484
+ `);
3485
+ process.stdout.write(` ~ org.yaml, committed and pushed
3486
+
3487
+ `);
3488
+ if (!opts.apply) {
3489
+ process.stdout.write(" Nothing was changed. Re-run with --apply.\n\n");
3490
+ return 0;
3491
+ }
3492
+ const gh = await localGitHub();
3493
+ if (!gh.ok) throw new Error(gh.error);
3494
+ for (const s of c.secrets) await deleteSecret(gh.gh, org.org, s.name, brains);
3495
+ writeFileSync4(file, setConnector(text2, org, id, null));
3496
+ report(commitAndPush(ws.opsDir, ["org.yaml"], `roster: disconnect ${c.name}`));
3497
+ return 0;
3498
+ }
3499
+ function report(done) {
3500
+ process.stdout.write(
3501
+ done.pushed ? ` committed and pushed org.yaml (${done.sha})
3502
+
3503
+ ` : done.committed ? ` committed org.yaml but could not push: ${done.note}. Push it yourself.
3504
+
3505
+ ` : ` org.yaml left uncommitted: ${done.note}
3506
+
3507
+ `
3508
+ );
3509
+ }
3510
+ function parseFlags5(argv) {
3511
+ const out = { secrets: [], set: {} };
3512
+ for (let i = 0; i < argv.length; i++) {
3513
+ const flag = argv[i];
3514
+ const value = () => {
3515
+ const v = argv[++i];
3516
+ if (v === void 0) throw new Error(`${flag} needs a value`);
3517
+ return v;
3518
+ };
3519
+ if (flag === "--apply") out.apply = true;
3520
+ else if (flag === "--read-only") out.readOnly = true;
3521
+ else if (flag === "--keep-key") out.keepKey = true;
3522
+ else if (flag === "--ops") out.ops = value();
3523
+ else if (flag === "--staff")
3524
+ out.staff = value().split(",").map((s) => s.trim()).filter(Boolean);
3525
+ else if (flag === "--url") out.url = value();
3526
+ else if (flag === "--command") out.command = value();
3527
+ else if (flag === "--secret") out.secrets.push(value());
3528
+ else if (flag === "--set") {
3529
+ const [k, ...v] = value().split("=");
3530
+ if (!k || !v.length) throw new Error("--set takes field=value");
3531
+ out.set[k] = v.join("=");
3532
+ } else throw new Error(`unknown flag ${flag}`);
3533
+ }
3534
+ return out;
3535
+ }
3536
+
2729
3537
  // src/commands/deploy.ts
2730
3538
  import { spawn } from "child_process";
2731
3539
  import { randomBytes as randomBytes2 } from "crypto";
2732
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, mkdtempSync as mkdtempSync2, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
3540
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, mkdtempSync as mkdtempSync2, readFileSync as readFileSync7, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "fs";
2733
3541
  import { tmpdir as tmpdir2 } from "os";
2734
- import { dirname as dirname6, join as join15 } from "path";
3542
+ import { dirname as dirname6, join as join16 } from "path";
2735
3543
  import { createInterface } from "readline/promises";
2736
3544
  import { fileURLToPath as fileURLToPath3 } from "url";
2737
3545
  var deployHelp = `
@@ -2763,15 +3571,15 @@ var CONFIG = "portal/wrangler.jsonc";
2763
3571
  var WORKFLOW = ".github/workflows/portal.yaml";
2764
3572
  var WRANGLER = "wrangler@4";
2765
3573
  async function deployCommand(argv) {
2766
- const opts = parseFlags5(argv);
3574
+ const opts = parseFlags6(argv);
2767
3575
  const ws = findWorkspace(opts.ops);
2768
3576
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
2769
3577
  const org = readOrg(ws.opsDir, parseYaml3);
2770
- const configPath = join15(ws.opsDir, CONFIG);
3578
+ const configPath = join16(ws.opsDir, CONFIG);
2771
3579
  const exists = existsSync6(configPath);
2772
3580
  let config;
2773
3581
  if (exists) {
2774
- config = parseJsonc(readFileSync6(configPath, "utf8"));
3582
+ config = parseJsonc(readFileSync7(configPath, "utf8"));
2775
3583
  if (opts.domain && opts.domain !== domainOf(config)) {
2776
3584
  config.routes = [{ pattern: opts.domain, custom_domain: true }];
2777
3585
  }
@@ -2795,7 +3603,7 @@ async function deployCommand(argv) {
2795
3603
  ` + (config.account_id ? ` account ${config.account_id}
2796
3604
  ` : "") + ` signs in the humans in org.yaml, with GitHub
2797
3605
  ` + (exists ? "" : ` writes ${ws.opsName}/${CONFIG} and ${ws.opsName}/${WORKFLOW}
2798
- `) + (config.vars.GITHUB_CLIENT_ID ? "" : " asks for the portal's GitHub OAuth App (a three-field form)\n") + ` deploys with ${WRANGLER}, as whoever wrangler is signed in as
3606
+ `) + (config.vars.GITHUB_CLIENT_ID ? "" : " asks for the portal's GitHub OAuth App (a three-field form)\n") + (opts.ci || hasConnectorStore(config) ? "" : " creates a KV namespace for connectors that sign in, such as Notion\n") + ` deploys with ${WRANGLER}, as whoever wrangler is signed in as
2799
3607
 
2800
3608
  `
2801
3609
  );
@@ -2823,24 +3631,40 @@ async function deployCommand(argv) {
2823
3631
  secrets.GITHUB_CLIENT_SECRET = app.secret;
2824
3632
  secrets.SESSION_KEY = randomBytes2(32).toString("base64");
2825
3633
  }
2826
- const tmp = mkdtempSync2(join15(tmpdir2(), "roster-deploy-"));
3634
+ const tmp = mkdtempSync2(join16(tmpdir2(), "roster-deploy-"));
2827
3635
  try {
2828
3636
  const full = {
2829
3637
  ...config,
2830
3638
  main: bundle.main,
2831
3639
  assets: { ...config.assets, directory: bundle.assets }
2832
3640
  };
2833
- writeFileSync4(join15(tmp, "wrangler.json"), JSON.stringify(full, null, 2));
3641
+ writeFileSync5(join16(tmp, "wrangler.json"), JSON.stringify(full, null, 2));
3642
+ if (!opts.ci && !hasConnectorStore(config)) {
3643
+ process.stdout.write(" creating a KV namespace for signed-in connectors\u2026\n");
3644
+ const id = await createNamespace(`${config.name}-connectors`, join16(tmp, "wrangler.json"));
3645
+ if (id) {
3646
+ config.kv_namespaces = [
3647
+ ...config.kv_namespaces ?? [],
3648
+ { binding: "CONNECTORS", id }
3649
+ ];
3650
+ full.kv_namespaces = config.kv_namespaces;
3651
+ writeFileSync5(join16(tmp, "wrangler.json"), JSON.stringify(full, null, 2));
3652
+ } else {
3653
+ process.stdout.write(
3654
+ " could not create it, so connectors that sign in are not offered yet. Run this again later.\n"
3655
+ );
3656
+ }
3657
+ }
2834
3658
  process.stdout.write(" deploying\u2026\n");
2835
- if (await wrangler(["deploy", "--config", join15(tmp, "wrangler.json")]) !== 0) {
3659
+ if (await wrangler(["deploy", "--config", join16(tmp, "wrangler.json")]) !== 0) {
2836
3660
  process.stderr.write("roster: wrangler could not deploy. Its own message is above.\n");
2837
3661
  return 1;
2838
3662
  }
2839
3663
  if (Object.keys(secrets).length) {
2840
- const file = join15(tmp, "secrets.json");
2841
- writeFileSync4(file, JSON.stringify(secrets), { mode: 384 });
3664
+ const file = join16(tmp, "secrets.json");
3665
+ writeFileSync5(file, JSON.stringify(secrets), { mode: 384 });
2842
3666
  process.stdout.write(" storing the App's secret and a session key on the Worker\u2026\n");
2843
- if (await wrangler(["secret", "bulk", file, "--config", join15(tmp, "wrangler.json")]) !== 0) {
3667
+ if (await wrangler(["secret", "bulk", file, "--config", join16(tmp, "wrangler.json")]) !== 0) {
2844
3668
  process.stderr.write("roster: the secrets were not stored. Run this again.\n");
2845
3669
  return 1;
2846
3670
  }
@@ -2850,11 +3674,11 @@ async function deployCommand(argv) {
2850
3674
  }
2851
3675
  if (!opts.ci) {
2852
3676
  mkdirSync3(dirname6(configPath), { recursive: true });
2853
- writeFileSync4(configPath, renderConfig(config));
2854
- const workflow = join15(ws.opsDir, WORKFLOW);
3677
+ writeFileSync5(configPath, renderConfig(config));
3678
+ const workflow = join16(ws.opsDir, WORKFLOW);
2855
3679
  if (!existsSync6(workflow)) {
2856
3680
  mkdirSync3(dirname6(workflow), { recursive: true });
2857
- writeFileSync4(workflow, WORKFLOW_TEXT);
3681
+ writeFileSync5(workflow, WORKFLOW_TEXT);
2858
3682
  }
2859
3683
  const done = commitAndPush(ws.opsDir, [CONFIG, WORKFLOW], "roster: the hosted portal");
2860
3684
  if (done.note && !done.committed) process.stdout.write(` ${done.note}
@@ -2908,6 +3732,30 @@ function newConfig(org, opsName, domain) {
2908
3732
  assets: { binding: "ASSETS", run_worker_first: true }
2909
3733
  };
2910
3734
  }
3735
+ function hasConnectorStore(config) {
3736
+ return (config.kv_namespaces ?? []).some(
3737
+ (k) => k.binding === "CONNECTORS"
3738
+ );
3739
+ }
3740
+ async function createNamespace(title, configFile) {
3741
+ const out = await new Promise((resolve7) => {
3742
+ let text2 = "";
3743
+ const child = spawn(
3744
+ "npx",
3745
+ ["--yes", WRANGLER, "kv", "namespace", "create", title, "--config", configFile],
3746
+ { stdio: ["ignore", "pipe", "inherit"] }
3747
+ );
3748
+ child.stdout.on("data", (b) => {
3749
+ text2 += String(b);
3750
+ });
3751
+ child.on("close", (code) => resolve7({ code: code ?? 1, text: text2 }));
3752
+ child.on("error", () => resolve7({ code: 1, text: text2 }));
3753
+ });
3754
+ return out.code === 0 ? namespaceId(out.text) : null;
3755
+ }
3756
+ function namespaceId(text2) {
3757
+ return /\bid\b["']?\s*[:=]\s*["']([0-9a-f]{32})["']/.exec(text2)?.[1] ?? null;
3758
+ }
2911
3759
  function domainOf(config) {
2912
3760
  return config.routes?.[0]?.pattern ?? "";
2913
3761
  }
@@ -2922,9 +3770,9 @@ function parseJsonc(text2) {
2922
3770
  }
2923
3771
  function workerBundle() {
2924
3772
  const here = dirname6(fileURLToPath3(import.meta.url));
2925
- for (const dist of [here, join15(here, "..", "..", "dist")]) {
2926
- const main3 = join15(dist, "worker", "index.js");
2927
- if (existsSync6(main3)) return { main: main3, assets: join15(dist, "worker", "assets") };
3773
+ for (const dist of [here, join16(here, "..", "..", "dist")]) {
3774
+ const main2 = join16(dist, "worker", "index.js");
3775
+ if (existsSync6(main2)) return { main: main2, assets: join16(dist, "worker", "assets") };
2928
3776
  }
2929
3777
  return null;
2930
3778
  }
@@ -2942,10 +3790,10 @@ async function wrangler(args) {
2942
3790
  return code;
2943
3791
  }
2944
3792
  function wranglerOnce(args) {
2945
- return new Promise((resolve8) => {
3793
+ return new Promise((resolve7) => {
2946
3794
  const child = spawn("npx", ["--yes", WRANGLER, ...args], { stdio: "inherit" });
2947
- child.on("close", (code) => resolve8(code ?? 1));
2948
- child.on("error", () => resolve8(1));
3795
+ child.on("close", (code) => resolve7(code ?? 1));
3796
+ child.on("error", () => resolve7(1));
2949
3797
  });
2950
3798
  }
2951
3799
  var WORKFLOW_TEXT = `# Redeploys the hosted portal: when its config changes, every morning so roster updates
@@ -2998,7 +3846,7 @@ jobs:
2998
3846
  - if: steps.ready.outputs.go == 'true'
2999
3847
  run: npx --yes @nanocollective/roster@latest portal deploy --ci --apply
3000
3848
  `;
3001
- function parseFlags5(argv) {
3849
+ function parseFlags6(argv) {
3002
3850
  const out = {};
3003
3851
  for (let i = 0; i < argv.length; i++) {
3004
3852
  const flag = argv[i];
@@ -3013,168 +3861,39 @@ function parseFlags5(argv) {
3013
3861
  }
3014
3862
 
3015
3863
  // src/commands/doctor.ts
3016
- import { existsSync as existsSync8, readdirSync as readdirSync5, readFileSync as readFileSync8 } from "fs";
3017
- import { join as join19 } from "path";
3018
-
3019
- // src/lib/callable.ts
3020
- function accessLink(org, repo) {
3021
- return `https://github.com/${org}/${repo}/settings/actions`;
3022
- }
3023
- async function allowOrgCallers(org, repo, gh = api) {
3024
- const link = accessLink(org, repo);
3025
- const path = `repos/${org}/${repo}/actions/permissions/access`;
3026
- const now = await gh(path);
3027
- if (now.ok && now.data?.access_level === "organization") return { ok: true, already: true, link };
3028
- const set = await gh(path, ["-X", "PUT", "-f", "access_level=organization"]);
3029
- if (set.ok) return { ok: true, link };
3030
- return { ok: false, error: refusal(set), link };
3031
- }
3032
- function refusal(res) {
3033
- const why = res.error ?? "unknown error";
3034
- if (res.status === 403 || res.status === 404) {
3035
- return `${why}. Setting this needs admin on the repo, and your gh token does not have it here`;
3036
- }
3037
- if (res.status === 422) return `${why}. GitHub only offers this on a private or internal repo`;
3038
- return why;
3039
- }
3040
-
3041
- // src/lib/localtoken.ts
3042
- import { execFile as execFile4 } from "child_process";
3864
+ import { existsSync as existsSync8, readdirSync as readdirSync5, readFileSync as readFileSync9 } from "fs";
3865
+ import { join as join20 } from "path";
3043
3866
 
3044
- // src/lib/github.ts
3045
- function githubClient(token, opts = {}) {
3046
- const doFetch = opts.fetch ?? fetch;
3047
- const base2 = (opts.base ?? "https://api.github.com").replace(/\/$/, "");
3048
- const limit = opts.remember ?? 500;
3049
- const seen = /* @__PURE__ */ new Map();
3050
- const headers = (accept) => ({
3051
- authorization: `Bearer ${token}`,
3052
- accept,
3053
- "user-agent": opts.userAgent ?? "roster-portal",
3054
- "x-github-api-version": "2022-11-28"
3055
- });
3056
- const request = async (method, path, o = {}) => {
3057
- const url = path.startsWith("https://") ? path : `${base2}/${path.replace(/^\//, "")}`;
3058
- const accept = o.accept ?? "application/vnd.github+json";
3059
- const as = o.as ?? "json";
3060
- const h = headers(accept);
3061
- const key = `${accept} ${url}`;
3062
- const kept = method === "GET" ? seen.get(key) : void 0;
3063
- if (kept) h["if-none-match"] = kept.etag;
3064
- let body2;
3065
- if (o.body !== void 0) {
3066
- body2 = JSON.stringify(o.body);
3067
- h["content-type"] = "application/json";
3068
- }
3069
- const reads = method === "GET" || o.retry === true;
3070
- let res;
3071
- for (let attempt = 0; ; attempt++) {
3072
- try {
3073
- res = await doFetch(url, { method, headers: h, body: body2 });
3074
- } catch (err) {
3075
- if (reads && attempt === 0) continue;
3076
- return { ok: false, error: `GitHub could not be reached: ${err.message}` };
3077
- }
3078
- if (reads && attempt === 0 && [502, 503, 504].includes(res.status)) {
3079
- await res.body?.cancel().catch(() => {
3080
- });
3081
- await new Promise((r) => setTimeout(r, 400));
3082
- continue;
3083
- }
3084
- break;
3085
- }
3086
- if (res.status === 304 && kept) {
3087
- seen.delete(key);
3088
- seen.set(key, kept);
3089
- return { ok: true, status: 304, data: kept.data, cached: true };
3090
- }
3091
- if (!res.ok) {
3092
- const text2 = await res.text().catch(() => "");
3093
- return { ok: false, status: res.status, error: message(res, text2) };
3094
- }
3095
- let data;
3096
- if (res.status === 204) data = void 0;
3097
- else if (as === "bytes") data = new Uint8Array(await res.arrayBuffer());
3098
- else if (as === "text") data = await res.text();
3099
- else {
3100
- const text2 = await res.text();
3101
- data = text2 ? JSON.parse(text2) : void 0;
3102
- }
3103
- const etag = res.headers.get("etag");
3104
- if (method === "GET" && etag && as !== "bytes") {
3105
- seen.set(key, { etag, data });
3106
- if (seen.size > limit) seen.delete(seen.keys().next().value);
3107
- }
3108
- return { ok: true, status: res.status, data };
3109
- };
3110
- const graphql2 = async (query2, vars = {}) => {
3111
- const res = await request(
3112
- "POST",
3113
- "graphql",
3114
- // A query reads; a mutation writes, and is never asked twice.
3115
- { body: { query: query2, variables: vars }, retry: !/^\s*mutation\b/.test(query2) }
3116
- );
3117
- if (!res.ok) return { ok: false, status: res.status, error: res.error };
3118
- const errors = res.data?.errors ?? [];
3119
- if (errors.length) return { ok: false, status: 200, error: errors[0].message };
3120
- return { ok: true, status: 200, data: res.data?.data };
3121
- };
3122
- return { request, graphql: graphql2 };
3123
- }
3124
- function message(res, text2) {
3125
- const remaining = res.headers.get("x-ratelimit-remaining");
3126
- if ((res.status === 403 || res.status === 429) && remaining === "0") {
3127
- return "GitHub's API limit for this hour is used up. It resets within the hour.";
3128
- }
3129
- try {
3130
- const parsed = JSON.parse(text2);
3131
- if (parsed.message) return parsed.message;
3132
- } catch {
3133
- }
3134
- if (res.status === 401) return "GitHub did not accept the token. Sign in again.";
3135
- if (res.status === 404) return "Not Found";
3136
- return `GitHub answered ${res.status} ${res.statusText}`.trim();
3137
- }
3138
- function splitRepo(repo) {
3139
- const [owner = "", name = ""] = repo.split("/");
3140
- return { owner, name };
3141
- }
3142
-
3143
- // src/lib/localtoken.ts
3144
- var pending = null;
3145
- function localGitHub() {
3146
- pending ??= find();
3147
- return pending;
3867
+ // src/lib/callable.ts
3868
+ function accessLink(org, repo) {
3869
+ return `https://github.com/${org}/${repo}/settings/actions`;
3148
3870
  }
3149
- async function find() {
3150
- const env = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
3151
- if (env) return { ok: true, gh: githubClient(env), token: env };
3152
- const token = await new Promise(
3153
- (resolve8) => execFile4(
3154
- "gh",
3155
- ["auth", "token"],
3156
- { encoding: "utf8" },
3157
- (err, out) => resolve8(err ? "" : out.trim())
3158
- )
3159
- );
3160
- if (!token) {
3161
- pending = null;
3162
- return {
3163
- ok: false,
3164
- error: "No GitHub token. Run `gh auth login`, or set GITHUB_TOKEN, and try again."
3165
- };
3871
+ async function allowOrgCallers(org, repo, gh = api) {
3872
+ const link = accessLink(org, repo);
3873
+ const path = `repos/${org}/${repo}/actions/permissions/access`;
3874
+ const now = await gh(path);
3875
+ if (now.ok && now.data?.access_level === "organization") return { ok: true, already: true, link };
3876
+ const set = await gh(path, ["-X", "PUT", "-f", "access_level=organization"]);
3877
+ if (set.ok) return { ok: true, link };
3878
+ return { ok: false, error: refusal(set), link };
3879
+ }
3880
+ function refusal(res) {
3881
+ const why = res.error ?? "unknown error";
3882
+ if (res.status === 403 || res.status === 404) {
3883
+ return `${why}. Setting this needs admin on the repo, and your gh token does not have it here`;
3166
3884
  }
3167
- return { ok: true, gh: githubClient(token), token };
3885
+ if (res.status === 422) return `${why}. GitHub only offers this on a private or internal repo`;
3886
+ return why;
3168
3887
  }
3169
3888
 
3170
3889
  // src/lib/memory.ts
3171
- import { join as join16 } from "path";
3890
+ import { join as join17 } from "path";
3172
3891
  var FACT_RE = /^- \*\*`([^`]+)`\*\*\s*·\s*(.*)$/;
3173
3892
  var PROVENANCE_RE = /^\[([a-z][a-z0-9-]*)\]\s*/;
3174
3893
  var NOTE_RE = /\s*·?\s*\[note\]\(([^)]+)\)\s*$/;
3175
3894
  var SO_RE = /\*\*So:\*\*\s*/;
3176
3895
  function parseMemory(dir) {
3177
- const indexPath = join16(dir, "INDEX.md");
3896
+ const indexPath = join17(dir, "INDEX.md");
3178
3897
  if (!existsSync2(indexPath)) throw new Error(`no memory index at ${indexPath}`);
3179
3898
  const lines = readFileSync2(indexPath, "utf8").split("\n");
3180
3899
  const facts = [];
@@ -3221,7 +3940,7 @@ function parseMemory(dir) {
3221
3940
  raw
3222
3941
  });
3223
3942
  });
3224
- const notesDir = join16(dir, "notes");
3943
+ const notesDir = join17(dir, "notes");
3225
3944
  const notes = existsSync2(notesDir) ? readdirSync2(notesDir).filter((f) => f.endsWith(".md")).sort() : [];
3226
3945
  return {
3227
3946
  facts,
@@ -3255,7 +3974,7 @@ function extractLinks(facts, notes, dir) {
3255
3974
  scan(f.slug, f.raw);
3256
3975
  }
3257
3976
  for (const note of notes) {
3258
- const path = join16(dir, "notes", note);
3977
+ const path = join17(dir, "notes", note);
3259
3978
  if (!existsSync2(path)) continue;
3260
3979
  scan(note, readFileSync2(path, "utf8"));
3261
3980
  }
@@ -3272,8 +3991,8 @@ function budgetsFor(org, manifest) {
3272
3991
  for (const source of [org, manifest]) {
3273
3992
  const memory = source?.memory;
3274
3993
  if (!memory || typeof memory !== "object") continue;
3275
- for (const [field, key] of Object.entries(BUDGET_KEYS)) {
3276
- const v = memory[key];
3994
+ for (const [field, key2] of Object.entries(BUDGET_KEYS)) {
3995
+ const v = memory[key2];
3277
3996
  if (typeof v === "number" && v > 0) out[field] = v;
3278
3997
  }
3279
3998
  }
@@ -3306,7 +4025,7 @@ function lintMemory(doc, dir, budgets = DEFAULT_BUDGETS) {
3306
4025
  }
3307
4026
  if (f.note) {
3308
4027
  linked.add(f.note.replace(/^notes\//, ""));
3309
- if (!existsSync2(join16(dir, f.note))) {
4028
+ if (!existsSync2(join17(dir, f.note))) {
3310
4029
  problems.push({
3311
4030
  level: "error",
3312
4031
  rule: "dangling-note",
@@ -3367,7 +4086,7 @@ function lintMemory(doc, dir, budgets = DEFAULT_BUDGETS) {
3367
4086
  function overBudget(doc, dir, budgets) {
3368
4087
  const out = [];
3369
4088
  const kb = (bytes2) => Math.round(bytes2 / 1024);
3370
- const index = join16(dir, "INDEX.md");
4089
+ const index = join17(dir, "INDEX.md");
3371
4090
  const indexBytes = existsSync2(index) ? statSync2(index).size : 0;
3372
4091
  if (indexBytes > budgets.indexKb * 1024) {
3373
4092
  const longest = [...doc.facts].sort((a, b) => b.raw.length - a.raw.length).slice(0, 3).map((f) => `\`${f.slug}\` (${f.raw.length})`);
@@ -3378,7 +4097,7 @@ function overBudget(doc, dir, budgets) {
3378
4097
  file: "memory/INDEX.md"
3379
4098
  });
3380
4099
  }
3381
- const log = join16(dir, "..", "log", "decisions.md");
4100
+ const log = join17(dir, "..", "log", "decisions.md");
3382
4101
  const logBytes = existsSync2(log) ? statSync2(log).size : 0;
3383
4102
  if (logBytes > budgets.decisionsKb * 1024) {
3384
4103
  out.push({
@@ -3481,11 +4200,11 @@ function useRecordStore(next) {
3481
4200
  store = next;
3482
4201
  }
3483
4202
  async function knownRecord(brain, id) {
3484
- const key = `${brain}#${id}`;
3485
- if (records.has(key)) return records.get(key);
4203
+ const key2 = `${brain}#${id}`;
4204
+ if (records.has(key2)) return records.get(key2);
3486
4205
  const kept = await store?.get(brain, id).catch(() => void 0);
3487
4206
  if (!kept) return void 0;
3488
- records.set(key, kept.record);
4207
+ records.set(key2, kept.record);
3489
4208
  return kept.record;
3490
4209
  }
3491
4210
  async function staffRuns(gh, brain, handle, days = 30, opts = {}) {
@@ -3595,17 +4314,17 @@ async function realRuns(gh, brain, workflow, since) {
3595
4314
  return { ok: true, data };
3596
4315
  }
3597
4316
  async function recordFor(gh, brain, id) {
3598
- const key = `${brain}#${id}`;
3599
- if (records.has(key)) return records.get(key);
3600
- const list = await gh.request(
4317
+ const key2 = `${brain}#${id}`;
4318
+ if (records.has(key2)) return records.get(key2);
4319
+ const list2 = await gh.request(
3601
4320
  "GET",
3602
4321
  `repos/${brain}/actions/runs/${id}/artifacts?name=roster-run`
3603
4322
  );
3604
- if (!list.ok) {
3605
- records.set(key, null);
4323
+ if (!list2.ok) {
4324
+ records.set(key2, null);
3606
4325
  return null;
3607
4326
  }
3608
- const artifact = (list.data?.artifacts ?? []).find((a) => !a.expired);
4327
+ const artifact = (list2.data?.artifacts ?? []).find((a) => !a.expired);
3609
4328
  let record = null;
3610
4329
  if (artifact) {
3611
4330
  const zip = await gh.request(
@@ -3614,7 +4333,7 @@ async function recordFor(gh, brain, id) {
3614
4333
  { as: "bytes" }
3615
4334
  );
3616
4335
  if (!zip.ok || !zip.data) {
3617
- records.set(key, null);
4336
+ records.set(key2, null);
3618
4337
  return null;
3619
4338
  }
3620
4339
  try {
@@ -3624,7 +4343,7 @@ async function recordFor(gh, brain, id) {
3624
4343
  record = null;
3625
4344
  }
3626
4345
  }
3627
- records.set(key, record);
4346
+ records.set(key2, record);
3628
4347
  await store?.put(brain, id, { record }).catch(() => {
3629
4348
  });
3630
4349
  return record;
@@ -3658,27 +4377,27 @@ import {
3658
4377
  mkdirSync as mkdirSync4,
3659
4378
  mkdtempSync as mkdtempSync4,
3660
4379
  readdirSync as readdirSync4,
3661
- readFileSync as readFileSync7,
4380
+ readFileSync as readFileSync8,
3662
4381
  rmSync as rmSync4,
3663
- writeFileSync as writeFileSync6
4382
+ writeFileSync as writeFileSync7
3664
4383
  } from "fs";
3665
4384
  import { tmpdir as tmpdir4 } from "os";
3666
- import { dirname as dirname7, join as join18 } from "path";
4385
+ import { dirname as dirname7, join as join19 } from "path";
3667
4386
 
3668
4387
  // src/lib/merge.ts
3669
4388
  import { execFileSync as execFileSync4 } from "child_process";
3670
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
4389
+ import { mkdtempSync as mkdtempSync3, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";
3671
4390
  import { tmpdir as tmpdir3 } from "os";
3672
- import { join as join17 } from "path";
4391
+ import { join as join18 } from "path";
3673
4392
  function merge3(current, base2, incoming) {
3674
- const dir = mkdtempSync3(join17(tmpdir3(), "roster-merge-"));
4393
+ const dir = mkdtempSync3(join18(tmpdir3(), "roster-merge-"));
3675
4394
  try {
3676
- const c = join17(dir, "current");
3677
- const b = join17(dir, "base");
3678
- const i = join17(dir, "incoming");
3679
- writeFileSync5(c, current);
3680
- writeFileSync5(b, base2);
3681
- writeFileSync5(i, incoming);
4395
+ const c = join18(dir, "current");
4396
+ const b = join18(dir, "base");
4397
+ const i = join18(dir, "incoming");
4398
+ writeFileSync6(c, current);
4399
+ writeFileSync6(b, base2);
4400
+ writeFileSync6(i, incoming);
3682
4401
  try {
3683
4402
  const text2 = execFileSync4(
3684
4403
  "git",
@@ -3744,17 +4463,17 @@ roster upgrade [--apply] [--check] [--baseline <git-ref>]
3744
4463
  been a manifest change. The diff is printed either way, so nothing goes quietly.
3745
4464
  `;
3746
4465
  async function upgradeCommand(argv) {
3747
- const opts = parseFlags6(argv);
4466
+ const opts = parseFlags7(argv);
3748
4467
  const ws = findWorkspace(opts.ops);
3749
4468
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
3750
4469
  const tplDir = opsTemplateDir();
3751
- const seedDir = join18(ws.opsDir, ".roster", "seed");
4470
+ const seedDir = join19(ws.opsDir, ".roster", "seed");
3752
4471
  if (opts.baseline) {
3753
4472
  return writeBaseline(ws.opsDir, seedDir, tplDir, opts.baseline);
3754
4473
  }
3755
4474
  const plans = planAll(tplDir, seedDir, ws.opsDir);
3756
4475
  const brains = planBrains(ws, parseYaml3);
3757
- report(ws, plans, opts);
4476
+ report2(ws, plans, opts);
3758
4477
  reportBrains(brains, opts);
3759
4478
  const blocked = plans.filter(
3760
4479
  (p) => p.verdict === "conflict" || p.verdict === "no-base" || p.verdict === "edited-managed"
@@ -3779,12 +4498,12 @@ function planAll(tplDir, seedDir, opsDir) {
3779
4498
  }
3780
4499
  function plan(rel, tplDir, seedDir, opsDir) {
3781
4500
  const kind = classify(rel);
3782
- const incoming = readFileSync7(join18(tplDir, rel), "utf8");
3783
- const currentPath = join18(opsDir, rel);
3784
- const basePath = join18(seedDir, rel);
4501
+ const incoming = readFileSync8(join19(tplDir, rel), "utf8");
4502
+ const currentPath = join19(opsDir, rel);
4503
+ const basePath = join19(seedDir, rel);
3785
4504
  const has = (p) => existsSync7(p);
3786
- const current = has(currentPath) ? readFileSync7(currentPath, "utf8") : null;
3787
- const base2 = has(basePath) ? readFileSync7(basePath, "utf8") : null;
4505
+ const current = has(currentPath) ? readFileSync8(currentPath, "utf8") : null;
4506
+ const base2 = has(basePath) ? readFileSync8(basePath, "utf8") : null;
3788
4507
  if (current === null) {
3789
4508
  return { rel, kind, verdict: "added", note: "new in the framework", next: incoming };
3790
4509
  }
@@ -3842,7 +4561,7 @@ var GLYPH = {
3842
4561
  "no-base": "?",
3843
4562
  "edited-managed": "!"
3844
4563
  };
3845
- function report(ws, plans, opts) {
4564
+ function report2(ws, plans, opts) {
3846
4565
  const width = Math.max(...plans.map((p) => p.rel.length)) + 2;
3847
4566
  process.stdout.write(`
3848
4567
  roster upgrade \u2014 ${ws.opsName}
@@ -3886,9 +4605,9 @@ function apply(opsDir, seedDir, tplDir, plans) {
3886
4605
  for (const p of plans) {
3887
4606
  if (p.verdict === "edited-managed") edited++;
3888
4607
  if (p.verdict === "conflict") {
3889
- const out = join18(opsDir, p.rel + ".roster-merge");
4608
+ const out = join19(opsDir, p.rel + ".roster-merge");
3890
4609
  mkdirSync4(dirname7(out), { recursive: true });
3891
- writeFileSync6(out, p.rejected);
4610
+ writeFileSync7(out, p.rejected);
3892
4611
  process.stdout.write(` wrote ${p.rel}.roster-merge \u2014 resolve it, then re-run
3893
4612
  `);
3894
4613
  left++;
@@ -3902,9 +4621,9 @@ function apply(opsDir, seedDir, tplDir, plans) {
3902
4621
  if (p.verdict === "same") seed(seedDir, tplDir, p.rel);
3903
4622
  continue;
3904
4623
  }
3905
- const dest = join18(opsDir, p.rel);
4624
+ const dest = join19(opsDir, p.rel);
3906
4625
  mkdirSync4(dirname7(dest), { recursive: true });
3907
- writeFileSync6(dest, p.next);
4626
+ writeFileSync7(dest, p.next);
3908
4627
  seed(seedDir, tplDir, p.rel);
3909
4628
  wrote++;
3910
4629
  }
@@ -3913,7 +4632,7 @@ function apply(opsDir, seedDir, tplDir, plans) {
3913
4632
  process.stdout.write(left ? `, ${left} left for you
3914
4633
 
3915
4634
  ` : "\n\n");
3916
- if (!left) writeFileSync6(join18(opsDir, ".roster-version"), stamp() + "\n");
4635
+ if (!left) writeFileSync7(join19(opsDir, ".roster-version"), stamp() + "\n");
3917
4636
  if (edited) {
3918
4637
  process.stdout.write(
3919
4638
  ` ${edited} framework file${edited === 1 ? "" : "s"} still carr${edited === 1 ? "ies" : "y"} a local edit. Move it into the framework, or doctor keeps failing.
@@ -3924,12 +4643,12 @@ function apply(opsDir, seedDir, tplDir, plans) {
3924
4643
  return left || edited ? 1 : 0;
3925
4644
  }
3926
4645
  function seed(seedDir, tplDir, rel) {
3927
- const dest = join18(seedDir, rel);
4646
+ const dest = join19(seedDir, rel);
3928
4647
  mkdirSync4(dirname7(dest), { recursive: true });
3929
- writeFileSync6(dest, readFileSync7(join18(tplDir, rel), "utf8"));
4648
+ writeFileSync7(dest, readFileSync8(join19(tplDir, rel), "utf8"));
3930
4649
  }
3931
4650
  function writeBaseline(opsDir, seedDir, tplDir, ref) {
3932
- const framework = join18(tplDir, "..", "..");
4651
+ const framework = join19(tplDir, "..", "..");
3933
4652
  let files;
3934
4653
  try {
3935
4654
  files = execFileSync5(
@@ -3950,16 +4669,16 @@ function writeBaseline(opsDir, seedDir, tplDir, ref) {
3950
4669
  encoding: "utf8",
3951
4670
  maxBuffer: 16 * 1024 * 1024
3952
4671
  });
3953
- const dest = join18(seedDir, rel);
4672
+ const dest = join19(seedDir, rel);
3954
4673
  mkdirSync4(dirname7(dest), { recursive: true });
3955
- writeFileSync6(dest, text2);
4674
+ writeFileSync7(dest, text2);
3956
4675
  }
3957
- writeFileSync6(join18(opsDir, ".roster-version"), `${ref}
4676
+ writeFileSync7(join19(opsDir, ".roster-version"), `${ref}
3958
4677
  `);
3959
4678
  process.stdout.write(
3960
4679
  `
3961
4680
  Recorded ${files.length} files as the base, from the framework at ${ref}.
3962
- Written to ${join18(opsDir, ".roster", "seed")} \u2014 commit it; it is what makes the next
4681
+ Written to ${join19(opsDir, ".roster", "seed")} \u2014 commit it; it is what makes the next
3963
4682
  upgrade a merge rather than a copy.
3964
4683
 
3965
4684
  Now run: roster upgrade
@@ -3972,7 +4691,7 @@ function stamp() {
3972
4691
  try {
3973
4692
  return execFileSync5(
3974
4693
  "git",
3975
- ["-C", join18(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
4694
+ ["-C", join19(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
3976
4695
  {
3977
4696
  encoding: "utf8",
3978
4697
  stdio: ["ignore", "pipe", "ignore"]
@@ -3982,7 +4701,7 @@ function stamp() {
3982
4701
  return "unknown";
3983
4702
  }
3984
4703
  }
3985
- function parseFlags6(argv) {
4704
+ function parseFlags7(argv) {
3986
4705
  const out = {};
3987
4706
  for (let i = 0; i < argv.length; i++) {
3988
4707
  const flag = argv[i];
@@ -4003,17 +4722,17 @@ function planBrains(ws, parseYaml3) {
4003
4722
  name: org.name,
4004
4723
  opsRepo: `${org.org}/${ws.opsName}`,
4005
4724
  opsDirName: ws.opsName,
4006
- human: readHumans(org)[0]?.github ?? "",
4007
- humanMarker: readHumans(org)[0]?.marker ?? "human",
4725
+ human: primaryHuman(org)?.github ?? "",
4726
+ humanMarker: primaryHuman(org)?.marker ?? "human",
4008
4727
  humanLogins: humanLogins(org),
4009
4728
  allowedTools: toolsOf(org)
4010
4729
  };
4011
4730
  const out = [];
4012
4731
  for (const entry of org.staff ?? []) {
4013
4732
  const dir = entry.dir ?? entry.handle;
4014
- const root2 = join18(ws.root, dir);
4733
+ const root2 = join19(ws.root, dir);
4015
4734
  const base2 = { handle: entry.handle, dir, root: root2, files: [] };
4016
- const manifestPath = join18(root2, "staff.yaml");
4735
+ const manifestPath = join19(root2, "staff.yaml");
4017
4736
  if (!existsSync7(manifestPath)) {
4018
4737
  out.push({ ...base2, problem: existsSync7(root2) ? "no staff.yaml" : "not checked out here" });
4019
4738
  continue;
@@ -4021,7 +4740,7 @@ function planBrains(ws, parseYaml3) {
4021
4740
  let want;
4022
4741
  try {
4023
4742
  const spec2 = specFromManifest(
4024
- parseYaml3(readFileSync7(manifestPath, "utf8"), "staff.yaml"),
4743
+ parseYaml3(readFileSync8(manifestPath, "utf8"), "staff.yaml"),
4025
4744
  dir
4026
4745
  );
4027
4746
  want = renderTree(brainTemplateDir(), tokensFor(orgSpec2, spec2));
@@ -4034,20 +4753,20 @@ function planBrains(ws, parseYaml3) {
4034
4753
  }
4035
4754
  for (const [rel, text2] of want) {
4036
4755
  const kind = classifyBrain(rel);
4037
- const live = join18(root2, rel);
4756
+ const live = join19(root2, rel);
4038
4757
  if (!existsSync7(live)) {
4039
4758
  base2.files.push({ rel, kind, verdict: "missing", next: text2 });
4040
4759
  continue;
4041
4760
  }
4042
4761
  if (kind === "scaffold") continue;
4043
- const have = readFileSync7(live, "utf8");
4762
+ const have = readFileSync8(live, "utf8");
4044
4763
  base2.files.push(
4045
4764
  have === text2 ? { rel, kind, verdict: "same" } : { rel, kind, verdict: "regenerate", next: text2, diff: unified(have, text2) }
4046
4765
  );
4047
4766
  }
4048
4767
  for (const rel of callerFiles(root2)) {
4049
4768
  if (want.has(rel)) continue;
4050
- const text2 = readFileSync7(join18(root2, rel), "utf8");
4769
+ const text2 = readFileSync8(join19(root2, rel), "utf8");
4051
4770
  if (!text2.includes(`${orgSpec2.opsRepo}/.github/workflows/session.yaml`)) continue;
4052
4771
  base2.files.push({ rel, kind: "generated", verdict: "obsolete" });
4053
4772
  }
@@ -4056,14 +4775,14 @@ function planBrains(ws, parseYaml3) {
4056
4775
  return out;
4057
4776
  }
4058
4777
  function unified(before, after) {
4059
- const dir = mkdtempSync4(join18(tmpdir4(), "roster-diff-"));
4778
+ const dir = mkdtempSync4(join19(tmpdir4(), "roster-diff-"));
4060
4779
  try {
4061
- writeFileSync6(join18(dir, "a"), before);
4062
- writeFileSync6(join18(dir, "b"), after);
4780
+ writeFileSync7(join19(dir, "a"), before);
4781
+ writeFileSync7(join19(dir, "b"), after);
4063
4782
  try {
4064
4783
  execFileSync5(
4065
4784
  "diff",
4066
- ["-u", "--label", "yours", "--label", "generated", join18(dir, "a"), join18(dir, "b")],
4785
+ ["-u", "--label", "yours", "--label", "generated", join19(dir, "a"), join19(dir, "b")],
4067
4786
  { encoding: "utf8" }
4068
4787
  );
4069
4788
  return "";
@@ -4076,7 +4795,7 @@ function unified(before, after) {
4076
4795
  }
4077
4796
  }
4078
4797
  function callerFiles(root2) {
4079
- const dir = join18(root2, ".github", "workflows");
4798
+ const dir = join19(root2, ".github", "workflows");
4080
4799
  if (!existsSync7(dir)) return [];
4081
4800
  return readdirSync4(dir).filter((n) => n.endsWith(".yaml") || n.endsWith(".yml")).map((n) => `.github/workflows/${n}`);
4082
4801
  }
@@ -4125,14 +4844,14 @@ function applyBrains(brains) {
4125
4844
  for (const b of brains) {
4126
4845
  for (const f of b.files) {
4127
4846
  if (f.verdict === "obsolete") {
4128
- rmSync4(join18(b.root, f.rel), { force: true });
4847
+ rmSync4(join19(b.root, f.rel), { force: true });
4129
4848
  wrote++;
4130
4849
  continue;
4131
4850
  }
4132
4851
  if (f.next === void 0) continue;
4133
- const dest = join18(b.root, f.rel);
4852
+ const dest = join19(b.root, f.rel);
4134
4853
  mkdirSync4(dirname7(dest), { recursive: true });
4135
- writeFileSync6(dest, f.next);
4854
+ writeFileSync7(dest, f.next);
4136
4855
  wrote++;
4137
4856
  }
4138
4857
  }
@@ -4183,6 +4902,7 @@ async function collect(opts) {
4183
4902
  findings.push(...checkBusiness(ws));
4184
4903
  findings.push(...checkPriorities(ws));
4185
4904
  findings.push(...await checkAgent(ws, org));
4905
+ findings.push(...checkConnectors(org));
4186
4906
  if (online) findings.push(...await checkOrgOnline(ws, org));
4187
4907
  if (online) findings.push(...await checkReviewGates(ws, org, composer));
4188
4908
  const perStaff = await Promise.all(staff.map((s) => checkStaff(ws, org, s, composer, online)));
@@ -4192,7 +4912,7 @@ async function collect(opts) {
4192
4912
  }
4193
4913
  async function doctorCommand(argv) {
4194
4914
  const only = argv[0] && !argv[0].startsWith("-") ? argv[0] : void 0;
4195
- const opts = parseFlags7(argv.slice(only ? 1 : 0));
4915
+ const opts = parseFlags8(argv.slice(only ? 1 : 0));
4196
4916
  const result = await collect({ ...opts, only });
4197
4917
  if (!result) {
4198
4918
  process.stderr.write(`roster: no staff member "${only}" in org.yaml
@@ -4204,7 +4924,7 @@ async function doctorCommand(argv) {
4204
4924
  JSON.stringify({ org: result.org.org, findings: result.findings }, null, 2) + "\n"
4205
4925
  );
4206
4926
  } else {
4207
- report2(result.org, result.findings, result.online, opts.offline === true);
4927
+ report3(result.org, result.findings, result.online, opts.offline === true);
4208
4928
  }
4209
4929
  return result.findings.some((f) => f.level === "fail") ? 1 : 0;
4210
4930
  }
@@ -4238,12 +4958,12 @@ function checkWorkspace(ws, org) {
4238
4958
  title: `org.yaml names ${org.repos?.length ?? 0} repos and ${org.staff?.length ?? 0} staff`
4239
4959
  });
4240
4960
  const humans = readHumans(org);
4241
- if (!humans.some((h) => h.github)) {
4961
+ if (!staffHumans(org).some((h) => h.github)) {
4242
4962
  out.push({
4243
4963
  scope,
4244
4964
  level: "fail",
4245
4965
  id: "human",
4246
- title: "org.yaml names no human with a github login",
4966
+ title: "org.yaml names no human with a github login who is not view-only",
4247
4967
  fix: "The mention callers gate on these logins. Without one nothing can wake an agent. Write `human: { github: you }`, or a `humans:` list for more than one."
4248
4968
  });
4249
4969
  } else if (humans.some((h) => !h.github)) {
@@ -4256,7 +4976,7 @@ function checkWorkspace(ws, org) {
4256
4976
  });
4257
4977
  }
4258
4978
  try {
4259
- const plans = planAll(opsTemplateDir(), join19(ws.opsDir, ".roster", "seed"), ws.opsDir);
4979
+ const plans = planAll(opsTemplateDir(), join20(ws.opsDir, ".roster", "seed"), ws.opsDir);
4260
4980
  const edited = plans.filter((p) => p.verdict === "edited-managed");
4261
4981
  const stale = plans.filter((p) => p.next !== void 0);
4262
4982
  const unmergeable = plans.filter((p) => p.verdict === "conflict" || p.verdict === "no-base");
@@ -4305,7 +5025,7 @@ async function checkAgent(ws, org) {
4305
5025
  const scope = "workspace";
4306
5026
  let agent;
4307
5027
  try {
4308
- const { resolveAgent } = await import(`file://${join19(ws.opsDir, "agents.mjs")}`);
5028
+ const { resolveAgent } = await import(`file://${join20(ws.opsDir, "agents.mjs")}`);
4309
5029
  agent = resolveAgent(org, {});
4310
5030
  } catch (err) {
4311
5031
  return [
@@ -4319,8 +5039,8 @@ async function checkAgent(ws, org) {
4319
5039
  ];
4320
5040
  }
4321
5041
  const out = [{ scope, level: "ok", id: "agent", title: `runs on ${agent.id}` }];
4322
- const orgFile = join19(ws.opsDir, "org.yaml");
4323
- if (existsSync8(orgFile) && /FILL IN/.test(readFileSync8(orgFile, "utf8"))) {
5042
+ const orgFile = join20(ws.opsDir, "org.yaml");
5043
+ if (existsSync8(orgFile) && /FILL IN/.test(readFileSync9(orgFile, "utf8"))) {
4324
5044
  out.push({
4325
5045
  scope,
4326
5046
  level: "fail",
@@ -4330,7 +5050,7 @@ async function checkAgent(ws, org) {
4330
5050
  });
4331
5051
  }
4332
5052
  if (!agent.config) return out;
4333
- const path = join19(ws.opsDir, agent.config.path);
5053
+ const path = join20(ws.opsDir, agent.config.path);
4334
5054
  if (!existsSync8(path)) {
4335
5055
  out.push({
4336
5056
  scope,
@@ -4341,7 +5061,7 @@ async function checkAgent(ws, org) {
4341
5061
  });
4342
5062
  return out;
4343
5063
  }
4344
- if (/FILL IN/.test(readFileSync8(path, "utf8"))) {
5064
+ if (/FILL IN/.test(readFileSync9(path, "utf8"))) {
4345
5065
  out.push({
4346
5066
  scope,
4347
5067
  level: "fail",
@@ -4353,7 +5073,7 @@ async function checkAgent(ws, org) {
4353
5073
  return out;
4354
5074
  }
4355
5075
  function checkBusiness(ws) {
4356
- const path = join19(ws.opsDir, "org", "business.md");
5076
+ const path = join20(ws.opsDir, "org", "business.md");
4357
5077
  if (!existsSync8(path)) {
4358
5078
  return [
4359
5079
  {
@@ -4365,7 +5085,7 @@ function checkBusiness(ws) {
4365
5085
  }
4366
5086
  ];
4367
5087
  }
4368
- if (looksUnwritten(readFileSync8(path, "utf8"))) {
5088
+ if (looksUnwritten(readFileSync9(path, "utf8"))) {
4369
5089
  return [
4370
5090
  {
4371
5091
  scope: "workspace",
@@ -4379,7 +5099,7 @@ function checkBusiness(ws) {
4379
5099
  return [{ scope: "workspace", level: "ok", id: "business", title: "org/business.md is written" }];
4380
5100
  }
4381
5101
  function checkPriorities(ws) {
4382
- const path = join19(ws.opsDir, "org", "priorities.md");
5102
+ const path = join20(ws.opsDir, "org", "priorities.md");
4383
5103
  if (!existsSync8(path)) {
4384
5104
  return [
4385
5105
  {
@@ -4391,7 +5111,7 @@ function checkPriorities(ws) {
4391
5111
  }
4392
5112
  ];
4393
5113
  }
4394
- if (looksUnwritten(readFileSync8(path, "utf8"))) {
5114
+ if (looksUnwritten(readFileSync9(path, "utf8"))) {
4395
5115
  return [
4396
5116
  {
4397
5117
  scope: "workspace",
@@ -4410,7 +5130,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4410
5130
  const scope = entry.handle;
4411
5131
  const out = [];
4412
5132
  const dir = entry.dir ?? entry.handle;
4413
- const root2 = join19(ws.root, dir);
5133
+ const root2 = join20(ws.root, dir);
4414
5134
  if (!existsSync8(root2)) {
4415
5135
  return [
4416
5136
  {
@@ -4422,7 +5142,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4422
5142
  }
4423
5143
  ];
4424
5144
  }
4425
- const manifestPath = join19(root2, "staff.yaml");
5145
+ const manifestPath = join20(root2, "staff.yaml");
4426
5146
  let manifest = {};
4427
5147
  if (!existsSync8(manifestPath)) {
4428
5148
  out.push({
@@ -4434,7 +5154,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4434
5154
  });
4435
5155
  } else {
4436
5156
  try {
4437
- manifest = composer.parseYaml(readFileSync8(manifestPath, "utf8"), "staff.yaml");
5157
+ manifest = composer.parseYaml(readFileSync9(manifestPath, "utf8"), "staff.yaml");
4438
5158
  if (manifest.handle !== entry.handle) {
4439
5159
  out.push({
4440
5160
  scope,
@@ -4463,7 +5183,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4463
5183
  });
4464
5184
  }
4465
5185
  }
4466
- const charterPath = join19(root2, "CHARTER.md");
5186
+ const charterPath = join20(root2, "CHARTER.md");
4467
5187
  out.push(
4468
5188
  existsSync8(charterPath) ? { scope, level: "ok", id: "charter", title: "CHARTER.md present" } : {
4469
5189
  scope,
@@ -4473,7 +5193,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4473
5193
  fix: "The charter is the personality; nothing else supplies it."
4474
5194
  }
4475
5195
  );
4476
- if (existsSync8(charterPath) && looksUnwritten(readFileSync8(charterPath, "utf8"))) {
5196
+ if (existsSync8(charterPath) && looksUnwritten(readFileSync9(charterPath, "utf8"))) {
4477
5197
  out.push({
4478
5198
  scope,
4479
5199
  level: "warn",
@@ -4482,8 +5202,8 @@ async function checkStaff(ws, org, entry, composer, online) {
4482
5202
  fix: `roster brief charter ${entry.handle}, or "Write the charter" on the portal's Staff screen`
4483
5203
  });
4484
5204
  }
4485
- const memDir = join19(root2, "memory");
4486
- if (!existsSync8(join19(memDir, "INDEX.md"))) {
5205
+ const memDir = join20(root2, "memory");
5206
+ if (!existsSync8(join20(memDir, "INDEX.md"))) {
4487
5207
  out.push({
4488
5208
  scope,
4489
5209
  level: "fail",
@@ -4580,7 +5300,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4580
5300
  fix: "A private reusable workflow is only callable inside its own org, so this can never resolve."
4581
5301
  });
4582
5302
  }
4583
- const local = join19(ws.opsDir, ref.slice(opsRepo.length + 1));
5303
+ const local = join20(ws.opsDir, ref.slice(opsRepo.length + 1));
4584
5304
  if (!existsSync8(local)) {
4585
5305
  out.push({
4586
5306
  scope,
@@ -4599,7 +5319,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4599
5319
  title: `2 callers, both pointing at ${opsRepo}`
4600
5320
  });
4601
5321
  }
4602
- const missing2 = (manifest.surfaces ?? []).map((s) => s.path).filter((p) => p && !existsSync8(join19(root2, p)));
5322
+ const missing2 = (manifest.surfaces ?? []).map((s) => s.path).filter((p) => p && !existsSync8(join20(root2, p)));
4603
5323
  if (missing2.length) {
4604
5324
  out.push({
4605
5325
  scope,
@@ -4610,8 +5330,9 @@ async function checkStaff(ws, org, entry, composer, online) {
4610
5330
  });
4611
5331
  }
4612
5332
  if (online && manifest.brain) {
4613
- const logins = readHumans(org).flatMap((h) => h.github ? [h.github] : []);
4614
- out.push(...await checkStaffOnline(scope, manifest, callers, logins));
5333
+ const logins = humanLogins(org);
5334
+ const keys = declared2(org).filter((c) => c.staff.includes(entry.handle) && !c.problem && c.auth === "key").map((c) => ({ name: c.name, secrets: c.secrets.map((x) => x.name) }));
5335
+ out.push(...await checkStaffOnline(scope, manifest, callers, logins, keys));
4615
5336
  }
4616
5337
  return out;
4617
5338
  }
@@ -4643,10 +5364,10 @@ function inferredCeiling(cancelled) {
4643
5364
  return most >= 2 ? best : null;
4644
5365
  }
4645
5366
  function readCallers(root2, handle) {
4646
- const dir = join19(root2, ".github", "workflows");
5367
+ const dir = join20(root2, ".github", "workflows");
4647
5368
  if (!existsSync8(dir)) return [];
4648
5369
  const mine = new RegExp(`^${handle}-(daily|mention)\\.ya?ml$`);
4649
- return readdirSync5(dir).filter((f) => mine.test(f)).sort().map((name) => ({ name, text: readFileSync8(join19(dir, name), "utf8") }));
5370
+ return readdirSync5(dir).filter((f) => mine.test(f)).sort().map((name) => ({ name, text: readFileSync9(join20(dir, name), "utf8") }));
4650
5371
  }
4651
5372
  async function checkOrgOnline(ws, org) {
4652
5373
  const out = [];
@@ -4726,10 +5447,10 @@ async function checkReviewGates(ws, org, composer) {
4726
5447
  );
4727
5448
  const apps = /* @__PURE__ */ new Set();
4728
5449
  for (const s of org.staff ?? []) {
4729
- const path = join19(ws.root, s.dir ?? s.handle, "staff.yaml");
5450
+ const path = join20(ws.root, s.dir ?? s.handle, "staff.yaml");
4730
5451
  if (!existsSync8(path)) continue;
4731
5452
  try {
4732
- const m = composer.parseYaml(readFileSync8(path, "utf8"), "staff.yaml");
5453
+ const m = composer.parseYaml(readFileSync9(path, "utf8"), "staff.yaml");
4733
5454
  for (const w of m.works_in ?? []) if (w?.repo) repos.add(String(w.repo));
4734
5455
  for (const i of m.identities ?? []) if (i?.app) apps.add(String(i.app));
4735
5456
  } catch {
@@ -4738,12 +5459,13 @@ async function checkReviewGates(ws, org, composer) {
4738
5459
  const readings = await Promise.all([...repos].map((r) => readGate(r, [...apps])));
4739
5460
  return readings.map((r) => ({ scope: "workspace", id: "review-gate", ...judgeGate(r) }));
4740
5461
  }
4741
- async function checkStaffOnline(scope, manifest, callers, humans = []) {
5462
+ async function checkStaffOnline(scope, manifest, callers, humans = [], connectors = []) {
4742
5463
  const out = [];
4743
5464
  const repo = manifest.brain;
4744
5465
  const needed = /* @__PURE__ */ new Set();
4745
5466
  for (const c of callers) {
4746
5467
  for (const m of c.text.matchAll(/secrets\.([A-Z0-9_]+)/g)) needed.add(m[1]);
5468
+ for (const name of inheritedSecrets(c.text)) needed.add(name);
4747
5469
  }
4748
5470
  const [secrets, orgSecrets, labels, runs, pinned, workflows, open2] = await Promise.all([
4749
5471
  api(`repos/${repo}/actions/secrets`),
@@ -4804,6 +5526,26 @@ async function checkStaffOnline(scope, manifest, callers, humans = []) {
4804
5526
  title: `all ${needed.size} referenced secrets present` + (fromOrg.length ? `, ${fromOrg.join(", ")} shared from the org` : "")
4805
5527
  }
4806
5528
  );
5529
+ for (const c of connectors) {
5530
+ const gone2 = c.secrets.filter((n) => !have.has(n) && !shared.has(n));
5531
+ if (!gone2.length) continue;
5532
+ out.push({
5533
+ scope,
5534
+ level: "warn",
5535
+ id: "connector.key",
5536
+ title: `${c.name} has no key on ${repo}: ${gone2.join(", ")}`,
5537
+ fix: "Runs go ahead without it. Store the key from the portal's Connectors page, or roster connector add with --apply."
5538
+ });
5539
+ }
5540
+ }
5541
+ if (connectors.length && callers.some((c) => !/^\s*secrets:\s*inherit\s*$/m.test(c.text))) {
5542
+ out.push({
5543
+ scope,
5544
+ level: "warn",
5545
+ id: "connector.caller",
5546
+ title: "the callers predate connectors, so no connector's key reaches a run",
5547
+ fix: "roster upgrade --apply regenerates them to pass their secrets on."
5548
+ });
4807
5549
  }
4808
5550
  if (!labels.ok) {
4809
5551
  out.push({
@@ -4815,8 +5557,8 @@ async function checkStaffOnline(scope, manifest, callers, humans = []) {
4815
5557
  });
4816
5558
  } else {
4817
5559
  const have = new Set(labels.data.map((l) => l.name));
4818
- const declared = Object.values(manifest.labels ?? {}).flat();
4819
- const gone = [...new Set(declared)].filter((l) => !have.has(l));
5560
+ const declared3 = Object.values(manifest.labels ?? {}).flat();
5561
+ const gone = [...new Set(declared3)].filter((l) => !have.has(l));
4820
5562
  out.push(
4821
5563
  gone.length ? {
4822
5564
  scope,
@@ -4978,19 +5720,19 @@ async function checkStaffOnline(scope, manifest, callers, humans = []) {
4978
5720
  return out;
4979
5721
  }
4980
5722
  async function checkWorkflows(scope, repo, skip) {
4981
- const list = await api(`repos/${repo}/actions/workflows?per_page=100`);
4982
- if (!list.ok) {
5723
+ const list2 = await api(`repos/${repo}/actions/workflows?per_page=100`);
5724
+ if (!list2.ok) {
4983
5725
  return [
4984
5726
  {
4985
5727
  scope,
4986
5728
  level: "warn",
4987
5729
  id: "workflows",
4988
- title: `cannot read the workflows on ${repo}: ${list.error}`,
5730
+ title: `cannot read the workflows on ${repo}: ${list2.error}`,
4989
5731
  fix: "Check your access to the repo; a failing workflow there would go unseen."
4990
5732
  }
4991
5733
  ];
4992
5734
  }
4993
- const mine = (list.data?.workflows ?? []).filter(
5735
+ const mine = (list2.data?.workflows ?? []).filter(
4994
5736
  (w) => w.state === "active" && !skip.has(w.path.split("/").pop() ?? "")
4995
5737
  );
4996
5738
  const streaks = await Promise.all(
@@ -5096,7 +5838,7 @@ async function checkBudgets(org, staff, whole) {
5096
5838
  return out;
5097
5839
  }
5098
5840
  var GLYPH2 = { ok: "\u2713", warn: "!", fail: "\u2717" };
5099
- function report2(org, found, online, asked) {
5841
+ function report3(org, found, online, asked) {
5100
5842
  process.stdout.write(`
5101
5843
  roster doctor \u2014 ${org.name} (${org.org})
5102
5844
  `);
@@ -5134,7 +5876,7 @@ function ago(iso) {
5134
5876
  if (s < 172800) return `${Math.round(s / 3600)}h ago`;
5135
5877
  return `${Math.round(s / 86400)}d ago`;
5136
5878
  }
5137
- function parseFlags7(argv) {
5879
+ function parseFlags8(argv) {
5138
5880
  const out = {};
5139
5881
  for (let i = 0; i < argv.length; i++) {
5140
5882
  if (argv[i] === "--offline") out.offline = true;
@@ -5170,13 +5912,61 @@ function unkindedAsks(scope, repo, issues, humans) {
5170
5912
  }
5171
5913
  ];
5172
5914
  }
5915
+ function inheritedSecrets(callerText) {
5916
+ if (!/^\s*secrets:\s*inherit\s*$/m.test(callerText)) return [];
5917
+ const input = (name) => callerText.match(new RegExp(`^\\s*${name}:\\s*([A-Z0-9_]+)\\s*$`, "m"))?.[1];
5918
+ const out = [];
5919
+ for (const prefix of [input("secret_prefix"), input("public_secret_prefix")]) {
5920
+ if (prefix) out.push(`${prefix}_APP_ID`, `${prefix}_APP_PRIVATE_KEY`);
5921
+ }
5922
+ const agent = input("agent_secret");
5923
+ if (agent) out.push(agent);
5924
+ return [...new Set(out)];
5925
+ }
5926
+ function checkConnectors(org) {
5927
+ const all = declared2(org);
5928
+ if (!all.length) return [];
5929
+ const scope = "workspace";
5930
+ const out = [];
5931
+ const handles = new Set((org.staff ?? []).map((s) => s.handle));
5932
+ for (const c of all) {
5933
+ if (c.problem) {
5934
+ out.push({
5935
+ scope,
5936
+ level: "warn",
5937
+ id: "connector",
5938
+ title: c.problem,
5939
+ fix: "Runs leave it out until this is fixed. See docs/connectors.md."
5940
+ });
5941
+ }
5942
+ const strangers = c.staff.filter((h) => !handles.has(h));
5943
+ if (strangers.length) {
5944
+ out.push({
5945
+ scope,
5946
+ level: "warn",
5947
+ id: "connector.staff",
5948
+ title: `${c.name} is given to ${strangers.join(", ")}, who is not in org.yaml's staff`,
5949
+ fix: "A handle there has to match a staff member's handle exactly."
5950
+ });
5951
+ }
5952
+ }
5953
+ if (!out.length) {
5954
+ out.push({
5955
+ scope,
5956
+ level: "ok",
5957
+ id: "connector",
5958
+ title: `${all.length} connector${all.length === 1 ? "" : "s"}: ${all.map((c) => c.name).join(", ")}`
5959
+ });
5960
+ }
5961
+ return out;
5962
+ }
5173
5963
 
5174
5964
  // src/commands/export.ts
5175
- import { writeFileSync as writeFileSync7 } from "fs";
5965
+ import { writeFileSync as writeFileSync8 } from "fs";
5176
5966
 
5177
5967
  // src/lib/export.ts
5178
5968
  import { execFileSync as execFileSync6 } from "child_process";
5179
- import { join as join20, relative as relative3 } from "path";
5969
+ import { join as join21, relative as relative3 } from "path";
5180
5970
  var gitHistory = {
5181
5971
  log: (root2, n, path) => gitLog(root2, n, path ? ["--", path] : []),
5182
5972
  factsChanged: (root2, since) => factsChanged(root2, since)
@@ -5187,11 +5977,11 @@ function buildExport(ws, org, parseYaml3, opts = {}) {
5187
5977
  const history = opts.history ?? gitHistory;
5188
5978
  for (const entry of org.staff ?? []) {
5189
5979
  const dir = entry.dir ?? entry.handle;
5190
- const root2 = join20(ws.root, dir);
5980
+ const root2 = join21(ws.root, dir);
5191
5981
  if (!existsSync2(root2)) continue;
5192
5982
  const manifest = readManifest2(root2, parseYaml3);
5193
- const memDir = join20(root2, "memory");
5194
- const doc = existsSync2(join20(memDir, "INDEX.md")) ? parseMemory(memDir) : { facts: [], sections: [], notes: [], preamble: "", links: [] };
5983
+ const memDir = join21(root2, "memory");
5984
+ const doc = existsSync2(join21(memDir, "INDEX.md")) ? parseMemory(memDir) : { facts: [], sections: [], notes: [], preamble: "", links: [] };
5195
5985
  const commits = history.log(root2, 25);
5196
5986
  staff.push({
5197
5987
  handle: entry.handle,
@@ -5211,7 +6001,7 @@ function buildExport(ws, org, parseYaml3, opts = {}) {
5211
6001
  sections: doc.sections,
5212
6002
  notes: doc.notes,
5213
6003
  links: doc.links,
5214
- problems: existsSync2(join20(memDir, "INDEX.md")) ? lintMemory(doc, memDir, budgetsFor(org, manifest)) : [],
6004
+ problems: existsSync2(join21(memDir, "INDEX.md")) ? lintMemory(doc, memDir, budgetsFor(org, manifest)) : [],
5215
6005
  surfaces: readSurfaces(root2, manifest.surfaces ?? []),
5216
6006
  recentCommits: commits,
5217
6007
  factsChanged: history.factsChanged(root2, opts.since ?? "14 days ago"),
@@ -5224,7 +6014,7 @@ function buildExport(ws, org, parseYaml3, opts = {}) {
5224
6014
  s.soloBots = s.bots.filter((b) => times.get(b) === 1);
5225
6015
  s.sharedBots = s.bots.filter((b) => (times.get(b) ?? 0) > 1);
5226
6016
  }
5227
- const humans = readHumans(org);
6017
+ const humans = staffHumans(org);
5228
6018
  return {
5229
6019
  org: org.org,
5230
6020
  name: org.name,
@@ -5239,7 +6029,7 @@ function botName(raw) {
5239
6029
  return String(raw).replace(/\[bot\]$/, "");
5240
6030
  }
5241
6031
  function readManifest2(root2, parseYaml3) {
5242
- const path = join20(root2, "staff.yaml");
6032
+ const path = join21(root2, "staff.yaml");
5243
6033
  if (!existsSync2(path)) return {};
5244
6034
  try {
5245
6035
  return parseYaml3(readFileSync2(path, "utf8"), "staff.yaml");
@@ -5248,16 +6038,16 @@ function readManifest2(root2, parseYaml3) {
5248
6038
  }
5249
6039
  }
5250
6040
  function readRig(root2, manifest, commits, history) {
5251
- const wfDir = join20(root2, ".github", "workflows");
5252
- const declared = manifest.surfaces ?? [];
6041
+ const wfDir = join21(root2, ".github", "workflows");
6042
+ const declared3 = manifest.surfaces ?? [];
5253
6043
  return {
5254
6044
  workflows: existsSync2(wfDir) ? readdirSync2(wfDir).filter((f) => /\.ya?ml$/.test(f)).sort() : [],
5255
- hasCharter: existsSync2(join20(root2, "CHARTER.md")),
5256
- charterStub: !existsSync2(join20(root2, "CHARTER.md")) || looksUnwritten(readFileSync2(join20(root2, "CHARTER.md"), "utf8")),
5257
- hasManifest: existsSync2(join20(root2, "staff.yaml")),
5258
- missingSurfaces: declared.filter((s) => s?.path && !existsSync2(join20(root2, s.path))).map((s) => s.path),
5259
- memoryBytes: bytesOf(join20(root2, "memory", "INDEX.md")),
5260
- notesBytes: dirBytes(join20(root2, "memory", "notes")),
6045
+ hasCharter: existsSync2(join21(root2, "CHARTER.md")),
6046
+ charterStub: !existsSync2(join21(root2, "CHARTER.md")) || looksUnwritten(readFileSync2(join21(root2, "CHARTER.md"), "utf8")),
6047
+ hasManifest: existsSync2(join21(root2, "staff.yaml")),
6048
+ missingSurfaces: declared3.filter((s) => s?.path && !existsSync2(join21(root2, s.path))).map((s) => s.path),
6049
+ memoryBytes: bytesOf(join21(root2, "memory", "INDEX.md")),
6050
+ notesBytes: dirBytes(join21(root2, "memory", "notes")),
5261
6051
  lastCommit: commits[0],
5262
6052
  lastMemoryCommit: history.log(root2, 1, "memory")[0]
5263
6053
  };
@@ -5273,17 +6063,17 @@ function dirBytes(dir) {
5273
6063
  if (!existsSync2(dir)) return 0;
5274
6064
  return walk2(dir, dir).reduce((n, f) => n + f.bytes, 0);
5275
6065
  }
5276
- function readSurfaces(root2, declared) {
5277
- return declared.filter((s) => s?.path && existsSync2(join20(root2, s.path))).map((s) => ({
6066
+ function readSurfaces(root2, declared3) {
6067
+ return declared3.filter((s) => s?.path && existsSync2(join21(root2, s.path))).map((s) => ({
5278
6068
  path: s.path,
5279
6069
  render: s.render ?? "doc",
5280
- files: walk2(join20(root2, s.path), root2)
6070
+ files: walk2(join21(root2, s.path), root2)
5281
6071
  }));
5282
6072
  }
5283
6073
  function walk2(dir, root2, out = []) {
5284
6074
  for (const name of readdirSync2(dir)) {
5285
6075
  if (SKIP.has(name)) continue;
5286
- const full = join20(dir, name);
6076
+ const full = join21(dir, name);
5287
6077
  const st = statSync2(full);
5288
6078
  if (st.isDirectory()) walk2(full, root2, out);
5289
6079
  else {
@@ -5374,7 +6164,7 @@ async function exportCommand(argv) {
5374
6164
  const data = buildExport(ws, readOrg(ws.opsDir, parseYaml3), parseYaml3);
5375
6165
  const json3 = JSON.stringify(data, null, 2);
5376
6166
  if (out) {
5377
- writeFileSync7(out, json3 + "\n");
6167
+ writeFileSync8(out, json3 + "\n");
5378
6168
  const facts = data.staff.reduce((n, s) => n + s.facts.length, 0);
5379
6169
  process.stdout.write(
5380
6170
  ` ${out} ${data.staff.length} staff, ${facts} facts, ${Math.round(json3.length / 1024)}kb
@@ -5387,13 +6177,13 @@ async function exportCommand(argv) {
5387
6177
  }
5388
6178
 
5389
6179
  // src/lib/audit.ts
5390
- import { join as join21 } from "path";
6180
+ import { join as join22 } from "path";
5391
6181
  var LONG_WORDS = 3500;
5392
6182
  var ECHO_CHARS = 60;
5393
6183
  function auditPrompt(ws, view, roots) {
5394
6184
  const out = [];
5395
6185
  const text2 = (rel) => {
5396
- const full = join21(ws.root, rel);
6186
+ const full = join22(ws.root, rel);
5397
6187
  return existsSync2(full) ? readFileSync2(full, "utf8") : "";
5398
6188
  };
5399
6189
  for (const layer of [...view.layers, ...view.runtime]) {
@@ -5447,9 +6237,9 @@ Decide which layer each one belongs in and remove it from the others.`
5447
6237
  want: `This prompt is ${words.toLocaleString()} words and is read in full on every run. Find what can go: anything restated, anything that was true once, anything an agent would do anyway. Cut more than you add, and tell me what you cut.`
5448
6238
  });
5449
6239
  }
5450
- const bases = [ws.root, ...roots.map((r) => join21(ws.root, r))];
6240
+ const bases = [ws.root, ...roots.map((r) => join22(ws.root, r))];
5451
6241
  for (const rel of namedPaths(view.composed)) {
5452
- if (bases.some((b) => existsSync2(join21(b, rel)))) continue;
6242
+ if (bases.some((b) => existsSync2(join22(b, rel)))) continue;
5453
6243
  out.push({
5454
6244
  id: "dangling",
5455
6245
  level: "warning",
@@ -5546,7 +6336,7 @@ function classifyFinding(id) {
5546
6336
  return "agent";
5547
6337
  }
5548
6338
  async function fixCommand(argv) {
5549
- const opts = parseFlags8(argv);
6339
+ const opts = parseFlags9(argv);
5550
6340
  const ws = findWorkspace(opts.ops);
5551
6341
  const items = await gather(ws, opts.offline === true);
5552
6342
  if (opts.json) {
@@ -5559,9 +6349,9 @@ async function fixCommand(argv) {
5559
6349
  }
5560
6350
  async function gather(ws, offline) {
5561
6351
  const items = [];
5562
- const report3 = await collect({ ops: ws.opsDir, offline });
5563
- if (!report3) return items;
5564
- for (const f of report3.findings) {
6352
+ const report4 = await collect({ ops: ws.opsDir, offline });
6353
+ if (!report4) return items;
6354
+ for (const f of report4.findings) {
5565
6355
  if (f.level === "ok") continue;
5566
6356
  items.push({
5567
6357
  id: f.id,
@@ -5648,7 +6438,7 @@ Nothing to fix. \`roster doctor\` is clean.
5648
6438
  "them is reverted by the next `roster upgrade`, and the mistake is invisible until it is",
5649
6439
  "expensive. Do not touch:",
5650
6440
  "",
5651
- `- \`${ws.opsName}/compose.mjs\`, \`agents.mjs\`, \`runner-plan.mjs\`, \`inflight.mjs\`, \`run-record.mjs\`, \`status-week.mjs\` \u2014 vendored from the framework.`,
6441
+ `- \`${ws.opsName}/compose.mjs\`, \`agents.mjs\`, \`connectors.mjs\`, \`runner-plan.mjs\`, \`inflight.mjs\`, \`run-record.mjs\`, \`status-week.mjs\` \u2014 vendored from the framework.`,
5652
6442
  `- \`${ws.opsName}/.github/workflows/\` and any brain's \`.github/workflows/\` \u2014 generated, and`,
5653
6443
  " GitHub App tokens cannot push changes there in any case.",
5654
6444
  `- \`${ws.opsName}/.roster/\` \u2014 the recorded merge base.`,
@@ -5706,7 +6496,7 @@ Nothing to fix. \`roster doctor\` is clean.
5706
6496
  function count(n, noun) {
5707
6497
  return `${n} ${noun}${n === 1 ? "" : "s"}`;
5708
6498
  }
5709
- function parseFlags8(argv) {
6499
+ function parseFlags9(argv) {
5710
6500
  const out = {};
5711
6501
  for (let i = 0; i < argv.length; i++) {
5712
6502
  const flag = argv[i];
@@ -5728,8 +6518,8 @@ function parseFlags8(argv) {
5728
6518
 
5729
6519
  // src/commands/init.ts
5730
6520
  import { execFileSync as execFileSync7 } from "child_process";
5731
- import { existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync9, writeFileSync as writeFileSync8 } from "fs";
5732
- import { dirname as dirname8, join as join22, resolve as resolve3 } from "path";
6521
+ import { existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync10, writeFileSync as writeFileSync9 } from "fs";
6522
+ import { dirname as dirname8, join as join23, resolve as resolve3 } from "path";
5733
6523
  var initHelp = `
5734
6524
  roster init --org <github-org> [--name "Acme"] [--human <login>] [--apply]
5735
6525
 
@@ -5759,7 +6549,7 @@ roster init --org <github-org> [--name "Acme"] [--human <login>] [--apply]
5759
6549
  After this: \`roster hire <handle>\` for the first staff member, then \`roster app <handle>\`.
5760
6550
  `;
5761
6551
  async function initCommand(argv) {
5762
- const opts = parseFlags9(argv);
6552
+ const opts = parseFlags10(argv);
5763
6553
  if (!opts.org) {
5764
6554
  process.stderr.write("roster: init needs --org <github-org>\n");
5765
6555
  return 2;
@@ -5774,7 +6564,7 @@ async function initCommand(argv) {
5774
6564
  const name = opts.name ?? opts.org;
5775
6565
  const opsName = opts.ops ?? "roster-ops";
5776
6566
  const root2 = resolve3(opts.dir ?? process.cwd());
5777
- const opsDir = join22(root2, opsName);
6567
+ const opsDir = join23(root2, opsName);
5778
6568
  const marker = opts.marker ?? human.split("-")[0];
5779
6569
  if (existsSync9(opsDir)) {
5780
6570
  process.stderr.write(`roster: ${opsDir} already exists. This org is already initialised.
@@ -5823,14 +6613,14 @@ async function initCommand(argv) {
5823
6613
  }
5824
6614
  mkdirSync5(opsDir, { recursive: true });
5825
6615
  for (const [rel, text2] of files) {
5826
- const dest = join22(opsDir, rel);
6616
+ const dest = join23(opsDir, rel);
5827
6617
  mkdirSync5(dirname8(dest), { recursive: true });
5828
- writeFileSync8(dest, text2);
6618
+ writeFileSync9(dest, text2);
5829
6619
  }
5830
6620
  for (const rel of templateFiles(opsTemplateDir())) {
5831
- const dest = join22(opsDir, ".roster", "seed", rel);
6621
+ const dest = join23(opsDir, ".roster", "seed", rel);
5832
6622
  mkdirSync5(dirname8(dest), { recursive: true });
5833
- writeFileSync8(dest, readFileSync9(join22(opsTemplateDir(), rel), "utf8"));
6623
+ writeFileSync9(dest, readFileSync10(join23(opsTemplateDir(), rel), "utf8"));
5834
6624
  }
5835
6625
  process.stdout.write(` wrote ${files.size} files and the recorded base
5836
6626
  `);
@@ -5880,7 +6670,7 @@ async function initCommand(argv) {
5880
6670
  async function initFiles(o) {
5881
6671
  const files = /* @__PURE__ */ new Map();
5882
6672
  for (const rel of templateFiles(opsTemplateDir())) {
5883
- files.set(rel, readFileSync9(join22(opsTemplateDir(), rel), "utf8"));
6673
+ files.set(rel, readFileSync10(join23(opsTemplateDir(), rel), "utf8"));
5884
6674
  }
5885
6675
  const agent = o.agent ?? "claude-code-action";
5886
6676
  const preset = await agentPreset(agent);
@@ -5905,7 +6695,7 @@ async function initFiles(o) {
5905
6695
  return files;
5906
6696
  }
5907
6697
  async function agentPreset(id) {
5908
- const path = join22(opsTemplateDir(), "agents.mjs");
6698
+ const path = join23(opsTemplateDir(), "agents.mjs");
5909
6699
  const { PRESETS } = await import(`file://${path}`);
5910
6700
  const preset = PRESETS[id];
5911
6701
  if (!preset) {
@@ -6039,7 +6829,7 @@ function stamp2() {
6039
6829
  try {
6040
6830
  return execFileSync7(
6041
6831
  "git",
6042
- ["-C", join22(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
6832
+ ["-C", join23(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
6043
6833
  {
6044
6834
  encoding: "utf8",
6045
6835
  stdio: ["ignore", "pipe", "ignore"]
@@ -6052,7 +6842,7 @@ function stamp2() {
6052
6842
  function git3(cwd, args) {
6053
6843
  execFileSync7("git", args, { cwd, stdio: ["ignore", "ignore", "pipe"] });
6054
6844
  }
6055
- function parseFlags9(argv) {
6845
+ function parseFlags10(argv) {
6056
6846
  const out = {};
6057
6847
  for (let i = 0; i < argv.length; i++) {
6058
6848
  const flag = argv[i];
@@ -6075,7 +6865,7 @@ function parseFlags9(argv) {
6075
6865
  }
6076
6866
 
6077
6867
  // src/commands/lint.ts
6078
- import { join as join23 } from "path";
6868
+ import { join as join24 } from "path";
6079
6869
  var lintHelp = `
6080
6870
  roster lint [handle]
6081
6871
 
@@ -6090,7 +6880,7 @@ roster lint [handle]
6090
6880
  `;
6091
6881
  async function lintCommand(argv) {
6092
6882
  const handle = argv[0] && !argv[0].startsWith("-") ? argv[0] : void 0;
6093
- const opts = parseFlags10(argv.slice(handle ? 1 : 0));
6883
+ const opts = parseFlags11(argv.slice(handle ? 1 : 0));
6094
6884
  const ws = findWorkspace(opts.ops);
6095
6885
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
6096
6886
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -6103,8 +6893,8 @@ async function lintCommand(argv) {
6103
6893
  let errors = 0;
6104
6894
  let warnings = 0;
6105
6895
  for (const s of staff) {
6106
- const root2 = join23(ws.root, s.dir ?? s.handle);
6107
- const dir = join23(root2, "memory");
6896
+ const root2 = join24(ws.root, s.dir ?? s.handle);
6897
+ const dir = join24(root2, "memory");
6108
6898
  const budgets = budgetsFor(org, readManifest2(root2, parseYaml3));
6109
6899
  let problems;
6110
6900
  let factCount = 0;
@@ -6148,7 +6938,7 @@ async function lintCommand(argv) {
6148
6938
  );
6149
6939
  return errors > 0 ? 1 : 0;
6150
6940
  }
6151
- function parseFlags10(argv) {
6941
+ function parseFlags11(argv) {
6152
6942
  const out = {};
6153
6943
  for (let i = 0; i < argv.length; i++) {
6154
6944
  if (argv[i] === "--quiet") out.quiet = true;
@@ -6160,14 +6950,14 @@ function parseFlags10(argv) {
6160
6950
 
6161
6951
  // src/commands/portal.ts
6162
6952
  import { randomBytes as randomBytes3 } from "crypto";
6163
- import { readFileSync as readFileSync13 } from "fs";
6953
+ import { readFileSync as readFileSync14 } from "fs";
6164
6954
  import { createServer as createServer2 } from "http";
6165
- import { join as join32, resolve as resolve7 } from "path";
6955
+ import { join as join32, resolve as resolve6 } from "path";
6166
6956
 
6167
6957
  // src/lib/attach.ts
6168
6958
  import { execFileSync as execFileSync8 } from "child_process";
6169
- import { existsSync as existsSync10, mkdirSync as mkdirSync6, writeFileSync as writeFileSync9 } from "fs";
6170
- import { basename, extname, join as join24 } from "path";
6959
+ import { existsSync as existsSync10, mkdirSync as mkdirSync6, writeFileSync as writeFileSync10 } from "fs";
6960
+ import { basename, extname, join as join25 } from "path";
6171
6961
  var MAX_UPLOAD = 25 * 1024 * 1024;
6172
6962
  var ATTACH_DIR = "attachments";
6173
6963
  function safeName(raw) {
@@ -6244,15 +7034,15 @@ function openBrowser(url) {
6244
7034
  // src/lib/sync.ts
6245
7035
  import { execFile as execFile5 } from "child_process";
6246
7036
  import { existsSync as existsSync11 } from "fs";
6247
- import { join as join25 } from "path";
7037
+ import { join as join26 } from "path";
6248
7038
  import { promisify as promisify3 } from "util";
6249
7039
  var run3 = promisify3(execFile5);
6250
7040
  async function syncRepos(root2, dirs) {
6251
- return Promise.all(dirs.map((dir) => syncOne(join25(root2, dir), dir)));
7041
+ return Promise.all(dirs.map((dir) => syncOne(join26(root2, dir), dir)));
6252
7042
  }
6253
7043
  async function syncOne(path, dir) {
6254
7044
  const base2 = { dir, behind: 0, ahead: 0, dirty: false, pulled: false };
6255
- if (!existsSync11(join25(path, ".git"))) return { ...base2, skipped: "no-remote" };
7045
+ if (!existsSync11(join26(path, ".git"))) return { ...base2, skipped: "no-remote" };
6256
7046
  const git4 = async (...args) => (await run3("git", ["-C", path, ...args], { encoding: "utf8" })).stdout.trim();
6257
7047
  try {
6258
7048
  const remotes = await git4("remote");
@@ -6287,25 +7077,25 @@ function reason(e) {
6287
7077
  }
6288
7078
 
6289
7079
  // src/portal/assets.ts
6290
- import { existsSync as existsSync12, readFileSync as readFileSync10, statSync as statSync3 } from "fs";
6291
- import { dirname as dirname9, extname as extname2, join as join26, resolve as resolve4 } from "path";
7080
+ import { existsSync as existsSync12, readFileSync as readFileSync11, statSync as statSync3 } from "fs";
7081
+ import { dirname as dirname9, extname as extname2, join as join27, resolve as resolve4 } from "path";
6292
7082
  import { fileURLToPath as fileURLToPath4 } from "url";
6293
7083
  function portalDir() {
6294
7084
  const fixed = frameworkRoot();
6295
- if (fixed) return join26(fixed, "templates", "portal");
7085
+ if (fixed) return join27(fixed, "templates", "portal");
6296
7086
  const here = dirname9(fileURLToPath4(import.meta.url));
6297
7087
  const candidates = [
6298
- join26(here, "..", "..", "templates", "portal"),
7088
+ join27(here, "..", "..", "templates", "portal"),
6299
7089
  // src/portal → package root
6300
- join26(here, "..", "templates", "portal")
7090
+ join27(here, "..", "templates", "portal")
6301
7091
  // dist → package root
6302
7092
  ];
6303
- for (const path of candidates) if (existsSync12(join26(path, "index.html"))) return path;
7093
+ for (const path of candidates) if (existsSync12(join27(path, "index.html"))) return path;
6304
7094
  throw new Error(`portal UI not found. Looked in:
6305
7095
  ${candidates.join("\n ")}`);
6306
7096
  }
6307
7097
  function portalIndex() {
6308
- return readFileSync10(join26(portalDir(), "index.html"), "utf8");
7098
+ return readFileSync11(join27(portalDir(), "index.html"), "utf8");
6309
7099
  }
6310
7100
  var ASSET_MIME = {
6311
7101
  ".css": "text/css; charset=utf-8",
@@ -6322,331 +7112,11 @@ function portalAsset(rel) {
6322
7112
  const type = ASSET_MIME[extname2(full).toLowerCase()];
6323
7113
  if (!type) return null;
6324
7114
  if (!existsSync12(full) || statSync3(full).isDirectory()) return null;
6325
- return { body: readFileSync10(full), type };
7115
+ return { body: readFileSync11(full), type };
6326
7116
  }
6327
7117
 
6328
7118
  // src/portal/handler.ts
6329
- import { join as join29, resolve as resolve6 } from "path";
6330
-
6331
- // templates/ops/compose.mjs
6332
- import * as nodeFs from "fs";
6333
- import { join as join27, dirname as dirname10, resolve as resolve5 } from "path";
6334
- import { fileURLToPath as fileURLToPath5 } from "url";
6335
- function parseYaml(text2, file = "<yaml>") {
6336
- const lines = [];
6337
- text2.split("\n").forEach((raw, i) => {
6338
- const noComment = stripComment(raw);
6339
- if (!noComment.trim()) return;
6340
- if (noComment.trim() === "---") return;
6341
- lines.push({ n: i + 1, indent: raw.match(/^ */)[0].length, text: noComment.trimEnd() });
6342
- });
6343
- let pos = 0;
6344
- const fail = (msg, line) => {
6345
- throw new Error(`${file}:${line?.n ?? "?"} ${msg}`);
6346
- };
6347
- function parseBlock(indent) {
6348
- const first = lines[pos];
6349
- if (!first) return null;
6350
- if (first.text.trim().startsWith("- ")) return parseList(indent);
6351
- return parseMap(indent);
6352
- }
6353
- function parseMap(indent) {
6354
- const out = {};
6355
- while (pos < lines.length) {
6356
- const line = lines[pos];
6357
- if (line.indent < indent) break;
6358
- if (line.indent > indent) fail("unexpected indentation", line);
6359
- const body2 = line.text.trim();
6360
- if (body2.startsWith("- ")) break;
6361
- const m = body2.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
6362
- if (!m) fail(`expected "key: value", got ${JSON.stringify(body2)}`, line);
6363
- const [, key, rest] = m;
6364
- pos++;
6365
- if (rest === "") {
6366
- const next = lines[pos];
6367
- if (next && next.indent > indent) out[key] = parseBlock(next.indent);
6368
- else out[key] = null;
6369
- } else {
6370
- out[key] = parseScalar(rest, line);
6371
- }
6372
- }
6373
- return out;
6374
- }
6375
- function parseList(indent) {
6376
- const out = [];
6377
- while (pos < lines.length) {
6378
- const line = lines[pos];
6379
- if (line.indent < indent) break;
6380
- const body2 = line.text.trim();
6381
- if (!body2.startsWith("- ")) break;
6382
- if (line.indent > indent) fail("unexpected indentation in list", line);
6383
- const item = body2.slice(2).trim();
6384
- pos++;
6385
- if (item.startsWith("{") && item.endsWith("}")) {
6386
- out.push(parseInlineMap(item, line));
6387
- } else if (/^[A-Za-z0-9_.-]+:/.test(item)) {
6388
- const sub = { ...parseInlinePair(item, line) };
6389
- while (pos < lines.length && lines[pos].indent > indent) {
6390
- const c = lines[pos];
6391
- const cm = c.text.trim().match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
6392
- if (!cm) fail(`expected "key: value" in list item, got ${JSON.stringify(c.text.trim())}`, c);
6393
- pos++;
6394
- if (cm[2] === "") {
6395
- const next = lines[pos];
6396
- sub[cm[1]] = next && next.indent > c.indent ? parseBlock(next.indent) : null;
6397
- } else {
6398
- sub[cm[1]] = parseScalar(cm[2], c);
6399
- }
6400
- }
6401
- out.push(sub);
6402
- } else {
6403
- out.push(parseScalar(item, line));
6404
- }
6405
- }
6406
- return out;
6407
- }
6408
- function parseInlinePair(item, line) {
6409
- const m = item.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
6410
- if (!m) fail("bad list item", line);
6411
- return { [m[1]]: m[2] === "" ? null : parseScalar(m[2], line) };
6412
- }
6413
- function parseInlineMap(item, line) {
6414
- const out = {};
6415
- for (const part of splitTopLevel(item.slice(1, -1))) {
6416
- if (!part.trim()) continue;
6417
- const m = part.match(/^\s*([A-Za-z0-9_.-]+)\s*:\s*(.*)$/);
6418
- if (!m) fail(`bad inline map entry ${JSON.stringify(part)}`, line);
6419
- out[m[1]] = parseScalar(m[2].trim(), line);
6420
- }
6421
- return out;
6422
- }
6423
- const root2 = parseBlock(lines.length ? lines[0].indent : 0);
6424
- if (pos < lines.length) fail("could not parse to end of file", lines[pos]);
6425
- return root2 ?? {};
6426
- }
6427
- function stripComment(raw) {
6428
- let out = "";
6429
- let quote = null;
6430
- for (let i = 0; i < raw.length; i++) {
6431
- const c = raw[i];
6432
- if (quote) {
6433
- out += c;
6434
- if (c === quote && raw[i - 1] !== "\\") quote = null;
6435
- continue;
6436
- }
6437
- if (c === '"' || c === "'") {
6438
- quote = c;
6439
- out += c;
6440
- continue;
6441
- }
6442
- if (c === "#" && (i === 0 || /\s/.test(raw[i - 1]))) break;
6443
- out += c;
6444
- }
6445
- return out;
6446
- }
6447
- function splitTopLevel(s) {
6448
- const parts = [];
6449
- let depth = 0;
6450
- let cur = "";
6451
- for (const c of s) {
6452
- if (c === "{" || c === "[") depth++;
6453
- if (c === "}" || c === "]") depth--;
6454
- if (c === "," && depth === 0) {
6455
- parts.push(cur);
6456
- cur = "";
6457
- continue;
6458
- }
6459
- cur += c;
6460
- }
6461
- parts.push(cur);
6462
- return parts;
6463
- }
6464
- function parseScalar(raw, line) {
6465
- const v = raw.trim();
6466
- if (v.startsWith("[") && v.endsWith("]")) {
6467
- const inner = v.slice(1, -1).trim();
6468
- return inner === "" ? [] : splitTopLevel(inner).map((s) => parseScalar(s, line));
6469
- }
6470
- if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) {
6471
- return v.slice(1, -1);
6472
- }
6473
- if (v === "true") return true;
6474
- if (v === "false") return false;
6475
- if (v === "null" || v === "~") return null;
6476
- if (/^-?\d+$/.test(v)) return Number(v);
6477
- return v;
6478
- }
6479
- var MAX_INCLUDE_DEPTH = 8;
6480
- var FENCE = "\0";
6481
- function render2(template, ctx, readPartial, depth = 0) {
6482
- if (depth > MAX_INCLUDE_DEPTH) throw new Error("include depth exceeded; a partial probably includes itself");
6483
- let out = template.replace(
6484
- /\{\{#if\s+([A-Za-z0-9_.]+)\s*\}\}\n?([\s\S]*?)\{\{\/if\}\}\n?/g,
6485
- (_, path, body2) => truthy(lookup2(ctx, path)) ? body2 : ""
6486
- );
6487
- out = out.replace(/\{\{>(\??)\s*([^}\s]+)\s*\}\}/g, (_, optional, rel) => {
6488
- const partial = readPartial(rel);
6489
- if (partial === null) {
6490
- if (optional) return "";
6491
- throw new Error(`partial not found: ${rel}`);
6492
- }
6493
- return render2(partial, ctx, readPartial, depth + 1).replace(/\n+$/, "");
6494
- });
6495
- out = out.replace(/\{\{\s*([A-Za-z0-9_.]+)\s*\}\}/g, (_, path) => {
6496
- const v = lookup2(ctx, path);
6497
- if (v === void 0 || v === null) {
6498
- if (path.startsWith("event.")) {
6499
- throw new Error(
6500
- `{{${path}}} needs trigger context, which arrives as ROSTER_CONTEXT.
6501
- A "mention" prompt is written for the comment that woke it, so it cannot
6502
- be composed without one. To see it locally:
6503
- ROSTER_CONTEXT='{"issue_number":"1","comment_id":"1","repo":"o/r"}' \\
6504
- node compose.mjs --staff <handle> --kind <kind>`
6505
- );
6506
- }
6507
- throw new Error(`unknown or empty placeholder: {{${path}}}`);
6508
- }
6509
- return String(v).replace(/\{\{/g, FENCE);
6510
- });
6511
- return depth === 0 ? out.replaceAll(FENCE, "{{") : out;
6512
- }
6513
- function lookup2(ctx, path) {
6514
- return path.split(".").reduce((acc, k) => acc == null ? void 0 : acc[k], ctx);
6515
- }
6516
- function truthy(v) {
6517
- return !(v === void 0 || v === null || v === false || v === "" || Array.isArray(v) && v.length === 0);
6518
- }
6519
- function readHumans2(org) {
6520
- const listed = Array.isArray(org?.humans) ? org.humans : org?.humans ? [org.humans] : [];
6521
- const out = [];
6522
- for (const entry of [...listed, org?.human].filter(Boolean)) {
6523
- const github = String(entry.github ?? entry.login ?? "").trim();
6524
- const name = String(entry.name ?? github).trim();
6525
- if (!github && !name) continue;
6526
- if (github && out.some((h) => h.github.toLowerCase() === github.toLowerCase())) continue;
6527
- out.push({
6528
- github,
6529
- name: name || github,
6530
- marker: String(entry.marker ?? "").trim() || defaultMarker2(name || github),
6531
- role: entry.role ?? void 0
6532
- });
6533
- }
6534
- return out;
6535
- }
6536
- function humanSentence(humans) {
6537
- const parts = humans.map((h) => h.github ? `${h.name} (@${h.github})` : h.name);
6538
- if (parts.length < 2) return parts[0] ?? "";
6539
- return `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
6540
- }
6541
- function defaultMarker2(name) {
6542
- return String(name).trim().split(/[\s-]+/)[0].toLowerCase().replace(/[^a-z0-9]/g, "") || "human";
6543
- }
6544
- function compose({
6545
- opsDir,
6546
- brainsDir,
6547
- staff,
6548
- kind,
6549
- runDir,
6550
- fs: fs2 = nodeFs,
6551
- context = process.env.ROSTER_CONTEXT
6552
- }) {
6553
- const { readFileSync: readFileSync18, existsSync: existsSync18 } = fs2;
6554
- const org = parseYaml(readFileSync18(join27(opsDir, "org.yaml"), "utf8"), "org.yaml");
6555
- const entry = (org.staff ?? []).find((s) => s.handle === staff);
6556
- if (!entry) {
6557
- const known = (org.staff ?? []).map((s) => s.handle).join(", ") || "none";
6558
- throw new Error(`unknown staff handle "${staff}". org.yaml knows: ${known}`);
6559
- }
6560
- const brainDir = resolve5(brainsDir, entry.dir ?? entry.handle);
6561
- const staffFile = join27(brainDir, "staff.yaml");
6562
- if (!existsSync18(staffFile)) throw new Error(`no staff.yaml at ${staffFile}`);
6563
- const self2 = parseYaml(readFileSync18(staffFile, "utf8"), `${entry.handle}/staff.yaml`);
6564
- const peers = (org.staff ?? []).filter((s) => s.handle !== staff).map((s) => ({ ...s, ...s.dir ? {} : { dir: s.handle } }));
6565
- let event2 = {};
6566
- if (context) {
6567
- try {
6568
- event2 = JSON.parse(context);
6569
- } catch (err) {
6570
- throw new Error(`ROSTER_CONTEXT is not valid JSON: ${err.message}`);
6571
- }
6572
- }
6573
- if (Object.keys(event2).length) event2 = { ...event2, no_comment: !event2.comment_id };
6574
- const trigger = String(event2.trigger ?? "");
6575
- event2 = {
6576
- ...event2,
6577
- from_peer: trigger === "peer",
6578
- from_human: trigger !== "peer",
6579
- follow_on: trigger === "follow-on"
6580
- };
6581
- const inflightFile = join27(runDir ?? join27(brainsDir, ".roster-run"), "inflight.md");
6582
- const inflight = existsSync18(inflightFile) ? readFileSync18(inflightFile, "utf8").trim() : "";
6583
- const humans = readHumans2(org);
6584
- const ctx = {
6585
- org,
6586
- event: event2,
6587
- // The first is who the prose addresses; `humans` is everybody the mention gate accepts.
6588
- human: humans[0] ?? org.human,
6589
- humans,
6590
- ops: { dir: org.ops_dir ?? "roster-ops" },
6591
- // `dir` lives in the org registry (it is where the checkout lands), everything
6592
- // else lives in the staff member's own manifest.
6593
- staff: {
6594
- ...self2,
6595
- dir: entry.dir ?? entry.handle,
6596
- // The repo this role contributes to but does not own. Named explicitly in the
6597
- // prompt because "a repo you do not own" is vaguer than an agent needs.
6598
- product: (self2.works_in ?? [])[0] ?? null,
6599
- // Absent from manifests written before it existed; the callers fall back to the same.
6600
- max_runs_per_day: self2.max_runs_per_day ?? 6,
6601
- // One staff member drafts next month's org/priorities.md, so there is one draft rather
6602
- // than one per person: whoever org.yaml lists first.
6603
- drafts_priorities: (org.staff ?? [])[0]?.handle === staff
6604
- },
6605
- peers,
6606
- peer: peers[0] ?? null,
6607
- kind,
6608
- // Convenience strings the fragments lean on, computed once here so a
6609
- // fragment never has to do string work.
6610
- peer_list: peers.map((p) => `- \`${p.dir}/\` - the ${p.name}'s brain`).join("\n"),
6611
- // Everybody who can wake this staff member and rule on their work, and the same list
6612
- // without the one the prose already names. Empty when there is only one, which is what
6613
- // makes `{{#if humans_extra}}` the right way to mention the others at all.
6614
- human_list: humanSentence(humans),
6615
- inflight,
6616
- humans_extra: humanSentence(humans.slice(1))
6617
- };
6618
- const readPartial = (rel) => {
6619
- const p = rel.startsWith("staff:") ? join27(brainDir, rel.slice(6)) : join27(opsDir, rel);
6620
- return existsSync18(p) ? readFileSync18(p, "utf8") : null;
6621
- };
6622
- const kindFile = join27(opsDir, "prompts", `${kind}.md`);
6623
- if (!existsSync18(kindFile)) throw new Error(`no prompt for kind "${kind}" at ${kindFile}`);
6624
- const body2 = render2(readFileSync18(kindFile, "utf8"), ctx, readPartial);
6625
- return body2.replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
6626
- }
6627
- function main(argv) {
6628
- const args = {};
6629
- for (let i = 0; i < argv.length; i += 2) {
6630
- if (!argv[i].startsWith("--")) throw new Error(`unexpected argument ${argv[i]}`);
6631
- args[argv[i].slice(2)] = argv[i + 1];
6632
- }
6633
- if (!args.staff || !args.kind) {
6634
- console.error("usage: node compose.mjs --staff <handle> --kind <daily|mention> [--ops DIR] [--brains DIR]");
6635
- process.exit(2);
6636
- }
6637
- const opsDir = resolve5(args.ops ?? dirname10(fileURLToPath5(import.meta.url)));
6638
- const brainsDir = resolve5(args.brains ?? join27(opsDir, ".."));
6639
- process.stdout.write(compose({ opsDir, brainsDir, staff: args.staff, kind: args.kind }));
6640
- }
6641
- var self = import.meta.url ? fileURLToPath5(import.meta.url) : "";
6642
- if (process.argv[1] && self.endsWith("compose.mjs") && resolve5(process.argv[1]) === resolve5(self)) {
6643
- try {
6644
- main(process.argv.slice(2));
6645
- } catch (err) {
6646
- console.error(`compose: ${err.message}`);
6647
- process.exit(1);
6648
- }
6649
- }
7119
+ import { join as join29, resolve as resolve5 } from "path";
6650
7120
 
6651
7121
  // src/lib/ask.ts
6652
7122
  var MAX_PATCH_LINES = 40;
@@ -6727,6 +7197,12 @@ ${ticks}`;
6727
7197
 
6728
7198
  // src/lib/act.ts
6729
7199
  var MERGE_METHODS = ["squash", "merge", "rebase"];
7200
+ function wouldWake(req, handles) {
7201
+ if (req.action === "ask") return true;
7202
+ const text2 = `${req.title ?? ""}
7203
+ ${req.body ?? ""}`.toLowerCase();
7204
+ return handles.some((h) => new RegExp(`@${h.toLowerCase()}(?![\\w-])`).test(text2));
7205
+ }
6730
7206
  async function act(gh, req) {
6731
7207
  const { action, repo } = req;
6732
7208
  if (action === "create") {
@@ -6854,11 +7330,11 @@ function whyNotMerged(ghError, pr) {
6854
7330
  String(c.conclusion || c.state || "")
6855
7331
  )
6856
7332
  );
6857
- const list = (cs) => cs.map(name).join(", ");
7333
+ const list2 = (cs) => cs.map(name).join(", ");
6858
7334
  if (pr?.mergeStateStatus === "BLOCKED" && failing.length)
6859
- return `Not merged: checks failed (${list(failing)}).`;
7335
+ return `Not merged: checks failed (${list2(failing)}).`;
6860
7336
  if (pr?.mergeStateStatus === "BLOCKED" && running.length)
6861
- return `Not merged: checks are still running (${list(running)}). Merge again once they pass.`;
7337
+ return `Not merged: checks are still running (${list2(running)}). Merge again once they pass.`;
6862
7338
  if (pr?.mergeStateStatus === "BLOCKED" && pr.reviewDecision === "REVIEW_REQUIRED")
6863
7339
  return "Not merged: the branch rules need an approving review first. Press Approve, then Merge.";
6864
7340
  if (pr?.mergeStateStatus === "BLOCKED" && pr.reviewDecision === "CHANGES_REQUESTED")
@@ -7380,11 +7856,11 @@ function runInfo(r) {
7380
7856
  async function findDispatched(gh, repo, workflow, since, o = {}) {
7381
7857
  const sleep = o.sleep ?? wait;
7382
7858
  for (let i = 0; i < (o.tries ?? 12); i++) {
7383
- const list = await gh.request(
7859
+ const list2 = await gh.request(
7384
7860
  "GET",
7385
7861
  `repos/${repo}/actions/workflows/${workflow}/runs?per_page=5`
7386
7862
  );
7387
- const found = list.ok ? pickRun((list.data?.workflow_runs ?? []).map(runInfo), since) : void 0;
7863
+ const found = list2.ok ? pickRun((list2.data?.workflow_runs ?? []).map(runInfo), since) : void 0;
7388
7864
  if (found) return found;
7389
7865
  await sleep(o.every ?? 2500);
7390
7866
  }
@@ -7399,7 +7875,7 @@ async function runState(gh, repo, id) {
7399
7875
  )
7400
7876
  ]);
7401
7877
  if (!run4.ok || !run4.data) throw new Error(`could not read run ${id}: ${run4.error}`);
7402
- const list = (jobs.data?.jobs ?? []).map((j) => ({
7878
+ const list2 = (jobs.data?.jobs ?? []).map((j) => ({
7403
7879
  name: String(j.name ?? ""),
7404
7880
  conclusion: String(j.conclusion ?? ""),
7405
7881
  steps: (j.steps ?? []).map((s) => ({
@@ -7407,7 +7883,7 @@ async function runState(gh, repo, id) {
7407
7883
  conclusion: String(s.conclusion ?? "")
7408
7884
  }))
7409
7885
  }));
7410
- return { ...runInfo(run4.data), failedAt: failedSteps(list) };
7886
+ return { ...runInfo(run4.data), failedAt: failedSteps(list2) };
7411
7887
  }
7412
7888
  function failedSteps(jobs) {
7413
7889
  const out = [];
@@ -7477,7 +7953,7 @@ function renderBrief2(text2, tokens) {
7477
7953
  return text2.replace(/%%([A-Z_]+)%%/g, (m, name) => tokens[name] ?? m);
7478
7954
  }
7479
7955
  function orgSpec(org, w) {
7480
- const humans = readHumans(org);
7956
+ const humans = staffHumans(org);
7481
7957
  const first = humans[0];
7482
7958
  return {
7483
7959
  org: org.org,
@@ -7497,18 +7973,180 @@ function workspaceRoots(org) {
7497
7973
  ];
7498
7974
  }
7499
7975
 
7976
+ // src/portal/session.ts
7977
+ var encoder = new TextEncoder();
7978
+ async function keyFrom(secret) {
7979
+ const raw = base64Decode(secret);
7980
+ if (raw.length !== 32) throw new Error("SESSION_KEY must be 32 bytes, base64-encoded");
7981
+ return crypto.subtle.importKey("raw", raw, "AES-GCM", false, [
7982
+ "encrypt",
7983
+ "decrypt"
7984
+ ]);
7985
+ }
7986
+ async function sealJson(value, secret) {
7987
+ const iv = crypto.getRandomValues(new Uint8Array(12));
7988
+ const body2 = await crypto.subtle.encrypt(
7989
+ { name: "AES-GCM", iv },
7990
+ await keyFrom(secret),
7991
+ encoder.encode(JSON.stringify(value))
7992
+ );
7993
+ return `${base64url(iv)}.${base64url(new Uint8Array(body2))}`;
7994
+ }
7995
+ async function openJson(value, secret) {
7996
+ const [iv, body2] = value.split(".");
7997
+ if (!iv || !body2) return null;
7998
+ try {
7999
+ const plain = await crypto.subtle.decrypt(
8000
+ { name: "AES-GCM", iv: base64Decode(iv) },
8001
+ await keyFrom(secret),
8002
+ base64Decode(body2)
8003
+ );
8004
+ return JSON.parse(new TextDecoder().decode(plain));
8005
+ } catch {
8006
+ return null;
8007
+ }
8008
+ }
8009
+ function base64url(bytes2) {
8010
+ let s = "";
8011
+ for (const b of bytes2) s += String.fromCharCode(b);
8012
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8013
+ }
8014
+ function base64Decode(s) {
8015
+ const std = s.replace(/-/g, "+").replace(/_/g, "/");
8016
+ const bin2 = atob(std + "=".repeat((4 - std.length % 4) % 4));
8017
+ const out = new Uint8Array(bin2.length);
8018
+ for (let i = 0; i < bin2.length; i++) out[i] = bin2.charCodeAt(i);
8019
+ return out;
8020
+ }
8021
+
8022
+ // src/portal/grants.ts
8023
+ var key = (connector) => `grant:${connector}`;
8024
+ async function readGrant(store2, secret, connector) {
8025
+ const sealed = await store2.get(key(connector));
8026
+ return sealed ? openJson(sealed, secret) : null;
8027
+ }
8028
+ async function writeGrant(store2, secret, g) {
8029
+ await store2.put(key(g.connector), await sealJson(g, secret));
8030
+ }
8031
+ async function dropGrant(store2, connector) {
8032
+ await store2.put(key(connector), "");
8033
+ }
8034
+ async function discover(resource, doFetch = fetch) {
8035
+ const r = new URL(resource);
8036
+ let issuer = r.origin;
8037
+ for (const path of [
8038
+ `/.well-known/oauth-protected-resource${r.pathname}`,
8039
+ "/.well-known/oauth-protected-resource"
8040
+ ]) {
8041
+ const res = await doFetch(r.origin + path).catch(() => null);
8042
+ if (!res?.ok) continue;
8043
+ const meta = await res.json().catch(() => ({}));
8044
+ if (meta.authorization_servers?.[0]) {
8045
+ issuer = meta.authorization_servers[0].replace(/\/+$/, "");
8046
+ break;
8047
+ }
8048
+ }
8049
+ const i = new URL(issuer);
8050
+ const suffix = i.pathname === "/" ? "" : i.pathname;
8051
+ for (const path of [
8052
+ `/.well-known/oauth-authorization-server${suffix}`,
8053
+ `/.well-known/openid-configuration${suffix}`
8054
+ ]) {
8055
+ const res = await doFetch(i.origin + path).catch(() => null);
8056
+ if (!res?.ok) continue;
8057
+ const meta = await res.json().catch(() => null);
8058
+ if (meta?.authorization_endpoint && meta.token_endpoint) return meta;
8059
+ }
8060
+ throw new Error(`could not find how to sign in to ${r.host}`);
8061
+ }
8062
+ async function clientFor(meta, redirectUri, name, store2, doFetch = fetch) {
8063
+ const remembered = `oauthclient:${meta.issuer}:${redirectUri}`;
8064
+ const kept = await store2.get(remembered);
8065
+ if (kept) return JSON.parse(kept);
8066
+ if (!meta.registration_endpoint) {
8067
+ throw new Error(`${new URL(meta.issuer).host} does not let a new app register itself`);
8068
+ }
8069
+ const res = await doFetch(meta.registration_endpoint, {
8070
+ method: "POST",
8071
+ headers: { "content-type": "application/json" },
8072
+ body: JSON.stringify({
8073
+ client_name: name,
8074
+ redirect_uris: [redirectUri],
8075
+ grant_types: ["authorization_code", "refresh_token"],
8076
+ response_types: ["code"],
8077
+ token_endpoint_auth_method: "none"
8078
+ })
8079
+ });
8080
+ const body2 = await res.json().catch(() => ({}));
8081
+ if (!res.ok || !body2.client_id)
8082
+ throw new Error(`registering with ${meta.issuer} failed (${res.status})`);
8083
+ const client = { clientId: body2.client_id, clientSecret: body2.client_secret };
8084
+ await store2.put(remembered, JSON.stringify(client));
8085
+ return client;
8086
+ }
8087
+ function verifier() {
8088
+ return b64url(crypto.getRandomValues(new Uint8Array(32)));
8089
+ }
8090
+ async function challenge(v) {
8091
+ return b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(v))));
8092
+ }
8093
+ async function tokenRequest(endpoint, form, doFetch = fetch) {
8094
+ const body2 = new URLSearchParams();
8095
+ for (const [k, v] of Object.entries(form)) if (v) body2.set(k, v);
8096
+ const res = await doFetch(endpoint, {
8097
+ method: "POST",
8098
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
8099
+ body: body2
8100
+ });
8101
+ return { status: res.status, ...await res.json().catch(() => ({})) };
8102
+ }
8103
+ async function exchange2(o, doFetch = fetch) {
8104
+ const t = await tokenRequest(
8105
+ o.tokenEndpoint,
8106
+ {
8107
+ grant_type: "authorization_code",
8108
+ code: o.code,
8109
+ redirect_uri: o.redirectUri,
8110
+ client_id: o.clientId,
8111
+ client_secret: o.clientSecret,
8112
+ code_verifier: o.verifier,
8113
+ resource: o.resource
8114
+ },
8115
+ doFetch
8116
+ );
8117
+ if (!t.access_token)
8118
+ throw new Error(t.error_description ?? t.error ?? `sign-in failed (${t.status})`);
8119
+ return {
8120
+ connector: o.connector,
8121
+ resource: o.resource,
8122
+ tokenEndpoint: o.tokenEndpoint,
8123
+ clientId: o.clientId,
8124
+ clientSecret: o.clientSecret,
8125
+ accessToken: t.access_token,
8126
+ refreshToken: t.refresh_token,
8127
+ expiresAt: Date.now() + (t.expires_in ?? 3600) * 1e3,
8128
+ by: o.by,
8129
+ at: (/* @__PURE__ */ new Date()).toISOString()
8130
+ };
8131
+ }
8132
+ function b64url(b) {
8133
+ let s = "";
8134
+ for (const x of b) s += String.fromCharCode(x);
8135
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8136
+ }
8137
+
7500
8138
  // src/portal/history.ts
7501
8139
  var DAYS = 14;
7502
8140
  async function loadHistory(gh, kv, repo, head2, now = Date.now()) {
7503
8141
  const since = new Date(now - DAYS * 864e5).toISOString();
7504
- const key = `history:${repo}@${head2}:${since.slice(0, 10)}`;
7505
- const kept = await kv.get(key);
8142
+ const key2 = `history:${repo}@${head2}:${since.slice(0, 10)}`;
8143
+ const kept = await kv.get(key2);
7506
8144
  if (kept) return JSON.parse(kept);
7507
- const list = (q) => gh.request("GET", `repos/${repo}/commits?sha=${head2}&${q}`);
8145
+ const list2 = (q) => gh.request("GET", `repos/${repo}/commits?sha=${head2}&${q}`);
7508
8146
  const [recent, memory, index] = await Promise.all([
7509
- list("per_page=25"),
7510
- list("path=memory&per_page=1"),
7511
- list(`path=memory/INDEX.md&since=${since}&per_page=100`)
8147
+ list2("per_page=25"),
8148
+ list2("path=memory&per_page=1"),
8149
+ list2(`path=memory/INDEX.md&since=${since}&per_page=100`)
7512
8150
  ]);
7513
8151
  const patches = await Promise.all(
7514
8152
  (index.data ?? []).map(async (c) => ({
@@ -7522,12 +8160,12 @@ async function loadHistory(gh, kv, repo, head2, now = Date.now()) {
7522
8160
  lastMemory: (memory.data ?? []).map(commit)[0],
7523
8161
  facts: factChanges(patches)
7524
8162
  };
7525
- if (recent.ok && memory.ok && index.ok) await kv.put(key, JSON.stringify(out));
8163
+ if (recent.ok && memory.ok && index.ok) await kv.put(key2, JSON.stringify(out));
7526
8164
  return out;
7527
8165
  }
7528
8166
  async function indexPatch(gh, kv, repo, sha) {
7529
- const key = `patch:${repo}@${sha}:memory/INDEX.md`;
7530
- const kept = await kv.get(key);
8167
+ const key2 = `patch:${repo}@${sha}:memory/INDEX.md`;
8168
+ const kept = await kv.get(key2);
7531
8169
  if (kept !== void 0) return kept;
7532
8170
  const res = await gh.request(
7533
8171
  "GET",
@@ -7535,7 +8173,7 @@ async function indexPatch(gh, kv, repo, sha) {
7535
8173
  );
7536
8174
  if (!res.ok) return "";
7537
8175
  const patch = res.data?.files?.find((f) => f.filename === "memory/INDEX.md")?.patch ?? "";
7538
- await kv.put(key, patch);
8176
+ await kv.put(key2, patch);
7539
8177
  return patch;
7540
8178
  }
7541
8179
  function commit(c) {
@@ -7607,7 +8245,7 @@ var Snapshots = class {
7607
8245
  const running = this.inflight.get(repo);
7608
8246
  if (running) return running;
7609
8247
  const say = (step) => {
7610
- for (const report3 of this.listeners.get(repo) ?? []) report3(repo, step);
8248
+ for (const report4 of this.listeners.get(repo) ?? []) report4(repo, step);
7611
8249
  };
7612
8250
  const work = this.load(gh, repo, pathsOnly, say).finally(() => {
7613
8251
  this.inflight.delete(repo);
@@ -7739,8 +8377,8 @@ var Snapshots = class {
7739
8377
  * start never asks at all.
7740
8378
  */
7741
8379
  async dates(gh, repo, snap, say, before) {
7742
- const key = `dates:${repo}@${snap.sha}`;
7743
- const kept = await this.kv.get(key);
8380
+ const key2 = `dates:${repo}@${snap.sha}`;
8381
+ const kept = await this.kv.get(key2);
7744
8382
  if (kept) {
7745
8383
  const map2 = JSON.parse(kept);
7746
8384
  for (const [path, e] of snap.files) e.mtime = map2[path];
@@ -7773,7 +8411,7 @@ var Snapshots = class {
7773
8411
  }
7774
8412
  const map = {};
7775
8413
  for (const [path, e] of snap.files) if (e.mtime) map[path] = e.mtime;
7776
- void this.kv.put(key, JSON.stringify(map));
8414
+ void this.kv.put(key2, JSON.stringify(map));
7777
8415
  }
7778
8416
  /** Every snapshot held, as one directory with a folder per repository, as a workspace has. */
7779
8417
  tree(dirOf) {
@@ -7850,6 +8488,7 @@ function createPortal(opts) {
7850
8488
  ws: { root: root2, opsDir: join29(root2, opts.opsName), opsName: opts.opsName },
7851
8489
  snapshots,
7852
8490
  kv: opts.kv,
8491
+ grants: opts.grants,
7853
8492
  bin: opts.bin ?? "roster",
7854
8493
  caches: {
7855
8494
  inbox: /* @__PURE__ */ new Map(),
@@ -7884,10 +8523,10 @@ async function handlePortal(req, portal, actor) {
7884
8523
  }
7885
8524
  async function ready(c, opts = {}) {
7886
8525
  const { portal, actor } = c;
7887
- const report3 = opts.report;
8526
+ const report4 = opts.report;
7888
8527
  const ops = await portal.snapshots.refresh(actor.gh, `${portal.org}/${portal.opsName}`, {
7889
8528
  force: opts.force,
7890
- report: report3
8529
+ report: report4
7891
8530
  });
7892
8531
  if (!ops.ok) {
7893
8532
  throw new HttpError(
@@ -7895,13 +8534,13 @@ async function ready(c, opts = {}) {
7895
8534
  `could not read ${portal.org}/${portal.opsName}: ${ops.error}`
7896
8535
  );
7897
8536
  }
7898
- report3?.(`${portal.org}/${portal.opsName}`, "ready");
8537
+ report4?.(`${portal.org}/${portal.opsName}`, "ready");
7899
8538
  const org = readOrg(portal.ws.opsDir, parseYaml2);
7900
8539
  const brains = (org.staff ?? []).map((s) => String(s.dir ?? s.handle));
7901
8540
  const products = opts.products ? (org.repos ?? []).map((r) => String(r.name)).filter((n) => n !== portal.opsName && !brains.includes(n)) : [];
7902
8541
  const results = await Promise.all([
7903
8542
  ...brains.map(
7904
- (d) => portal.snapshots.refresh(actor.gh, `${portal.org}/${d}`, { force: opts.force, report: report3 }).then((r) => ({ dir: d, ...r }))
8543
+ (d) => portal.snapshots.refresh(actor.gh, `${portal.org}/${d}`, { force: opts.force, report: report4 }).then((r) => ({ dir: d, ...r }))
7905
8544
  ),
7906
8545
  ...products.map(
7907
8546
  (d) => portal.snapshots.refresh(actor.gh, `${portal.org}/${d}`, { force: opts.force, pathsOnly: true }).then((r) => ({ dir: d, ...r }))
@@ -7937,10 +8576,10 @@ var ROUTES = {
7937
8576
  const out = writable.getWriter();
7938
8577
  const line = (o) => out.write(new TextEncoder().encode(`${JSON.stringify(o)}
7939
8578
  `));
7940
- const report3 = (repo, step) => {
8579
+ const report4 = (repo, step) => {
7941
8580
  void line({ repo: repo.slice(repo.indexOf("/") + 1), step });
7942
8581
  };
7943
- void orgExport(c, report3).then((org) => line({ org })).catch(
8582
+ void orgExport(c, report4).then((org) => line({ org })).catch(
7944
8583
  (err) => line({ error: String(err?.message ?? err), status: err.status })
7945
8584
  ).finally(() => out.close());
7946
8585
  return new Response(readable, {
@@ -8002,10 +8641,10 @@ var ROUTES = {
8002
8641
  try {
8003
8642
  const view = promptView(portal.ws, compose2, handle, brainDir, kind);
8004
8643
  for (const p of auditPrompt(portal.ws, view, roots)) {
8005
- const key = `${p.id}|${p.path ?? ""}|${p.title}`;
8006
- const seen = found.get(key);
8644
+ const key2 = `${p.id}|${p.path ?? ""}|${p.title}`;
8645
+ const seen = found.get(key2);
8007
8646
  if (seen) seen.kinds.push(kind);
8008
- else found.set(key, { ...p, kind, kinds: [kind] });
8647
+ else found.set(key2, { ...p, kind, kinds: [kind] });
8009
8648
  }
8010
8649
  } catch (err) {
8011
8650
  errors.push({ kind, error: String(err.message) });
@@ -8184,6 +8823,256 @@ var ROUTES = {
8184
8823
  await commitFile(portal, actor.gh, dir, rest.join("/"), payload.text, message2, base2)
8185
8824
  );
8186
8825
  },
8826
+ /* Connectors: what is offered, what this org has, and whether each one's keys are stored. */
8827
+ "/api/connectors": async (c) => {
8828
+ const { portal, actor } = c;
8829
+ const { org } = await ready(c);
8830
+ const brains = (org.staff ?? []).map((s) => `${portal.org}/${s.dir ?? s.handle}`);
8831
+ const stored = await secretsOn(actor.gh, brains);
8832
+ const readable = [...stored.values()].filter((v) => v !== null);
8833
+ const connectors = await Promise.all(
8834
+ declared2(org).map(async (x) => {
8835
+ let keys = null;
8836
+ let signedIn = null;
8837
+ if (x.auth === "key" && x.secrets.length) {
8838
+ if (!readable.length) keys = "unknown";
8839
+ else {
8840
+ const on = readable.filter((set) => x.secrets.every((s) => set.has(s.name))).length;
8841
+ keys = on === readable.length ? "stored" : on === 0 ? "missing" : "partial";
8842
+ }
8843
+ }
8844
+ if (x.auth === "oauth" && portal.grants) {
8845
+ const g = await readGrant(portal.grants.store, portal.grants.secret, x.id);
8846
+ if (g) signedIn = { by: g.by, at: g.at };
8847
+ }
8848
+ const { entry: _entry, ...rest } = x;
8849
+ return { ...rest, keys, signedIn };
8850
+ })
8851
+ );
8852
+ return json({
8853
+ catalogue: catalogueView(),
8854
+ connectors,
8855
+ staff: (org.staff ?? []).map((s) => ({
8856
+ handle: String(s.handle),
8857
+ name: String(s.name ?? s.handle)
8858
+ })),
8859
+ signIn: Boolean(portal.grants),
8860
+ canWrite: !isViewOnly(org, actor.id)
8861
+ });
8862
+ },
8863
+ /* Whether a key works, before it is stored. The key goes to the service and nowhere else. */
8864
+ "/api/connectors/check": async (c) => {
8865
+ if (!c.actor.canWrite) return refuse();
8866
+ const p = await body(c.req);
8867
+ const id = String(p.id ?? "");
8868
+ if (!CATALOGUE2[id]) return json({ error: `roster does not know ${id}` }, 400);
8869
+ const values = p.values ?? {};
8870
+ const wrong = wrongValue(id, values);
8871
+ if (wrong) return json({ state: "rejected", note: wrong });
8872
+ return json(await checkKey(id, values));
8873
+ },
8874
+ /* Add a connector, or change who has it: the keys to GitHub secrets, then org.yaml. */
8875
+ "/api/connectors/save": async (c) => {
8876
+ const { portal, actor } = c;
8877
+ if (!actor.canWrite) return refuse();
8878
+ const { org } = await ready(c, { force: true });
8879
+ const p = await body(c.req);
8880
+ const id = String(p.id ?? "");
8881
+ const known = CATALOGUE2[id];
8882
+ const existing = org.connectors?.[id];
8883
+ if (!known && !existing) return json({ error: `roster does not know ${id}` }, 400);
8884
+ const handles = new Set((org.staff ?? []).map((s) => String(s.handle)));
8885
+ const staff = (p.staff ?? []).map(String).filter((h) => handles.has(h));
8886
+ if (!staff.length) return json({ error: "Pick at least one staff member." }, 400);
8887
+ const entry = { staff, read_only: p.readOnly === true };
8888
+ for (const f of known?.fields ?? []) {
8889
+ if (!f.secret) entry[f.id] = (p.settings?.[f.id] ?? "").trim() || void 0;
8890
+ }
8891
+ if (known?.auth === "oauth") entry.portal = portal.grants?.base;
8892
+ const values = Object.fromEntries(
8893
+ Object.entries(p.values ?? {}).map(([k, v]) => [k, String(v ?? "").trim()])
8894
+ );
8895
+ const giving = Object.values(values).some(Boolean);
8896
+ if (known && known.auth !== "oauth") {
8897
+ const wrong2 = wrongValue(
8898
+ id,
8899
+ { ...p.settings, ...values },
8900
+ { keepKeys: Boolean(existing) && !giving }
8901
+ );
8902
+ if (wrong2) return json({ error: wrong2 }, 400);
8903
+ }
8904
+ if (giving && known) {
8905
+ const checked = await checkKey(id, { ...p.settings, ...values });
8906
+ if (checked.state === "rejected") return json({ error: checked.note }, 400);
8907
+ }
8908
+ const brains = (org.staff ?? []).map((s) => `${portal.org}/${s.dir ?? s.handle}`);
8909
+ const stored = [];
8910
+ for (const f of (known?.fields ?? []).filter((x) => x.secret)) {
8911
+ const v = values[f.id];
8912
+ if (!v) continue;
8913
+ const name2 = secretName2(id, f.id);
8914
+ stored.push({ name: name2, ...await storeSecret(actor.gh, portal.org, name2, v, brains) });
8915
+ }
8916
+ const opsFile = portal.snapshots.get(`${portal.org}/${portal.opsName}`)?.files.get("org.yaml");
8917
+ const before = opsFile?.text ?? "";
8918
+ const after = setConnector(before, org, id, entry);
8919
+ const wrong = validateOrgYaml(after, parseYaml2);
8920
+ if (wrong) return json({ error: wrong }, 400);
8921
+ const name = known?.name ?? id;
8922
+ const committed = await commitFile(
8923
+ portal,
8924
+ actor.gh,
8925
+ portal.opsName,
8926
+ "org.yaml",
8927
+ after,
8928
+ existing ? `portal: change who has ${name}` : `portal: connect ${name}`,
8929
+ before
8930
+ );
8931
+ return json({ ok: true, stored, committed });
8932
+ },
8933
+ /* Take a connector away: its keys, its sign-in, and its entry in org.yaml. */
8934
+ "/api/connectors/remove": async (c) => {
8935
+ const { portal, actor } = c;
8936
+ if (!actor.canWrite) return refuse();
8937
+ const { org } = await ready(c, { force: true });
8938
+ const id = String((await body(c.req)).id ?? "");
8939
+ const x = declared2(org).find((d) => d.id === id);
8940
+ if (!x) return json({ error: `org.yaml has no connector ${id}` }, 400);
8941
+ const brains = (org.staff ?? []).map((s) => `${portal.org}/${s.dir ?? s.handle}`);
8942
+ for (const s of x.secrets) await deleteSecret(actor.gh, portal.org, s.name, brains);
8943
+ if (x.auth === "oauth" && portal.grants) await dropGrant(portal.grants.store, id);
8944
+ const before = portal.snapshots.get(`${portal.org}/${portal.opsName}`)?.files.get("org.yaml")?.text ?? "";
8945
+ const committed = await commitFile(
8946
+ portal,
8947
+ actor.gh,
8948
+ portal.opsName,
8949
+ "org.yaml",
8950
+ setConnector(before, org, id, null),
8951
+ `portal: disconnect ${x.name}`,
8952
+ before
8953
+ );
8954
+ return json({ ok: true, committed });
8955
+ },
8956
+ /* The start of a sign-in: where to send the person, and a sealed note of what they asked for. */
8957
+ "/api/connectors/signin": async (c) => {
8958
+ const { portal, actor } = c;
8959
+ if (!actor.canWrite) return refuse();
8960
+ if (!portal.grants) {
8961
+ return json(
8962
+ { error: "Signing in to a service needs the hosted portal, with a store for sign-ins." },
8963
+ 400
8964
+ );
8965
+ }
8966
+ const p = await body(c.req);
8967
+ const id = String(p.id ?? "");
8968
+ const known = CATALOGUE2[id];
8969
+ if (!known?.oauth) return json({ error: `${id} does not sign in` }, 400);
8970
+ const { org } = await ready(c);
8971
+ const handles = new Set((org.staff ?? []).map((s) => String(s.handle)));
8972
+ const staff = (p.staff ?? []).map(String).filter((h) => handles.has(h));
8973
+ if (!staff.length) return json({ error: "Pick at least one staff member." }, 400);
8974
+ const redirect = `${portal.grants.base}/connectors/callback`;
8975
+ const meta = await discover(known.oauth.resource);
8976
+ const client = await clientFor(
8977
+ meta,
8978
+ redirect,
8979
+ `Roster (${portal.org})`,
8980
+ portal.grants.store
8981
+ );
8982
+ const v = verifier();
8983
+ const state = verifier();
8984
+ const pending2 = await sealJson(
8985
+ {
8986
+ kind: "connector",
8987
+ id,
8988
+ staff,
8989
+ readOnly: p.readOnly === true,
8990
+ verifier: v,
8991
+ state,
8992
+ tokenEndpoint: meta.token_endpoint,
8993
+ ...client,
8994
+ exp: Date.now() + 6e5
8995
+ },
8996
+ portal.grants.secret
8997
+ );
8998
+ const go = new URL(meta.authorization_endpoint);
8999
+ for (const [k, val] of Object.entries({
9000
+ response_type: "code",
9001
+ client_id: client.clientId,
9002
+ redirect_uri: redirect,
9003
+ code_challenge: await challenge(v),
9004
+ code_challenge_method: "S256",
9005
+ state,
9006
+ resource: known.oauth.resource
9007
+ })) {
9008
+ go.searchParams.set(k, val);
9009
+ }
9010
+ return new Response(JSON.stringify({ url: go.toString() }), {
9011
+ headers: {
9012
+ "content-type": JSON_TYPE,
9013
+ "cache-control": "no-store",
9014
+ "set-cookie": `roster_connector=${pending2}; Path=/connectors/callback; HttpOnly; Secure; SameSite=Lax; Max-Age=600`
9015
+ }
9016
+ });
9017
+ },
9018
+ /* Where the service sends the person back. The sealed note from the start is the write guard:
9019
+ only a sign-in this page began, for this person, in the last ten minutes, lands. */
9020
+ "/connectors/callback": async (c) => {
9021
+ const { portal, actor, req, url } = c;
9022
+ if (!portal.grants) return notFound();
9023
+ const back = (msg) => new Response(null, {
9024
+ status: 302,
9025
+ headers: {
9026
+ location: `/#/-/connectors${msg ? `?e=${encodeURIComponent(msg)}` : ""}`,
9027
+ "set-cookie": "roster_connector=; Path=/connectors/callback; Max-Age=0"
9028
+ }
9029
+ });
9030
+ const raw = /(?:^|;\s*)roster_connector=([^;]+)/.exec(req.headers.get("cookie") ?? "")?.[1];
9031
+ const pending2 = raw ? await openJson(raw, portal.grants.secret) : null;
9032
+ if (pending2?.kind !== "connector" || pending2.exp < Date.now()) {
9033
+ return back("The sign-in took too long. Try again.");
9034
+ }
9035
+ if (url.searchParams.get("state") !== pending2.state)
9036
+ return back("The sign-in did not match. Try again.");
9037
+ const code = url.searchParams.get("code");
9038
+ if (!code)
9039
+ return back(url.searchParams.get("error_description") ?? "The sign-in was cancelled.");
9040
+ const known = CATALOGUE2[pending2.id];
9041
+ if (!known?.oauth) return back("That service is not one roster signs in to.");
9042
+ try {
9043
+ const grant = await exchange2({
9044
+ connector: pending2.id,
9045
+ resource: known.oauth.resource,
9046
+ tokenEndpoint: pending2.tokenEndpoint,
9047
+ clientId: pending2.clientId,
9048
+ clientSecret: pending2.clientSecret,
9049
+ code,
9050
+ verifier: pending2.verifier,
9051
+ redirectUri: `${portal.grants.base}/connectors/callback`,
9052
+ by: actor.id
9053
+ });
9054
+ await writeGrant(portal.grants.store, portal.grants.secret, grant);
9055
+ const { org } = await ready(c, { force: true });
9056
+ const before = portal.snapshots.get(`${portal.org}/${portal.opsName}`)?.files.get("org.yaml")?.text ?? "";
9057
+ const after = setConnector(before, org, pending2.id, {
9058
+ staff: pending2.staff,
9059
+ read_only: pending2.readOnly,
9060
+ portal: portal.grants.base
9061
+ });
9062
+ await commitFile(
9063
+ portal,
9064
+ actor.gh,
9065
+ portal.opsName,
9066
+ "org.yaml",
9067
+ after,
9068
+ `portal: connect ${known.name}`,
9069
+ before
9070
+ );
9071
+ } catch (err) {
9072
+ return back(err.message);
9073
+ }
9074
+ return back("");
9075
+ },
8187
9076
  /* Acting on GitHub as the person: reply, close, reopen, open, approve, merge, ask. */
8188
9077
  "/api/act": async (c) => {
8189
9078
  const { req, portal, actor } = c;
@@ -8197,6 +9086,15 @@ var ROUTES = {
8197
9086
  if (payload.action === "ask" && !known.includes(payload.ask?.pr?.repo ?? "")) {
8198
9087
  return json({ error: `${payload.ask?.pr?.repo ?? ""} is not a repo in org.yaml` }, 400);
8199
9088
  }
9089
+ const handles = (org.staff ?? []).map((s) => String(s.handle));
9090
+ if (isViewOnly(org, actor.id) && wouldWake(payload, handles)) {
9091
+ return json(
9092
+ {
9093
+ error: "You are view-only in org.yaml, so this would not reach the staff. Nothing was posted."
9094
+ },
9095
+ 403
9096
+ );
9097
+ }
8200
9098
  try {
8201
9099
  const result = await act(actor.gh, payload);
8202
9100
  portal.caches.inbox.delete(actor.id);
@@ -8454,8 +9352,8 @@ ${diff}`,
8454
9352
  const { req, url, portal, actor } = c;
8455
9353
  await ready(c, { products: true });
8456
9354
  const rel = url.searchParams.get("path") ?? "";
8457
- const full = resolve6(portal.ws.root, rel);
8458
- if (!full.startsWith(`${resolve6(portal.ws.root)}/`) || !existsSync2(full)) return notFound();
9355
+ const full = resolve5(portal.ws.root, rel);
9356
+ if (!full.startsWith(`${resolve5(portal.ws.root)}/`) || !existsSync2(full)) return notFound();
8459
9357
  const st = statSync2(full);
8460
9358
  if (st.isDirectory()) return notFound();
8461
9359
  const inside = full.slice(portal.ws.root.length + 1);
@@ -8467,8 +9365,8 @@ ${diff}`,
8467
9365
  bytes2 = new Uint8Array(readFileSync2(full));
8468
9366
  } catch {
8469
9367
  const snap = portal.snapshots.get(`${portal.org}/${dir}`);
8470
- const key = `${dir}@${snap?.sha}:${path}`;
8471
- let got = portal.caches.files.get(key);
9368
+ const key2 = `${dir}@${snap?.sha}:${path}`;
9369
+ let got = portal.caches.files.get(key2);
8472
9370
  if (!got) {
8473
9371
  const res = await actor.gh.request(
8474
9372
  "GET",
@@ -8477,7 +9375,7 @@ ${diff}`,
8477
9375
  );
8478
9376
  if (!res.ok || !res.data) return json({ error: res.error }, 502);
8479
9377
  got = res.data;
8480
- remember(portal.caches.files, key, got);
9378
+ remember(portal.caches.files, key2, got);
8481
9379
  }
8482
9380
  bytes2 = got;
8483
9381
  }
@@ -8510,18 +9408,18 @@ ${diff}`,
8510
9408
  return new Response(bytes2, { headers: { "content-type": type, "cache-control": "no-store" } });
8511
9409
  }
8512
9410
  };
8513
- async function orgExport(c, report3) {
9411
+ async function orgExport(c, report4) {
8514
9412
  const { portal, actor } = c;
8515
- const { org, brains } = await ready(c, { report: report3 });
9413
+ const { org, brains } = await ready(c, { report: report4 });
8516
9414
  const byRoot = /* @__PURE__ */ new Map();
8517
9415
  await Promise.all(
8518
9416
  brains.map(async (dir) => {
8519
9417
  const repo = `${portal.org}/${dir}`;
8520
9418
  const snap = portal.snapshots.get(repo);
8521
9419
  if (!snap) return;
8522
- report3?.(repo, "reading recent history");
9420
+ report4?.(repo, "reading recent history");
8523
9421
  byRoot.set(join29(portal.ws.root, dir), await loadHistory(actor.gh, portal.kv, repo, snap.sha));
8524
- report3?.(repo, "ready");
9422
+ report4?.(repo, "ready");
8525
9423
  })
8526
9424
  );
8527
9425
  const data = buildExport(portal.ws, org, parseYaml2, { history: loadedHistory(byRoot) });
@@ -8594,7 +9492,7 @@ async function commitFile(portal, gh, dir, path, body2, message2, base2) {
8594
9492
  };
8595
9493
  }
8596
9494
  async function upload(gh, repo, name, data) {
8597
- const bytes2 = fromBase64(data);
9495
+ const bytes2 = fromBase642(data);
8598
9496
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
8599
9497
  const listing = await gh.request(
8600
9498
  "GET",
@@ -8686,14 +9584,14 @@ function base64(bytes2) {
8686
9584
  }
8687
9585
  return btoa(s);
8688
9586
  }
8689
- function fromBase64(data) {
9587
+ function fromBase642(data) {
8690
9588
  const s = atob(data);
8691
9589
  const out = new Uint8Array(s.length);
8692
9590
  for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
8693
9591
  return out;
8694
9592
  }
8695
- function remember(map, key, bytes2) {
8696
- map.set(key, bytes2);
9593
+ function remember(map, key2, bytes2) {
9594
+ map.set(key2, bytes2);
8697
9595
  let total = 0;
8698
9596
  for (const v of map.values()) total += v.length;
8699
9597
  for (const k of map.keys()) {
@@ -8742,27 +9640,27 @@ var MIME = {
8742
9640
  function memoryKV(limit = 2e4) {
8743
9641
  const map = /* @__PURE__ */ new Map();
8744
9642
  return {
8745
- async get(key) {
8746
- return map.get(key);
9643
+ async get(key2) {
9644
+ return map.get(key2);
8747
9645
  },
8748
- async put(key, value) {
8749
- map.set(key, value);
9646
+ async put(key2, value) {
9647
+ map.set(key2, value);
8750
9648
  if (map.size > limit) map.delete(map.keys().next().value);
8751
9649
  }
8752
9650
  };
8753
9651
  }
8754
9652
  function layeredKV(slow, fast = memoryKV()) {
8755
9653
  return {
8756
- async get(key) {
8757
- const hit = await fast.get(key);
9654
+ async get(key2) {
9655
+ const hit = await fast.get(key2);
8758
9656
  if (hit !== void 0) return hit;
8759
- const found = await slow.get(key).catch(() => void 0);
8760
- if (found !== void 0) await fast.put(key, found);
9657
+ const found = await slow.get(key2).catch(() => void 0);
9658
+ if (found !== void 0) await fast.put(key2, found);
8761
9659
  return found;
8762
9660
  },
8763
- async put(key, value) {
8764
- await fast.put(key, value);
8765
- await slow.put(key, value).catch(() => {
9661
+ async put(key2, value) {
9662
+ await fast.put(key2, value);
9663
+ await slow.put(key2, value).catch(() => {
8766
9664
  });
8767
9665
  }
8768
9666
  };
@@ -8770,23 +9668,23 @@ function layeredKV(slow, fast = memoryKV()) {
8770
9668
 
8771
9669
  // src/portal/kv-disk.ts
8772
9670
  import { createHash } from "crypto";
8773
- import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync11, writeFileSync as writeFileSync10 } from "fs";
9671
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "fs";
8774
9672
  import { homedir } from "os";
8775
9673
  import { join as join30 } from "path";
8776
9674
  function diskKV(dir = defaultDir()) {
8777
- const path = (key) => {
8778
- const h = createHash("sha1").update(key).digest("hex");
9675
+ const path = (key2) => {
9676
+ const h = createHash("sha1").update(key2).digest("hex");
8779
9677
  return join30(dir, h.slice(0, 2), h.slice(2));
8780
9678
  };
8781
9679
  return {
8782
- async get(key) {
8783
- const p = path(key);
8784
- return existsSync13(p) ? readFileSync11(p, "utf8") : void 0;
9680
+ async get(key2) {
9681
+ const p = path(key2);
9682
+ return existsSync13(p) ? readFileSync12(p, "utf8") : void 0;
8785
9683
  },
8786
- async put(key, value) {
8787
- const p = path(key);
9684
+ async put(key2, value) {
9685
+ const p = path(key2);
8788
9686
  mkdirSync7(join30(p, ".."), { recursive: true });
8789
- writeFileSync10(p, value);
9687
+ writeFileSync11(p, value);
8790
9688
  }
8791
9689
  };
8792
9690
  }
@@ -8795,7 +9693,7 @@ function defaultDir() {
8795
9693
  }
8796
9694
 
8797
9695
  // src/commands/retire.ts
8798
- import { existsSync as existsSync14, readdirSync as readdirSync6, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "fs";
9696
+ import { existsSync as existsSync14, readdirSync as readdirSync6, readFileSync as readFileSync13, writeFileSync as writeFileSync12 } from "fs";
8799
9697
  import { join as join31 } from "path";
8800
9698
  var retireHelp = `
8801
9699
  roster retire <handle>
@@ -8826,7 +9724,7 @@ async function retireCommand(argv) {
8826
9724
  process.stderr.write("roster: retire needs a handle, e.g. `roster retire cmo`\n");
8827
9725
  return 2;
8828
9726
  }
8829
- const opts = parseFlags11(argv.slice(1));
9727
+ const opts = parseFlags12(argv.slice(1));
8830
9728
  const ws = findWorkspace(opts.ops);
8831
9729
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
8832
9730
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -8861,7 +9759,7 @@ function buildRetirePlan(ws, org, handle, parseYaml3) {
8861
9759
  const otherDir = other.dir ?? other.handle;
8862
9760
  const path = join31(ws.root, otherDir, "staff.yaml");
8863
9761
  if (!existsSync14(path)) continue;
8864
- const text2 = readFileSync12(path, "utf8");
9762
+ const text2 = readFileSync13(path, "utf8");
8865
9763
  if (!new RegExp(`handle: ${handle}[,\\s}]`).test(text2)) continue;
8866
9764
  const theirs = readManifest3(join31(ws.root, otherDir), parseYaml3);
8867
9765
  peers.push({
@@ -8930,8 +9828,8 @@ async function applyRetirePlan(ws, plan2) {
8930
9828
  process.stdout.write(" removed from org.yaml\n");
8931
9829
  for (const p of plan2.peers) {
8932
9830
  const path = join31(ws.root, p.dir, "staff.yaml");
8933
- const text2 = readFileSync12(path, "utf8");
8934
- writeFileSync11(path, removePeerLine(text2, plan2.handle));
9831
+ const text2 = readFileSync13(path, "utf8");
9832
+ writeFileSync12(path, removePeerLine(text2, plan2.handle));
8935
9833
  process.stdout.write(` removed from ${p.dir}/staff.yaml
8936
9834
  `);
8937
9835
  if (!p.brain) continue;
@@ -8958,8 +9856,8 @@ async function applyRetirePlan(ws, plan2) {
8958
9856
  }
8959
9857
  function removeFromOrgYaml(ws, plan2) {
8960
9858
  const path = join31(ws.opsDir, "org.yaml");
8961
- const text2 = readFileSync12(path, "utf8");
8962
- writeFileSync11(path, removeOrgLines(text2, plan2.handle, plan2.dir));
9859
+ const text2 = readFileSync13(path, "utf8");
9860
+ writeFileSync12(path, removeOrgLines(text2, plan2.handle, plan2.dir));
8963
9861
  }
8964
9862
  function removeOrgLines(text2, handle, dir) {
8965
9863
  return text2.split("\n").filter((line) => {
@@ -8980,16 +9878,16 @@ function readManifest3(root2, parseYaml3) {
8980
9878
  const path = join31(root2, "staff.yaml");
8981
9879
  if (!existsSync14(path)) return null;
8982
9880
  try {
8983
- return parseYaml3(readFileSync12(path, "utf8"), "staff.yaml");
9881
+ return parseYaml3(readFileSync13(path, "utf8"), "staff.yaml");
8984
9882
  } catch {
8985
9883
  return null;
8986
9884
  }
8987
9885
  }
8988
9886
  function countFacts(indexPath) {
8989
9887
  if (!existsSync14(indexPath)) return 0;
8990
- return (readFileSync12(indexPath, "utf8").match(/^- \*\*`/gm) ?? []).length;
9888
+ return (readFileSync13(indexPath, "utf8").match(/^- \*\*`/gm) ?? []).length;
8991
9889
  }
8992
- function parseFlags11(argv) {
9890
+ function parseFlags12(argv) {
8993
9891
  const out = {};
8994
9892
  for (let i = 0; i < argv.length; i++) {
8995
9893
  const flag = argv[i];
@@ -9036,10 +9934,10 @@ var pendingApps = /* @__PURE__ */ new Map();
9036
9934
  var appResults = /* @__PURE__ */ new Map();
9037
9935
  async function portalCommand(argv) {
9038
9936
  if (argv[0] === "deploy") return deployCommand(argv.slice(1));
9039
- const opts = parseFlags12(argv);
9937
+ const opts = parseFlags13(argv);
9040
9938
  let port = opts.port ?? 4300;
9041
9939
  const host = opts.host ?? "127.0.0.1";
9042
- const startedIn = resolve7(opts.ops ?? opts.dir ?? process.cwd());
9940
+ const startedIn = resolve6(opts.ops ?? opts.dir ?? process.cwd());
9043
9941
  let ws = tryWorkspace(startedIn);
9044
9942
  let composer = ws ? await loadComposer(ws.opsDir) : await loadFrameworkComposer();
9045
9943
  const _compose = (...args) => composer.compose(...args);
@@ -9135,7 +10033,7 @@ async function portalCommand(argv) {
9135
10033
  }
9136
10034
  const dir = entry.dir ?? entry.handle;
9137
10035
  const spec2 = specFromManifest(
9138
- parseYaml3(readFileSync13(join32(ws.root, dir, "staff.yaml"), "utf8"), "staff.yaml"),
10036
+ parseYaml3(readFileSync14(join32(ws.root, dir, "staff.yaml"), "utf8"), "staff.yaml"),
9139
10037
  dir
9140
10038
  );
9141
10039
  const isPublic = payload.scope === "public";
@@ -9289,7 +10187,7 @@ async function portalCommand(argv) {
9289
10187
  res.writeHead(400).end("bad request");
9290
10188
  return;
9291
10189
  }
9292
- const list = await ghJson([
10190
+ const list2 = await ghJson([
9293
10191
  "repo",
9294
10192
  "list",
9295
10193
  org,
@@ -9299,8 +10197,8 @@ async function portalCommand(argv) {
9299
10197
  "name,visibility,description"
9300
10198
  ]);
9301
10199
  json2(res, {
9302
- repos: list.ok ? list.data ?? [] : [],
9303
- error: list.ok ? void 0 : list.error
10200
+ repos: list2.ok ? list2.data ?? [] : [],
10201
+ error: list2.ok ? void 0 : list2.error
9304
10202
  });
9305
10203
  return;
9306
10204
  }
@@ -9319,7 +10217,7 @@ async function portalCommand(argv) {
9319
10217
  return;
9320
10218
  }
9321
10219
  const path = join32(ws.opsDir, "org.yaml");
9322
- const text2 = readFileSync13(path, "utf8");
10220
+ const text2 = readFileSync14(path, "utf8");
9323
10221
  if (new RegExp(`name: ${name}[,\\s}]`).test(text2)) {
9324
10222
  json2(res, { ok: true, note: "already there" });
9325
10223
  return;
@@ -9391,13 +10289,13 @@ async function portalCommand(argv) {
9391
10289
  }
9392
10290
  res.writeHead(404).end("not found");
9393
10291
  };
9394
- const body2 = (req, limit = 1e6) => new Promise((resolve8, reject) => {
10292
+ const body2 = (req, limit = 1e6) => new Promise((resolve7, reject) => {
9395
10293
  let buf = "";
9396
10294
  req.on("data", (c) => {
9397
10295
  buf += c;
9398
10296
  if (buf.length > limit) reject(new Error("body too large"));
9399
10297
  });
9400
- req.on("end", () => resolve8(buf));
10298
+ req.on("end", () => resolve7(buf));
9401
10299
  req.on("error", reject);
9402
10300
  });
9403
10301
  const server = createServer2((req, res) => {
@@ -9484,7 +10382,7 @@ async function portalCommand(argv) {
9484
10382
  return;
9485
10383
  }
9486
10384
  if (url.pathname === "/api/doctor") {
9487
- collect({ ops: ws?.opsDir, offline: url.searchParams.get("offline") === "1" }).then((report3) => json2(res, report3 ?? { findings: [], online: false, empty: true }, true)).catch((err) => {
10385
+ collect({ ops: ws?.opsDir, offline: url.searchParams.get("offline") === "1" }).then((report4) => json2(res, report4 ?? { findings: [], online: false, empty: true }, true)).catch((err) => {
9488
10386
  res.writeHead(200, { "content-type": "application/json" });
9489
10387
  res.end(JSON.stringify({ findings: [], error: String(err?.message ?? err) }));
9490
10388
  });
@@ -9667,7 +10565,7 @@ function capture() {
9667
10565
  text: () => chunks.join("")
9668
10566
  };
9669
10567
  }
9670
- function parseFlags12(argv) {
10568
+ function parseFlags13(argv) {
9671
10569
  const out = {};
9672
10570
  for (let i = 0; i < argv.length; i++) {
9673
10571
  const flag = argv[i];
@@ -9688,7 +10586,7 @@ function parseFlags12(argv) {
9688
10586
  return out;
9689
10587
  }
9690
10588
  function bytes(req) {
9691
- return new Promise((resolve8, reject) => {
10589
+ return new Promise((resolve7, reject) => {
9692
10590
  const chunks = [];
9693
10591
  let size2 = 0;
9694
10592
  req.on("data", (c) => {
@@ -9696,7 +10594,7 @@ function bytes(req) {
9696
10594
  if (size2 > Math.ceil(MAX_UPLOAD * 1.4) + 1e6) reject(new Error("body too large"));
9697
10595
  else chunks.push(c);
9698
10596
  });
9699
- req.on("end", () => resolve8(Buffer.concat(chunks)));
10597
+ req.on("end", () => resolve7(Buffer.concat(chunks)));
9700
10598
  req.on("error", reject);
9701
10599
  });
9702
10600
  }
@@ -9707,14 +10605,14 @@ function signedOut(error) {
9707
10605
 
9708
10606
  // src/commands/prompt.ts
9709
10607
  import { execFileSync as execFileSync9 } from "child_process";
9710
- import { existsSync as existsSync15, mkdtempSync as mkdtempSync5, readFileSync as readFileSync15, writeFileSync as writeFileSync12 } from "fs";
10608
+ import { existsSync as existsSync15, mkdtempSync as mkdtempSync5, readFileSync as readFileSync16, writeFileSync as writeFileSync13 } from "fs";
9711
10609
  import { tmpdir as tmpdir5 } from "os";
9712
10610
  import { join as join33 } from "path";
9713
10611
 
9714
10612
  // src/lib/livePrompt.ts
9715
- import { readFileSync as readFileSync14 } from "fs";
10613
+ import { readFileSync as readFileSync15 } from "fs";
9716
10614
  function extractLivePrompt(workflowPath) {
9717
- const lines = readFileSync14(workflowPath, "utf8").split("\n");
10615
+ const lines = readFileSync15(workflowPath, "utf8").split("\n");
9718
10616
  const start = lines.findIndex((l) => /^\s*prompt:\s*\|/.test(l));
9719
10617
  if (start === -1) throw new Error(`no "prompt: |" block in ${workflowPath}`);
9720
10618
  const blockIndent = (lines[start].match(/^\s*/)?.[0].length ?? 0) + 2;
@@ -9754,7 +10652,7 @@ async function promptCommand(argv) {
9754
10652
  process.stderr.write(promptHelp);
9755
10653
  return 2;
9756
10654
  }
9757
- const opts = parseFlags13(argv.slice(1));
10655
+ const opts = parseFlags14(argv.slice(1));
9758
10656
  const ws = findWorkspace(opts.ops);
9759
10657
  const { compose: compose3, parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
9760
10658
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -9778,8 +10676,8 @@ async function promptCommand(argv) {
9778
10676
  const dir = mkdtempSync5(join33(tmpdir5(), "roster-diff-"));
9779
10677
  const a = join33(dir, "live.md");
9780
10678
  const b = join33(dir, "composed.md");
9781
- writeFileSync12(a, normalise(live));
9782
- writeFileSync12(b, normalise(composed));
10679
+ writeFileSync13(a, normalise(live));
10680
+ writeFileSync13(b, normalise(composed));
9783
10681
  const entry = org.staff?.find((s) => s.handle === handle);
9784
10682
  process.stdout.write(`
9785
10683
  ${entry?.name ?? handle} \xB7 ${kind}
@@ -9812,16 +10710,16 @@ async function gatherInflight(opsDir, root2, handle) {
9812
10710
  const org = readOrg(opsDir, parseYaml3);
9813
10711
  const entry = org.staff?.find((s) => s.handle === handle);
9814
10712
  const manifestPath = join33(root2, entry?.dir ?? handle, "staff.yaml");
9815
- const manifest = existsSync15(manifestPath) ? parseYaml3(readFileSync15(manifestPath, "utf8"), "staff.yaml") : {};
10713
+ const manifest = existsSync15(manifestPath) ? parseYaml3(readFileSync16(manifestPath, "utf8"), "staff.yaml") : {};
9816
10714
  const gh = (args) => execFileSync9("gh", args, { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
9817
10715
  const dir = mkdtempSync5(join33(tmpdir5(), "roster-inflight-"));
9818
- writeFileSync12(join33(dir, "inflight.md"), describe2(gather2({ org, manifest, gh })));
10716
+ writeFileSync13(join33(dir, "inflight.md"), describe2(gather2({ org, manifest, gh })));
9819
10717
  return dir;
9820
10718
  }
9821
10719
  function normalise(text2) {
9822
10720
  return text2.split("\n").map((l) => l.replace(/\s+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
9823
10721
  }
9824
- function parseFlags13(argv) {
10722
+ function parseFlags14(argv) {
9825
10723
  const out = {};
9826
10724
  for (let i = 0; i < argv.length; i++) {
9827
10725
  const flag = argv[i];
@@ -9844,7 +10742,7 @@ function parseFlags13(argv) {
9844
10742
  }
9845
10743
 
9846
10744
  // src/commands/run.ts
9847
- import { existsSync as existsSync16, readFileSync as readFileSync16 } from "fs";
10745
+ import { existsSync as existsSync16, readFileSync as readFileSync17 } from "fs";
9848
10746
  import { join as join34 } from "path";
9849
10747
  var runHelp = `
9850
10748
  roster run <handle> [--no-wait] [--apply]
@@ -9870,7 +10768,7 @@ async function runCommand(argv) {
9870
10768
  process.stderr.write("roster: run needs a staff handle, e.g. `roster run cto`\n");
9871
10769
  return 2;
9872
10770
  }
9873
- const opts = parseFlags14(argv.slice(1));
10771
+ const opts = parseFlags15(argv.slice(1));
9874
10772
  const ws = findWorkspace(opts.ops);
9875
10773
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
9876
10774
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -9888,7 +10786,7 @@ async function runCommand(argv) {
9888
10786
  return 2;
9889
10787
  }
9890
10788
  const spec2 = specFromManifest(
9891
- parseYaml3(readFileSync16(manifestPath, "utf8"), "staff.yaml"),
10789
+ parseYaml3(readFileSync17(manifestPath, "utf8"), "staff.yaml"),
9892
10790
  dir
9893
10791
  );
9894
10792
  const workflow = dailyWorkflow(handle);
@@ -9967,7 +10865,7 @@ async function runCommand(argv) {
9967
10865
  );
9968
10866
  return 1;
9969
10867
  }
9970
- function parseFlags14(argv) {
10868
+ function parseFlags15(argv) {
9971
10869
  const out = {};
9972
10870
  for (let i = 0; i < argv.length; i++) {
9973
10871
  const flag = argv[i];
@@ -9983,7 +10881,7 @@ function parseFlags14(argv) {
9983
10881
  }
9984
10882
 
9985
10883
  // src/lib/runstore.ts
9986
- import { existsSync as existsSync17, mkdirSync as mkdirSync8, readFileSync as readFileSync17, writeFileSync as writeFileSync13 } from "fs";
10884
+ import { existsSync as existsSync17, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync14 } from "fs";
9987
10885
  import { homedir as homedir2 } from "os";
9988
10886
  import { join as join35 } from "path";
9989
10887
  function diskRecordStore(dir = defaultDir2()) {
@@ -9992,11 +10890,11 @@ function diskRecordStore(dir = defaultDir2()) {
9992
10890
  async get(brain, id) {
9993
10891
  const path = file(brain, id);
9994
10892
  if (!existsSync17(path)) return void 0;
9995
- return JSON.parse(readFileSync17(path, "utf8"));
10893
+ return JSON.parse(readFileSync18(path, "utf8"));
9996
10894
  },
9997
10895
  async put(brain, id, value) {
9998
10896
  mkdirSync8(join35(dir, brain.replace("/", "__")), { recursive: true });
9999
- writeFileSync13(file(brain, id), JSON.stringify(value));
10897
+ writeFileSync14(file(brain, id), JSON.stringify(value));
10000
10898
  }
10001
10899
  };
10002
10900
  }
@@ -10018,6 +10916,7 @@ roster \u2014 an agent-run org, powered by GitHub
10018
10916
  roster hire <handle> scaffold a new staff member
10019
10917
  roster app <handle> create their GitHub App and set its secrets
10020
10918
  roster credential store the agent's credential, once for the org
10919
+ roster connector give staff an outside service: Sentry, Linear, Stripe\u2026
10021
10920
  roster run <handle> start one daily run now, and follow it to the end
10022
10921
  roster retire <handle> stop a staff member, keeping their repo and their memory
10023
10922
  roster upgrade carry framework changes into this tenant
@@ -10038,6 +10937,7 @@ var COMMANDS = {
10038
10937
  hire: hireCommand,
10039
10938
  app: appCommand,
10040
10939
  credential: credentialCommand,
10940
+ connector: connectorCommand,
10041
10941
  run: runCommand,
10042
10942
  retire: retireCommand,
10043
10943
  portal: portalCommand,
@@ -10054,13 +10954,14 @@ var HELPS = {
10054
10954
  hire: hireHelp,
10055
10955
  app: appHelp,
10056
10956
  credential: credentialHelp,
10957
+ connector: connectorHelp,
10057
10958
  run: runHelp,
10058
10959
  retire: retireHelp,
10059
10960
  portal: portalHelp,
10060
10961
  deploy: deployHelp,
10061
10962
  export: exportHelp
10062
10963
  };
10063
- async function main2(argv) {
10964
+ async function main(argv) {
10064
10965
  const raw = rewriteOutput();
10065
10966
  useRecordStore(diskRecordStore());
10066
10967
  const [command, ...rest] = argv;
@@ -10092,7 +10993,7 @@ ${HELP}`);
10092
10993
  }
10093
10994
  return run4(rest);
10094
10995
  }
10095
- main2(process.argv.slice(2)).then((code) => process.exit(code)).catch((err) => {
10996
+ main(process.argv.slice(2)).then((code) => process.exit(code)).catch((err) => {
10096
10997
  process.stderr.write(`roster: ${err instanceof Error ? err.message : String(err)}
10097
10998
  `);
10098
10999
  process.exit(1);