@nanocollective/roster 0.1.0-beta.14 → 0.1.0-beta.16

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 +1703 -820
  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 +2743 -1014
  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 +5 -1
  22. package/docs/export.md +1 -1
  23. package/docs/extending.md +1 -1
  24. package/docs/hosting.md +13 -1
  25. package/docs/memory.md +1 -1
  26. package/docs/org-yaml.md +25 -1
  27. package/docs/portal.md +18 -1
  28. package/docs/prompts.md +1 -1
  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 +12 -0
  41. package/templates/ops/connectors.mjs +722 -0
  42. package/templates/ops/prompts/_identity.md +14 -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) {
@@ -1388,13 +1398,13 @@ function validateOrgYaml(text2, parseYaml3) {
1388
1398
  return `that is not YAML compose.mjs can read: ${err.message}`;
1389
1399
  }
1390
1400
  if (!doc || typeof doc !== "object") return "org.yaml has to be a mapping";
1391
- for (const key of ["org", "name"]) {
1392
- if (!doc[key] || typeof doc[key] !== "string") {
1393
- 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`;
1394
1404
  }
1395
1405
  }
1396
- for (const key of ["staff", "repos", "humans"]) {
1397
- 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`;
1398
1408
  }
1399
1409
  for (const s of doc.staff ?? []) {
1400
1410
  if (!s?.handle) return "every staff entry needs a handle";
@@ -1569,6 +1579,575 @@ function parseFlags2(argv) {
1569
1579
  return out;
1570
1580
  }
1571
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
+
1572
2151
  // src/lib/credential.ts
1573
2152
  async function planCredential(org, name, brains, opts = {}, gh = api) {
1574
2153
  const base2 = { name, org, brains };
@@ -1635,7 +2214,7 @@ function repoName(full) {
1635
2214
  }
1636
2215
 
1637
2216
  // src/lib/setup.ts
1638
- import { execFile as execFile3 } from "child_process";
2217
+ import { execFile as execFile4 } from "child_process";
1639
2218
  import { mkdirSync } from "fs";
1640
2219
  import { join as join12 } from "path";
1641
2220
  var AGENTS = [
@@ -1678,13 +2257,13 @@ async function setupStatus(startedIn) {
1678
2257
  const ready2 = await ghReady();
1679
2258
  let orgs = [];
1680
2259
  if (ready2.ok) {
1681
- const list = await ghJson([
2260
+ const list2 = await ghJson([
1682
2261
  "api",
1683
2262
  "user/orgs?per_page=100",
1684
2263
  "--jq",
1685
2264
  "[.[] | {login}]"
1686
2265
  ]);
1687
- if (list.ok) orgs = (list.data ?? []).map((o) => o.login).sort();
2266
+ if (list2.ok) orgs = (list2.data ?? []).map((o) => o.login).sort();
1688
2267
  }
1689
2268
  return {
1690
2269
  tenant: found ? {
@@ -1725,11 +2304,11 @@ function readProducts(opsDir) {
1725
2304
  }
1726
2305
  return out;
1727
2306
  }
1728
- function readBlockNames(opsDir, block, key) {
2307
+ function readBlockNames(opsDir, block, key2) {
1729
2308
  const path = join12(opsDir, "org.yaml");
1730
2309
  if (!existsSync2(path)) return [];
1731
2310
  const names = [];
1732
- const pattern = new RegExp(`\\b${key}:\\s*([\\w.-]+)`);
2311
+ const pattern = new RegExp(`\\b${key2}:\\s*([\\w.-]+)`);
1733
2312
  let inside = false;
1734
2313
  for (const line of readFileSync2(path, "utf8").split("\n")) {
1735
2314
  if (new RegExp(`^${block}:\\s*$`).test(line)) {
@@ -1787,7 +2366,7 @@ async function joinTenant(root2, org) {
1787
2366
  }
1788
2367
  function clone(url, into) {
1789
2368
  return new Promise((ok, fail) => {
1790
- execFile3("git", ["clone", "-q", url, into], (err) => err ? fail(err) : ok());
2369
+ execFile4("git", ["clone", "-q", url, into], (err) => err ? fail(err) : ok());
1791
2370
  });
1792
2371
  }
1793
2372
 
@@ -1804,36 +2383,6 @@ function askKinds(labels) {
1804
2383
  return labels.filter((l) => ASK_KINDS.includes(l));
1805
2384
  }
1806
2385
 
1807
- // src/lib/commit.ts
1808
- import { execFileSync as execFileSync2 } from "child_process";
1809
- function commitAndPush(repoDir, paths, message2) {
1810
- const git4 = (args) => execFileSync2("git", ["-C", repoDir, ...args], {
1811
- encoding: "utf8",
1812
- stdio: ["ignore", "pipe", "pipe"]
1813
- });
1814
- try {
1815
- if (!git4(["status", "--porcelain", "--", ...paths]).trim()) {
1816
- return { committed: false, pushed: false, note: "nothing to commit" };
1817
- }
1818
- git4(["add", "--", ...paths]);
1819
- git4(["commit", "-q", "-m", message2, "--", ...paths]);
1820
- } catch (err) {
1821
- return { committed: false, pushed: false, note: short2(err) };
1822
- }
1823
- const sha = git4(["rev-parse", "--short", "HEAD"]).trim();
1824
- try {
1825
- git4(["push", "-q"]);
1826
- } catch (err) {
1827
- return { committed: true, pushed: false, sha, note: short2(err) };
1828
- }
1829
- return { committed: true, pushed: true, sha };
1830
- }
1831
- function short2(e) {
1832
- const msg = e instanceof Error ? e.stderr?.toString() || e.message : String(e);
1833
- const line = msg.split("\n").find((l) => l.trim()) ?? msg;
1834
- return line.length > 200 ? line.slice(0, 199) + "\u2026" : line;
1835
- }
1836
-
1837
2386
  // src/lib/reviewgate.ts
1838
2387
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
1839
2388
  import { tmpdir } from "os";
@@ -2360,6 +2909,20 @@ async function applyPlan(ws, plan2, opts) {
2360
2909
  process.stdout.write(` ${shared.note}
2361
2910
  `);
2362
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
+ }
2363
2926
  git(root2, ["init", "-q", "-b", "main"]);
2364
2927
  git(root2, ["add", "-A"]);
2365
2928
  git(root2, ["commit", "-q", "-m", `roster: scaffold ${staff.name}`]);
@@ -2499,15 +3062,15 @@ function addToOrgYaml(ws, plan2) {
2499
3062
  const withStaff = insertUnder(text2, "staff", staffLine);
2500
3063
  writeFileSync3(path, insertUnder(withStaff, "repos", repoLine));
2501
3064
  }
2502
- function insertUnder(text2, key, line) {
2503
- const empty = new RegExp(`^${key}:\\s*\\[\\]\\s*$`, "m");
2504
- 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}:
2505
3068
  ${line.trimEnd()}`);
2506
- const heading = new RegExp(`^${key}:\\s*$`, "m");
3069
+ const heading = new RegExp(`^${key2}:\\s*$`, "m");
2507
3070
  const m = heading.exec(text2);
2508
3071
  if (!m) return `${text2.trimEnd()}
2509
3072
 
2510
- ${key}:
3073
+ ${key2}:
2511
3074
  ${line.trimEnd()}
2512
3075
  `;
2513
3076
  const lines = text2.split("\n");
@@ -2689,18 +3252,18 @@ function howTo(org) {
2689
3252
  function readSecret(prompt) {
2690
3253
  const stdin = process.stdin;
2691
3254
  if (!stdin.isTTY) {
2692
- return new Promise((resolve8, reject) => {
3255
+ return new Promise((resolve7, reject) => {
2693
3256
  let buf = "";
2694
3257
  stdin.setEncoding("utf8");
2695
3258
  stdin.on("data", (c) => {
2696
3259
  buf += c;
2697
3260
  });
2698
- stdin.on("end", () => resolve8(buf.trim()));
3261
+ stdin.on("end", () => resolve7(buf.trim()));
2699
3262
  stdin.on("error", reject);
2700
3263
  });
2701
3264
  }
2702
3265
  process.stdout.write(prompt);
2703
- return new Promise((resolve8, reject) => {
3266
+ return new Promise((resolve7, reject) => {
2704
3267
  let buf = "";
2705
3268
  stdin.setRawMode(true);
2706
3269
  stdin.setEncoding("utf8");
@@ -2711,7 +3274,7 @@ function readSecret(prompt) {
2711
3274
  stdin.off("data", onData);
2712
3275
  process.stdout.write("\n");
2713
3276
  if (err) reject(err);
2714
- else resolve8(buf.trim());
3277
+ else resolve7(buf.trim());
2715
3278
  };
2716
3279
  const onData = (chunk) => {
2717
3280
  for (const ch of chunk) {
@@ -2739,12 +3302,244 @@ function parseFlags4(argv) {
2739
3302
  return out;
2740
3303
  }
2741
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
+
2742
3537
  // src/commands/deploy.ts
2743
3538
  import { spawn } from "child_process";
2744
3539
  import { randomBytes as randomBytes2 } from "crypto";
2745
- 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";
2746
3541
  import { tmpdir as tmpdir2 } from "os";
2747
- import { dirname as dirname6, join as join15 } from "path";
3542
+ import { dirname as dirname6, join as join16 } from "path";
2748
3543
  import { createInterface } from "readline/promises";
2749
3544
  import { fileURLToPath as fileURLToPath3 } from "url";
2750
3545
  var deployHelp = `
@@ -2776,15 +3571,15 @@ var CONFIG = "portal/wrangler.jsonc";
2776
3571
  var WORKFLOW = ".github/workflows/portal.yaml";
2777
3572
  var WRANGLER = "wrangler@4";
2778
3573
  async function deployCommand(argv) {
2779
- const opts = parseFlags5(argv);
3574
+ const opts = parseFlags6(argv);
2780
3575
  const ws = findWorkspace(opts.ops);
2781
3576
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
2782
3577
  const org = readOrg(ws.opsDir, parseYaml3);
2783
- const configPath = join15(ws.opsDir, CONFIG);
3578
+ const configPath = join16(ws.opsDir, CONFIG);
2784
3579
  const exists = existsSync6(configPath);
2785
3580
  let config;
2786
3581
  if (exists) {
2787
- config = parseJsonc(readFileSync6(configPath, "utf8"));
3582
+ config = parseJsonc(readFileSync7(configPath, "utf8"));
2788
3583
  if (opts.domain && opts.domain !== domainOf(config)) {
2789
3584
  config.routes = [{ pattern: opts.domain, custom_domain: true }];
2790
3585
  }
@@ -2808,7 +3603,7 @@ async function deployCommand(argv) {
2808
3603
  ` + (config.account_id ? ` account ${config.account_id}
2809
3604
  ` : "") + ` signs in the humans in org.yaml, with GitHub
2810
3605
  ` + (exists ? "" : ` writes ${ws.opsName}/${CONFIG} and ${ws.opsName}/${WORKFLOW}
2811
- `) + (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") + (hasConnectorStore(config) ? "" : " binds a KV namespace for connectors that sign in, such as Notion\n") + ` deploys with ${WRANGLER}, as whoever wrangler is signed in as
2812
3607
 
2813
3608
  `
2814
3609
  );
@@ -2836,24 +3631,40 @@ async function deployCommand(argv) {
2836
3631
  secrets.GITHUB_CLIENT_SECRET = app.secret;
2837
3632
  secrets.SESSION_KEY = randomBytes2(32).toString("base64");
2838
3633
  }
2839
- const tmp = mkdtempSync2(join15(tmpdir2(), "roster-deploy-"));
3634
+ const tmp = mkdtempSync2(join16(tmpdir2(), "roster-deploy-"));
2840
3635
  try {
2841
3636
  const full = {
2842
3637
  ...config,
2843
3638
  main: bundle.main,
2844
3639
  assets: { ...config.assets, directory: bundle.assets }
2845
3640
  };
2846
- writeFileSync4(join15(tmp, "wrangler.json"), JSON.stringify(full, null, 2));
3641
+ writeFileSync5(join16(tmp, "wrangler.json"), JSON.stringify(full, null, 2));
3642
+ if (!hasConnectorStore(config)) {
3643
+ process.stdout.write(" finding the KV namespace for signed-in connectors\u2026\n");
3644
+ const id = await namespaceFor(`${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
+ }
2847
3658
  process.stdout.write(" deploying\u2026\n");
2848
- if (await wrangler(["deploy", "--config", join15(tmp, "wrangler.json")]) !== 0) {
3659
+ if (await wrangler(["deploy", "--config", join16(tmp, "wrangler.json")]) !== 0) {
2849
3660
  process.stderr.write("roster: wrangler could not deploy. Its own message is above.\n");
2850
3661
  return 1;
2851
3662
  }
2852
3663
  if (Object.keys(secrets).length) {
2853
- const file = join15(tmp, "secrets.json");
2854
- writeFileSync4(file, JSON.stringify(secrets), { mode: 384 });
3664
+ const file = join16(tmp, "secrets.json");
3665
+ writeFileSync5(file, JSON.stringify(secrets), { mode: 384 });
2855
3666
  process.stdout.write(" storing the App's secret and a session key on the Worker\u2026\n");
2856
- 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) {
2857
3668
  process.stderr.write("roster: the secrets were not stored. Run this again.\n");
2858
3669
  return 1;
2859
3670
  }
@@ -2863,11 +3674,11 @@ async function deployCommand(argv) {
2863
3674
  }
2864
3675
  if (!opts.ci) {
2865
3676
  mkdirSync3(dirname6(configPath), { recursive: true });
2866
- writeFileSync4(configPath, renderConfig(config));
2867
- const workflow = join15(ws.opsDir, WORKFLOW);
3677
+ writeFileSync5(configPath, renderConfig(config));
3678
+ const workflow = join16(ws.opsDir, WORKFLOW);
2868
3679
  if (!existsSync6(workflow)) {
2869
3680
  mkdirSync3(dirname6(workflow), { recursive: true });
2870
- writeFileSync4(workflow, WORKFLOW_TEXT);
3681
+ writeFileSync5(workflow, WORKFLOW_TEXT);
2871
3682
  }
2872
3683
  const done = commitAndPush(ws.opsDir, [CONFIG, WORKFLOW], "roster: the hosted portal");
2873
3684
  if (done.note && !done.committed) process.stdout.write(` ${done.note}
@@ -2921,6 +3732,44 @@ function newConfig(org, opsName, domain) {
2921
3732
  assets: { binding: "ASSETS", run_worker_first: true }
2922
3733
  };
2923
3734
  }
3735
+ function hasConnectorStore(config) {
3736
+ return (config.kv_namespaces ?? []).some(
3737
+ (k) => k.binding === "CONNECTORS"
3738
+ );
3739
+ }
3740
+ async function namespaceFor(title, configFile) {
3741
+ const listed = await captured(["kv", "namespace", "list", "--config", configFile]);
3742
+ if (listed.code === 0) {
3743
+ const found = existingNamespace(listed.text, title);
3744
+ if (found) return found;
3745
+ }
3746
+ const made = await captured(["kv", "namespace", "create", title, "--config", configFile]);
3747
+ return made.code === 0 ? namespaceId(made.text) : null;
3748
+ }
3749
+ function captured(args) {
3750
+ return new Promise((resolve7) => {
3751
+ let text2 = "";
3752
+ const child = spawn("npx", ["--yes", WRANGLER, ...args], {
3753
+ stdio: ["ignore", "pipe", "inherit"]
3754
+ });
3755
+ child.stdout.on("data", (b) => {
3756
+ text2 += String(b);
3757
+ });
3758
+ child.on("close", (code) => resolve7({ code: code ?? 1, text: text2 }));
3759
+ child.on("error", () => resolve7({ code: 1, text: text2 }));
3760
+ });
3761
+ }
3762
+ function existingNamespace(text2, title) {
3763
+ try {
3764
+ const list2 = JSON.parse(text2.slice(text2.indexOf("[")));
3765
+ return list2.find((n) => n.title === title)?.id ?? null;
3766
+ } catch {
3767
+ return null;
3768
+ }
3769
+ }
3770
+ function namespaceId(text2) {
3771
+ return /\bid\b["']?\s*[:=]\s*["']([0-9a-f]{32})["']/.exec(text2)?.[1] ?? null;
3772
+ }
2924
3773
  function domainOf(config) {
2925
3774
  return config.routes?.[0]?.pattern ?? "";
2926
3775
  }
@@ -2935,9 +3784,9 @@ function parseJsonc(text2) {
2935
3784
  }
2936
3785
  function workerBundle() {
2937
3786
  const here = dirname6(fileURLToPath3(import.meta.url));
2938
- for (const dist of [here, join15(here, "..", "..", "dist")]) {
2939
- const main3 = join15(dist, "worker", "index.js");
2940
- if (existsSync6(main3)) return { main: main3, assets: join15(dist, "worker", "assets") };
3787
+ for (const dist of [here, join16(here, "..", "..", "dist")]) {
3788
+ const main2 = join16(dist, "worker", "index.js");
3789
+ if (existsSync6(main2)) return { main: main2, assets: join16(dist, "worker", "assets") };
2941
3790
  }
2942
3791
  return null;
2943
3792
  }
@@ -2955,10 +3804,10 @@ async function wrangler(args) {
2955
3804
  return code;
2956
3805
  }
2957
3806
  function wranglerOnce(args) {
2958
- return new Promise((resolve8) => {
3807
+ return new Promise((resolve7) => {
2959
3808
  const child = spawn("npx", ["--yes", WRANGLER, ...args], { stdio: "inherit" });
2960
- child.on("close", (code) => resolve8(code ?? 1));
2961
- child.on("error", () => resolve8(1));
3809
+ child.on("close", (code) => resolve7(code ?? 1));
3810
+ child.on("error", () => resolve7(1));
2962
3811
  });
2963
3812
  }
2964
3813
  var WORKFLOW_TEXT = `# Redeploys the hosted portal: when its config changes, every morning so roster updates
@@ -3011,7 +3860,7 @@ jobs:
3011
3860
  - if: steps.ready.outputs.go == 'true'
3012
3861
  run: npx --yes @nanocollective/roster@latest portal deploy --ci --apply
3013
3862
  `;
3014
- function parseFlags5(argv) {
3863
+ function parseFlags6(argv) {
3015
3864
  const out = {};
3016
3865
  for (let i = 0; i < argv.length; i++) {
3017
3866
  const flag = argv[i];
@@ -3026,168 +3875,39 @@ function parseFlags5(argv) {
3026
3875
  }
3027
3876
 
3028
3877
  // src/commands/doctor.ts
3029
- import { existsSync as existsSync8, readdirSync as readdirSync5, readFileSync as readFileSync8 } from "fs";
3030
- import { join as join19 } from "path";
3878
+ import { existsSync as existsSync8, readdirSync as readdirSync5, readFileSync as readFileSync9 } from "fs";
3879
+ import { join as join20 } from "path";
3031
3880
 
3032
3881
  // src/lib/callable.ts
3033
- function accessLink(org, repo) {
3034
- return `https://github.com/${org}/${repo}/settings/actions`;
3035
- }
3036
- async function allowOrgCallers(org, repo, gh = api) {
3037
- const link = accessLink(org, repo);
3038
- const path = `repos/${org}/${repo}/actions/permissions/access`;
3039
- const now = await gh(path);
3040
- if (now.ok && now.data?.access_level === "organization") return { ok: true, already: true, link };
3041
- const set = await gh(path, ["-X", "PUT", "-f", "access_level=organization"]);
3042
- if (set.ok) return { ok: true, link };
3043
- return { ok: false, error: refusal(set), link };
3044
- }
3045
- function refusal(res) {
3046
- const why = res.error ?? "unknown error";
3047
- if (res.status === 403 || res.status === 404) {
3048
- return `${why}. Setting this needs admin on the repo, and your gh token does not have it here`;
3049
- }
3050
- if (res.status === 422) return `${why}. GitHub only offers this on a private or internal repo`;
3051
- return why;
3052
- }
3053
-
3054
- // src/lib/localtoken.ts
3055
- import { execFile as execFile4 } from "child_process";
3056
-
3057
- // src/lib/github.ts
3058
- function githubClient(token, opts = {}) {
3059
- const doFetch = opts.fetch ?? fetch;
3060
- const base2 = (opts.base ?? "https://api.github.com").replace(/\/$/, "");
3061
- const limit = opts.remember ?? 500;
3062
- const seen = /* @__PURE__ */ new Map();
3063
- const headers = (accept) => ({
3064
- authorization: `Bearer ${token}`,
3065
- accept,
3066
- "user-agent": opts.userAgent ?? "roster-portal",
3067
- "x-github-api-version": "2022-11-28"
3068
- });
3069
- const request = async (method, path, o = {}) => {
3070
- const url = path.startsWith("https://") ? path : `${base2}/${path.replace(/^\//, "")}`;
3071
- const accept = o.accept ?? "application/vnd.github+json";
3072
- const as = o.as ?? "json";
3073
- const h = headers(accept);
3074
- const key = `${accept} ${url}`;
3075
- const kept = method === "GET" ? seen.get(key) : void 0;
3076
- if (kept) h["if-none-match"] = kept.etag;
3077
- let body2;
3078
- if (o.body !== void 0) {
3079
- body2 = JSON.stringify(o.body);
3080
- h["content-type"] = "application/json";
3081
- }
3082
- const reads = method === "GET" || o.retry === true;
3083
- let res;
3084
- for (let attempt = 0; ; attempt++) {
3085
- try {
3086
- res = await doFetch(url, { method, headers: h, body: body2 });
3087
- } catch (err) {
3088
- if (reads && attempt === 0) continue;
3089
- return { ok: false, error: `GitHub could not be reached: ${err.message}` };
3090
- }
3091
- if (reads && attempt === 0 && [502, 503, 504].includes(res.status)) {
3092
- await res.body?.cancel().catch(() => {
3093
- });
3094
- await new Promise((r) => setTimeout(r, 400));
3095
- continue;
3096
- }
3097
- break;
3098
- }
3099
- if (res.status === 304 && kept) {
3100
- seen.delete(key);
3101
- seen.set(key, kept);
3102
- return { ok: true, status: 304, data: kept.data, cached: true };
3103
- }
3104
- if (!res.ok) {
3105
- const text2 = await res.text().catch(() => "");
3106
- return { ok: false, status: res.status, error: message(res, text2) };
3107
- }
3108
- let data;
3109
- if (res.status === 204) data = void 0;
3110
- else if (as === "bytes") data = new Uint8Array(await res.arrayBuffer());
3111
- else if (as === "text") data = await res.text();
3112
- else {
3113
- const text2 = await res.text();
3114
- data = text2 ? JSON.parse(text2) : void 0;
3115
- }
3116
- const etag = res.headers.get("etag");
3117
- if (method === "GET" && etag && as !== "bytes") {
3118
- seen.set(key, { etag, data });
3119
- if (seen.size > limit) seen.delete(seen.keys().next().value);
3120
- }
3121
- return { ok: true, status: res.status, data };
3122
- };
3123
- const graphql2 = async (query2, vars = {}) => {
3124
- const res = await request(
3125
- "POST",
3126
- "graphql",
3127
- // A query reads; a mutation writes, and is never asked twice.
3128
- { body: { query: query2, variables: vars }, retry: !/^\s*mutation\b/.test(query2) }
3129
- );
3130
- if (!res.ok) return { ok: false, status: res.status, error: res.error };
3131
- const errors = res.data?.errors ?? [];
3132
- if (errors.length) return { ok: false, status: 200, error: errors[0].message };
3133
- return { ok: true, status: 200, data: res.data?.data };
3134
- };
3135
- return { request, graphql: graphql2 };
3136
- }
3137
- function message(res, text2) {
3138
- const remaining = res.headers.get("x-ratelimit-remaining");
3139
- if ((res.status === 403 || res.status === 429) && remaining === "0") {
3140
- return "GitHub's API limit for this hour is used up. It resets within the hour.";
3141
- }
3142
- try {
3143
- const parsed = JSON.parse(text2);
3144
- if (parsed.message) return parsed.message;
3145
- } catch {
3146
- }
3147
- if (res.status === 401) return "GitHub did not accept the token. Sign in again.";
3148
- if (res.status === 404) return "Not Found";
3149
- return `GitHub answered ${res.status} ${res.statusText}`.trim();
3150
- }
3151
- function splitRepo(repo) {
3152
- const [owner = "", name = ""] = repo.split("/");
3153
- return { owner, name };
3882
+ function accessLink(org, repo) {
3883
+ return `https://github.com/${org}/${repo}/settings/actions`;
3154
3884
  }
3155
-
3156
- // src/lib/localtoken.ts
3157
- var pending = null;
3158
- function localGitHub() {
3159
- pending ??= find();
3160
- return pending;
3885
+ async function allowOrgCallers(org, repo, gh = api) {
3886
+ const link = accessLink(org, repo);
3887
+ const path = `repos/${org}/${repo}/actions/permissions/access`;
3888
+ const now = await gh(path);
3889
+ if (now.ok && now.data?.access_level === "organization") return { ok: true, already: true, link };
3890
+ const set = await gh(path, ["-X", "PUT", "-f", "access_level=organization"]);
3891
+ if (set.ok) return { ok: true, link };
3892
+ return { ok: false, error: refusal(set), link };
3161
3893
  }
3162
- async function find() {
3163
- const env = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
3164
- if (env) return { ok: true, gh: githubClient(env), token: env };
3165
- const token = await new Promise(
3166
- (resolve8) => execFile4(
3167
- "gh",
3168
- ["auth", "token"],
3169
- { encoding: "utf8" },
3170
- (err, out) => resolve8(err ? "" : out.trim())
3171
- )
3172
- );
3173
- if (!token) {
3174
- pending = null;
3175
- return {
3176
- ok: false,
3177
- error: "No GitHub token. Run `gh auth login`, or set GITHUB_TOKEN, and try again."
3178
- };
3894
+ function refusal(res) {
3895
+ const why = res.error ?? "unknown error";
3896
+ if (res.status === 403 || res.status === 404) {
3897
+ return `${why}. Setting this needs admin on the repo, and your gh token does not have it here`;
3179
3898
  }
3180
- return { ok: true, gh: githubClient(token), token };
3899
+ if (res.status === 422) return `${why}. GitHub only offers this on a private or internal repo`;
3900
+ return why;
3181
3901
  }
3182
3902
 
3183
3903
  // src/lib/memory.ts
3184
- import { join as join16 } from "path";
3904
+ import { join as join17 } from "path";
3185
3905
  var FACT_RE = /^- \*\*`([^`]+)`\*\*\s*·\s*(.*)$/;
3186
3906
  var PROVENANCE_RE = /^\[([a-z][a-z0-9-]*)\]\s*/;
3187
3907
  var NOTE_RE = /\s*·?\s*\[note\]\(([^)]+)\)\s*$/;
3188
3908
  var SO_RE = /\*\*So:\*\*\s*/;
3189
3909
  function parseMemory(dir) {
3190
- const indexPath = join16(dir, "INDEX.md");
3910
+ const indexPath = join17(dir, "INDEX.md");
3191
3911
  if (!existsSync2(indexPath)) throw new Error(`no memory index at ${indexPath}`);
3192
3912
  const lines = readFileSync2(indexPath, "utf8").split("\n");
3193
3913
  const facts = [];
@@ -3234,7 +3954,7 @@ function parseMemory(dir) {
3234
3954
  raw
3235
3955
  });
3236
3956
  });
3237
- const notesDir = join16(dir, "notes");
3957
+ const notesDir = join17(dir, "notes");
3238
3958
  const notes = existsSync2(notesDir) ? readdirSync2(notesDir).filter((f) => f.endsWith(".md")).sort() : [];
3239
3959
  return {
3240
3960
  facts,
@@ -3268,7 +3988,7 @@ function extractLinks(facts, notes, dir) {
3268
3988
  scan(f.slug, f.raw);
3269
3989
  }
3270
3990
  for (const note of notes) {
3271
- const path = join16(dir, "notes", note);
3991
+ const path = join17(dir, "notes", note);
3272
3992
  if (!existsSync2(path)) continue;
3273
3993
  scan(note, readFileSync2(path, "utf8"));
3274
3994
  }
@@ -3285,8 +4005,8 @@ function budgetsFor(org, manifest) {
3285
4005
  for (const source of [org, manifest]) {
3286
4006
  const memory = source?.memory;
3287
4007
  if (!memory || typeof memory !== "object") continue;
3288
- for (const [field, key] of Object.entries(BUDGET_KEYS)) {
3289
- const v = memory[key];
4008
+ for (const [field, key2] of Object.entries(BUDGET_KEYS)) {
4009
+ const v = memory[key2];
3290
4010
  if (typeof v === "number" && v > 0) out[field] = v;
3291
4011
  }
3292
4012
  }
@@ -3319,7 +4039,7 @@ function lintMemory(doc, dir, budgets = DEFAULT_BUDGETS) {
3319
4039
  }
3320
4040
  if (f.note) {
3321
4041
  linked.add(f.note.replace(/^notes\//, ""));
3322
- if (!existsSync2(join16(dir, f.note))) {
4042
+ if (!existsSync2(join17(dir, f.note))) {
3323
4043
  problems.push({
3324
4044
  level: "error",
3325
4045
  rule: "dangling-note",
@@ -3380,7 +4100,7 @@ function lintMemory(doc, dir, budgets = DEFAULT_BUDGETS) {
3380
4100
  function overBudget(doc, dir, budgets) {
3381
4101
  const out = [];
3382
4102
  const kb = (bytes2) => Math.round(bytes2 / 1024);
3383
- const index = join16(dir, "INDEX.md");
4103
+ const index = join17(dir, "INDEX.md");
3384
4104
  const indexBytes = existsSync2(index) ? statSync2(index).size : 0;
3385
4105
  if (indexBytes > budgets.indexKb * 1024) {
3386
4106
  const longest = [...doc.facts].sort((a, b) => b.raw.length - a.raw.length).slice(0, 3).map((f) => `\`${f.slug}\` (${f.raw.length})`);
@@ -3391,7 +4111,7 @@ function overBudget(doc, dir, budgets) {
3391
4111
  file: "memory/INDEX.md"
3392
4112
  });
3393
4113
  }
3394
- const log = join16(dir, "..", "log", "decisions.md");
4114
+ const log = join17(dir, "..", "log", "decisions.md");
3395
4115
  const logBytes = existsSync2(log) ? statSync2(log).size : 0;
3396
4116
  if (logBytes > budgets.decisionsKb * 1024) {
3397
4117
  out.push({
@@ -3494,11 +4214,11 @@ function useRecordStore(next) {
3494
4214
  store = next;
3495
4215
  }
3496
4216
  async function knownRecord(brain, id) {
3497
- const key = `${brain}#${id}`;
3498
- if (records.has(key)) return records.get(key);
4217
+ const key2 = `${brain}#${id}`;
4218
+ if (records.has(key2)) return records.get(key2);
3499
4219
  const kept = await store?.get(brain, id).catch(() => void 0);
3500
4220
  if (!kept) return void 0;
3501
- records.set(key, kept.record);
4221
+ records.set(key2, kept.record);
3502
4222
  return kept.record;
3503
4223
  }
3504
4224
  async function staffRuns(gh, brain, handle, days = 30, opts = {}) {
@@ -3608,17 +4328,17 @@ async function realRuns(gh, brain, workflow, since) {
3608
4328
  return { ok: true, data };
3609
4329
  }
3610
4330
  async function recordFor(gh, brain, id) {
3611
- const key = `${brain}#${id}`;
3612
- if (records.has(key)) return records.get(key);
3613
- const list = await gh.request(
4331
+ const key2 = `${brain}#${id}`;
4332
+ if (records.has(key2)) return records.get(key2);
4333
+ const list2 = await gh.request(
3614
4334
  "GET",
3615
4335
  `repos/${brain}/actions/runs/${id}/artifacts?name=roster-run`
3616
4336
  );
3617
- if (!list.ok) {
3618
- records.set(key, null);
4337
+ if (!list2.ok) {
4338
+ records.set(key2, null);
3619
4339
  return null;
3620
4340
  }
3621
- const artifact = (list.data?.artifacts ?? []).find((a) => !a.expired);
4341
+ const artifact = (list2.data?.artifacts ?? []).find((a) => !a.expired);
3622
4342
  let record = null;
3623
4343
  if (artifact) {
3624
4344
  const zip = await gh.request(
@@ -3627,7 +4347,7 @@ async function recordFor(gh, brain, id) {
3627
4347
  { as: "bytes" }
3628
4348
  );
3629
4349
  if (!zip.ok || !zip.data) {
3630
- records.set(key, null);
4350
+ records.set(key2, null);
3631
4351
  return null;
3632
4352
  }
3633
4353
  try {
@@ -3637,7 +4357,7 @@ async function recordFor(gh, brain, id) {
3637
4357
  record = null;
3638
4358
  }
3639
4359
  }
3640
- records.set(key, record);
4360
+ records.set(key2, record);
3641
4361
  await store?.put(brain, id, { record }).catch(() => {
3642
4362
  });
3643
4363
  return record;
@@ -3671,27 +4391,27 @@ import {
3671
4391
  mkdirSync as mkdirSync4,
3672
4392
  mkdtempSync as mkdtempSync4,
3673
4393
  readdirSync as readdirSync4,
3674
- readFileSync as readFileSync7,
4394
+ readFileSync as readFileSync8,
3675
4395
  rmSync as rmSync4,
3676
- writeFileSync as writeFileSync6
4396
+ writeFileSync as writeFileSync7
3677
4397
  } from "fs";
3678
4398
  import { tmpdir as tmpdir4 } from "os";
3679
- import { dirname as dirname7, join as join18 } from "path";
4399
+ import { dirname as dirname7, join as join19 } from "path";
3680
4400
 
3681
4401
  // src/lib/merge.ts
3682
4402
  import { execFileSync as execFileSync4 } from "child_process";
3683
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
4403
+ import { mkdtempSync as mkdtempSync3, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";
3684
4404
  import { tmpdir as tmpdir3 } from "os";
3685
- import { join as join17 } from "path";
4405
+ import { join as join18 } from "path";
3686
4406
  function merge3(current, base2, incoming) {
3687
- const dir = mkdtempSync3(join17(tmpdir3(), "roster-merge-"));
4407
+ const dir = mkdtempSync3(join18(tmpdir3(), "roster-merge-"));
3688
4408
  try {
3689
- const c = join17(dir, "current");
3690
- const b = join17(dir, "base");
3691
- const i = join17(dir, "incoming");
3692
- writeFileSync5(c, current);
3693
- writeFileSync5(b, base2);
3694
- writeFileSync5(i, incoming);
4409
+ const c = join18(dir, "current");
4410
+ const b = join18(dir, "base");
4411
+ const i = join18(dir, "incoming");
4412
+ writeFileSync6(c, current);
4413
+ writeFileSync6(b, base2);
4414
+ writeFileSync6(i, incoming);
3695
4415
  try {
3696
4416
  const text2 = execFileSync4(
3697
4417
  "git",
@@ -3757,17 +4477,17 @@ roster upgrade [--apply] [--check] [--baseline <git-ref>]
3757
4477
  been a manifest change. The diff is printed either way, so nothing goes quietly.
3758
4478
  `;
3759
4479
  async function upgradeCommand(argv) {
3760
- const opts = parseFlags6(argv);
4480
+ const opts = parseFlags7(argv);
3761
4481
  const ws = findWorkspace(opts.ops);
3762
4482
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
3763
4483
  const tplDir = opsTemplateDir();
3764
- const seedDir = join18(ws.opsDir, ".roster", "seed");
4484
+ const seedDir = join19(ws.opsDir, ".roster", "seed");
3765
4485
  if (opts.baseline) {
3766
4486
  return writeBaseline(ws.opsDir, seedDir, tplDir, opts.baseline);
3767
4487
  }
3768
4488
  const plans = planAll(tplDir, seedDir, ws.opsDir);
3769
4489
  const brains = planBrains(ws, parseYaml3);
3770
- report(ws, plans, opts);
4490
+ report2(ws, plans, opts);
3771
4491
  reportBrains(brains, opts);
3772
4492
  const blocked = plans.filter(
3773
4493
  (p) => p.verdict === "conflict" || p.verdict === "no-base" || p.verdict === "edited-managed"
@@ -3792,12 +4512,12 @@ function planAll(tplDir, seedDir, opsDir) {
3792
4512
  }
3793
4513
  function plan(rel, tplDir, seedDir, opsDir) {
3794
4514
  const kind = classify(rel);
3795
- const incoming = readFileSync7(join18(tplDir, rel), "utf8");
3796
- const currentPath = join18(opsDir, rel);
3797
- const basePath = join18(seedDir, rel);
4515
+ const incoming = readFileSync8(join19(tplDir, rel), "utf8");
4516
+ const currentPath = join19(opsDir, rel);
4517
+ const basePath = join19(seedDir, rel);
3798
4518
  const has = (p) => existsSync7(p);
3799
- const current = has(currentPath) ? readFileSync7(currentPath, "utf8") : null;
3800
- const base2 = has(basePath) ? readFileSync7(basePath, "utf8") : null;
4519
+ const current = has(currentPath) ? readFileSync8(currentPath, "utf8") : null;
4520
+ const base2 = has(basePath) ? readFileSync8(basePath, "utf8") : null;
3801
4521
  if (current === null) {
3802
4522
  return { rel, kind, verdict: "added", note: "new in the framework", next: incoming };
3803
4523
  }
@@ -3855,7 +4575,7 @@ var GLYPH = {
3855
4575
  "no-base": "?",
3856
4576
  "edited-managed": "!"
3857
4577
  };
3858
- function report(ws, plans, opts) {
4578
+ function report2(ws, plans, opts) {
3859
4579
  const width = Math.max(...plans.map((p) => p.rel.length)) + 2;
3860
4580
  process.stdout.write(`
3861
4581
  roster upgrade \u2014 ${ws.opsName}
@@ -3899,9 +4619,9 @@ function apply(opsDir, seedDir, tplDir, plans) {
3899
4619
  for (const p of plans) {
3900
4620
  if (p.verdict === "edited-managed") edited++;
3901
4621
  if (p.verdict === "conflict") {
3902
- const out = join18(opsDir, p.rel + ".roster-merge");
4622
+ const out = join19(opsDir, p.rel + ".roster-merge");
3903
4623
  mkdirSync4(dirname7(out), { recursive: true });
3904
- writeFileSync6(out, p.rejected);
4624
+ writeFileSync7(out, p.rejected);
3905
4625
  process.stdout.write(` wrote ${p.rel}.roster-merge \u2014 resolve it, then re-run
3906
4626
  `);
3907
4627
  left++;
@@ -3915,9 +4635,9 @@ function apply(opsDir, seedDir, tplDir, plans) {
3915
4635
  if (p.verdict === "same") seed(seedDir, tplDir, p.rel);
3916
4636
  continue;
3917
4637
  }
3918
- const dest = join18(opsDir, p.rel);
4638
+ const dest = join19(opsDir, p.rel);
3919
4639
  mkdirSync4(dirname7(dest), { recursive: true });
3920
- writeFileSync6(dest, p.next);
4640
+ writeFileSync7(dest, p.next);
3921
4641
  seed(seedDir, tplDir, p.rel);
3922
4642
  wrote++;
3923
4643
  }
@@ -3926,7 +4646,7 @@ function apply(opsDir, seedDir, tplDir, plans) {
3926
4646
  process.stdout.write(left ? `, ${left} left for you
3927
4647
 
3928
4648
  ` : "\n\n");
3929
- if (!left) writeFileSync6(join18(opsDir, ".roster-version"), stamp() + "\n");
4649
+ if (!left) writeFileSync7(join19(opsDir, ".roster-version"), stamp() + "\n");
3930
4650
  if (edited) {
3931
4651
  process.stdout.write(
3932
4652
  ` ${edited} framework file${edited === 1 ? "" : "s"} still carr${edited === 1 ? "ies" : "y"} a local edit. Move it into the framework, or doctor keeps failing.
@@ -3937,12 +4657,12 @@ function apply(opsDir, seedDir, tplDir, plans) {
3937
4657
  return left || edited ? 1 : 0;
3938
4658
  }
3939
4659
  function seed(seedDir, tplDir, rel) {
3940
- const dest = join18(seedDir, rel);
4660
+ const dest = join19(seedDir, rel);
3941
4661
  mkdirSync4(dirname7(dest), { recursive: true });
3942
- writeFileSync6(dest, readFileSync7(join18(tplDir, rel), "utf8"));
4662
+ writeFileSync7(dest, readFileSync8(join19(tplDir, rel), "utf8"));
3943
4663
  }
3944
4664
  function writeBaseline(opsDir, seedDir, tplDir, ref) {
3945
- const framework = join18(tplDir, "..", "..");
4665
+ const framework = join19(tplDir, "..", "..");
3946
4666
  let files;
3947
4667
  try {
3948
4668
  files = execFileSync5(
@@ -3963,16 +4683,16 @@ function writeBaseline(opsDir, seedDir, tplDir, ref) {
3963
4683
  encoding: "utf8",
3964
4684
  maxBuffer: 16 * 1024 * 1024
3965
4685
  });
3966
- const dest = join18(seedDir, rel);
4686
+ const dest = join19(seedDir, rel);
3967
4687
  mkdirSync4(dirname7(dest), { recursive: true });
3968
- writeFileSync6(dest, text2);
4688
+ writeFileSync7(dest, text2);
3969
4689
  }
3970
- writeFileSync6(join18(opsDir, ".roster-version"), `${ref}
4690
+ writeFileSync7(join19(opsDir, ".roster-version"), `${ref}
3971
4691
  `);
3972
4692
  process.stdout.write(
3973
4693
  `
3974
4694
  Recorded ${files.length} files as the base, from the framework at ${ref}.
3975
- Written to ${join18(opsDir, ".roster", "seed")} \u2014 commit it; it is what makes the next
4695
+ Written to ${join19(opsDir, ".roster", "seed")} \u2014 commit it; it is what makes the next
3976
4696
  upgrade a merge rather than a copy.
3977
4697
 
3978
4698
  Now run: roster upgrade
@@ -3985,7 +4705,7 @@ function stamp() {
3985
4705
  try {
3986
4706
  return execFileSync5(
3987
4707
  "git",
3988
- ["-C", join18(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
4708
+ ["-C", join19(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
3989
4709
  {
3990
4710
  encoding: "utf8",
3991
4711
  stdio: ["ignore", "pipe", "ignore"]
@@ -3995,7 +4715,7 @@ function stamp() {
3995
4715
  return "unknown";
3996
4716
  }
3997
4717
  }
3998
- function parseFlags6(argv) {
4718
+ function parseFlags7(argv) {
3999
4719
  const out = {};
4000
4720
  for (let i = 0; i < argv.length; i++) {
4001
4721
  const flag = argv[i];
@@ -4024,9 +4744,9 @@ function planBrains(ws, parseYaml3) {
4024
4744
  const out = [];
4025
4745
  for (const entry of org.staff ?? []) {
4026
4746
  const dir = entry.dir ?? entry.handle;
4027
- const root2 = join18(ws.root, dir);
4747
+ const root2 = join19(ws.root, dir);
4028
4748
  const base2 = { handle: entry.handle, dir, root: root2, files: [] };
4029
- const manifestPath = join18(root2, "staff.yaml");
4749
+ const manifestPath = join19(root2, "staff.yaml");
4030
4750
  if (!existsSync7(manifestPath)) {
4031
4751
  out.push({ ...base2, problem: existsSync7(root2) ? "no staff.yaml" : "not checked out here" });
4032
4752
  continue;
@@ -4034,7 +4754,7 @@ function planBrains(ws, parseYaml3) {
4034
4754
  let want;
4035
4755
  try {
4036
4756
  const spec2 = specFromManifest(
4037
- parseYaml3(readFileSync7(manifestPath, "utf8"), "staff.yaml"),
4757
+ parseYaml3(readFileSync8(manifestPath, "utf8"), "staff.yaml"),
4038
4758
  dir
4039
4759
  );
4040
4760
  want = renderTree(brainTemplateDir(), tokensFor(orgSpec2, spec2));
@@ -4047,20 +4767,20 @@ function planBrains(ws, parseYaml3) {
4047
4767
  }
4048
4768
  for (const [rel, text2] of want) {
4049
4769
  const kind = classifyBrain(rel);
4050
- const live = join18(root2, rel);
4770
+ const live = join19(root2, rel);
4051
4771
  if (!existsSync7(live)) {
4052
4772
  base2.files.push({ rel, kind, verdict: "missing", next: text2 });
4053
4773
  continue;
4054
4774
  }
4055
4775
  if (kind === "scaffold") continue;
4056
- const have = readFileSync7(live, "utf8");
4776
+ const have = readFileSync8(live, "utf8");
4057
4777
  base2.files.push(
4058
4778
  have === text2 ? { rel, kind, verdict: "same" } : { rel, kind, verdict: "regenerate", next: text2, diff: unified(have, text2) }
4059
4779
  );
4060
4780
  }
4061
4781
  for (const rel of callerFiles(root2)) {
4062
4782
  if (want.has(rel)) continue;
4063
- const text2 = readFileSync7(join18(root2, rel), "utf8");
4783
+ const text2 = readFileSync8(join19(root2, rel), "utf8");
4064
4784
  if (!text2.includes(`${orgSpec2.opsRepo}/.github/workflows/session.yaml`)) continue;
4065
4785
  base2.files.push({ rel, kind: "generated", verdict: "obsolete" });
4066
4786
  }
@@ -4069,14 +4789,14 @@ function planBrains(ws, parseYaml3) {
4069
4789
  return out;
4070
4790
  }
4071
4791
  function unified(before, after) {
4072
- const dir = mkdtempSync4(join18(tmpdir4(), "roster-diff-"));
4792
+ const dir = mkdtempSync4(join19(tmpdir4(), "roster-diff-"));
4073
4793
  try {
4074
- writeFileSync6(join18(dir, "a"), before);
4075
- writeFileSync6(join18(dir, "b"), after);
4794
+ writeFileSync7(join19(dir, "a"), before);
4795
+ writeFileSync7(join19(dir, "b"), after);
4076
4796
  try {
4077
4797
  execFileSync5(
4078
4798
  "diff",
4079
- ["-u", "--label", "yours", "--label", "generated", join18(dir, "a"), join18(dir, "b")],
4799
+ ["-u", "--label", "yours", "--label", "generated", join19(dir, "a"), join19(dir, "b")],
4080
4800
  { encoding: "utf8" }
4081
4801
  );
4082
4802
  return "";
@@ -4089,7 +4809,7 @@ function unified(before, after) {
4089
4809
  }
4090
4810
  }
4091
4811
  function callerFiles(root2) {
4092
- const dir = join18(root2, ".github", "workflows");
4812
+ const dir = join19(root2, ".github", "workflows");
4093
4813
  if (!existsSync7(dir)) return [];
4094
4814
  return readdirSync4(dir).filter((n) => n.endsWith(".yaml") || n.endsWith(".yml")).map((n) => `.github/workflows/${n}`);
4095
4815
  }
@@ -4138,14 +4858,14 @@ function applyBrains(brains) {
4138
4858
  for (const b of brains) {
4139
4859
  for (const f of b.files) {
4140
4860
  if (f.verdict === "obsolete") {
4141
- rmSync4(join18(b.root, f.rel), { force: true });
4861
+ rmSync4(join19(b.root, f.rel), { force: true });
4142
4862
  wrote++;
4143
4863
  continue;
4144
4864
  }
4145
4865
  if (f.next === void 0) continue;
4146
- const dest = join18(b.root, f.rel);
4866
+ const dest = join19(b.root, f.rel);
4147
4867
  mkdirSync4(dirname7(dest), { recursive: true });
4148
- writeFileSync6(dest, f.next);
4868
+ writeFileSync7(dest, f.next);
4149
4869
  wrote++;
4150
4870
  }
4151
4871
  }
@@ -4196,6 +4916,7 @@ async function collect(opts) {
4196
4916
  findings.push(...checkBusiness(ws));
4197
4917
  findings.push(...checkPriorities(ws));
4198
4918
  findings.push(...await checkAgent(ws, org));
4919
+ findings.push(...checkConnectors(org));
4199
4920
  if (online) findings.push(...await checkOrgOnline(ws, org));
4200
4921
  if (online) findings.push(...await checkReviewGates(ws, org, composer));
4201
4922
  const perStaff = await Promise.all(staff.map((s) => checkStaff(ws, org, s, composer, online)));
@@ -4205,7 +4926,7 @@ async function collect(opts) {
4205
4926
  }
4206
4927
  async function doctorCommand(argv) {
4207
4928
  const only = argv[0] && !argv[0].startsWith("-") ? argv[0] : void 0;
4208
- const opts = parseFlags7(argv.slice(only ? 1 : 0));
4929
+ const opts = parseFlags8(argv.slice(only ? 1 : 0));
4209
4930
  const result = await collect({ ...opts, only });
4210
4931
  if (!result) {
4211
4932
  process.stderr.write(`roster: no staff member "${only}" in org.yaml
@@ -4217,7 +4938,7 @@ async function doctorCommand(argv) {
4217
4938
  JSON.stringify({ org: result.org.org, findings: result.findings }, null, 2) + "\n"
4218
4939
  );
4219
4940
  } else {
4220
- report2(result.org, result.findings, result.online, opts.offline === true);
4941
+ report3(result.org, result.findings, result.online, opts.offline === true);
4221
4942
  }
4222
4943
  return result.findings.some((f) => f.level === "fail") ? 1 : 0;
4223
4944
  }
@@ -4269,7 +4990,7 @@ function checkWorkspace(ws, org) {
4269
4990
  });
4270
4991
  }
4271
4992
  try {
4272
- const plans = planAll(opsTemplateDir(), join19(ws.opsDir, ".roster", "seed"), ws.opsDir);
4993
+ const plans = planAll(opsTemplateDir(), join20(ws.opsDir, ".roster", "seed"), ws.opsDir);
4273
4994
  const edited = plans.filter((p) => p.verdict === "edited-managed");
4274
4995
  const stale = plans.filter((p) => p.next !== void 0);
4275
4996
  const unmergeable = plans.filter((p) => p.verdict === "conflict" || p.verdict === "no-base");
@@ -4318,7 +5039,7 @@ async function checkAgent(ws, org) {
4318
5039
  const scope = "workspace";
4319
5040
  let agent;
4320
5041
  try {
4321
- const { resolveAgent } = await import(`file://${join19(ws.opsDir, "agents.mjs")}`);
5042
+ const { resolveAgent } = await import(`file://${join20(ws.opsDir, "agents.mjs")}`);
4322
5043
  agent = resolveAgent(org, {});
4323
5044
  } catch (err) {
4324
5045
  return [
@@ -4332,8 +5053,8 @@ async function checkAgent(ws, org) {
4332
5053
  ];
4333
5054
  }
4334
5055
  const out = [{ scope, level: "ok", id: "agent", title: `runs on ${agent.id}` }];
4335
- const orgFile = join19(ws.opsDir, "org.yaml");
4336
- if (existsSync8(orgFile) && /FILL IN/.test(readFileSync8(orgFile, "utf8"))) {
5056
+ const orgFile = join20(ws.opsDir, "org.yaml");
5057
+ if (existsSync8(orgFile) && /FILL IN/.test(readFileSync9(orgFile, "utf8"))) {
4337
5058
  out.push({
4338
5059
  scope,
4339
5060
  level: "fail",
@@ -4343,7 +5064,7 @@ async function checkAgent(ws, org) {
4343
5064
  });
4344
5065
  }
4345
5066
  if (!agent.config) return out;
4346
- const path = join19(ws.opsDir, agent.config.path);
5067
+ const path = join20(ws.opsDir, agent.config.path);
4347
5068
  if (!existsSync8(path)) {
4348
5069
  out.push({
4349
5070
  scope,
@@ -4354,7 +5075,7 @@ async function checkAgent(ws, org) {
4354
5075
  });
4355
5076
  return out;
4356
5077
  }
4357
- if (/FILL IN/.test(readFileSync8(path, "utf8"))) {
5078
+ if (/FILL IN/.test(readFileSync9(path, "utf8"))) {
4358
5079
  out.push({
4359
5080
  scope,
4360
5081
  level: "fail",
@@ -4366,7 +5087,7 @@ async function checkAgent(ws, org) {
4366
5087
  return out;
4367
5088
  }
4368
5089
  function checkBusiness(ws) {
4369
- const path = join19(ws.opsDir, "org", "business.md");
5090
+ const path = join20(ws.opsDir, "org", "business.md");
4370
5091
  if (!existsSync8(path)) {
4371
5092
  return [
4372
5093
  {
@@ -4378,7 +5099,7 @@ function checkBusiness(ws) {
4378
5099
  }
4379
5100
  ];
4380
5101
  }
4381
- if (looksUnwritten(readFileSync8(path, "utf8"))) {
5102
+ if (looksUnwritten(readFileSync9(path, "utf8"))) {
4382
5103
  return [
4383
5104
  {
4384
5105
  scope: "workspace",
@@ -4392,7 +5113,7 @@ function checkBusiness(ws) {
4392
5113
  return [{ scope: "workspace", level: "ok", id: "business", title: "org/business.md is written" }];
4393
5114
  }
4394
5115
  function checkPriorities(ws) {
4395
- const path = join19(ws.opsDir, "org", "priorities.md");
5116
+ const path = join20(ws.opsDir, "org", "priorities.md");
4396
5117
  if (!existsSync8(path)) {
4397
5118
  return [
4398
5119
  {
@@ -4404,7 +5125,7 @@ function checkPriorities(ws) {
4404
5125
  }
4405
5126
  ];
4406
5127
  }
4407
- if (looksUnwritten(readFileSync8(path, "utf8"))) {
5128
+ if (looksUnwritten(readFileSync9(path, "utf8"))) {
4408
5129
  return [
4409
5130
  {
4410
5131
  scope: "workspace",
@@ -4423,7 +5144,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4423
5144
  const scope = entry.handle;
4424
5145
  const out = [];
4425
5146
  const dir = entry.dir ?? entry.handle;
4426
- const root2 = join19(ws.root, dir);
5147
+ const root2 = join20(ws.root, dir);
4427
5148
  if (!existsSync8(root2)) {
4428
5149
  return [
4429
5150
  {
@@ -4435,7 +5156,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4435
5156
  }
4436
5157
  ];
4437
5158
  }
4438
- const manifestPath = join19(root2, "staff.yaml");
5159
+ const manifestPath = join20(root2, "staff.yaml");
4439
5160
  let manifest = {};
4440
5161
  if (!existsSync8(manifestPath)) {
4441
5162
  out.push({
@@ -4447,7 +5168,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4447
5168
  });
4448
5169
  } else {
4449
5170
  try {
4450
- manifest = composer.parseYaml(readFileSync8(manifestPath, "utf8"), "staff.yaml");
5171
+ manifest = composer.parseYaml(readFileSync9(manifestPath, "utf8"), "staff.yaml");
4451
5172
  if (manifest.handle !== entry.handle) {
4452
5173
  out.push({
4453
5174
  scope,
@@ -4476,7 +5197,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4476
5197
  });
4477
5198
  }
4478
5199
  }
4479
- const charterPath = join19(root2, "CHARTER.md");
5200
+ const charterPath = join20(root2, "CHARTER.md");
4480
5201
  out.push(
4481
5202
  existsSync8(charterPath) ? { scope, level: "ok", id: "charter", title: "CHARTER.md present" } : {
4482
5203
  scope,
@@ -4486,7 +5207,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4486
5207
  fix: "The charter is the personality; nothing else supplies it."
4487
5208
  }
4488
5209
  );
4489
- if (existsSync8(charterPath) && looksUnwritten(readFileSync8(charterPath, "utf8"))) {
5210
+ if (existsSync8(charterPath) && looksUnwritten(readFileSync9(charterPath, "utf8"))) {
4490
5211
  out.push({
4491
5212
  scope,
4492
5213
  level: "warn",
@@ -4495,8 +5216,8 @@ async function checkStaff(ws, org, entry, composer, online) {
4495
5216
  fix: `roster brief charter ${entry.handle}, or "Write the charter" on the portal's Staff screen`
4496
5217
  });
4497
5218
  }
4498
- const memDir = join19(root2, "memory");
4499
- if (!existsSync8(join19(memDir, "INDEX.md"))) {
5219
+ const memDir = join20(root2, "memory");
5220
+ if (!existsSync8(join20(memDir, "INDEX.md"))) {
4500
5221
  out.push({
4501
5222
  scope,
4502
5223
  level: "fail",
@@ -4593,7 +5314,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4593
5314
  fix: "A private reusable workflow is only callable inside its own org, so this can never resolve."
4594
5315
  });
4595
5316
  }
4596
- const local = join19(ws.opsDir, ref.slice(opsRepo.length + 1));
5317
+ const local = join20(ws.opsDir, ref.slice(opsRepo.length + 1));
4597
5318
  if (!existsSync8(local)) {
4598
5319
  out.push({
4599
5320
  scope,
@@ -4612,7 +5333,7 @@ async function checkStaff(ws, org, entry, composer, online) {
4612
5333
  title: `2 callers, both pointing at ${opsRepo}`
4613
5334
  });
4614
5335
  }
4615
- const missing2 = (manifest.surfaces ?? []).map((s) => s.path).filter((p) => p && !existsSync8(join19(root2, p)));
5336
+ const missing2 = (manifest.surfaces ?? []).map((s) => s.path).filter((p) => p && !existsSync8(join20(root2, p)));
4616
5337
  if (missing2.length) {
4617
5338
  out.push({
4618
5339
  scope,
@@ -4624,7 +5345,8 @@ async function checkStaff(ws, org, entry, composer, online) {
4624
5345
  }
4625
5346
  if (online && manifest.brain) {
4626
5347
  const logins = humanLogins(org);
4627
- out.push(...await checkStaffOnline(scope, manifest, callers, logins));
5348
+ 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) }));
5349
+ out.push(...await checkStaffOnline(scope, manifest, callers, logins, keys));
4628
5350
  }
4629
5351
  return out;
4630
5352
  }
@@ -4656,10 +5378,10 @@ function inferredCeiling(cancelled) {
4656
5378
  return most >= 2 ? best : null;
4657
5379
  }
4658
5380
  function readCallers(root2, handle) {
4659
- const dir = join19(root2, ".github", "workflows");
5381
+ const dir = join20(root2, ".github", "workflows");
4660
5382
  if (!existsSync8(dir)) return [];
4661
5383
  const mine = new RegExp(`^${handle}-(daily|mention)\\.ya?ml$`);
4662
- return readdirSync5(dir).filter((f) => mine.test(f)).sort().map((name) => ({ name, text: readFileSync8(join19(dir, name), "utf8") }));
5384
+ return readdirSync5(dir).filter((f) => mine.test(f)).sort().map((name) => ({ name, text: readFileSync9(join20(dir, name), "utf8") }));
4663
5385
  }
4664
5386
  async function checkOrgOnline(ws, org) {
4665
5387
  const out = [];
@@ -4739,10 +5461,10 @@ async function checkReviewGates(ws, org, composer) {
4739
5461
  );
4740
5462
  const apps = /* @__PURE__ */ new Set();
4741
5463
  for (const s of org.staff ?? []) {
4742
- const path = join19(ws.root, s.dir ?? s.handle, "staff.yaml");
5464
+ const path = join20(ws.root, s.dir ?? s.handle, "staff.yaml");
4743
5465
  if (!existsSync8(path)) continue;
4744
5466
  try {
4745
- const m = composer.parseYaml(readFileSync8(path, "utf8"), "staff.yaml");
5467
+ const m = composer.parseYaml(readFileSync9(path, "utf8"), "staff.yaml");
4746
5468
  for (const w of m.works_in ?? []) if (w?.repo) repos.add(String(w.repo));
4747
5469
  for (const i of m.identities ?? []) if (i?.app) apps.add(String(i.app));
4748
5470
  } catch {
@@ -4751,12 +5473,13 @@ async function checkReviewGates(ws, org, composer) {
4751
5473
  const readings = await Promise.all([...repos].map((r) => readGate(r, [...apps])));
4752
5474
  return readings.map((r) => ({ scope: "workspace", id: "review-gate", ...judgeGate(r) }));
4753
5475
  }
4754
- async function checkStaffOnline(scope, manifest, callers, humans = []) {
5476
+ async function checkStaffOnline(scope, manifest, callers, humans = [], connectors = []) {
4755
5477
  const out = [];
4756
5478
  const repo = manifest.brain;
4757
5479
  const needed = /* @__PURE__ */ new Set();
4758
5480
  for (const c of callers) {
4759
5481
  for (const m of c.text.matchAll(/secrets\.([A-Z0-9_]+)/g)) needed.add(m[1]);
5482
+ for (const name of inheritedSecrets(c.text)) needed.add(name);
4760
5483
  }
4761
5484
  const [secrets, orgSecrets, labels, runs, pinned, workflows, open2] = await Promise.all([
4762
5485
  api(`repos/${repo}/actions/secrets`),
@@ -4817,6 +5540,26 @@ async function checkStaffOnline(scope, manifest, callers, humans = []) {
4817
5540
  title: `all ${needed.size} referenced secrets present` + (fromOrg.length ? `, ${fromOrg.join(", ")} shared from the org` : "")
4818
5541
  }
4819
5542
  );
5543
+ for (const c of connectors) {
5544
+ const gone2 = c.secrets.filter((n) => !have.has(n) && !shared.has(n));
5545
+ if (!gone2.length) continue;
5546
+ out.push({
5547
+ scope,
5548
+ level: "warn",
5549
+ id: "connector.key",
5550
+ title: `${c.name} has no key on ${repo}: ${gone2.join(", ")}`,
5551
+ fix: "Runs go ahead without it. Store the key from the portal's Connectors page, or roster connector add with --apply."
5552
+ });
5553
+ }
5554
+ }
5555
+ if (connectors.length && callers.some((c) => !/^\s*secrets:\s*inherit\s*$/m.test(c.text))) {
5556
+ out.push({
5557
+ scope,
5558
+ level: "warn",
5559
+ id: "connector.caller",
5560
+ title: "the callers predate connectors, so no connector's key reaches a run",
5561
+ fix: "roster upgrade --apply regenerates them to pass their secrets on."
5562
+ });
4820
5563
  }
4821
5564
  if (!labels.ok) {
4822
5565
  out.push({
@@ -4828,8 +5571,8 @@ async function checkStaffOnline(scope, manifest, callers, humans = []) {
4828
5571
  });
4829
5572
  } else {
4830
5573
  const have = new Set(labels.data.map((l) => l.name));
4831
- const declared = Object.values(manifest.labels ?? {}).flat();
4832
- const gone = [...new Set(declared)].filter((l) => !have.has(l));
5574
+ const declared3 = Object.values(manifest.labels ?? {}).flat();
5575
+ const gone = [...new Set(declared3)].filter((l) => !have.has(l));
4833
5576
  out.push(
4834
5577
  gone.length ? {
4835
5578
  scope,
@@ -4991,19 +5734,19 @@ async function checkStaffOnline(scope, manifest, callers, humans = []) {
4991
5734
  return out;
4992
5735
  }
4993
5736
  async function checkWorkflows(scope, repo, skip) {
4994
- const list = await api(`repos/${repo}/actions/workflows?per_page=100`);
4995
- if (!list.ok) {
5737
+ const list2 = await api(`repos/${repo}/actions/workflows?per_page=100`);
5738
+ if (!list2.ok) {
4996
5739
  return [
4997
5740
  {
4998
5741
  scope,
4999
5742
  level: "warn",
5000
5743
  id: "workflows",
5001
- title: `cannot read the workflows on ${repo}: ${list.error}`,
5744
+ title: `cannot read the workflows on ${repo}: ${list2.error}`,
5002
5745
  fix: "Check your access to the repo; a failing workflow there would go unseen."
5003
5746
  }
5004
5747
  ];
5005
5748
  }
5006
- const mine = (list.data?.workflows ?? []).filter(
5749
+ const mine = (list2.data?.workflows ?? []).filter(
5007
5750
  (w) => w.state === "active" && !skip.has(w.path.split("/").pop() ?? "")
5008
5751
  );
5009
5752
  const streaks = await Promise.all(
@@ -5109,7 +5852,7 @@ async function checkBudgets(org, staff, whole) {
5109
5852
  return out;
5110
5853
  }
5111
5854
  var GLYPH2 = { ok: "\u2713", warn: "!", fail: "\u2717" };
5112
- function report2(org, found, online, asked) {
5855
+ function report3(org, found, online, asked) {
5113
5856
  process.stdout.write(`
5114
5857
  roster doctor \u2014 ${org.name} (${org.org})
5115
5858
  `);
@@ -5147,7 +5890,7 @@ function ago(iso) {
5147
5890
  if (s < 172800) return `${Math.round(s / 3600)}h ago`;
5148
5891
  return `${Math.round(s / 86400)}d ago`;
5149
5892
  }
5150
- function parseFlags7(argv) {
5893
+ function parseFlags8(argv) {
5151
5894
  const out = {};
5152
5895
  for (let i = 0; i < argv.length; i++) {
5153
5896
  if (argv[i] === "--offline") out.offline = true;
@@ -5183,13 +5926,61 @@ function unkindedAsks(scope, repo, issues, humans) {
5183
5926
  }
5184
5927
  ];
5185
5928
  }
5929
+ function inheritedSecrets(callerText) {
5930
+ if (!/^\s*secrets:\s*inherit\s*$/m.test(callerText)) return [];
5931
+ const input = (name) => callerText.match(new RegExp(`^\\s*${name}:\\s*([A-Z0-9_]+)\\s*$`, "m"))?.[1];
5932
+ const out = [];
5933
+ for (const prefix of [input("secret_prefix"), input("public_secret_prefix")]) {
5934
+ if (prefix) out.push(`${prefix}_APP_ID`, `${prefix}_APP_PRIVATE_KEY`);
5935
+ }
5936
+ const agent = input("agent_secret");
5937
+ if (agent) out.push(agent);
5938
+ return [...new Set(out)];
5939
+ }
5940
+ function checkConnectors(org) {
5941
+ const all = declared2(org);
5942
+ if (!all.length) return [];
5943
+ const scope = "workspace";
5944
+ const out = [];
5945
+ const handles = new Set((org.staff ?? []).map((s) => s.handle));
5946
+ for (const c of all) {
5947
+ if (c.problem) {
5948
+ out.push({
5949
+ scope,
5950
+ level: "warn",
5951
+ id: "connector",
5952
+ title: c.problem,
5953
+ fix: "Runs leave it out until this is fixed. See docs/connectors.md."
5954
+ });
5955
+ }
5956
+ const strangers = c.staff.filter((h) => !handles.has(h));
5957
+ if (strangers.length) {
5958
+ out.push({
5959
+ scope,
5960
+ level: "warn",
5961
+ id: "connector.staff",
5962
+ title: `${c.name} is given to ${strangers.join(", ")}, who is not in org.yaml's staff`,
5963
+ fix: "A handle there has to match a staff member's handle exactly."
5964
+ });
5965
+ }
5966
+ }
5967
+ if (!out.length) {
5968
+ out.push({
5969
+ scope,
5970
+ level: "ok",
5971
+ id: "connector",
5972
+ title: `${all.length} connector${all.length === 1 ? "" : "s"}: ${all.map((c) => c.name).join(", ")}`
5973
+ });
5974
+ }
5975
+ return out;
5976
+ }
5186
5977
 
5187
5978
  // src/commands/export.ts
5188
- import { writeFileSync as writeFileSync7 } from "fs";
5979
+ import { writeFileSync as writeFileSync8 } from "fs";
5189
5980
 
5190
5981
  // src/lib/export.ts
5191
5982
  import { execFileSync as execFileSync6 } from "child_process";
5192
- import { join as join20, relative as relative3 } from "path";
5983
+ import { join as join21, relative as relative3 } from "path";
5193
5984
  var gitHistory = {
5194
5985
  log: (root2, n, path) => gitLog(root2, n, path ? ["--", path] : []),
5195
5986
  factsChanged: (root2, since) => factsChanged(root2, since)
@@ -5200,11 +5991,11 @@ function buildExport(ws, org, parseYaml3, opts = {}) {
5200
5991
  const history = opts.history ?? gitHistory;
5201
5992
  for (const entry of org.staff ?? []) {
5202
5993
  const dir = entry.dir ?? entry.handle;
5203
- const root2 = join20(ws.root, dir);
5994
+ const root2 = join21(ws.root, dir);
5204
5995
  if (!existsSync2(root2)) continue;
5205
5996
  const manifest = readManifest2(root2, parseYaml3);
5206
- const memDir = join20(root2, "memory");
5207
- const doc = existsSync2(join20(memDir, "INDEX.md")) ? parseMemory(memDir) : { facts: [], sections: [], notes: [], preamble: "", links: [] };
5997
+ const memDir = join21(root2, "memory");
5998
+ const doc = existsSync2(join21(memDir, "INDEX.md")) ? parseMemory(memDir) : { facts: [], sections: [], notes: [], preamble: "", links: [] };
5208
5999
  const commits = history.log(root2, 25);
5209
6000
  staff.push({
5210
6001
  handle: entry.handle,
@@ -5224,7 +6015,7 @@ function buildExport(ws, org, parseYaml3, opts = {}) {
5224
6015
  sections: doc.sections,
5225
6016
  notes: doc.notes,
5226
6017
  links: doc.links,
5227
- problems: existsSync2(join20(memDir, "INDEX.md")) ? lintMemory(doc, memDir, budgetsFor(org, manifest)) : [],
6018
+ problems: existsSync2(join21(memDir, "INDEX.md")) ? lintMemory(doc, memDir, budgetsFor(org, manifest)) : [],
5228
6019
  surfaces: readSurfaces(root2, manifest.surfaces ?? []),
5229
6020
  recentCommits: commits,
5230
6021
  factsChanged: history.factsChanged(root2, opts.since ?? "14 days ago"),
@@ -5252,7 +6043,7 @@ function botName(raw) {
5252
6043
  return String(raw).replace(/\[bot\]$/, "");
5253
6044
  }
5254
6045
  function readManifest2(root2, parseYaml3) {
5255
- const path = join20(root2, "staff.yaml");
6046
+ const path = join21(root2, "staff.yaml");
5256
6047
  if (!existsSync2(path)) return {};
5257
6048
  try {
5258
6049
  return parseYaml3(readFileSync2(path, "utf8"), "staff.yaml");
@@ -5261,16 +6052,16 @@ function readManifest2(root2, parseYaml3) {
5261
6052
  }
5262
6053
  }
5263
6054
  function readRig(root2, manifest, commits, history) {
5264
- const wfDir = join20(root2, ".github", "workflows");
5265
- const declared = manifest.surfaces ?? [];
6055
+ const wfDir = join21(root2, ".github", "workflows");
6056
+ const declared3 = manifest.surfaces ?? [];
5266
6057
  return {
5267
6058
  workflows: existsSync2(wfDir) ? readdirSync2(wfDir).filter((f) => /\.ya?ml$/.test(f)).sort() : [],
5268
- hasCharter: existsSync2(join20(root2, "CHARTER.md")),
5269
- charterStub: !existsSync2(join20(root2, "CHARTER.md")) || looksUnwritten(readFileSync2(join20(root2, "CHARTER.md"), "utf8")),
5270
- hasManifest: existsSync2(join20(root2, "staff.yaml")),
5271
- missingSurfaces: declared.filter((s) => s?.path && !existsSync2(join20(root2, s.path))).map((s) => s.path),
5272
- memoryBytes: bytesOf(join20(root2, "memory", "INDEX.md")),
5273
- notesBytes: dirBytes(join20(root2, "memory", "notes")),
6059
+ hasCharter: existsSync2(join21(root2, "CHARTER.md")),
6060
+ charterStub: !existsSync2(join21(root2, "CHARTER.md")) || looksUnwritten(readFileSync2(join21(root2, "CHARTER.md"), "utf8")),
6061
+ hasManifest: existsSync2(join21(root2, "staff.yaml")),
6062
+ missingSurfaces: declared3.filter((s) => s?.path && !existsSync2(join21(root2, s.path))).map((s) => s.path),
6063
+ memoryBytes: bytesOf(join21(root2, "memory", "INDEX.md")),
6064
+ notesBytes: dirBytes(join21(root2, "memory", "notes")),
5274
6065
  lastCommit: commits[0],
5275
6066
  lastMemoryCommit: history.log(root2, 1, "memory")[0]
5276
6067
  };
@@ -5286,17 +6077,17 @@ function dirBytes(dir) {
5286
6077
  if (!existsSync2(dir)) return 0;
5287
6078
  return walk2(dir, dir).reduce((n, f) => n + f.bytes, 0);
5288
6079
  }
5289
- function readSurfaces(root2, declared) {
5290
- return declared.filter((s) => s?.path && existsSync2(join20(root2, s.path))).map((s) => ({
6080
+ function readSurfaces(root2, declared3) {
6081
+ return declared3.filter((s) => s?.path && existsSync2(join21(root2, s.path))).map((s) => ({
5291
6082
  path: s.path,
5292
6083
  render: s.render ?? "doc",
5293
- files: walk2(join20(root2, s.path), root2)
6084
+ files: walk2(join21(root2, s.path), root2)
5294
6085
  }));
5295
6086
  }
5296
6087
  function walk2(dir, root2, out = []) {
5297
6088
  for (const name of readdirSync2(dir)) {
5298
6089
  if (SKIP.has(name)) continue;
5299
- const full = join20(dir, name);
6090
+ const full = join21(dir, name);
5300
6091
  const st = statSync2(full);
5301
6092
  if (st.isDirectory()) walk2(full, root2, out);
5302
6093
  else {
@@ -5387,7 +6178,7 @@ async function exportCommand(argv) {
5387
6178
  const data = buildExport(ws, readOrg(ws.opsDir, parseYaml3), parseYaml3);
5388
6179
  const json3 = JSON.stringify(data, null, 2);
5389
6180
  if (out) {
5390
- writeFileSync7(out, json3 + "\n");
6181
+ writeFileSync8(out, json3 + "\n");
5391
6182
  const facts = data.staff.reduce((n, s) => n + s.facts.length, 0);
5392
6183
  process.stdout.write(
5393
6184
  ` ${out} ${data.staff.length} staff, ${facts} facts, ${Math.round(json3.length / 1024)}kb
@@ -5400,13 +6191,13 @@ async function exportCommand(argv) {
5400
6191
  }
5401
6192
 
5402
6193
  // src/lib/audit.ts
5403
- import { join as join21 } from "path";
6194
+ import { join as join22 } from "path";
5404
6195
  var LONG_WORDS = 3500;
5405
6196
  var ECHO_CHARS = 60;
5406
6197
  function auditPrompt(ws, view, roots) {
5407
6198
  const out = [];
5408
6199
  const text2 = (rel) => {
5409
- const full = join21(ws.root, rel);
6200
+ const full = join22(ws.root, rel);
5410
6201
  return existsSync2(full) ? readFileSync2(full, "utf8") : "";
5411
6202
  };
5412
6203
  for (const layer of [...view.layers, ...view.runtime]) {
@@ -5460,9 +6251,9 @@ Decide which layer each one belongs in and remove it from the others.`
5460
6251
  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.`
5461
6252
  });
5462
6253
  }
5463
- const bases = [ws.root, ...roots.map((r) => join21(ws.root, r))];
6254
+ const bases = [ws.root, ...roots.map((r) => join22(ws.root, r))];
5464
6255
  for (const rel of namedPaths(view.composed)) {
5465
- if (bases.some((b) => existsSync2(join21(b, rel)))) continue;
6256
+ if (bases.some((b) => existsSync2(join22(b, rel)))) continue;
5466
6257
  out.push({
5467
6258
  id: "dangling",
5468
6259
  level: "warning",
@@ -5559,7 +6350,7 @@ function classifyFinding(id) {
5559
6350
  return "agent";
5560
6351
  }
5561
6352
  async function fixCommand(argv) {
5562
- const opts = parseFlags8(argv);
6353
+ const opts = parseFlags9(argv);
5563
6354
  const ws = findWorkspace(opts.ops);
5564
6355
  const items = await gather(ws, opts.offline === true);
5565
6356
  if (opts.json) {
@@ -5572,9 +6363,9 @@ async function fixCommand(argv) {
5572
6363
  }
5573
6364
  async function gather(ws, offline) {
5574
6365
  const items = [];
5575
- const report3 = await collect({ ops: ws.opsDir, offline });
5576
- if (!report3) return items;
5577
- for (const f of report3.findings) {
6366
+ const report4 = await collect({ ops: ws.opsDir, offline });
6367
+ if (!report4) return items;
6368
+ for (const f of report4.findings) {
5578
6369
  if (f.level === "ok") continue;
5579
6370
  items.push({
5580
6371
  id: f.id,
@@ -5661,7 +6452,7 @@ Nothing to fix. \`roster doctor\` is clean.
5661
6452
  "them is reverted by the next `roster upgrade`, and the mistake is invisible until it is",
5662
6453
  "expensive. Do not touch:",
5663
6454
  "",
5664
- `- \`${ws.opsName}/compose.mjs\`, \`agents.mjs\`, \`runner-plan.mjs\`, \`inflight.mjs\`, \`run-record.mjs\`, \`status-week.mjs\` \u2014 vendored from the framework.`,
6455
+ `- \`${ws.opsName}/compose.mjs\`, \`agents.mjs\`, \`connectors.mjs\`, \`runner-plan.mjs\`, \`inflight.mjs\`, \`run-record.mjs\`, \`status-week.mjs\` \u2014 vendored from the framework.`,
5665
6456
  `- \`${ws.opsName}/.github/workflows/\` and any brain's \`.github/workflows/\` \u2014 generated, and`,
5666
6457
  " GitHub App tokens cannot push changes there in any case.",
5667
6458
  `- \`${ws.opsName}/.roster/\` \u2014 the recorded merge base.`,
@@ -5719,7 +6510,7 @@ Nothing to fix. \`roster doctor\` is clean.
5719
6510
  function count(n, noun) {
5720
6511
  return `${n} ${noun}${n === 1 ? "" : "s"}`;
5721
6512
  }
5722
- function parseFlags8(argv) {
6513
+ function parseFlags9(argv) {
5723
6514
  const out = {};
5724
6515
  for (let i = 0; i < argv.length; i++) {
5725
6516
  const flag = argv[i];
@@ -5741,8 +6532,8 @@ function parseFlags8(argv) {
5741
6532
 
5742
6533
  // src/commands/init.ts
5743
6534
  import { execFileSync as execFileSync7 } from "child_process";
5744
- import { existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync9, writeFileSync as writeFileSync8 } from "fs";
5745
- import { dirname as dirname8, join as join22, resolve as resolve3 } from "path";
6535
+ import { existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync10, writeFileSync as writeFileSync9 } from "fs";
6536
+ import { dirname as dirname8, join as join23, resolve as resolve3 } from "path";
5746
6537
  var initHelp = `
5747
6538
  roster init --org <github-org> [--name "Acme"] [--human <login>] [--apply]
5748
6539
 
@@ -5772,7 +6563,7 @@ roster init --org <github-org> [--name "Acme"] [--human <login>] [--apply]
5772
6563
  After this: \`roster hire <handle>\` for the first staff member, then \`roster app <handle>\`.
5773
6564
  `;
5774
6565
  async function initCommand(argv) {
5775
- const opts = parseFlags9(argv);
6566
+ const opts = parseFlags10(argv);
5776
6567
  if (!opts.org) {
5777
6568
  process.stderr.write("roster: init needs --org <github-org>\n");
5778
6569
  return 2;
@@ -5787,7 +6578,7 @@ async function initCommand(argv) {
5787
6578
  const name = opts.name ?? opts.org;
5788
6579
  const opsName = opts.ops ?? "roster-ops";
5789
6580
  const root2 = resolve3(opts.dir ?? process.cwd());
5790
- const opsDir = join22(root2, opsName);
6581
+ const opsDir = join23(root2, opsName);
5791
6582
  const marker = opts.marker ?? human.split("-")[0];
5792
6583
  if (existsSync9(opsDir)) {
5793
6584
  process.stderr.write(`roster: ${opsDir} already exists. This org is already initialised.
@@ -5836,14 +6627,14 @@ async function initCommand(argv) {
5836
6627
  }
5837
6628
  mkdirSync5(opsDir, { recursive: true });
5838
6629
  for (const [rel, text2] of files) {
5839
- const dest = join22(opsDir, rel);
6630
+ const dest = join23(opsDir, rel);
5840
6631
  mkdirSync5(dirname8(dest), { recursive: true });
5841
- writeFileSync8(dest, text2);
6632
+ writeFileSync9(dest, text2);
5842
6633
  }
5843
6634
  for (const rel of templateFiles(opsTemplateDir())) {
5844
- const dest = join22(opsDir, ".roster", "seed", rel);
6635
+ const dest = join23(opsDir, ".roster", "seed", rel);
5845
6636
  mkdirSync5(dirname8(dest), { recursive: true });
5846
- writeFileSync8(dest, readFileSync9(join22(opsTemplateDir(), rel), "utf8"));
6637
+ writeFileSync9(dest, readFileSync10(join23(opsTemplateDir(), rel), "utf8"));
5847
6638
  }
5848
6639
  process.stdout.write(` wrote ${files.size} files and the recorded base
5849
6640
  `);
@@ -5893,7 +6684,7 @@ async function initCommand(argv) {
5893
6684
  async function initFiles(o) {
5894
6685
  const files = /* @__PURE__ */ new Map();
5895
6686
  for (const rel of templateFiles(opsTemplateDir())) {
5896
- files.set(rel, readFileSync9(join22(opsTemplateDir(), rel), "utf8"));
6687
+ files.set(rel, readFileSync10(join23(opsTemplateDir(), rel), "utf8"));
5897
6688
  }
5898
6689
  const agent = o.agent ?? "claude-code-action";
5899
6690
  const preset = await agentPreset(agent);
@@ -5918,7 +6709,7 @@ async function initFiles(o) {
5918
6709
  return files;
5919
6710
  }
5920
6711
  async function agentPreset(id) {
5921
- const path = join22(opsTemplateDir(), "agents.mjs");
6712
+ const path = join23(opsTemplateDir(), "agents.mjs");
5922
6713
  const { PRESETS } = await import(`file://${path}`);
5923
6714
  const preset = PRESETS[id];
5924
6715
  if (!preset) {
@@ -6052,7 +6843,7 @@ function stamp2() {
6052
6843
  try {
6053
6844
  return execFileSync7(
6054
6845
  "git",
6055
- ["-C", join22(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
6846
+ ["-C", join23(opsTemplateDir(), "..", ".."), "rev-parse", "--short", "HEAD"],
6056
6847
  {
6057
6848
  encoding: "utf8",
6058
6849
  stdio: ["ignore", "pipe", "ignore"]
@@ -6065,7 +6856,7 @@ function stamp2() {
6065
6856
  function git3(cwd, args) {
6066
6857
  execFileSync7("git", args, { cwd, stdio: ["ignore", "ignore", "pipe"] });
6067
6858
  }
6068
- function parseFlags9(argv) {
6859
+ function parseFlags10(argv) {
6069
6860
  const out = {};
6070
6861
  for (let i = 0; i < argv.length; i++) {
6071
6862
  const flag = argv[i];
@@ -6088,7 +6879,7 @@ function parseFlags9(argv) {
6088
6879
  }
6089
6880
 
6090
6881
  // src/commands/lint.ts
6091
- import { join as join23 } from "path";
6882
+ import { join as join24 } from "path";
6092
6883
  var lintHelp = `
6093
6884
  roster lint [handle]
6094
6885
 
@@ -6103,7 +6894,7 @@ roster lint [handle]
6103
6894
  `;
6104
6895
  async function lintCommand(argv) {
6105
6896
  const handle = argv[0] && !argv[0].startsWith("-") ? argv[0] : void 0;
6106
- const opts = parseFlags10(argv.slice(handle ? 1 : 0));
6897
+ const opts = parseFlags11(argv.slice(handle ? 1 : 0));
6107
6898
  const ws = findWorkspace(opts.ops);
6108
6899
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
6109
6900
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -6116,8 +6907,8 @@ async function lintCommand(argv) {
6116
6907
  let errors = 0;
6117
6908
  let warnings = 0;
6118
6909
  for (const s of staff) {
6119
- const root2 = join23(ws.root, s.dir ?? s.handle);
6120
- const dir = join23(root2, "memory");
6910
+ const root2 = join24(ws.root, s.dir ?? s.handle);
6911
+ const dir = join24(root2, "memory");
6121
6912
  const budgets = budgetsFor(org, readManifest2(root2, parseYaml3));
6122
6913
  let problems;
6123
6914
  let factCount = 0;
@@ -6161,7 +6952,7 @@ async function lintCommand(argv) {
6161
6952
  );
6162
6953
  return errors > 0 ? 1 : 0;
6163
6954
  }
6164
- function parseFlags10(argv) {
6955
+ function parseFlags11(argv) {
6165
6956
  const out = {};
6166
6957
  for (let i = 0; i < argv.length; i++) {
6167
6958
  if (argv[i] === "--quiet") out.quiet = true;
@@ -6173,14 +6964,14 @@ function parseFlags10(argv) {
6173
6964
 
6174
6965
  // src/commands/portal.ts
6175
6966
  import { randomBytes as randomBytes3 } from "crypto";
6176
- import { readFileSync as readFileSync13 } from "fs";
6967
+ import { readFileSync as readFileSync14 } from "fs";
6177
6968
  import { createServer as createServer2 } from "http";
6178
- import { join as join32, resolve as resolve7 } from "path";
6969
+ import { join as join32, resolve as resolve6 } from "path";
6179
6970
 
6180
6971
  // src/lib/attach.ts
6181
6972
  import { execFileSync as execFileSync8 } from "child_process";
6182
- import { existsSync as existsSync10, mkdirSync as mkdirSync6, writeFileSync as writeFileSync9 } from "fs";
6183
- import { basename, extname, join as join24 } from "path";
6973
+ import { existsSync as existsSync10, mkdirSync as mkdirSync6, writeFileSync as writeFileSync10 } from "fs";
6974
+ import { basename, extname, join as join25 } from "path";
6184
6975
  var MAX_UPLOAD = 25 * 1024 * 1024;
6185
6976
  var ATTACH_DIR = "attachments";
6186
6977
  function safeName(raw) {
@@ -6257,15 +7048,15 @@ function openBrowser(url) {
6257
7048
  // src/lib/sync.ts
6258
7049
  import { execFile as execFile5 } from "child_process";
6259
7050
  import { existsSync as existsSync11 } from "fs";
6260
- import { join as join25 } from "path";
7051
+ import { join as join26 } from "path";
6261
7052
  import { promisify as promisify3 } from "util";
6262
7053
  var run3 = promisify3(execFile5);
6263
7054
  async function syncRepos(root2, dirs) {
6264
- return Promise.all(dirs.map((dir) => syncOne(join25(root2, dir), dir)));
7055
+ return Promise.all(dirs.map((dir) => syncOne(join26(root2, dir), dir)));
6265
7056
  }
6266
7057
  async function syncOne(path, dir) {
6267
7058
  const base2 = { dir, behind: 0, ahead: 0, dirty: false, pulled: false };
6268
- if (!existsSync11(join25(path, ".git"))) return { ...base2, skipped: "no-remote" };
7059
+ if (!existsSync11(join26(path, ".git"))) return { ...base2, skipped: "no-remote" };
6269
7060
  const git4 = async (...args) => (await run3("git", ["-C", path, ...args], { encoding: "utf8" })).stdout.trim();
6270
7061
  try {
6271
7062
  const remotes = await git4("remote");
@@ -6300,25 +7091,25 @@ function reason(e) {
6300
7091
  }
6301
7092
 
6302
7093
  // src/portal/assets.ts
6303
- import { existsSync as existsSync12, readFileSync as readFileSync10, statSync as statSync3 } from "fs";
6304
- import { dirname as dirname9, extname as extname2, join as join26, resolve as resolve4 } from "path";
7094
+ import { existsSync as existsSync12, readFileSync as readFileSync11, statSync as statSync3 } from "fs";
7095
+ import { dirname as dirname9, extname as extname2, join as join27, resolve as resolve4 } from "path";
6305
7096
  import { fileURLToPath as fileURLToPath4 } from "url";
6306
7097
  function portalDir() {
6307
7098
  const fixed = frameworkRoot();
6308
- if (fixed) return join26(fixed, "templates", "portal");
7099
+ if (fixed) return join27(fixed, "templates", "portal");
6309
7100
  const here = dirname9(fileURLToPath4(import.meta.url));
6310
7101
  const candidates = [
6311
- join26(here, "..", "..", "templates", "portal"),
7102
+ join27(here, "..", "..", "templates", "portal"),
6312
7103
  // src/portal → package root
6313
- join26(here, "..", "templates", "portal")
7104
+ join27(here, "..", "templates", "portal")
6314
7105
  // dist → package root
6315
7106
  ];
6316
- for (const path of candidates) if (existsSync12(join26(path, "index.html"))) return path;
7107
+ for (const path of candidates) if (existsSync12(join27(path, "index.html"))) return path;
6317
7108
  throw new Error(`portal UI not found. Looked in:
6318
7109
  ${candidates.join("\n ")}`);
6319
7110
  }
6320
7111
  function portalIndex() {
6321
- return readFileSync10(join26(portalDir(), "index.html"), "utf8");
7112
+ return readFileSync11(join27(portalDir(), "index.html"), "utf8");
6322
7113
  }
6323
7114
  var ASSET_MIME = {
6324
7115
  ".css": "text/css; charset=utf-8",
@@ -6335,335 +7126,11 @@ function portalAsset(rel) {
6335
7126
  const type = ASSET_MIME[extname2(full).toLowerCase()];
6336
7127
  if (!type) return null;
6337
7128
  if (!existsSync12(full) || statSync3(full).isDirectory()) return null;
6338
- return { body: readFileSync10(full), type };
7129
+ return { body: readFileSync11(full), type };
6339
7130
  }
6340
7131
 
6341
7132
  // src/portal/handler.ts
6342
- import { join as join29, resolve as resolve6 } from "path";
6343
-
6344
- // templates/ops/compose.mjs
6345
- import * as nodeFs from "fs";
6346
- import { join as join27, dirname as dirname10, resolve as resolve5 } from "path";
6347
- import { fileURLToPath as fileURLToPath5 } from "url";
6348
- function parseYaml(text2, file = "<yaml>") {
6349
- const lines = [];
6350
- text2.split("\n").forEach((raw, i) => {
6351
- const noComment = stripComment(raw);
6352
- if (!noComment.trim()) return;
6353
- if (noComment.trim() === "---") return;
6354
- lines.push({ n: i + 1, indent: raw.match(/^ */)[0].length, text: noComment.trimEnd() });
6355
- });
6356
- let pos = 0;
6357
- const fail = (msg, line) => {
6358
- throw new Error(`${file}:${line?.n ?? "?"} ${msg}`);
6359
- };
6360
- function parseBlock(indent) {
6361
- const first = lines[pos];
6362
- if (!first) return null;
6363
- if (first.text.trim().startsWith("- ")) return parseList(indent);
6364
- return parseMap(indent);
6365
- }
6366
- function parseMap(indent) {
6367
- const out = {};
6368
- while (pos < lines.length) {
6369
- const line = lines[pos];
6370
- if (line.indent < indent) break;
6371
- if (line.indent > indent) fail("unexpected indentation", line);
6372
- const body2 = line.text.trim();
6373
- if (body2.startsWith("- ")) break;
6374
- const m = body2.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
6375
- if (!m) fail(`expected "key: value", got ${JSON.stringify(body2)}`, line);
6376
- const [, key, rest] = m;
6377
- pos++;
6378
- if (rest === "") {
6379
- const next = lines[pos];
6380
- if (next && next.indent > indent) out[key] = parseBlock(next.indent);
6381
- else out[key] = null;
6382
- } else {
6383
- out[key] = parseScalar(rest, line);
6384
- }
6385
- }
6386
- return out;
6387
- }
6388
- function parseList(indent) {
6389
- const out = [];
6390
- while (pos < lines.length) {
6391
- const line = lines[pos];
6392
- if (line.indent < indent) break;
6393
- const body2 = line.text.trim();
6394
- if (!body2.startsWith("- ")) break;
6395
- if (line.indent > indent) fail("unexpected indentation in list", line);
6396
- const item = body2.slice(2).trim();
6397
- pos++;
6398
- if (item.startsWith("{") && item.endsWith("}")) {
6399
- out.push(parseInlineMap(item, line));
6400
- } else if (/^[A-Za-z0-9_.-]+:/.test(item)) {
6401
- const sub = { ...parseInlinePair(item, line) };
6402
- while (pos < lines.length && lines[pos].indent > indent) {
6403
- const c = lines[pos];
6404
- const cm = c.text.trim().match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
6405
- if (!cm) fail(`expected "key: value" in list item, got ${JSON.stringify(c.text.trim())}`, c);
6406
- pos++;
6407
- if (cm[2] === "") {
6408
- const next = lines[pos];
6409
- sub[cm[1]] = next && next.indent > c.indent ? parseBlock(next.indent) : null;
6410
- } else {
6411
- sub[cm[1]] = parseScalar(cm[2], c);
6412
- }
6413
- }
6414
- out.push(sub);
6415
- } else {
6416
- out.push(parseScalar(item, line));
6417
- }
6418
- }
6419
- return out;
6420
- }
6421
- function parseInlinePair(item, line) {
6422
- const m = item.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
6423
- if (!m) fail("bad list item", line);
6424
- return { [m[1]]: m[2] === "" ? null : parseScalar(m[2], line) };
6425
- }
6426
- function parseInlineMap(item, line) {
6427
- const out = {};
6428
- for (const part of splitTopLevel(item.slice(1, -1))) {
6429
- if (!part.trim()) continue;
6430
- const m = part.match(/^\s*([A-Za-z0-9_.-]+)\s*:\s*(.*)$/);
6431
- if (!m) fail(`bad inline map entry ${JSON.stringify(part)}`, line);
6432
- out[m[1]] = parseScalar(m[2].trim(), line);
6433
- }
6434
- return out;
6435
- }
6436
- const root2 = parseBlock(lines.length ? lines[0].indent : 0);
6437
- if (pos < lines.length) fail("could not parse to end of file", lines[pos]);
6438
- return root2 ?? {};
6439
- }
6440
- function stripComment(raw) {
6441
- let out = "";
6442
- let quote = null;
6443
- for (let i = 0; i < raw.length; i++) {
6444
- const c = raw[i];
6445
- if (quote) {
6446
- out += c;
6447
- if (c === quote && raw[i - 1] !== "\\") quote = null;
6448
- continue;
6449
- }
6450
- if (c === '"' || c === "'") {
6451
- quote = c;
6452
- out += c;
6453
- continue;
6454
- }
6455
- if (c === "#" && (i === 0 || /\s/.test(raw[i - 1]))) break;
6456
- out += c;
6457
- }
6458
- return out;
6459
- }
6460
- function splitTopLevel(s) {
6461
- const parts = [];
6462
- let depth = 0;
6463
- let cur = "";
6464
- for (const c of s) {
6465
- if (c === "{" || c === "[") depth++;
6466
- if (c === "}" || c === "]") depth--;
6467
- if (c === "," && depth === 0) {
6468
- parts.push(cur);
6469
- cur = "";
6470
- continue;
6471
- }
6472
- cur += c;
6473
- }
6474
- parts.push(cur);
6475
- return parts;
6476
- }
6477
- function parseScalar(raw, line) {
6478
- const v = raw.trim();
6479
- if (v.startsWith("[") && v.endsWith("]")) {
6480
- const inner = v.slice(1, -1).trim();
6481
- return inner === "" ? [] : splitTopLevel(inner).map((s) => parseScalar(s, line));
6482
- }
6483
- if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) {
6484
- return v.slice(1, -1);
6485
- }
6486
- if (v === "true") return true;
6487
- if (v === "false") return false;
6488
- if (v === "null" || v === "~") return null;
6489
- if (/^-?\d+$/.test(v)) return Number(v);
6490
- return v;
6491
- }
6492
- var MAX_INCLUDE_DEPTH = 8;
6493
- var FENCE = "\0";
6494
- function render2(template, ctx, readPartial, depth = 0) {
6495
- if (depth > MAX_INCLUDE_DEPTH) throw new Error("include depth exceeded; a partial probably includes itself");
6496
- let out = template.replace(
6497
- /\{\{#if\s+([A-Za-z0-9_.]+)\s*\}\}\n?([\s\S]*?)\{\{\/if\}\}\n?/g,
6498
- (_, path, body2) => truthy(lookup2(ctx, path)) ? body2 : ""
6499
- );
6500
- out = out.replace(/\{\{>(\??)\s*([^}\s]+)\s*\}\}/g, (_, optional, rel) => {
6501
- const partial = readPartial(rel);
6502
- if (partial === null) {
6503
- if (optional) return "";
6504
- throw new Error(`partial not found: ${rel}`);
6505
- }
6506
- return render2(partial, ctx, readPartial, depth + 1).replace(/\n+$/, "");
6507
- });
6508
- out = out.replace(/\{\{\s*([A-Za-z0-9_.]+)\s*\}\}/g, (_, path) => {
6509
- const v = lookup2(ctx, path);
6510
- if (v === void 0 || v === null) {
6511
- if (path.startsWith("event.")) {
6512
- throw new Error(
6513
- `{{${path}}} needs trigger context, which arrives as ROSTER_CONTEXT.
6514
- A "mention" prompt is written for the comment that woke it, so it cannot
6515
- be composed without one. To see it locally:
6516
- ROSTER_CONTEXT='{"issue_number":"1","comment_id":"1","repo":"o/r"}' \\
6517
- node compose.mjs --staff <handle> --kind <kind>`
6518
- );
6519
- }
6520
- throw new Error(`unknown or empty placeholder: {{${path}}}`);
6521
- }
6522
- return String(v).replace(/\{\{/g, FENCE);
6523
- });
6524
- return depth === 0 ? out.replaceAll(FENCE, "{{") : out;
6525
- }
6526
- function lookup2(ctx, path) {
6527
- return path.split(".").reduce((acc, k) => acc == null ? void 0 : acc[k], ctx);
6528
- }
6529
- function truthy(v) {
6530
- return !(v === void 0 || v === null || v === false || v === "" || Array.isArray(v) && v.length === 0);
6531
- }
6532
- function readHumans2(org) {
6533
- const listed = Array.isArray(org?.humans) ? org.humans : org?.humans ? [org.humans] : [];
6534
- const out = [];
6535
- for (const entry of [...listed, org?.human].filter(Boolean)) {
6536
- const github = String(entry.github ?? entry.login ?? "").trim();
6537
- const name = String(entry.name ?? github).trim();
6538
- if (!github && !name) continue;
6539
- if (github && out.some((h) => h.github.toLowerCase() === github.toLowerCase())) continue;
6540
- out.push({
6541
- github,
6542
- name: name || github,
6543
- marker: String(entry.marker ?? "").trim() || defaultMarker2(name || github),
6544
- role: entry.role ?? void 0,
6545
- ...entry.view_only === true ? { viewOnly: true } : {}
6546
- });
6547
- }
6548
- return out;
6549
- }
6550
- function humanSentence(humans) {
6551
- const parts = humans.map((h) => h.github ? `${h.name} (@${h.github})` : h.name);
6552
- if (parts.length < 2) return parts[0] ?? "";
6553
- return `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
6554
- }
6555
- function defaultMarker2(name) {
6556
- return String(name).trim().split(/[\s-]+/)[0].toLowerCase().replace(/[^a-z0-9]/g, "") || "human";
6557
- }
6558
- function compose({
6559
- opsDir,
6560
- brainsDir,
6561
- staff,
6562
- kind,
6563
- runDir,
6564
- fs: fs2 = nodeFs,
6565
- context = process.env.ROSTER_CONTEXT
6566
- }) {
6567
- const { readFileSync: readFileSync18, existsSync: existsSync18 } = fs2;
6568
- const org = parseYaml(readFileSync18(join27(opsDir, "org.yaml"), "utf8"), "org.yaml");
6569
- const entry = (org.staff ?? []).find((s) => s.handle === staff);
6570
- if (!entry) {
6571
- const known = (org.staff ?? []).map((s) => s.handle).join(", ") || "none";
6572
- throw new Error(`unknown staff handle "${staff}". org.yaml knows: ${known}`);
6573
- }
6574
- const brainDir = resolve5(brainsDir, entry.dir ?? entry.handle);
6575
- const staffFile = join27(brainDir, "staff.yaml");
6576
- if (!existsSync18(staffFile)) throw new Error(`no staff.yaml at ${staffFile}`);
6577
- const self2 = parseYaml(readFileSync18(staffFile, "utf8"), `${entry.handle}/staff.yaml`);
6578
- const peers = (org.staff ?? []).filter((s) => s.handle !== staff).map((s) => ({ ...s, ...s.dir ? {} : { dir: s.handle } }));
6579
- let event2 = {};
6580
- if (context) {
6581
- try {
6582
- event2 = JSON.parse(context);
6583
- } catch (err) {
6584
- throw new Error(`ROSTER_CONTEXT is not valid JSON: ${err.message}`);
6585
- }
6586
- }
6587
- if (Object.keys(event2).length) event2 = { ...event2, no_comment: !event2.comment_id };
6588
- const trigger = String(event2.trigger ?? "");
6589
- event2 = {
6590
- ...event2,
6591
- from_peer: trigger === "peer",
6592
- from_human: trigger !== "peer",
6593
- follow_on: trigger === "follow-on"
6594
- };
6595
- const inflightFile = join27(runDir ?? join27(brainsDir, ".roster-run"), "inflight.md");
6596
- const inflight = existsSync18(inflightFile) ? readFileSync18(inflightFile, "utf8").trim() : "";
6597
- const everyone = readHumans2(org);
6598
- const humans = everyone.filter((h) => !h.viewOnly);
6599
- const ctx = {
6600
- org,
6601
- event: event2,
6602
- // The first is who the prose addresses; `humans` is everybody the mention gate accepts.
6603
- human: humans[0] ?? org.human,
6604
- humans,
6605
- ops: { dir: org.ops_dir ?? "roster-ops" },
6606
- // `dir` lives in the org registry (it is where the checkout lands), everything
6607
- // else lives in the staff member's own manifest.
6608
- staff: {
6609
- ...self2,
6610
- dir: entry.dir ?? entry.handle,
6611
- // The repo this role contributes to but does not own. Named explicitly in the
6612
- // prompt because "a repo you do not own" is vaguer than an agent needs.
6613
- product: (self2.works_in ?? [])[0] ?? null,
6614
- // Absent from manifests written before it existed; the callers fall back to the same.
6615
- max_runs_per_day: self2.max_runs_per_day ?? 6,
6616
- // One staff member drafts next month's org/priorities.md, so there is one draft rather
6617
- // than one per person: whoever org.yaml lists first.
6618
- drafts_priorities: (org.staff ?? [])[0]?.handle === staff
6619
- },
6620
- peers,
6621
- peer: peers[0] ?? null,
6622
- kind,
6623
- // Convenience strings the fragments lean on, computed once here so a
6624
- // fragment never has to do string work.
6625
- peer_list: peers.map((p) => `- \`${p.dir}/\` - the ${p.name}'s brain`).join("\n"),
6626
- // Everybody who can wake this staff member and rule on their work, and the same list
6627
- // without the one the prose already names. Empty when there is only one, which is what
6628
- // makes `{{#if humans_extra}}` the right way to mention the others at all.
6629
- human_list: humanSentence(humans),
6630
- inflight,
6631
- humans_extra: humanSentence(humans.slice(1)),
6632
- // Who can read along and cannot rule. Empty, and the paragraph gone, when nobody is.
6633
- humans_viewing: humanSentence(everyone.filter((h) => h.viewOnly))
6634
- };
6635
- const readPartial = (rel) => {
6636
- const p = rel.startsWith("staff:") ? join27(brainDir, rel.slice(6)) : join27(opsDir, rel);
6637
- return existsSync18(p) ? readFileSync18(p, "utf8") : null;
6638
- };
6639
- const kindFile = join27(opsDir, "prompts", `${kind}.md`);
6640
- if (!existsSync18(kindFile)) throw new Error(`no prompt for kind "${kind}" at ${kindFile}`);
6641
- const body2 = render2(readFileSync18(kindFile, "utf8"), ctx, readPartial);
6642
- return body2.replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
6643
- }
6644
- function main(argv) {
6645
- const args = {};
6646
- for (let i = 0; i < argv.length; i += 2) {
6647
- if (!argv[i].startsWith("--")) throw new Error(`unexpected argument ${argv[i]}`);
6648
- args[argv[i].slice(2)] = argv[i + 1];
6649
- }
6650
- if (!args.staff || !args.kind) {
6651
- console.error("usage: node compose.mjs --staff <handle> --kind <daily|mention> [--ops DIR] [--brains DIR]");
6652
- process.exit(2);
6653
- }
6654
- const opsDir = resolve5(args.ops ?? dirname10(fileURLToPath5(import.meta.url)));
6655
- const brainsDir = resolve5(args.brains ?? join27(opsDir, ".."));
6656
- process.stdout.write(compose({ opsDir, brainsDir, staff: args.staff, kind: args.kind }));
6657
- }
6658
- var self = import.meta.url ? fileURLToPath5(import.meta.url) : "";
6659
- if (process.argv[1] && self.endsWith("compose.mjs") && resolve5(process.argv[1]) === resolve5(self)) {
6660
- try {
6661
- main(process.argv.slice(2));
6662
- } catch (err) {
6663
- console.error(`compose: ${err.message}`);
6664
- process.exit(1);
6665
- }
6666
- }
7133
+ import { join as join29, resolve as resolve5 } from "path";
6667
7134
 
6668
7135
  // src/lib/ask.ts
6669
7136
  var MAX_PATCH_LINES = 40;
@@ -6877,11 +7344,11 @@ function whyNotMerged(ghError, pr) {
6877
7344
  String(c.conclusion || c.state || "")
6878
7345
  )
6879
7346
  );
6880
- const list = (cs) => cs.map(name).join(", ");
7347
+ const list2 = (cs) => cs.map(name).join(", ");
6881
7348
  if (pr?.mergeStateStatus === "BLOCKED" && failing.length)
6882
- return `Not merged: checks failed (${list(failing)}).`;
7349
+ return `Not merged: checks failed (${list2(failing)}).`;
6883
7350
  if (pr?.mergeStateStatus === "BLOCKED" && running.length)
6884
- return `Not merged: checks are still running (${list(running)}). Merge again once they pass.`;
7351
+ return `Not merged: checks are still running (${list2(running)}). Merge again once they pass.`;
6885
7352
  if (pr?.mergeStateStatus === "BLOCKED" && pr.reviewDecision === "REVIEW_REQUIRED")
6886
7353
  return "Not merged: the branch rules need an approving review first. Press Approve, then Merge.";
6887
7354
  if (pr?.mergeStateStatus === "BLOCKED" && pr.reviewDecision === "CHANGES_REQUESTED")
@@ -7403,11 +7870,11 @@ function runInfo(r) {
7403
7870
  async function findDispatched(gh, repo, workflow, since, o = {}) {
7404
7871
  const sleep = o.sleep ?? wait;
7405
7872
  for (let i = 0; i < (o.tries ?? 12); i++) {
7406
- const list = await gh.request(
7873
+ const list2 = await gh.request(
7407
7874
  "GET",
7408
7875
  `repos/${repo}/actions/workflows/${workflow}/runs?per_page=5`
7409
7876
  );
7410
- const found = list.ok ? pickRun((list.data?.workflow_runs ?? []).map(runInfo), since) : void 0;
7877
+ const found = list2.ok ? pickRun((list2.data?.workflow_runs ?? []).map(runInfo), since) : void 0;
7411
7878
  if (found) return found;
7412
7879
  await sleep(o.every ?? 2500);
7413
7880
  }
@@ -7422,7 +7889,7 @@ async function runState(gh, repo, id) {
7422
7889
  )
7423
7890
  ]);
7424
7891
  if (!run4.ok || !run4.data) throw new Error(`could not read run ${id}: ${run4.error}`);
7425
- const list = (jobs.data?.jobs ?? []).map((j) => ({
7892
+ const list2 = (jobs.data?.jobs ?? []).map((j) => ({
7426
7893
  name: String(j.name ?? ""),
7427
7894
  conclusion: String(j.conclusion ?? ""),
7428
7895
  steps: (j.steps ?? []).map((s) => ({
@@ -7430,7 +7897,7 @@ async function runState(gh, repo, id) {
7430
7897
  conclusion: String(s.conclusion ?? "")
7431
7898
  }))
7432
7899
  }));
7433
- return { ...runInfo(run4.data), failedAt: failedSteps(list) };
7900
+ return { ...runInfo(run4.data), failedAt: failedSteps(list2) };
7434
7901
  }
7435
7902
  function failedSteps(jobs) {
7436
7903
  const out = [];
@@ -7520,18 +7987,180 @@ function workspaceRoots(org) {
7520
7987
  ];
7521
7988
  }
7522
7989
 
7990
+ // src/portal/session.ts
7991
+ var encoder = new TextEncoder();
7992
+ async function keyFrom(secret) {
7993
+ const raw = base64Decode(secret);
7994
+ if (raw.length !== 32) throw new Error("SESSION_KEY must be 32 bytes, base64-encoded");
7995
+ return crypto.subtle.importKey("raw", raw, "AES-GCM", false, [
7996
+ "encrypt",
7997
+ "decrypt"
7998
+ ]);
7999
+ }
8000
+ async function sealJson(value, secret) {
8001
+ const iv = crypto.getRandomValues(new Uint8Array(12));
8002
+ const body2 = await crypto.subtle.encrypt(
8003
+ { name: "AES-GCM", iv },
8004
+ await keyFrom(secret),
8005
+ encoder.encode(JSON.stringify(value))
8006
+ );
8007
+ return `${base64url(iv)}.${base64url(new Uint8Array(body2))}`;
8008
+ }
8009
+ async function openJson(value, secret) {
8010
+ const [iv, body2] = value.split(".");
8011
+ if (!iv || !body2) return null;
8012
+ try {
8013
+ const plain = await crypto.subtle.decrypt(
8014
+ { name: "AES-GCM", iv: base64Decode(iv) },
8015
+ await keyFrom(secret),
8016
+ base64Decode(body2)
8017
+ );
8018
+ return JSON.parse(new TextDecoder().decode(plain));
8019
+ } catch {
8020
+ return null;
8021
+ }
8022
+ }
8023
+ function base64url(bytes2) {
8024
+ let s = "";
8025
+ for (const b of bytes2) s += String.fromCharCode(b);
8026
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8027
+ }
8028
+ function base64Decode(s) {
8029
+ const std = s.replace(/-/g, "+").replace(/_/g, "/");
8030
+ const bin2 = atob(std + "=".repeat((4 - std.length % 4) % 4));
8031
+ const out = new Uint8Array(bin2.length);
8032
+ for (let i = 0; i < bin2.length; i++) out[i] = bin2.charCodeAt(i);
8033
+ return out;
8034
+ }
8035
+
8036
+ // src/portal/grants.ts
8037
+ var key = (connector) => `grant:${connector}`;
8038
+ async function readGrant(store2, secret, connector) {
8039
+ const sealed = await store2.get(key(connector));
8040
+ return sealed ? openJson(sealed, secret) : null;
8041
+ }
8042
+ async function writeGrant(store2, secret, g) {
8043
+ await store2.put(key(g.connector), await sealJson(g, secret));
8044
+ }
8045
+ async function dropGrant(store2, connector) {
8046
+ await store2.put(key(connector), "");
8047
+ }
8048
+ async function discover(resource, doFetch = fetch) {
8049
+ const r = new URL(resource);
8050
+ let issuer = r.origin;
8051
+ for (const path of [
8052
+ `/.well-known/oauth-protected-resource${r.pathname}`,
8053
+ "/.well-known/oauth-protected-resource"
8054
+ ]) {
8055
+ const res = await doFetch(r.origin + path).catch(() => null);
8056
+ if (!res?.ok) continue;
8057
+ const meta = await res.json().catch(() => ({}));
8058
+ if (meta.authorization_servers?.[0]) {
8059
+ issuer = meta.authorization_servers[0].replace(/\/+$/, "");
8060
+ break;
8061
+ }
8062
+ }
8063
+ const i = new URL(issuer);
8064
+ const suffix = i.pathname === "/" ? "" : i.pathname;
8065
+ for (const path of [
8066
+ `/.well-known/oauth-authorization-server${suffix}`,
8067
+ `/.well-known/openid-configuration${suffix}`
8068
+ ]) {
8069
+ const res = await doFetch(i.origin + path).catch(() => null);
8070
+ if (!res?.ok) continue;
8071
+ const meta = await res.json().catch(() => null);
8072
+ if (meta?.authorization_endpoint && meta.token_endpoint) return meta;
8073
+ }
8074
+ throw new Error(`could not find how to sign in to ${r.host}`);
8075
+ }
8076
+ async function clientFor(meta, redirectUri, name, store2, doFetch = fetch) {
8077
+ const remembered = `oauthclient:${meta.issuer}:${redirectUri}`;
8078
+ const kept = await store2.get(remembered);
8079
+ if (kept) return JSON.parse(kept);
8080
+ if (!meta.registration_endpoint) {
8081
+ throw new Error(`${new URL(meta.issuer).host} does not let a new app register itself`);
8082
+ }
8083
+ const res = await doFetch(meta.registration_endpoint, {
8084
+ method: "POST",
8085
+ headers: { "content-type": "application/json" },
8086
+ body: JSON.stringify({
8087
+ client_name: name,
8088
+ redirect_uris: [redirectUri],
8089
+ grant_types: ["authorization_code", "refresh_token"],
8090
+ response_types: ["code"],
8091
+ token_endpoint_auth_method: "none"
8092
+ })
8093
+ });
8094
+ const body2 = await res.json().catch(() => ({}));
8095
+ if (!res.ok || !body2.client_id)
8096
+ throw new Error(`registering with ${meta.issuer} failed (${res.status})`);
8097
+ const client = { clientId: body2.client_id, clientSecret: body2.client_secret };
8098
+ await store2.put(remembered, JSON.stringify(client));
8099
+ return client;
8100
+ }
8101
+ function verifier() {
8102
+ return b64url(crypto.getRandomValues(new Uint8Array(32)));
8103
+ }
8104
+ async function challenge(v) {
8105
+ return b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(v))));
8106
+ }
8107
+ async function tokenRequest(endpoint, form, doFetch = fetch) {
8108
+ const body2 = new URLSearchParams();
8109
+ for (const [k, v] of Object.entries(form)) if (v) body2.set(k, v);
8110
+ const res = await doFetch(endpoint, {
8111
+ method: "POST",
8112
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
8113
+ body: body2
8114
+ });
8115
+ return { status: res.status, ...await res.json().catch(() => ({})) };
8116
+ }
8117
+ async function exchange2(o, doFetch = fetch) {
8118
+ const t = await tokenRequest(
8119
+ o.tokenEndpoint,
8120
+ {
8121
+ grant_type: "authorization_code",
8122
+ code: o.code,
8123
+ redirect_uri: o.redirectUri,
8124
+ client_id: o.clientId,
8125
+ client_secret: o.clientSecret,
8126
+ code_verifier: o.verifier,
8127
+ resource: o.resource
8128
+ },
8129
+ doFetch
8130
+ );
8131
+ if (!t.access_token)
8132
+ throw new Error(t.error_description ?? t.error ?? `sign-in failed (${t.status})`);
8133
+ return {
8134
+ connector: o.connector,
8135
+ resource: o.resource,
8136
+ tokenEndpoint: o.tokenEndpoint,
8137
+ clientId: o.clientId,
8138
+ clientSecret: o.clientSecret,
8139
+ accessToken: t.access_token,
8140
+ refreshToken: t.refresh_token,
8141
+ expiresAt: Date.now() + (t.expires_in ?? 3600) * 1e3,
8142
+ by: o.by,
8143
+ at: (/* @__PURE__ */ new Date()).toISOString()
8144
+ };
8145
+ }
8146
+ function b64url(b) {
8147
+ let s = "";
8148
+ for (const x of b) s += String.fromCharCode(x);
8149
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8150
+ }
8151
+
7523
8152
  // src/portal/history.ts
7524
8153
  var DAYS = 14;
7525
8154
  async function loadHistory(gh, kv, repo, head2, now = Date.now()) {
7526
8155
  const since = new Date(now - DAYS * 864e5).toISOString();
7527
- const key = `history:${repo}@${head2}:${since.slice(0, 10)}`;
7528
- const kept = await kv.get(key);
8156
+ const key2 = `history:${repo}@${head2}:${since.slice(0, 10)}`;
8157
+ const kept = await kv.get(key2);
7529
8158
  if (kept) return JSON.parse(kept);
7530
- const list = (q) => gh.request("GET", `repos/${repo}/commits?sha=${head2}&${q}`);
8159
+ const list2 = (q) => gh.request("GET", `repos/${repo}/commits?sha=${head2}&${q}`);
7531
8160
  const [recent, memory, index] = await Promise.all([
7532
- list("per_page=25"),
7533
- list("path=memory&per_page=1"),
7534
- list(`path=memory/INDEX.md&since=${since}&per_page=100`)
8161
+ list2("per_page=25"),
8162
+ list2("path=memory&per_page=1"),
8163
+ list2(`path=memory/INDEX.md&since=${since}&per_page=100`)
7535
8164
  ]);
7536
8165
  const patches = await Promise.all(
7537
8166
  (index.data ?? []).map(async (c) => ({
@@ -7545,12 +8174,12 @@ async function loadHistory(gh, kv, repo, head2, now = Date.now()) {
7545
8174
  lastMemory: (memory.data ?? []).map(commit)[0],
7546
8175
  facts: factChanges(patches)
7547
8176
  };
7548
- if (recent.ok && memory.ok && index.ok) await kv.put(key, JSON.stringify(out));
8177
+ if (recent.ok && memory.ok && index.ok) await kv.put(key2, JSON.stringify(out));
7549
8178
  return out;
7550
8179
  }
7551
8180
  async function indexPatch(gh, kv, repo, sha) {
7552
- const key = `patch:${repo}@${sha}:memory/INDEX.md`;
7553
- const kept = await kv.get(key);
8181
+ const key2 = `patch:${repo}@${sha}:memory/INDEX.md`;
8182
+ const kept = await kv.get(key2);
7554
8183
  if (kept !== void 0) return kept;
7555
8184
  const res = await gh.request(
7556
8185
  "GET",
@@ -7558,7 +8187,7 @@ async function indexPatch(gh, kv, repo, sha) {
7558
8187
  );
7559
8188
  if (!res.ok) return "";
7560
8189
  const patch = res.data?.files?.find((f) => f.filename === "memory/INDEX.md")?.patch ?? "";
7561
- await kv.put(key, patch);
8190
+ await kv.put(key2, patch);
7562
8191
  return patch;
7563
8192
  }
7564
8193
  function commit(c) {
@@ -7630,7 +8259,7 @@ var Snapshots = class {
7630
8259
  const running = this.inflight.get(repo);
7631
8260
  if (running) return running;
7632
8261
  const say = (step) => {
7633
- for (const report3 of this.listeners.get(repo) ?? []) report3(repo, step);
8262
+ for (const report4 of this.listeners.get(repo) ?? []) report4(repo, step);
7634
8263
  };
7635
8264
  const work = this.load(gh, repo, pathsOnly, say).finally(() => {
7636
8265
  this.inflight.delete(repo);
@@ -7762,8 +8391,8 @@ var Snapshots = class {
7762
8391
  * start never asks at all.
7763
8392
  */
7764
8393
  async dates(gh, repo, snap, say, before) {
7765
- const key = `dates:${repo}@${snap.sha}`;
7766
- const kept = await this.kv.get(key);
8394
+ const key2 = `dates:${repo}@${snap.sha}`;
8395
+ const kept = await this.kv.get(key2);
7767
8396
  if (kept) {
7768
8397
  const map2 = JSON.parse(kept);
7769
8398
  for (const [path, e] of snap.files) e.mtime = map2[path];
@@ -7796,7 +8425,7 @@ var Snapshots = class {
7796
8425
  }
7797
8426
  const map = {};
7798
8427
  for (const [path, e] of snap.files) if (e.mtime) map[path] = e.mtime;
7799
- void this.kv.put(key, JSON.stringify(map));
8428
+ void this.kv.put(key2, JSON.stringify(map));
7800
8429
  }
7801
8430
  /** Every snapshot held, as one directory with a folder per repository, as a workspace has. */
7802
8431
  tree(dirOf) {
@@ -7873,6 +8502,7 @@ function createPortal(opts) {
7873
8502
  ws: { root: root2, opsDir: join29(root2, opts.opsName), opsName: opts.opsName },
7874
8503
  snapshots,
7875
8504
  kv: opts.kv,
8505
+ grants: opts.grants,
7876
8506
  bin: opts.bin ?? "roster",
7877
8507
  caches: {
7878
8508
  inbox: /* @__PURE__ */ new Map(),
@@ -7907,10 +8537,10 @@ async function handlePortal(req, portal, actor) {
7907
8537
  }
7908
8538
  async function ready(c, opts = {}) {
7909
8539
  const { portal, actor } = c;
7910
- const report3 = opts.report;
8540
+ const report4 = opts.report;
7911
8541
  const ops = await portal.snapshots.refresh(actor.gh, `${portal.org}/${portal.opsName}`, {
7912
8542
  force: opts.force,
7913
- report: report3
8543
+ report: report4
7914
8544
  });
7915
8545
  if (!ops.ok) {
7916
8546
  throw new HttpError(
@@ -7918,13 +8548,13 @@ async function ready(c, opts = {}) {
7918
8548
  `could not read ${portal.org}/${portal.opsName}: ${ops.error}`
7919
8549
  );
7920
8550
  }
7921
- report3?.(`${portal.org}/${portal.opsName}`, "ready");
8551
+ report4?.(`${portal.org}/${portal.opsName}`, "ready");
7922
8552
  const org = readOrg(portal.ws.opsDir, parseYaml2);
7923
8553
  const brains = (org.staff ?? []).map((s) => String(s.dir ?? s.handle));
7924
8554
  const products = opts.products ? (org.repos ?? []).map((r) => String(r.name)).filter((n) => n !== portal.opsName && !brains.includes(n)) : [];
7925
8555
  const results = await Promise.all([
7926
8556
  ...brains.map(
7927
- (d) => portal.snapshots.refresh(actor.gh, `${portal.org}/${d}`, { force: opts.force, report: report3 }).then((r) => ({ dir: d, ...r }))
8557
+ (d) => portal.snapshots.refresh(actor.gh, `${portal.org}/${d}`, { force: opts.force, report: report4 }).then((r) => ({ dir: d, ...r }))
7928
8558
  ),
7929
8559
  ...products.map(
7930
8560
  (d) => portal.snapshots.refresh(actor.gh, `${portal.org}/${d}`, { force: opts.force, pathsOnly: true }).then((r) => ({ dir: d, ...r }))
@@ -7960,10 +8590,10 @@ var ROUTES = {
7960
8590
  const out = writable.getWriter();
7961
8591
  const line = (o) => out.write(new TextEncoder().encode(`${JSON.stringify(o)}
7962
8592
  `));
7963
- const report3 = (repo, step) => {
8593
+ const report4 = (repo, step) => {
7964
8594
  void line({ repo: repo.slice(repo.indexOf("/") + 1), step });
7965
8595
  };
7966
- void orgExport(c, report3).then((org) => line({ org })).catch(
8596
+ void orgExport(c, report4).then((org) => line({ org })).catch(
7967
8597
  (err) => line({ error: String(err?.message ?? err), status: err.status })
7968
8598
  ).finally(() => out.close());
7969
8599
  return new Response(readable, {
@@ -8025,10 +8655,10 @@ var ROUTES = {
8025
8655
  try {
8026
8656
  const view = promptView(portal.ws, compose2, handle, brainDir, kind);
8027
8657
  for (const p of auditPrompt(portal.ws, view, roots)) {
8028
- const key = `${p.id}|${p.path ?? ""}|${p.title}`;
8029
- const seen = found.get(key);
8658
+ const key2 = `${p.id}|${p.path ?? ""}|${p.title}`;
8659
+ const seen = found.get(key2);
8030
8660
  if (seen) seen.kinds.push(kind);
8031
- else found.set(key, { ...p, kind, kinds: [kind] });
8661
+ else found.set(key2, { ...p, kind, kinds: [kind] });
8032
8662
  }
8033
8663
  } catch (err) {
8034
8664
  errors.push({ kind, error: String(err.message) });
@@ -8207,6 +8837,256 @@ var ROUTES = {
8207
8837
  await commitFile(portal, actor.gh, dir, rest.join("/"), payload.text, message2, base2)
8208
8838
  );
8209
8839
  },
8840
+ /* Connectors: what is offered, what this org has, and whether each one's keys are stored. */
8841
+ "/api/connectors": async (c) => {
8842
+ const { portal, actor } = c;
8843
+ const { org } = await ready(c);
8844
+ const brains = (org.staff ?? []).map((s) => `${portal.org}/${s.dir ?? s.handle}`);
8845
+ const stored = await secretsOn(actor.gh, brains);
8846
+ const readable = [...stored.values()].filter((v) => v !== null);
8847
+ const connectors = await Promise.all(
8848
+ declared2(org).map(async (x) => {
8849
+ let keys = null;
8850
+ let signedIn = null;
8851
+ if (x.auth === "key" && x.secrets.length) {
8852
+ if (!readable.length) keys = "unknown";
8853
+ else {
8854
+ const on = readable.filter((set) => x.secrets.every((s) => set.has(s.name))).length;
8855
+ keys = on === readable.length ? "stored" : on === 0 ? "missing" : "partial";
8856
+ }
8857
+ }
8858
+ if (x.auth === "oauth" && portal.grants) {
8859
+ const g = await readGrant(portal.grants.store, portal.grants.secret, x.id);
8860
+ if (g) signedIn = { by: g.by, at: g.at };
8861
+ }
8862
+ const { entry: _entry, ...rest } = x;
8863
+ return { ...rest, keys, signedIn };
8864
+ })
8865
+ );
8866
+ return json({
8867
+ catalogue: catalogueView(),
8868
+ connectors,
8869
+ staff: (org.staff ?? []).map((s) => ({
8870
+ handle: String(s.handle),
8871
+ name: String(s.name ?? s.handle)
8872
+ })),
8873
+ signIn: Boolean(portal.grants),
8874
+ canWrite: !isViewOnly(org, actor.id)
8875
+ });
8876
+ },
8877
+ /* Whether a key works, before it is stored. The key goes to the service and nowhere else. */
8878
+ "/api/connectors/check": async (c) => {
8879
+ if (!c.actor.canWrite) return refuse();
8880
+ const p = await body(c.req);
8881
+ const id = String(p.id ?? "");
8882
+ if (!CATALOGUE2[id]) return json({ error: `roster does not know ${id}` }, 400);
8883
+ const values = p.values ?? {};
8884
+ const wrong = wrongValue(id, values);
8885
+ if (wrong) return json({ state: "rejected", note: wrong });
8886
+ return json(await checkKey(id, values));
8887
+ },
8888
+ /* Add a connector, or change who has it: the keys to GitHub secrets, then org.yaml. */
8889
+ "/api/connectors/save": async (c) => {
8890
+ const { portal, actor } = c;
8891
+ if (!actor.canWrite) return refuse();
8892
+ const { org } = await ready(c, { force: true });
8893
+ const p = await body(c.req);
8894
+ const id = String(p.id ?? "");
8895
+ const known = CATALOGUE2[id];
8896
+ const existing = org.connectors?.[id];
8897
+ if (!known && !existing) return json({ error: `roster does not know ${id}` }, 400);
8898
+ const handles = new Set((org.staff ?? []).map((s) => String(s.handle)));
8899
+ const staff = (p.staff ?? []).map(String).filter((h) => handles.has(h));
8900
+ if (!staff.length) return json({ error: "Pick at least one staff member." }, 400);
8901
+ const entry = { staff, read_only: p.readOnly === true };
8902
+ for (const f of known?.fields ?? []) {
8903
+ if (!f.secret) entry[f.id] = (p.settings?.[f.id] ?? "").trim() || void 0;
8904
+ }
8905
+ if (known?.auth === "oauth") entry.portal = portal.grants?.base;
8906
+ const values = Object.fromEntries(
8907
+ Object.entries(p.values ?? {}).map(([k, v]) => [k, String(v ?? "").trim()])
8908
+ );
8909
+ const giving = Object.values(values).some(Boolean);
8910
+ if (known && known.auth !== "oauth") {
8911
+ const wrong2 = wrongValue(
8912
+ id,
8913
+ { ...p.settings, ...values },
8914
+ { keepKeys: Boolean(existing) && !giving }
8915
+ );
8916
+ if (wrong2) return json({ error: wrong2 }, 400);
8917
+ }
8918
+ if (giving && known) {
8919
+ const checked = await checkKey(id, { ...p.settings, ...values });
8920
+ if (checked.state === "rejected") return json({ error: checked.note }, 400);
8921
+ }
8922
+ const brains = (org.staff ?? []).map((s) => `${portal.org}/${s.dir ?? s.handle}`);
8923
+ const stored = [];
8924
+ for (const f of (known?.fields ?? []).filter((x) => x.secret)) {
8925
+ const v = values[f.id];
8926
+ if (!v) continue;
8927
+ const name2 = secretName2(id, f.id);
8928
+ stored.push({ name: name2, ...await storeSecret(actor.gh, portal.org, name2, v, brains) });
8929
+ }
8930
+ const opsFile = portal.snapshots.get(`${portal.org}/${portal.opsName}`)?.files.get("org.yaml");
8931
+ const before = opsFile?.text ?? "";
8932
+ const after = setConnector(before, org, id, entry);
8933
+ const wrong = validateOrgYaml(after, parseYaml2);
8934
+ if (wrong) return json({ error: wrong }, 400);
8935
+ const name = known?.name ?? id;
8936
+ const committed = await commitFile(
8937
+ portal,
8938
+ actor.gh,
8939
+ portal.opsName,
8940
+ "org.yaml",
8941
+ after,
8942
+ existing ? `portal: change who has ${name}` : `portal: connect ${name}`,
8943
+ before
8944
+ );
8945
+ return json({ ok: true, stored, committed });
8946
+ },
8947
+ /* Take a connector away: its keys, its sign-in, and its entry in org.yaml. */
8948
+ "/api/connectors/remove": async (c) => {
8949
+ const { portal, actor } = c;
8950
+ if (!actor.canWrite) return refuse();
8951
+ const { org } = await ready(c, { force: true });
8952
+ const id = String((await body(c.req)).id ?? "");
8953
+ const x = declared2(org).find((d) => d.id === id);
8954
+ if (!x) return json({ error: `org.yaml has no connector ${id}` }, 400);
8955
+ const brains = (org.staff ?? []).map((s) => `${portal.org}/${s.dir ?? s.handle}`);
8956
+ for (const s of x.secrets) await deleteSecret(actor.gh, portal.org, s.name, brains);
8957
+ if (x.auth === "oauth" && portal.grants) await dropGrant(portal.grants.store, id);
8958
+ const before = portal.snapshots.get(`${portal.org}/${portal.opsName}`)?.files.get("org.yaml")?.text ?? "";
8959
+ const committed = await commitFile(
8960
+ portal,
8961
+ actor.gh,
8962
+ portal.opsName,
8963
+ "org.yaml",
8964
+ setConnector(before, org, id, null),
8965
+ `portal: disconnect ${x.name}`,
8966
+ before
8967
+ );
8968
+ return json({ ok: true, committed });
8969
+ },
8970
+ /* The start of a sign-in: where to send the person, and a sealed note of what they asked for. */
8971
+ "/api/connectors/signin": async (c) => {
8972
+ const { portal, actor } = c;
8973
+ if (!actor.canWrite) return refuse();
8974
+ if (!portal.grants) {
8975
+ return json(
8976
+ { error: "Signing in to a service needs the hosted portal, with a store for sign-ins." },
8977
+ 400
8978
+ );
8979
+ }
8980
+ const p = await body(c.req);
8981
+ const id = String(p.id ?? "");
8982
+ const known = CATALOGUE2[id];
8983
+ if (!known?.oauth) return json({ error: `${id} does not sign in` }, 400);
8984
+ const { org } = await ready(c);
8985
+ const handles = new Set((org.staff ?? []).map((s) => String(s.handle)));
8986
+ const staff = (p.staff ?? []).map(String).filter((h) => handles.has(h));
8987
+ if (!staff.length) return json({ error: "Pick at least one staff member." }, 400);
8988
+ const redirect = `${portal.grants.base}/connectors/callback`;
8989
+ const meta = await discover(known.oauth.resource);
8990
+ const client = await clientFor(
8991
+ meta,
8992
+ redirect,
8993
+ `Roster (${portal.org})`,
8994
+ portal.grants.store
8995
+ );
8996
+ const v = verifier();
8997
+ const state = verifier();
8998
+ const pending2 = await sealJson(
8999
+ {
9000
+ kind: "connector",
9001
+ id,
9002
+ staff,
9003
+ readOnly: p.readOnly === true,
9004
+ verifier: v,
9005
+ state,
9006
+ tokenEndpoint: meta.token_endpoint,
9007
+ ...client,
9008
+ exp: Date.now() + 6e5
9009
+ },
9010
+ portal.grants.secret
9011
+ );
9012
+ const go = new URL(meta.authorization_endpoint);
9013
+ for (const [k, val] of Object.entries({
9014
+ response_type: "code",
9015
+ client_id: client.clientId,
9016
+ redirect_uri: redirect,
9017
+ code_challenge: await challenge(v),
9018
+ code_challenge_method: "S256",
9019
+ state,
9020
+ resource: known.oauth.resource
9021
+ })) {
9022
+ go.searchParams.set(k, val);
9023
+ }
9024
+ return new Response(JSON.stringify({ url: go.toString() }), {
9025
+ headers: {
9026
+ "content-type": JSON_TYPE,
9027
+ "cache-control": "no-store",
9028
+ "set-cookie": `roster_connector=${pending2}; Path=/connectors/callback; HttpOnly; Secure; SameSite=Lax; Max-Age=600`
9029
+ }
9030
+ });
9031
+ },
9032
+ /* Where the service sends the person back. The sealed note from the start is the write guard:
9033
+ only a sign-in this page began, for this person, in the last ten minutes, lands. */
9034
+ "/connectors/callback": async (c) => {
9035
+ const { portal, actor, req, url } = c;
9036
+ if (!portal.grants) return notFound();
9037
+ const back = (msg) => new Response(null, {
9038
+ status: 302,
9039
+ headers: {
9040
+ location: `/#/-/connectors${msg ? `?e=${encodeURIComponent(msg)}` : ""}`,
9041
+ "set-cookie": "roster_connector=; Path=/connectors/callback; Max-Age=0"
9042
+ }
9043
+ });
9044
+ const raw = /(?:^|;\s*)roster_connector=([^;]+)/.exec(req.headers.get("cookie") ?? "")?.[1];
9045
+ const pending2 = raw ? await openJson(raw, portal.grants.secret) : null;
9046
+ if (pending2?.kind !== "connector" || pending2.exp < Date.now()) {
9047
+ return back("The sign-in took too long. Try again.");
9048
+ }
9049
+ if (url.searchParams.get("state") !== pending2.state)
9050
+ return back("The sign-in did not match. Try again.");
9051
+ const code = url.searchParams.get("code");
9052
+ if (!code)
9053
+ return back(url.searchParams.get("error_description") ?? "The sign-in was cancelled.");
9054
+ const known = CATALOGUE2[pending2.id];
9055
+ if (!known?.oauth) return back("That service is not one roster signs in to.");
9056
+ try {
9057
+ const grant = await exchange2({
9058
+ connector: pending2.id,
9059
+ resource: known.oauth.resource,
9060
+ tokenEndpoint: pending2.tokenEndpoint,
9061
+ clientId: pending2.clientId,
9062
+ clientSecret: pending2.clientSecret,
9063
+ code,
9064
+ verifier: pending2.verifier,
9065
+ redirectUri: `${portal.grants.base}/connectors/callback`,
9066
+ by: actor.id
9067
+ });
9068
+ await writeGrant(portal.grants.store, portal.grants.secret, grant);
9069
+ const { org } = await ready(c, { force: true });
9070
+ const before = portal.snapshots.get(`${portal.org}/${portal.opsName}`)?.files.get("org.yaml")?.text ?? "";
9071
+ const after = setConnector(before, org, pending2.id, {
9072
+ staff: pending2.staff,
9073
+ read_only: pending2.readOnly,
9074
+ portal: portal.grants.base
9075
+ });
9076
+ await commitFile(
9077
+ portal,
9078
+ actor.gh,
9079
+ portal.opsName,
9080
+ "org.yaml",
9081
+ after,
9082
+ `portal: connect ${known.name}`,
9083
+ before
9084
+ );
9085
+ } catch (err) {
9086
+ return back(err.message);
9087
+ }
9088
+ return back("");
9089
+ },
8210
9090
  /* Acting on GitHub as the person: reply, close, reopen, open, approve, merge, ask. */
8211
9091
  "/api/act": async (c) => {
8212
9092
  const { req, portal, actor } = c;
@@ -8486,8 +9366,8 @@ ${diff}`,
8486
9366
  const { req, url, portal, actor } = c;
8487
9367
  await ready(c, { products: true });
8488
9368
  const rel = url.searchParams.get("path") ?? "";
8489
- const full = resolve6(portal.ws.root, rel);
8490
- if (!full.startsWith(`${resolve6(portal.ws.root)}/`) || !existsSync2(full)) return notFound();
9369
+ const full = resolve5(portal.ws.root, rel);
9370
+ if (!full.startsWith(`${resolve5(portal.ws.root)}/`) || !existsSync2(full)) return notFound();
8491
9371
  const st = statSync2(full);
8492
9372
  if (st.isDirectory()) return notFound();
8493
9373
  const inside = full.slice(portal.ws.root.length + 1);
@@ -8499,8 +9379,8 @@ ${diff}`,
8499
9379
  bytes2 = new Uint8Array(readFileSync2(full));
8500
9380
  } catch {
8501
9381
  const snap = portal.snapshots.get(`${portal.org}/${dir}`);
8502
- const key = `${dir}@${snap?.sha}:${path}`;
8503
- let got = portal.caches.files.get(key);
9382
+ const key2 = `${dir}@${snap?.sha}:${path}`;
9383
+ let got = portal.caches.files.get(key2);
8504
9384
  if (!got) {
8505
9385
  const res = await actor.gh.request(
8506
9386
  "GET",
@@ -8509,7 +9389,7 @@ ${diff}`,
8509
9389
  );
8510
9390
  if (!res.ok || !res.data) return json({ error: res.error }, 502);
8511
9391
  got = res.data;
8512
- remember(portal.caches.files, key, got);
9392
+ remember(portal.caches.files, key2, got);
8513
9393
  }
8514
9394
  bytes2 = got;
8515
9395
  }
@@ -8542,18 +9422,18 @@ ${diff}`,
8542
9422
  return new Response(bytes2, { headers: { "content-type": type, "cache-control": "no-store" } });
8543
9423
  }
8544
9424
  };
8545
- async function orgExport(c, report3) {
9425
+ async function orgExport(c, report4) {
8546
9426
  const { portal, actor } = c;
8547
- const { org, brains } = await ready(c, { report: report3 });
9427
+ const { org, brains } = await ready(c, { report: report4 });
8548
9428
  const byRoot = /* @__PURE__ */ new Map();
8549
9429
  await Promise.all(
8550
9430
  brains.map(async (dir) => {
8551
9431
  const repo = `${portal.org}/${dir}`;
8552
9432
  const snap = portal.snapshots.get(repo);
8553
9433
  if (!snap) return;
8554
- report3?.(repo, "reading recent history");
9434
+ report4?.(repo, "reading recent history");
8555
9435
  byRoot.set(join29(portal.ws.root, dir), await loadHistory(actor.gh, portal.kv, repo, snap.sha));
8556
- report3?.(repo, "ready");
9436
+ report4?.(repo, "ready");
8557
9437
  })
8558
9438
  );
8559
9439
  const data = buildExport(portal.ws, org, parseYaml2, { history: loadedHistory(byRoot) });
@@ -8626,7 +9506,7 @@ async function commitFile(portal, gh, dir, path, body2, message2, base2) {
8626
9506
  };
8627
9507
  }
8628
9508
  async function upload(gh, repo, name, data) {
8629
- const bytes2 = fromBase64(data);
9509
+ const bytes2 = fromBase642(data);
8630
9510
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
8631
9511
  const listing = await gh.request(
8632
9512
  "GET",
@@ -8718,14 +9598,14 @@ function base64(bytes2) {
8718
9598
  }
8719
9599
  return btoa(s);
8720
9600
  }
8721
- function fromBase64(data) {
9601
+ function fromBase642(data) {
8722
9602
  const s = atob(data);
8723
9603
  const out = new Uint8Array(s.length);
8724
9604
  for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
8725
9605
  return out;
8726
9606
  }
8727
- function remember(map, key, bytes2) {
8728
- map.set(key, bytes2);
9607
+ function remember(map, key2, bytes2) {
9608
+ map.set(key2, bytes2);
8729
9609
  let total = 0;
8730
9610
  for (const v of map.values()) total += v.length;
8731
9611
  for (const k of map.keys()) {
@@ -8774,27 +9654,27 @@ var MIME = {
8774
9654
  function memoryKV(limit = 2e4) {
8775
9655
  const map = /* @__PURE__ */ new Map();
8776
9656
  return {
8777
- async get(key) {
8778
- return map.get(key);
9657
+ async get(key2) {
9658
+ return map.get(key2);
8779
9659
  },
8780
- async put(key, value) {
8781
- map.set(key, value);
9660
+ async put(key2, value) {
9661
+ map.set(key2, value);
8782
9662
  if (map.size > limit) map.delete(map.keys().next().value);
8783
9663
  }
8784
9664
  };
8785
9665
  }
8786
9666
  function layeredKV(slow, fast = memoryKV()) {
8787
9667
  return {
8788
- async get(key) {
8789
- const hit = await fast.get(key);
9668
+ async get(key2) {
9669
+ const hit = await fast.get(key2);
8790
9670
  if (hit !== void 0) return hit;
8791
- const found = await slow.get(key).catch(() => void 0);
8792
- if (found !== void 0) await fast.put(key, found);
9671
+ const found = await slow.get(key2).catch(() => void 0);
9672
+ if (found !== void 0) await fast.put(key2, found);
8793
9673
  return found;
8794
9674
  },
8795
- async put(key, value) {
8796
- await fast.put(key, value);
8797
- await slow.put(key, value).catch(() => {
9675
+ async put(key2, value) {
9676
+ await fast.put(key2, value);
9677
+ await slow.put(key2, value).catch(() => {
8798
9678
  });
8799
9679
  }
8800
9680
  };
@@ -8802,23 +9682,23 @@ function layeredKV(slow, fast = memoryKV()) {
8802
9682
 
8803
9683
  // src/portal/kv-disk.ts
8804
9684
  import { createHash } from "crypto";
8805
- import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync11, writeFileSync as writeFileSync10 } from "fs";
9685
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "fs";
8806
9686
  import { homedir } from "os";
8807
9687
  import { join as join30 } from "path";
8808
9688
  function diskKV(dir = defaultDir()) {
8809
- const path = (key) => {
8810
- const h = createHash("sha1").update(key).digest("hex");
9689
+ const path = (key2) => {
9690
+ const h = createHash("sha1").update(key2).digest("hex");
8811
9691
  return join30(dir, h.slice(0, 2), h.slice(2));
8812
9692
  };
8813
9693
  return {
8814
- async get(key) {
8815
- const p = path(key);
8816
- return existsSync13(p) ? readFileSync11(p, "utf8") : void 0;
9694
+ async get(key2) {
9695
+ const p = path(key2);
9696
+ return existsSync13(p) ? readFileSync12(p, "utf8") : void 0;
8817
9697
  },
8818
- async put(key, value) {
8819
- const p = path(key);
9698
+ async put(key2, value) {
9699
+ const p = path(key2);
8820
9700
  mkdirSync7(join30(p, ".."), { recursive: true });
8821
- writeFileSync10(p, value);
9701
+ writeFileSync11(p, value);
8822
9702
  }
8823
9703
  };
8824
9704
  }
@@ -8827,7 +9707,7 @@ function defaultDir() {
8827
9707
  }
8828
9708
 
8829
9709
  // src/commands/retire.ts
8830
- import { existsSync as existsSync14, readdirSync as readdirSync6, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "fs";
9710
+ import { existsSync as existsSync14, readdirSync as readdirSync6, readFileSync as readFileSync13, writeFileSync as writeFileSync12 } from "fs";
8831
9711
  import { join as join31 } from "path";
8832
9712
  var retireHelp = `
8833
9713
  roster retire <handle>
@@ -8858,7 +9738,7 @@ async function retireCommand(argv) {
8858
9738
  process.stderr.write("roster: retire needs a handle, e.g. `roster retire cmo`\n");
8859
9739
  return 2;
8860
9740
  }
8861
- const opts = parseFlags11(argv.slice(1));
9741
+ const opts = parseFlags12(argv.slice(1));
8862
9742
  const ws = findWorkspace(opts.ops);
8863
9743
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
8864
9744
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -8893,7 +9773,7 @@ function buildRetirePlan(ws, org, handle, parseYaml3) {
8893
9773
  const otherDir = other.dir ?? other.handle;
8894
9774
  const path = join31(ws.root, otherDir, "staff.yaml");
8895
9775
  if (!existsSync14(path)) continue;
8896
- const text2 = readFileSync12(path, "utf8");
9776
+ const text2 = readFileSync13(path, "utf8");
8897
9777
  if (!new RegExp(`handle: ${handle}[,\\s}]`).test(text2)) continue;
8898
9778
  const theirs = readManifest3(join31(ws.root, otherDir), parseYaml3);
8899
9779
  peers.push({
@@ -8962,8 +9842,8 @@ async function applyRetirePlan(ws, plan2) {
8962
9842
  process.stdout.write(" removed from org.yaml\n");
8963
9843
  for (const p of plan2.peers) {
8964
9844
  const path = join31(ws.root, p.dir, "staff.yaml");
8965
- const text2 = readFileSync12(path, "utf8");
8966
- writeFileSync11(path, removePeerLine(text2, plan2.handle));
9845
+ const text2 = readFileSync13(path, "utf8");
9846
+ writeFileSync12(path, removePeerLine(text2, plan2.handle));
8967
9847
  process.stdout.write(` removed from ${p.dir}/staff.yaml
8968
9848
  `);
8969
9849
  if (!p.brain) continue;
@@ -8990,8 +9870,8 @@ async function applyRetirePlan(ws, plan2) {
8990
9870
  }
8991
9871
  function removeFromOrgYaml(ws, plan2) {
8992
9872
  const path = join31(ws.opsDir, "org.yaml");
8993
- const text2 = readFileSync12(path, "utf8");
8994
- writeFileSync11(path, removeOrgLines(text2, plan2.handle, plan2.dir));
9873
+ const text2 = readFileSync13(path, "utf8");
9874
+ writeFileSync12(path, removeOrgLines(text2, plan2.handle, plan2.dir));
8995
9875
  }
8996
9876
  function removeOrgLines(text2, handle, dir) {
8997
9877
  return text2.split("\n").filter((line) => {
@@ -9012,16 +9892,16 @@ function readManifest3(root2, parseYaml3) {
9012
9892
  const path = join31(root2, "staff.yaml");
9013
9893
  if (!existsSync14(path)) return null;
9014
9894
  try {
9015
- return parseYaml3(readFileSync12(path, "utf8"), "staff.yaml");
9895
+ return parseYaml3(readFileSync13(path, "utf8"), "staff.yaml");
9016
9896
  } catch {
9017
9897
  return null;
9018
9898
  }
9019
9899
  }
9020
9900
  function countFacts(indexPath) {
9021
9901
  if (!existsSync14(indexPath)) return 0;
9022
- return (readFileSync12(indexPath, "utf8").match(/^- \*\*`/gm) ?? []).length;
9902
+ return (readFileSync13(indexPath, "utf8").match(/^- \*\*`/gm) ?? []).length;
9023
9903
  }
9024
- function parseFlags11(argv) {
9904
+ function parseFlags12(argv) {
9025
9905
  const out = {};
9026
9906
  for (let i = 0; i < argv.length; i++) {
9027
9907
  const flag = argv[i];
@@ -9068,10 +9948,10 @@ var pendingApps = /* @__PURE__ */ new Map();
9068
9948
  var appResults = /* @__PURE__ */ new Map();
9069
9949
  async function portalCommand(argv) {
9070
9950
  if (argv[0] === "deploy") return deployCommand(argv.slice(1));
9071
- const opts = parseFlags12(argv);
9951
+ const opts = parseFlags13(argv);
9072
9952
  let port = opts.port ?? 4300;
9073
9953
  const host = opts.host ?? "127.0.0.1";
9074
- const startedIn = resolve7(opts.ops ?? opts.dir ?? process.cwd());
9954
+ const startedIn = resolve6(opts.ops ?? opts.dir ?? process.cwd());
9075
9955
  let ws = tryWorkspace(startedIn);
9076
9956
  let composer = ws ? await loadComposer(ws.opsDir) : await loadFrameworkComposer();
9077
9957
  const _compose = (...args) => composer.compose(...args);
@@ -9167,7 +10047,7 @@ async function portalCommand(argv) {
9167
10047
  }
9168
10048
  const dir = entry.dir ?? entry.handle;
9169
10049
  const spec2 = specFromManifest(
9170
- parseYaml3(readFileSync13(join32(ws.root, dir, "staff.yaml"), "utf8"), "staff.yaml"),
10050
+ parseYaml3(readFileSync14(join32(ws.root, dir, "staff.yaml"), "utf8"), "staff.yaml"),
9171
10051
  dir
9172
10052
  );
9173
10053
  const isPublic = payload.scope === "public";
@@ -9321,7 +10201,7 @@ async function portalCommand(argv) {
9321
10201
  res.writeHead(400).end("bad request");
9322
10202
  return;
9323
10203
  }
9324
- const list = await ghJson([
10204
+ const list2 = await ghJson([
9325
10205
  "repo",
9326
10206
  "list",
9327
10207
  org,
@@ -9331,8 +10211,8 @@ async function portalCommand(argv) {
9331
10211
  "name,visibility,description"
9332
10212
  ]);
9333
10213
  json2(res, {
9334
- repos: list.ok ? list.data ?? [] : [],
9335
- error: list.ok ? void 0 : list.error
10214
+ repos: list2.ok ? list2.data ?? [] : [],
10215
+ error: list2.ok ? void 0 : list2.error
9336
10216
  });
9337
10217
  return;
9338
10218
  }
@@ -9351,7 +10231,7 @@ async function portalCommand(argv) {
9351
10231
  return;
9352
10232
  }
9353
10233
  const path = join32(ws.opsDir, "org.yaml");
9354
- const text2 = readFileSync13(path, "utf8");
10234
+ const text2 = readFileSync14(path, "utf8");
9355
10235
  if (new RegExp(`name: ${name}[,\\s}]`).test(text2)) {
9356
10236
  json2(res, { ok: true, note: "already there" });
9357
10237
  return;
@@ -9423,13 +10303,13 @@ async function portalCommand(argv) {
9423
10303
  }
9424
10304
  res.writeHead(404).end("not found");
9425
10305
  };
9426
- const body2 = (req, limit = 1e6) => new Promise((resolve8, reject) => {
10306
+ const body2 = (req, limit = 1e6) => new Promise((resolve7, reject) => {
9427
10307
  let buf = "";
9428
10308
  req.on("data", (c) => {
9429
10309
  buf += c;
9430
10310
  if (buf.length > limit) reject(new Error("body too large"));
9431
10311
  });
9432
- req.on("end", () => resolve8(buf));
10312
+ req.on("end", () => resolve7(buf));
9433
10313
  req.on("error", reject);
9434
10314
  });
9435
10315
  const server = createServer2((req, res) => {
@@ -9516,7 +10396,7 @@ async function portalCommand(argv) {
9516
10396
  return;
9517
10397
  }
9518
10398
  if (url.pathname === "/api/doctor") {
9519
- collect({ ops: ws?.opsDir, offline: url.searchParams.get("offline") === "1" }).then((report3) => json2(res, report3 ?? { findings: [], online: false, empty: true }, true)).catch((err) => {
10399
+ collect({ ops: ws?.opsDir, offline: url.searchParams.get("offline") === "1" }).then((report4) => json2(res, report4 ?? { findings: [], online: false, empty: true }, true)).catch((err) => {
9520
10400
  res.writeHead(200, { "content-type": "application/json" });
9521
10401
  res.end(JSON.stringify({ findings: [], error: String(err?.message ?? err) }));
9522
10402
  });
@@ -9699,7 +10579,7 @@ function capture() {
9699
10579
  text: () => chunks.join("")
9700
10580
  };
9701
10581
  }
9702
- function parseFlags12(argv) {
10582
+ function parseFlags13(argv) {
9703
10583
  const out = {};
9704
10584
  for (let i = 0; i < argv.length; i++) {
9705
10585
  const flag = argv[i];
@@ -9720,7 +10600,7 @@ function parseFlags12(argv) {
9720
10600
  return out;
9721
10601
  }
9722
10602
  function bytes(req) {
9723
- return new Promise((resolve8, reject) => {
10603
+ return new Promise((resolve7, reject) => {
9724
10604
  const chunks = [];
9725
10605
  let size2 = 0;
9726
10606
  req.on("data", (c) => {
@@ -9728,7 +10608,7 @@ function bytes(req) {
9728
10608
  if (size2 > Math.ceil(MAX_UPLOAD * 1.4) + 1e6) reject(new Error("body too large"));
9729
10609
  else chunks.push(c);
9730
10610
  });
9731
- req.on("end", () => resolve8(Buffer.concat(chunks)));
10611
+ req.on("end", () => resolve7(Buffer.concat(chunks)));
9732
10612
  req.on("error", reject);
9733
10613
  });
9734
10614
  }
@@ -9739,14 +10619,14 @@ function signedOut(error) {
9739
10619
 
9740
10620
  // src/commands/prompt.ts
9741
10621
  import { execFileSync as execFileSync9 } from "child_process";
9742
- import { existsSync as existsSync15, mkdtempSync as mkdtempSync5, readFileSync as readFileSync15, writeFileSync as writeFileSync12 } from "fs";
10622
+ import { existsSync as existsSync15, mkdtempSync as mkdtempSync5, readFileSync as readFileSync16, writeFileSync as writeFileSync13 } from "fs";
9743
10623
  import { tmpdir as tmpdir5 } from "os";
9744
10624
  import { join as join33 } from "path";
9745
10625
 
9746
10626
  // src/lib/livePrompt.ts
9747
- import { readFileSync as readFileSync14 } from "fs";
10627
+ import { readFileSync as readFileSync15 } from "fs";
9748
10628
  function extractLivePrompt(workflowPath) {
9749
- const lines = readFileSync14(workflowPath, "utf8").split("\n");
10629
+ const lines = readFileSync15(workflowPath, "utf8").split("\n");
9750
10630
  const start = lines.findIndex((l) => /^\s*prompt:\s*\|/.test(l));
9751
10631
  if (start === -1) throw new Error(`no "prompt: |" block in ${workflowPath}`);
9752
10632
  const blockIndent = (lines[start].match(/^\s*/)?.[0].length ?? 0) + 2;
@@ -9786,7 +10666,7 @@ async function promptCommand(argv) {
9786
10666
  process.stderr.write(promptHelp);
9787
10667
  return 2;
9788
10668
  }
9789
- const opts = parseFlags13(argv.slice(1));
10669
+ const opts = parseFlags14(argv.slice(1));
9790
10670
  const ws = findWorkspace(opts.ops);
9791
10671
  const { compose: compose3, parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
9792
10672
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -9810,8 +10690,8 @@ async function promptCommand(argv) {
9810
10690
  const dir = mkdtempSync5(join33(tmpdir5(), "roster-diff-"));
9811
10691
  const a = join33(dir, "live.md");
9812
10692
  const b = join33(dir, "composed.md");
9813
- writeFileSync12(a, normalise(live));
9814
- writeFileSync12(b, normalise(composed));
10693
+ writeFileSync13(a, normalise(live));
10694
+ writeFileSync13(b, normalise(composed));
9815
10695
  const entry = org.staff?.find((s) => s.handle === handle);
9816
10696
  process.stdout.write(`
9817
10697
  ${entry?.name ?? handle} \xB7 ${kind}
@@ -9844,16 +10724,16 @@ async function gatherInflight(opsDir, root2, handle) {
9844
10724
  const org = readOrg(opsDir, parseYaml3);
9845
10725
  const entry = org.staff?.find((s) => s.handle === handle);
9846
10726
  const manifestPath = join33(root2, entry?.dir ?? handle, "staff.yaml");
9847
- const manifest = existsSync15(manifestPath) ? parseYaml3(readFileSync15(manifestPath, "utf8"), "staff.yaml") : {};
10727
+ const manifest = existsSync15(manifestPath) ? parseYaml3(readFileSync16(manifestPath, "utf8"), "staff.yaml") : {};
9848
10728
  const gh = (args) => execFileSync9("gh", args, { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
9849
10729
  const dir = mkdtempSync5(join33(tmpdir5(), "roster-inflight-"));
9850
- writeFileSync12(join33(dir, "inflight.md"), describe2(gather2({ org, manifest, gh })));
10730
+ writeFileSync13(join33(dir, "inflight.md"), describe2(gather2({ org, manifest, gh })));
9851
10731
  return dir;
9852
10732
  }
9853
10733
  function normalise(text2) {
9854
10734
  return text2.split("\n").map((l) => l.replace(/\s+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
9855
10735
  }
9856
- function parseFlags13(argv) {
10736
+ function parseFlags14(argv) {
9857
10737
  const out = {};
9858
10738
  for (let i = 0; i < argv.length; i++) {
9859
10739
  const flag = argv[i];
@@ -9876,7 +10756,7 @@ function parseFlags13(argv) {
9876
10756
  }
9877
10757
 
9878
10758
  // src/commands/run.ts
9879
- import { existsSync as existsSync16, readFileSync as readFileSync16 } from "fs";
10759
+ import { existsSync as existsSync16, readFileSync as readFileSync17 } from "fs";
9880
10760
  import { join as join34 } from "path";
9881
10761
  var runHelp = `
9882
10762
  roster run <handle> [--no-wait] [--apply]
@@ -9902,7 +10782,7 @@ async function runCommand(argv) {
9902
10782
  process.stderr.write("roster: run needs a staff handle, e.g. `roster run cto`\n");
9903
10783
  return 2;
9904
10784
  }
9905
- const opts = parseFlags14(argv.slice(1));
10785
+ const opts = parseFlags15(argv.slice(1));
9906
10786
  const ws = findWorkspace(opts.ops);
9907
10787
  const { parseYaml: parseYaml3 } = await loadComposer(ws.opsDir);
9908
10788
  const org = readOrg(ws.opsDir, parseYaml3);
@@ -9920,7 +10800,7 @@ async function runCommand(argv) {
9920
10800
  return 2;
9921
10801
  }
9922
10802
  const spec2 = specFromManifest(
9923
- parseYaml3(readFileSync16(manifestPath, "utf8"), "staff.yaml"),
10803
+ parseYaml3(readFileSync17(manifestPath, "utf8"), "staff.yaml"),
9924
10804
  dir
9925
10805
  );
9926
10806
  const workflow = dailyWorkflow(handle);
@@ -9999,7 +10879,7 @@ async function runCommand(argv) {
9999
10879
  );
10000
10880
  return 1;
10001
10881
  }
10002
- function parseFlags14(argv) {
10882
+ function parseFlags15(argv) {
10003
10883
  const out = {};
10004
10884
  for (let i = 0; i < argv.length; i++) {
10005
10885
  const flag = argv[i];
@@ -10015,7 +10895,7 @@ function parseFlags14(argv) {
10015
10895
  }
10016
10896
 
10017
10897
  // src/lib/runstore.ts
10018
- import { existsSync as existsSync17, mkdirSync as mkdirSync8, readFileSync as readFileSync17, writeFileSync as writeFileSync13 } from "fs";
10898
+ import { existsSync as existsSync17, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync14 } from "fs";
10019
10899
  import { homedir as homedir2 } from "os";
10020
10900
  import { join as join35 } from "path";
10021
10901
  function diskRecordStore(dir = defaultDir2()) {
@@ -10024,11 +10904,11 @@ function diskRecordStore(dir = defaultDir2()) {
10024
10904
  async get(brain, id) {
10025
10905
  const path = file(brain, id);
10026
10906
  if (!existsSync17(path)) return void 0;
10027
- return JSON.parse(readFileSync17(path, "utf8"));
10907
+ return JSON.parse(readFileSync18(path, "utf8"));
10028
10908
  },
10029
10909
  async put(brain, id, value) {
10030
10910
  mkdirSync8(join35(dir, brain.replace("/", "__")), { recursive: true });
10031
- writeFileSync13(file(brain, id), JSON.stringify(value));
10911
+ writeFileSync14(file(brain, id), JSON.stringify(value));
10032
10912
  }
10033
10913
  };
10034
10914
  }
@@ -10050,6 +10930,7 @@ roster \u2014 an agent-run org, powered by GitHub
10050
10930
  roster hire <handle> scaffold a new staff member
10051
10931
  roster app <handle> create their GitHub App and set its secrets
10052
10932
  roster credential store the agent's credential, once for the org
10933
+ roster connector give staff an outside service: Sentry, Linear, Stripe\u2026
10053
10934
  roster run <handle> start one daily run now, and follow it to the end
10054
10935
  roster retire <handle> stop a staff member, keeping their repo and their memory
10055
10936
  roster upgrade carry framework changes into this tenant
@@ -10070,6 +10951,7 @@ var COMMANDS = {
10070
10951
  hire: hireCommand,
10071
10952
  app: appCommand,
10072
10953
  credential: credentialCommand,
10954
+ connector: connectorCommand,
10073
10955
  run: runCommand,
10074
10956
  retire: retireCommand,
10075
10957
  portal: portalCommand,
@@ -10086,13 +10968,14 @@ var HELPS = {
10086
10968
  hire: hireHelp,
10087
10969
  app: appHelp,
10088
10970
  credential: credentialHelp,
10971
+ connector: connectorHelp,
10089
10972
  run: runHelp,
10090
10973
  retire: retireHelp,
10091
10974
  portal: portalHelp,
10092
10975
  deploy: deployHelp,
10093
10976
  export: exportHelp
10094
10977
  };
10095
- async function main2(argv) {
10978
+ async function main(argv) {
10096
10979
  const raw = rewriteOutput();
10097
10980
  useRecordStore(diskRecordStore());
10098
10981
  const [command, ...rest] = argv;
@@ -10124,7 +11007,7 @@ ${HELP}`);
10124
11007
  }
10125
11008
  return run4(rest);
10126
11009
  }
10127
- main2(process.argv.slice(2)).then((code) => process.exit(code)).catch((err) => {
11010
+ main(process.argv.slice(2)).then((code) => process.exit(code)).catch((err) => {
10128
11011
  process.stderr.write(`roster: ${err instanceof Error ? err.message : String(err)}
10129
11012
  `);
10130
11013
  process.exit(1);