@join-pantheon/cli 0.38.1 → 0.38.3

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.
package/dist/relay.js CHANGED
@@ -439,8 +439,14 @@ const LOOP_WINDOW_MS = 60_000;
439
439
  function loopMs(ns) {
440
440
  return Math.max(0, Math.round((ns / 1e6 - LOOP_RESOLUTION_MS) * 100) / 100);
441
441
  }
442
+ const CLAIM_RATE = 120;
443
+ const ROSTER_EVERY_MS = 500;
444
+ const CLOSE_COMPACT_REST = 20;
445
+ const CLOSE_COMPACT_REST_MAX_MS = 60_000;
446
+ const OUTBOX_MAX = 5_000;
442
447
  const LINK_CLOSED = "Different words were typed here, so this link is closed. That's all: the 6-digit code in the same email still works. Give it to your coding agent.";
443
448
  const LINK_GONE = "This link has expired (they last 10 minutes), a newer Pantheon email replaced it, or it was already used. Use the code in the newest Pantheon email, or ask your coding agent to send a new one.";
449
+ const STORAGE_NO_ENTRY = "the relay's disk is refusing writes, so it cannot let you in right now — reconnect in a moment";
444
450
  const STORAGE_HELD = "the relay received this but has not saved it yet — its disk is refusing writes. It is kept, and reaches the team when the disk recovers; do not send it again.";
445
451
  export function backupExcludes(dir, keep) {
446
452
  const always = ["--exclude=*.tmp", "--exclude=./geoip"];
@@ -624,6 +630,14 @@ export class Relay {
624
630
  goalView(sp, g, held) {
625
631
  return g.state === "CLOSED" ? g : withLast(g, this.lastsOf(sp).get(g.id), held?.has(g.id) ?? false);
626
632
  }
633
+ welcomeGoal(sp, g, held, aged) {
634
+ if (g.state === "CLOSED" && aged.has(g.id) && g.closed_summary !== undefined) {
635
+ const slim = { ...g };
636
+ delete slim.closed_summary;
637
+ return slim;
638
+ }
639
+ return this.goalView(sp, g, held);
640
+ }
627
641
  heldIn(sp) {
628
642
  return heldGoals(sp.obligations.values(), (id) => sp.ledger.find(id)?.goal);
629
643
  }
@@ -682,6 +696,7 @@ export class Relay {
682
696
  closing = false;
683
697
  fsyncOff = false;
684
698
  compactedAt = new Map();
699
+ get outboxMax() { return this.opts.outboxMax ?? OUTBOX_MAX; }
685
700
  sessionSeq = 0;
686
701
  spaceCreates = new Map();
687
702
  limits;
@@ -839,6 +854,14 @@ export class Relay {
839
854
  await new Promise((r) => this.wss.close(() => r()));
840
855
  await new Promise((r) => setImmediate(r));
841
856
  for (const sp of this.spaces.values()) {
857
+ if (sp.rosterTimer) {
858
+ clearTimeout(sp.rosterTimer);
859
+ sp.rosterTimer = undefined;
860
+ }
861
+ if (sp.closeCompactTimer) {
862
+ clearTimeout(sp.closeCompactTimer);
863
+ sp.closeCompactTimer = undefined;
864
+ }
842
865
  try {
843
866
  sp.store.close(sp.goals, sp.obligations, sp.profiles);
844
867
  }
@@ -2972,7 +2995,7 @@ ${body}`;
2972
2995
  }
2973
2996
  quarantining = new Set();
2974
2997
  moveToQuarantine(stem) {
2975
- const sufs = [".members.json", ".members.json.tmp", ".jsonl", ".jsonl.tmp", ".state.json", ".state.json.tmp", ".usage.json", ".usage.json.tmp"];
2998
+ const sufs = [".members.json", ".members.json.tmp", ".jsonl", ".jsonl.tmp", ".state.json", ".state.json.tmp", ".usage.json", ".usage.json.tmp", ".closed-goals.json", ".closed-goals.json.tmp"];
2976
2999
  let files = [];
2977
3000
  try {
2978
3001
  files = readdirSync(this.dataDir);
@@ -2982,7 +3005,7 @@ ${body}`;
2982
3005
  }
2983
3006
  const mine = [
2984
3007
  ...sufs.flatMap((x) => (files.includes(`${stem}${x}`) ? [`${stem}${x}`] : [])),
2985
- ...files.filter((f) => f.startsWith(`${stem}.usage.json.corrupt-`)),
3008
+ ...files.filter((f) => f.startsWith(`${stem}.usage.json.corrupt-`) || f.startsWith(`${stem}.closed-goals.json.corrupt-`) || f.startsWith(`${stem}.closed-goals.json.not-joined-`)),
2986
3009
  ];
2987
3010
  if (!mine.length)
2988
3011
  return { ok: false, error: `no files of "${stem}" to move`, moved: [], rolledBack: true };
@@ -3022,7 +3045,7 @@ ${body}`;
3022
3045
  }
3023
3046
  verifyRemoved(stem, attempt) {
3024
3047
  void writerFor(this.dataDir, stem).whenWritten().then(() => {
3025
- const left = [".jsonl", ".state.json", ".members.json", ".usage.json"].filter((x) => existsSync(join(this.dataDir, `${stem}${x}`)));
3048
+ const left = [".jsonl", ".state.json", ".members.json", ".usage.json", ".closed-goals.json"].filter((x) => existsSync(join(this.dataDir, `${stem}${x}`)));
3026
3049
  if (!left.length)
3027
3050
  return;
3028
3051
  const m = this.moveToQuarantine(stem);
@@ -3570,8 +3593,9 @@ ${body}`;
3570
3593
  }
3571
3594
  sleepingTeamState(name, safe, records, sig, index) {
3572
3595
  const st = new StateStore(this.dataDir, safe);
3573
- const loaded = st.load({ expectHistory: records.length > 0 });
3574
3596
  const allow = new Allowlist(this.dataDir, safe);
3597
+ st.teamId = () => allow.peekId();
3598
+ const loaded = st.load({ expectHistory: records.length > 0 });
3575
3599
  const teamName = allow.recordedName() ?? records.find((r) => r.space)?.space ?? name;
3576
3600
  let savedAt = null;
3577
3601
  try {
@@ -3755,7 +3779,7 @@ ${body}`;
3755
3779
  return out;
3756
3780
  }
3757
3781
  async teamFilesSig(safe) {
3758
- const files = [".jsonl", ".state.json", ".members.json", ".usage.json"].map((suf) => join(this.dataDir, `${safe}${suf}`));
3782
+ const files = [".jsonl", ".state.json", ".members.json", ".usage.json", ".closed-goals.json"].map((suf) => join(this.dataDir, `${safe}${suf}`));
3759
3783
  if (files.some((f) => pendingView(this.dataDir, safe, f) !== undefined))
3760
3784
  return `pending:${Date.now()}:${Math.random()}`;
3761
3785
  const st = await Promise.all(files.map((f) => fsp.stat(f).then((x) => `${x.size}:${x.mtimeMs}`, () => "-")));
@@ -4748,7 +4772,8 @@ pantheon start</code></pre>
4748
4772
  const found = this.tombstoneRecord(m.space);
4749
4773
  const otherSpelling = !!found && !found.corrupt && !found.unreadable && safeName(found.name) !== safeName(m.space);
4750
4774
  const tomb = otherSpelling && (this.live(m.space) || this.spaceOnDisk(m.space)) ? null : found;
4751
- if (!this.live(m.space) && !this.spaceOnDisk(m.space) && this.leftoverState(safeName(m.space)).state !== "live") {
4775
+ const leftHere = !this.live(m.space) && !this.spaceOnDisk(m.space) ? this.leftoverState(safeName(m.space)) : null;
4776
+ if (leftHere && leftHere.state !== "live" && !leftHere.nameFree) {
4752
4777
  this.log(`! REFUSED ${m.member}: "${m.space}" still has a deleted team's files without their member list`);
4753
4778
  return reject("SPACE_DELETED", coveredNameWords(m.space), { gone: null });
4754
4779
  }
@@ -4836,6 +4861,8 @@ pantheon start</code></pre>
4836
4861
  this.accounts?.recordSpace(sp.name, pre?.ok ? pre.account.id : null);
4837
4862
  }
4838
4863
  }
4864
+ if ((sp.outbox?.length ?? 0) >= this.outboxMax)
4865
+ return reject("STORAGE", STORAGE_NO_ENTRY);
4839
4866
  let acctSession = null;
4840
4867
  if (this.requireAccounts && this.accounts && !this.localTrusted(ip)) {
4841
4868
  const auth = this.accounts.authorize(m.pubkey, m.member);
@@ -5004,7 +5031,7 @@ pantheon start</code></pre>
5004
5031
  }
5005
5032
  this.send(ws, {
5006
5033
  t: "welcome", member: me.id, session: sessionId, space: sp.name, seq: sp.ledger.head,
5007
- roster: this.roster(sp), now: Date.now(), goals: ((held) => [...sp.goals.values()].map((g) => this.goalView(sp, g, held)))(this.heldIn(sp)),
5034
+ roster: this.roster(sp), now: Date.now(), goals: ((held, aged) => [...sp.goals.values()].map((g) => this.welcomeGoal(sp, g, held, aged)))(this.heldIn(sp), sp.store.agedIds(sp.goals)),
5008
5035
  obligations: [...sp.obligations.values()], members: this.members(sp), profiles: [...sp.profiles.values()],
5009
5036
  space_id: sp.allow.spaceId(), repos: sp.allow.repoList(), features: [...this.features],
5010
5037
  ...(acct ? { plan: this.planView(acct, sp) } : {}),
@@ -5040,6 +5067,9 @@ pantheon start</code></pre>
5040
5067
  if (delegated && m.t !== "act" && m.t !== "open_goal" && m.t !== "claim" && m.t !== "worker_state") {
5041
5068
  return fail("NOT_FOR_A_RUN", `an unattended run cannot ${m.t.replace(/_/g, " ")} — its member does that from their own session`, m.cid);
5042
5069
  }
5070
+ if (m.t !== "worker_state" && (space.outbox?.length ?? 0) >= this.outboxMax) {
5071
+ return fail("STORAGE_BUSY", "the relay's disk is behind on this team's writes, so this was not taken. Wait a few seconds, then send it again.", m.cid);
5072
+ }
5043
5073
  if (m.t === "publish_profile") {
5044
5074
  if (m.profile.member !== me.id) {
5045
5075
  return fail("PROFILE_NOT_YOURS", `you may publish only the profile for ${me.id}`, m.cid);
@@ -5156,7 +5186,7 @@ pantheon start</code></pre>
5156
5186
  me.worker = { state: m.state, ...(detail ? { detail } : {}), ...(until ? { until } : {}), ...(m.idle_ms !== undefined ? { idle_ms: m.idle_ms } : {}),
5157
5187
  ...(reason ? { reason } : {}), ...(m.ref ? { ref: m.ref } : {}), ...(m.goal ? { goal: m.goal } : {}),
5158
5188
  ...(m.mode && this.features.includes("autopilot") ? { mode: m.mode } : {}), at: now };
5159
- this.broadcast(space, () => ({ t: "roster", roster: this.roster(space), now: Date.now() }));
5189
+ this.rosterSoon(space);
5160
5190
  return;
5161
5191
  }
5162
5192
  if (m.t === "delete_space") {
@@ -5291,6 +5321,8 @@ pantheon start</code></pre>
5291
5321
  return;
5292
5322
  }
5293
5323
  if (m.t === "claim") {
5324
+ if (!this.claimOk(me))
5325
+ return fail("RATE_LIMIT", "too many claims too fast — wait a few seconds", m.cid);
5294
5326
  if (role === "worker") {
5295
5327
  const plan = this.spacePlan(space.name);
5296
5328
  if (plan && !plan.limits.wake)
@@ -5379,6 +5411,11 @@ pantheon start</code></pre>
5379
5411
  return fail("NOT_ALLOWED_TO_WAKE", `"${origin.from}" is not permitted to wake a worker on this machine`, m.cid);
5380
5412
  }
5381
5413
  }
5414
+ if (o.claimed_by && o.claimed_by.session === sessionId && o.claimed_by.role === role) {
5415
+ o.claimed_by.at = Date.now();
5416
+ this.send(ws, { t: "ack", ...(m.cid ? { cid: m.cid } : {}), id: o.id, seq: space.ledger.head });
5417
+ return;
5418
+ }
5382
5419
  o.claimed_by = { session: sessionId, role, at: Date.now() };
5383
5420
  space.store.noteFirstClaim({ ob: o.id, ref: o.ref, owner: o.owner, at: o.claimed_by.at, by: role === "worker" ? "worker" : "person" });
5384
5421
  this.broadcast(space, { t: "claimed", obligation: o.id, session: sessionId, member: me.id });
@@ -5550,14 +5587,8 @@ pantheon start</code></pre>
5550
5587
  this.countUsage(sp, (b, now) => { countMessage(b, rec.act, role, now); if (closed)
5551
5588
  countGoal(b, "closed", now); });
5552
5589
  }
5553
- if (wasFull && m.act === "CLOSE") {
5554
- try {
5555
- this.compactSpace(space);
5556
- }
5557
- catch (e) {
5558
- this.noteStorageFailure(`[${space.name}] compacting after a close`, e);
5559
- }
5560
- }
5590
+ if (wasFull && m.act === "CLOSE")
5591
+ this.compactAfterClose(space);
5561
5592
  space.recent.set(fp, { id: rec.id, seq: rec.seq, at: Date.now() });
5562
5593
  for (const [k, v] of space.recent)
5563
5594
  if (Date.now() - v.at > LIMITS.dedupeWindowMs)
@@ -6247,6 +6278,7 @@ pantheon start</code></pre>
6247
6278
  if (goal) {
6248
6279
  goal.state = "CLOSED";
6249
6280
  goal.closed_summary = rec.body;
6281
+ goal.closed_at = rec.ts;
6250
6282
  const dt = rec.meta?.defers_to;
6251
6283
  if (dt)
6252
6284
  goal.defers_to = dt;
@@ -6329,6 +6361,31 @@ pantheon start</code></pre>
6329
6361
  me.stamps.push(now);
6330
6362
  return true;
6331
6363
  }
6364
+ claimOk(me) {
6365
+ const now = Date.now();
6366
+ const st = (me.claimStamps ?? []).filter((t) => now - t < LIMITS.rateWindowMs);
6367
+ me.claimStamps = st;
6368
+ if (st.length >= CLAIM_RATE)
6369
+ return false;
6370
+ st.push(now);
6371
+ return true;
6372
+ }
6373
+ rosterSoon(sp) {
6374
+ if (sp.rosterTimer)
6375
+ return;
6376
+ const since = Date.now() - (sp.rosterAt ?? 0);
6377
+ const go = () => {
6378
+ sp.rosterTimer = undefined;
6379
+ if (this.closing || sp.deleted || this.spaces.get(spaceKey(sp.name)) !== sp)
6380
+ return;
6381
+ sp.rosterAt = Date.now();
6382
+ this.broadcast(sp, () => ({ t: "roster", roster: this.roster(sp), now: Date.now() }), "roster");
6383
+ };
6384
+ if (since >= ROSTER_EVERY_MS)
6385
+ return go();
6386
+ sp.rosterTimer = setTimeout(go, ROSTER_EVERY_MS - since);
6387
+ sp.rosterTimer.unref?.();
6388
+ }
6332
6389
  mayCreateSpace(ip) {
6333
6390
  const now = Date.now();
6334
6391
  if (!this.localTrusted(ip)) {
@@ -6425,11 +6482,11 @@ pantheon start</code></pre>
6425
6482
  }
6426
6483
  deleteSpaceFiles(name) {
6427
6484
  const safe = name.replace(/[^a-z0-9._-]/gi, "_");
6428
- for (const suffix of [".jsonl", ".state.json", ".members.json", ".usage.json"])
6485
+ for (const suffix of [".jsonl", ".state.json", ".members.json", ".usage.json", ".closed-goals.json"])
6429
6486
  writerFor(this.dataDir, safe).remove(join(this.dataDir, `${safe}${suffix}`));
6430
6487
  try {
6431
6488
  for (const f of readdirSync(this.dataDir))
6432
- if (f.startsWith(`${safe}.usage.json.corrupt-`))
6489
+ if (f.startsWith(`${safe}.usage.json.corrupt-`) || f.startsWith(`${safe}.closed-goals.json.corrupt-`) || f.startsWith(`${safe}.closed-goals.json.not-joined-`))
6433
6490
  writerFor(this.dataDir, safe).remove(join(this.dataDir, f));
6434
6491
  }
6435
6492
  catch { }
@@ -6463,7 +6520,7 @@ pantheon start</code></pre>
6463
6520
  const safe = name.replace(/[^a-z0-9._-]/gi, "_");
6464
6521
  {
6465
6522
  const ls = this.leftoverState(safe);
6466
- if (ls.state === "covered" || (ls.state === "unsure" && !this.spaceOnDisk(name)))
6523
+ if (ls.state === "covered" || (ls.state === "unsure" && !ls.nameFree && !this.spaceOnDisk(name)))
6467
6524
  return null;
6468
6525
  }
6469
6526
  const allow = new Allowlist(this.dataDir, safe);
@@ -6495,6 +6552,8 @@ pantheon start</code></pre>
6495
6552
  const store = new StateStore(this.dataDir, safe);
6496
6553
  store.headOf = () => ledger.head;
6497
6554
  store.onError = (e) => this.noteStorageFailure(`[${name}] snapshot save`, e);
6555
+ store.teamId = () => allow.peekId();
6556
+ store.onNote = (line) => this.log(`! [${name}] ${line}`);
6498
6557
  const restored = store.load({ quarantine: true, expectHistory: ledger.size > 0 });
6499
6558
  if (!restored.unclean && restored.ledgerHead !== undefined && restored.ledgerHead > ledger.head) {
6500
6559
  if (ledger.size > 0) {
@@ -6702,6 +6761,9 @@ pantheon start</code></pre>
6702
6761
  }
6703
6762
  for (const o of sp.obligations.values())
6704
6763
  o.created_at = sp.ledger.find(o.ref)?.ts ?? o.created_at;
6764
+ for (const g of sp.store.closedGoals())
6765
+ if (!sp.goals.has(g.id))
6766
+ sp.goals.set(g.id, g);
6705
6767
  let open = 0;
6706
6768
  for (const g of sp.goals.values()) {
6707
6769
  if (g.state === "CLOSED")
@@ -6737,8 +6799,36 @@ pantheon start</code></pre>
6737
6799
  ...(kindFromOpening(meta?.goal_sig, mm[4]) ? { kind: kindFromOpening(meta?.goal_sig, mm[4]) } : {}),
6738
6800
  };
6739
6801
  }
6740
- compactSpace(sp) {
6741
- this.compactedAt.set(sp.name, Date.now());
6802
+ compactAfterClose(sp) {
6803
+ if (sp.closeCompactTimer)
6804
+ return;
6805
+ const run = () => {
6806
+ sp.closeCompactTimer = undefined;
6807
+ if (this.closing || sp.deleted || this.spaces.get(spaceKey(sp.name)) !== sp)
6808
+ return;
6809
+ const over = sp.ledger.bytes - this.maxLedgerBytes;
6810
+ if (over < 0)
6811
+ return;
6812
+ const began = performance.now();
6813
+ try {
6814
+ this.compactSpace(sp, over + 1);
6815
+ }
6816
+ catch (e) {
6817
+ this.noteStorageFailure(`[${sp.name}] compacting after a close`, e);
6818
+ }
6819
+ sp.closeCompactAt = performance.now();
6820
+ sp.closeCompactMs = sp.closeCompactAt - began;
6821
+ };
6822
+ const rest = Math.min(CLOSE_COMPACT_REST_MAX_MS, CLOSE_COMPACT_REST * (sp.closeCompactMs ?? 0));
6823
+ const wait = sp.closeCompactAt === undefined ? 0 : rest - (performance.now() - sp.closeCompactAt);
6824
+ if (wait <= 0)
6825
+ return run();
6826
+ sp.closeCompactTimer = setTimeout(run, wait);
6827
+ sp.closeCompactTimer.unref?.();
6828
+ }
6829
+ compactSpace(sp, onlyIfFrees) {
6830
+ if (onlyIfFrees === undefined)
6831
+ this.compactedAt.set(sp.name, Date.now());
6742
6832
  if (sp.unclean)
6743
6833
  return;
6744
6834
  const isLive = (goal) => {
@@ -6753,8 +6843,10 @@ pantheon start</code></pre>
6753
6843
  const { dropped, kept, newestDropped } = sp.ledger.compact({
6754
6844
  keepRecent: this.opts.ledgerKeepRecent ?? LIMITS.ledgerKeepRecent, isLive, keep: (id) => referenced.has(id),
6755
6845
  presence: { is: (r) => r.act === "JOIN" || r.act === "LEAVE", keepRecent: this.opts.ledgerKeepPresence ?? LIMITS.ledgerKeepPresence },
6846
+ ...(onlyIfFrees !== undefined ? { onlyIfFrees } : {}),
6756
6847
  });
6757
6848
  if (dropped) {
6849
+ this.compactedAt.set(sp.name, Date.now());
6758
6850
  sp.store.noteCompacted(fromGaps);
6759
6851
  sp.store.noteCompacted(newestDropped);
6760
6852
  sp.store.gapsChecked = { seq: sp.ledger.head, kept: sp.ledger.size };
@@ -6880,12 +6972,12 @@ pantheon start</code></pre>
6880
6972
  const sp = this.spaceOf.get(ws);
6881
6973
  const payload = JSON.stringify(msg);
6882
6974
  const run = () => this.write(ws, payload);
6883
- if (!sp) {
6975
+ if (!sp || ((msg.t === "error" || msg.t === "pong") && (sp.outbox?.length ?? 0) >= this.outboxMax)) {
6884
6976
  run();
6885
6977
  return Buffer.byteLength(payload);
6886
6978
  }
6887
6979
  const instead = msg.t === "ack" && msg.cid ? { cid: msg.cid } : msg.t === "welcome" ? {} : null;
6888
- const message = msg.t === "welcome" ? "the relay's disk is refusing writes, so it cannot let you in right now — reconnect in a moment" : STORAGE_HELD;
6980
+ const message = msg.t === "welcome" ? STORAGE_NO_ENTRY : STORAGE_HELD;
6889
6981
  this.out(sp, run, instead ? { ws, payload: JSON.stringify({ t: "error", code: "STORAGE", message, ...instead }), hangUp: msg.t === "welcome" } : undefined);
6890
6982
  return Buffer.byteLength(payload);
6891
6983
  }
@@ -6903,7 +6995,7 @@ pantheon start</code></pre>
6903
6995
  ws.send(payload);
6904
6996
  return true;
6905
6997
  }
6906
- broadcast(sp, msg) {
6998
+ broadcast(sp, msg, key) {
6907
6999
  this.out(sp, () => {
6908
7000
  const m = typeof msg === "function" ? msg() : msg;
6909
7001
  const payload = JSON.stringify(m);
@@ -6919,15 +7011,19 @@ pantheon start</code></pre>
6919
7011
  if (reached && seq !== null && seq > mem.delivered_seq)
6920
7012
  mem.delivered_seq = seq;
6921
7013
  }
6922
- });
7014
+ }, undefined, key);
6923
7015
  }
6924
- out(sp, run, failed) {
7016
+ out(sp, run, failed, key) {
6925
7017
  const w = busyWriter(this.dataDir, safeName(sp.name));
6926
7018
  if (!sp.outbox?.length && !w)
6927
7019
  return run();
6928
7020
  if (failed && w?.failing)
6929
7021
  return this.sendFailed(failed);
6930
- (sp.outbox ??= []).push({ run, w, ticket: w ? w.ticket : 0, ...(failed ? { failed } : {}) });
7022
+ if (key && sp.outbox?.some((h) => h.key === key))
7023
+ return;
7024
+ if (failed?.hangUp && (sp.outbox?.length ?? 0) >= this.outboxMax)
7025
+ return this.sendFailed(failed);
7026
+ (sp.outbox ??= []).push({ run, w, ticket: w ? w.ticket : 0, ...(failed ? { failed } : {}), ...(key ? { key } : {}) });
6931
7027
  if (w)
6932
7028
  void w.whenWritten(w.ticket).then(() => this.release(sp));
6933
7029
  }
@@ -1,7 +1,8 @@
1
1
  import { signInRefused } from "./agent-outage.js";
2
2
  import { execFileSync } from "node:child_process";
3
3
  import { gitCallEnv, safeGitArgs } from "./git-safe.js";
4
- import { checkRepoCommand } from "./agents.js";
4
+ import { agentById, cannotStartWords, checkRepoCommand } from "./agents.js";
5
+ import { programOf, startFailureOf, startWhy } from "./agent-start.js";
5
6
  import { bashRuleMatches, GIT_DENY_RULES } from "./claude-confine.js";
6
7
  const AGENT_LABEL = { "claude-code": "Claude Code", codex: "Codex", cursor: "Cursor", copilot: "GitHub Copilot", kiro: "Kiro" };
7
8
  export const SIGN_IN_FIX = {
@@ -133,6 +134,16 @@ export function diagnoseRun(f, probe = gitProbe) {
133
134
  ? { cause: "not_signed_in", says: `${label} refused ${w.what}, so the run couldn't start.`, fix: `${w.fix[0].toUpperCase()}${w.fix.slice(1)}.` }
134
135
  : { cause: "not_signed_in", says: `${label} is signed out on this computer, so the run couldn't start.`, fix: `Sign in once and the next run works: ${SIGN_IN_FIX[f.agent ?? ""] ?? "sign in to the agent CLI on this machine"}.` };
135
136
  }
137
+ const backend = f.exited || f.agentCmd || !f.agent ? undefined : agentById(f.agent);
138
+ const notStarted = backend ? startFailureOf(f.detail, { agent: backend.id, ...(f.os ? { os: f.os } : {}), ...(f.ranMs !== undefined ? { ranMs: f.ranMs } : {}), ...(f.binary ? { binary: f.binary } : {}) }) : null;
139
+ if (backend && notStarted) {
140
+ const w = cannotStartWords(backend, { ...notStarted, why: startWhy(notStarted.kind, programOf(f.binary ?? backend.binaries[0]), notStarted.needs) }, f.os ? { os: f.os } : {});
141
+ return {
142
+ cause: "agent_not_installed",
143
+ says: `${backend.label} could not be started on this computer, so the run never began: ${w.why}.`,
144
+ fix: w.fix,
145
+ };
146
+ }
136
147
  if (f.allowBash && (f.agent ?? "claude-code") === "claude-code" && (f.os ?? process.platform) === "linux" && SANDBOX_RE.test(f.detail)) {
137
148
  return {
138
149
  cause: "sandbox_unavailable",
package/dist/store.js CHANGED
@@ -1,9 +1,26 @@
1
- import { readFileSync, existsSync, mkdirSync, renameSync, openSync, writeSync, fsyncSync, closeSync, chmodSync } from "node:fs";
2
- import { dirname, join } from "node:path";
1
+ import { readFileSync, existsSync, mkdirSync, renameSync, openSync, writeSync, fsyncSync, closeSync, chmodSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
3
  import { emptyRefusals } from "./admin-stats.js";
4
4
  import { pendingView, writerFor } from "./disk-writer.js";
5
5
  import { emptyUsage, parseUsage } from "./usage.js";
6
6
  export const USAGE_SAVE_MS = 5_000;
7
+ export const CLOSED_AGE_MS = 30 * 24 * 60 * 60_000;
8
+ export const CLOSED_KEEP = 200;
9
+ const AGED_RECHECK_MS = 10 * 60_000;
10
+ export function closedAt(g) {
11
+ return typeof g.closed_at === "number" && Number.isFinite(g.closed_at) ? g.closed_at : g.opened_at;
12
+ }
13
+ export function agedClosed(goals, now = Date.now(), age = CLOSED_AGE_MS, keep = CLOSED_KEEP) {
14
+ const closed = [...goals].filter((g) => g.state === "CLOSED");
15
+ if (closed.length <= keep)
16
+ return new Set();
17
+ closed.sort((a, b) => closedAt(b) - closedAt(a));
18
+ const out = new Set();
19
+ for (const g of closed.slice(keep))
20
+ if (now - closedAt(g) > age)
21
+ out.add(g.id);
22
+ return out;
23
+ }
7
24
  export const FIRST_CLAIMS_KEEP_MS = 31 * 86_400_000;
8
25
  export const FIRST_CLAIMS_MAX = 5_000;
9
26
  export function ensurePrivateDir(dir) {
@@ -118,12 +135,129 @@ export class StateStore {
118
135
  usageFile;
119
136
  usageTimer = null;
120
137
  usageDirty = false;
138
+ closedFile;
139
+ closedOnDisk = new Map();
140
+ aged = null;
141
+ closedUnreadable = false;
142
+ teamId;
143
+ onNote;
121
144
  constructor(dir, stem) {
122
145
  this.dir = dir;
123
146
  this.stem = stem;
124
147
  this.file = join(dir, `${stem}.state.json`);
125
148
  this.usageFile = join(dir, `${stem}.usage.json`);
149
+ this.closedFile = join(dir, `${stem}.closed-goals.json`);
150
+ }
151
+ agedIds(goals, now = Date.now()) {
152
+ if (!this.aged || this.aged.size !== goals.size || now - this.aged.at > AGED_RECHECK_MS) {
153
+ this.aged = { ids: agedClosed(goals.values(), now), at: now, size: goals.size };
154
+ }
155
+ return this.aged.ids;
156
+ }
157
+ isAged(goals, g) {
158
+ return g.state === "CLOSED" && this.agedIds(goals).has(g.id);
126
159
  }
160
+ loadClosed(quarantine, known) {
161
+ this.closedOnDisk = new Map();
162
+ this.closedUnreadable = false;
163
+ let text;
164
+ try {
165
+ const pending = pendingView(this.dir, this.stem, this.closedFile);
166
+ if (pending === null || (pending === undefined && !existsSync(this.closedFile)))
167
+ return this.closedOnDisk;
168
+ text = pending ? pending.toString("utf8") : readFileSync(this.closedFile, "utf8");
169
+ }
170
+ catch (e) {
171
+ const code = e.code ?? "EIO";
172
+ if (code === "ENOENT")
173
+ return this.closedOnDisk;
174
+ this.closedUnreadable = true;
175
+ this.onNote?.(`old closed goals' file ${basename(this.closedFile)} cannot be read right now (${code}): the team is loaded without it, and the file is left as it is`);
176
+ return this.closedOnDisk;
177
+ }
178
+ let team = null;
179
+ const read = new Map();
180
+ let whole = false;
181
+ try {
182
+ const raw = JSON.parse(text);
183
+ const all = raw && typeof raw === "object" && raw.goals && typeof raw.goals === "object" && !Array.isArray(raw.goals) ? raw.goals : null;
184
+ if (!all)
185
+ throw new Error("not a closed-goals file");
186
+ if (raw.team !== undefined && (typeof raw.team !== "string" || !raw.team))
187
+ throw new Error("not a closed-goals file");
188
+ team = typeof raw.team === "string" ? raw.team : null;
189
+ for (const [id, v] of Object.entries(all)) {
190
+ const g = v;
191
+ if (g && typeof g === "object" && g.id === id && typeof g.title === "string" && typeof g.closed_summary === "string" && Array.isArray(g.members))
192
+ read.set(id, { ...g, state: "CLOSED" });
193
+ }
194
+ whole = read.size === Object.keys(all).length;
195
+ }
196
+ catch {
197
+ const aside = quarantine ? this.moveAside("corrupt") : null;
198
+ this.closedUnreadable = !aside;
199
+ this.onNote?.(`old closed goals' file ${basename(this.closedFile)} does not parse: ${aside ? `moved aside to ${basename(aside)}` : "left as it is, and never written over"}`);
200
+ return this.closedOnDisk;
201
+ }
202
+ const mine = this.teamId?.() ?? null;
203
+ if (team !== null) {
204
+ if (team === mine) {
205
+ this.closedOnDisk = read;
206
+ return this.closedOnDisk;
207
+ }
208
+ return this.notJoined(quarantine, read.size, `was written for another team (${team})`);
209
+ }
210
+ const own = new Map([...read].filter(([id]) => known?.has(id)));
211
+ if (own.size === read.size) {
212
+ this.closedOnDisk = own;
213
+ if (quarantine && mine && own.size && whole)
214
+ writerFor(this.dir, this.stem).replace(this.closedFile, this.closedText(own), 0o600, "first");
215
+ return this.closedOnDisk;
216
+ }
217
+ const why = known
218
+ ? `names no team and holds ${read.size - own.size} goal(s) this team's snapshot does not have`
219
+ : "names no team, and this team has no readable snapshot to check it against";
220
+ if (!own.size)
221
+ return this.notJoined(quarantine, read.size, why);
222
+ this.closedOnDisk = own;
223
+ let aside = null;
224
+ if (quarantine) {
225
+ aside = `${this.closedFile}.not-joined-${Date.now()}`;
226
+ try {
227
+ writeFileSync(aside, text, { mode: 0o600, flag: "wx" });
228
+ }
229
+ catch {
230
+ aside = null;
231
+ }
232
+ if (aside)
233
+ writerFor(this.dir, this.stem).replace(this.closedFile, this.closedText(own), 0o600, "first");
234
+ }
235
+ this.closedUnreadable = !aside;
236
+ this.onNote?.(`old closed goals' file ${basename(this.closedFile)} ${why}: only this team's ${own.size} were read; ${aside ? `the file as it was is kept for the operator as ${basename(aside)}` : "the file is left as it is, and never written over"}`);
237
+ return this.closedOnDisk;
238
+ }
239
+ moveAside(as) {
240
+ const aside = `${this.closedFile}.${as}-${Date.now()}`;
241
+ try {
242
+ renameSync(this.closedFile, aside);
243
+ return aside;
244
+ }
245
+ catch {
246
+ return null;
247
+ }
248
+ }
249
+ notJoined(quarantine, goals, why) {
250
+ const aside = quarantine ? this.moveAside("not-joined") : null;
251
+ this.closedUnreadable = !aside;
252
+ this.closedOnDisk = new Map();
253
+ this.onNote?.(`old closed goals' file ${basename(this.closedFile)} ${why}: none of its ${goals} goal(s) was read into this team; ${aside ? `kept for the operator as ${basename(aside)}` : "left as it is, and never written over"}`);
254
+ return this.closedOnDisk;
255
+ }
256
+ closedText(goals) {
257
+ const team = this.teamId?.() ?? null;
258
+ return JSON.stringify({ v: 1, ...(team ? { team } : {}), goals: Object.fromEntries(goals) }) + "\n";
259
+ }
260
+ closedGoals() { return [...this.closedOnDisk.values()].map((g) => ({ ...g, members: [...g.members] })); }
127
261
  loadUsage(quarantine) {
128
262
  try {
129
263
  const pending = pendingView(this.dir, this.stem, this.usageFile);
@@ -177,6 +311,8 @@ export class StateStore {
177
311
  this.loadUsage(!!opts.quarantine);
178
312
  const pending = pendingView(this.dir, this.stem, this.file);
179
313
  if (pending === null || (pending === undefined && !existsSync(this.file))) {
314
+ this.loadClosed(!!opts.quarantine, null);
315
+ this.aged = null;
180
316
  return { goals, obligations, profiles, unclean: opts.expectHistory ? "the state snapshot is missing but the ledger has history" : null };
181
317
  }
182
318
  try {
@@ -188,6 +324,13 @@ export class StateStore {
188
324
  }
189
325
  for (const g of snap.goals ?? [])
190
326
  goals.set(g.id, g);
327
+ const kept = this.loadClosed(!!opts.quarantine, goals);
328
+ for (const [id, whole] of kept) {
329
+ const g = goals.get(id);
330
+ if (g && g.closed_summary === undefined && whole.closed_summary !== undefined)
331
+ goals.set(id, { ...g, closed_summary: whole.closed_summary });
332
+ }
333
+ this.aged = null;
191
334
  for (const o of snap.obligations ?? []) {
192
335
  obligations.set(o.id, o.claimed_by ? { ...o, claimed_by: { ...o.claimed_by, at: Date.now() } } : o);
193
336
  }
@@ -228,6 +371,8 @@ export class StateStore {
228
371
  }
229
372
  catch { }
230
373
  }
374
+ this.loadClosed(!!opts.quarantine, null);
375
+ this.aged = null;
231
376
  return { goals: new Map(), obligations: new Map(), profiles: new Map(), unclean: why, ...(quarantined ? { quarantined } : {}) };
232
377
  }
233
378
  }
@@ -251,10 +396,34 @@ export class StateStore {
251
396
  }
252
397
  onError;
253
398
  flush(goals, obligations, profiles) {
399
+ let list = [...goals.values()];
400
+ if (!this.closedUnreadable) {
401
+ const aged = this.agedIds(goals);
402
+ const next = new Map(this.closedOnDisk);
403
+ let grew = false;
404
+ if (aged.size) {
405
+ list = list.map((g) => {
406
+ if (g.state !== "CLOSED" || !aged.has(g.id) || g.closed_summary === undefined)
407
+ return g;
408
+ const had = next.get(g.id);
409
+ if (!had || had.closed_summary !== g.closed_summary) {
410
+ next.set(g.id, { ...g, members: [...g.members] });
411
+ grew = true;
412
+ }
413
+ const rest = { ...g };
414
+ delete rest.closed_summary;
415
+ return rest;
416
+ });
417
+ }
418
+ if (grew) {
419
+ writerFor(this.dir, this.stem).replace(this.closedFile, this.closedText(next), 0o600, "first");
420
+ this.closedOnDisk = next;
421
+ }
422
+ }
254
423
  const snap = {
255
424
  ...this.extra,
256
425
  v: 2,
257
- goals: [...goals.values()],
426
+ goals: list,
258
427
  obligations: [...obligations.values()],
259
428
  profiles: [...profiles.values()],
260
429
  ...(this.refusals.total ? { refusals: this.refusals } : {}),
@@ -265,7 +434,7 @@ export class StateStore {
265
434
  ...(this.gapsChecked ? { gaps_checked: this.gapsChecked } : {}),
266
435
  saved_at: Date.now(),
267
436
  };
268
- writerFor(this.dir, this.stem).replace(this.file, JSON.stringify(snap, null, 2) + "\n");
437
+ writerFor(this.dir, this.stem).replace(this.file, JSON.stringify(snap) + "\n");
269
438
  }
270
439
  keptFirstClaims(now = Date.now()) {
271
440
  for (const [k, c] of this.firstClaims)
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { CONFIG_DIR } from "./config.js";
5
5
  import { repoRoot, PKG_NAME } from "./upgrade.js";
6
+ import { readRolledBack } from "./upgrade-probation.js";
6
7
  import { VERSION } from "./version.js";
7
8
  import { npmSpawn } from "./which.js";
8
9
  import { proxyEnvFor } from "./network.js";
@@ -44,9 +45,11 @@ export function updateStatus(deps) {
44
45
  return { behind: cache?.behind ?? 0, refreshed: false, latest: cache?.latest };
45
46
  }
46
47
  }
47
- export function versionLine(version, behind, latest) {
48
+ export function versionLine(version, behind, latest, held) {
48
49
  if (behind <= 0)
49
50
  return `pantheon ${version}`;
51
+ if (latest && held && latest === held)
52
+ return `pantheon ${version}`;
50
53
  if (latest && !semverGt(latest, version))
51
54
  return `pantheon ${version}`;
52
55
  return latest
@@ -94,10 +97,22 @@ export function defaultDeps(home) {
94
97
  }
95
98
  },
96
99
  current: () => VERSION,
100
+ held: () => { try {
101
+ return readRolledBack()?.version ?? null;
102
+ }
103
+ catch {
104
+ return null;
105
+ } },
97
106
  };
98
107
  }
99
108
  export function updateBanner(version, deps = defaultDeps()) {
100
109
  const { behind, latest } = updateStatus(deps);
101
- return versionLine(version, behind, latest);
110
+ const held = behind > 0 && latest ? (() => { try {
111
+ return deps.held?.() ?? null;
112
+ }
113
+ catch {
114
+ return null;
115
+ } })() : null;
116
+ return versionLine(version, behind, latest, held);
102
117
  }
103
118
  //# sourceMappingURL=update-check.js.map