@join-pantheon/cli 0.35.1 → 0.35.2-rc.2

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.
@@ -0,0 +1,55 @@
1
+ import { cap, esc, plural, split, stackedColumns } from "./admin-ui.js";
2
+ import { dur } from "./flow-stats.js";
3
+ export function topPair(f) {
4
+ let top = null, ties = 0;
5
+ for (const [from, row] of Object.entries(f.matrix.n))
6
+ for (const [to, n] of Object.entries(row)) {
7
+ if (!top || n > top.n) {
8
+ top = { from, to, n };
9
+ ties = 0;
10
+ }
11
+ else if (n === top.n)
12
+ ties++;
13
+ }
14
+ return top ? { ...top, ties } : null;
15
+ }
16
+ export function askMatrix(f, range) {
17
+ if (!f.matrix.from.length)
18
+ return `<p class="muted" style="margin:0">Nobody asked anyone ${range}.</p>`;
19
+ const max = Math.max(1, ...Object.values(f.matrix.n).flatMap((r) => Object.values(r)));
20
+ const cell = (n, from, to) => {
21
+ if (!n)
22
+ return `<td class="z" aria-label="${esc(cap(from))} asked ${esc(cap(to))}: none">·</td>`;
23
+ const a = 0.18 + 0.82 * (n / max);
24
+ return `<td class="h" tabindex="0" data-tip="${plural(n, "ask")}|${esc(cap(from))} asked ${esc(cap(to))}" aria-label="${esc(cap(from))} asked ${esc(cap(to))}: ${n}" style="--a:${a.toFixed(2)}">${n}</td>`;
25
+ };
26
+ return `<table class="matrix" aria-label="Who asked whom, ${range}">
27
+ <thead><tr><th></th>${f.matrix.to.map((p) => `<th scope="col">${esc(cap(p))}</th>`).join("")}</tr></thead>
28
+ <tbody>${f.matrix.from.map((from) => `<tr><th scope="row" class="rowh">${esc(cap(from))}</th>${f.matrix.to.map((to) => from === to ? `<td class="self" aria-hidden="true"></td>` : cell(f.matrix.n[from]?.[to] ?? 0, from, to)).join("")}</tr>`).join("")}</tbody>
29
+ </table>`;
30
+ }
31
+ export function handoffsRow(f, series14, range) {
32
+ const top = topPair(f);
33
+ return `<div class="grid2 even sec" id="handoffs">
34
+ <section class="card pad" aria-labelledby="h-who">
35
+ <div class="sechead" style="margin-bottom:10px"><h2 id="h-who">Who asked whom</h2><p>rows asked, columns were asked</p></div>
36
+ <div class="scroll">${askMatrix(f, range)}</div>
37
+ ${top ? `<p class="note">Stronger teal means more asks. ${top.ties ? `The most from one person to another ${range} is ${plural(top.n, "request")}, shared by ${top.ties + 1} pairs (${esc(cap(top.from))} to ${esc(cap(top.to))} is one).` : `${esc(cap(top.from))} handed ${plural(top.n, "request")} to ${esc(cap(top.to))} ${range}, the most of any pair.`}</p>` : ""}
38
+ </section>
39
+ <section class="card pad" aria-labelledby="h-daily">
40
+ <div class="sechead" style="margin-bottom:4px"><h2 id="h-daily">Messages per day</h2><p>the last 14 UTC days</p></div>
41
+ ${stackedColumns({ days: [...series14], width: 620, height: 190, step: 3, label: `Messages per day for 14 days. ${f.messages.total} ${range}, ${f.messages.worker} by workers.` })}
42
+ </section>
43
+ </div>`;
44
+ }
45
+ export function carriedSection(f, range) {
46
+ const rows = f.carried.map((c) => `<tr><td class="span"><b class="who">${esc(cap(c.who))}</b><span class="sub">${esc(c.agent)}</span></td><td data-l="Asked" class="r num">${c.asked}</td><td data-l="Answered by" class="span">${split(c.byWorker, c.byPerson, c.asked, 140)}<span class="sub num">${c.byWorker} by their worker · ${c.byPerson} by ${esc(cap(c.who))} in person</span></td><td data-l="Median time to answer" class="r num">${c.medianMs !== null ? dur(c.medianMs) : `<span class="quiet">none yet</span>`}</td><td data-l="Open now" class="r num">${c.open || `<span class="quiet">0</span>`}</td></tr>`).join("");
47
+ return `<section class="sec" id="carried" aria-labelledby="h-carry">
48
+ <div class="sechead"><h2 id="h-carry">Who carried the work</h2><p>requests each person was asked ${range}, and whether their worker or they answered</p></div>
49
+ <div class="card"><table class="rt">
50
+ <thead><tr><th>Asked of</th><th class="r">Asked</th><th>Answered by</th><th class="r">Median time to answer</th><th class="r">Open now</th></tr></thead>
51
+ <tbody>${rows || `<tr><td colspan="5" class="empty">Nobody was asked anything ${range}.</td></tr>`}</tbody>
52
+ </table></div>
53
+ </section>`;
54
+ }
55
+ //# sourceMappingURL=flow-visuals.js.map
package/dist/ledger.js CHANGED
@@ -155,13 +155,34 @@ export class Ledger {
155
155
  return this.records.length;
156
156
  }
157
157
  compact(opts) {
158
- const cut = Math.max(0, this.records.length - opts.keepRecent);
159
- if (cut === 0)
160
- return { dropped: 0, kept: this.records.length, newestDropped: null };
158
+ const n = this.records.length;
159
+ const pres = opts.presence;
160
+ let inTail;
161
+ if (!pres) {
162
+ const cut = Math.max(0, n - opts.keepRecent);
163
+ if (cut === 0)
164
+ return { dropped: 0, kept: n, newestDropped: null };
165
+ inTail = (_r, i) => i >= cut;
166
+ }
167
+ else {
168
+ const tail = new Uint8Array(n);
169
+ let real = 0, seen = 0;
170
+ for (let i = n - 1; i >= 0; i--) {
171
+ if (pres.is(this.records[i])) {
172
+ if (seen++ < pres.keepRecent)
173
+ tail[i] = 1;
174
+ }
175
+ else if (real++ < opts.keepRecent)
176
+ tail[i] = 1;
177
+ }
178
+ if (real <= opts.keepRecent && seen <= pres.keepRecent)
179
+ return { dropped: 0, kept: n, newestDropped: null };
180
+ inTail = (_r, i) => tail[i] === 1;
181
+ }
161
182
  let newestDropped = null;
162
183
  const kept = this.records.filter((r, i) => {
163
- const keep = i >= cut || opts.isLive(r.goal) || (opts.keep?.(r.id) ?? false);
164
- if (!keep && (newestDropped === null || r.ts > newestDropped))
184
+ const keep = inTail(r, i) || opts.isLive(r.goal) || (opts.keep?.(r.id) ?? false);
185
+ if (!keep && !pres?.is(r) && (newestDropped === null || r.ts > newestDropped))
165
186
  newestDropped = r.ts;
166
187
  return keep;
167
188
  });
package/dist/mcp.js CHANGED
@@ -300,6 +300,7 @@ export async function runMcp() {
300
300
  ? { ...g, kind: undefined } : g;
301
301
  const askedHere = new Set();
302
302
  const handedHere = [];
303
+ const askedAgainOnce = new Set();
303
304
  const handed = (o) => o.kind === "ANSWER" && handedHere.some((h) => h.ref
304
305
  ? h.ref === o.ref
305
306
  : h.goal !== null && h.goal === o.goal && o.claimed_by?.session === client.session);
@@ -564,6 +565,20 @@ A goal for it (${left}) may be open with nothing in it — close it with pantheo
564
565
  if (mine.length === 1)
565
566
  ref = mine[0].ref;
566
567
  }
568
+ if (act === "ESCALATE" && role === "worker") {
569
+ const key = `${ref ?? ""}\n${goal ?? ""}`;
570
+ const settled = (id) => client.mineSince(0).some((a) => (a.act === "ANSWER" || a.act === "RETRACT") && a.ref === id);
571
+ const first = askedAgainOnce.has(key) ? undefined
572
+ : handedHere.find((h) => h.act === "ESCALATE" && h.id && h.ref === (ref ?? null) && h.goal === (goal ?? null) && !settled(h.id));
573
+ if (first?.id) {
574
+ askedAgainOnce.add(key);
575
+ const said = (first.said ?? "").replace(/\s+/g, " ").trim();
576
+ return fail(`pantheon: not sent — this run already asked your human about this (${first.id}): "${said.length > 200 ? `${said.slice(0, 199)}…` : said}". ` +
577
+ `They have not answered yet, and a second question about the same thing puts two near-identical decisions in front of them. ` +
578
+ `The same question in other words: send nothing, and finish. Something to add to it: pantheon_send NOTE with ref ${first.id}. ` +
579
+ `A genuinely different decision: send this ESCALATE again and it goes through.\n (ALREADY_ESCALATED)`);
580
+ }
581
+ }
567
582
  const baseSha = act === "DELIVERED" ? (base ?? process.env.PANTHEON_BASE) : undefined;
568
583
  const named = act === "HUMAN_REQUIRED" && named_by_requester === true;
569
584
  const meta = branch || commit || remote || baseSha || decision_domains?.length || named
@@ -660,7 +675,7 @@ A goal for it (${left}) may be open with nothing in it — close it with pantheo
660
675
  if (act === "ASK")
661
676
  askedHere.add(r.id);
662
677
  if (act === "ESCALATE" || act === "HUMAN_REQUIRED")
663
- handedHere.push({ goal: goal ?? null, ref: ref ?? null });
678
+ handedHere.push({ goal: goal ?? null, ref: ref ?? null, act, id: r.id, said: summary ?? body });
664
679
  return text(`sent ${act} — id=${r.id} seq=${r.seq}${thread}${pickup}${survived}${unrecorded}${linkNote ? `\n\nnote: ${linkNote}` : ""}${afterSendLine(act, (opened !== null && question === true) || isQuestionGoal(asSeen(client.goals.get(goal ?? "") ?? {})), role === "worker" ? { owesMore: stillOwed().length > 0 } : undefined)}`);
665
680
  }));
666
681
  server.registerTool("pantheon_open_goal", {
package/dist/pickup.js CHANGED
@@ -106,6 +106,7 @@ export function pickupEstimate(peer, o = {}) {
106
106
  export function awaitingDecision(list, o) {
107
107
  const human = `human:${o.owner}`;
108
108
  return list.some((x) => x.kind === "HUMAN" && x.owner === human &&
109
- (x.about ? !!o.ref && x.about === o.ref : !!o.goal && x.goal === o.goal && (x.created_at ?? 0) >= (o.created_at ?? 0)));
109
+ (x.about ? !!o.ref && x.about === o.ref
110
+ : !!o.goal && x.goal === o.goal && (x.created_at ?? 0) >= (o.created_at ?? 0) && !!x.body?.startsWith(`${o.owner} escalated: `)));
110
111
  }
111
112
  //# sourceMappingURL=pickup.js.map
package/dist/protocol.js CHANGED
@@ -55,6 +55,7 @@ export const LIMITS = {
55
55
  cursorTtlMs: 7 * 24 * 60 * 60 * 1_000,
56
56
  watchPollMs: 2_000,
57
57
  ledgerKeepRecent: 5_000,
58
+ ledgerKeepPresence: 1_000,
58
59
  ledgerCompactEveryMs: 10 * 60 * 1_000,
59
60
  activityFreshMs: 5 * 60 * 1_000,
60
61
  accountFreshMs: 10 * 60 * 1_000,
package/dist/relay.js CHANGED
@@ -14,6 +14,7 @@ import { fingerprint, newNonce, verifyChallenge, verifyActivity, verifyAccount,
14
14
  import { ADMIN_SESSION_MS, Accounts, normalizeEmail, normalizeUsername, validEmail, validUsername, VIEWER_DEFAULT_DAYS, VIEWER_MAX_DAYS, VIEWER_SESSION_MAX_MS } from "./accounts.js";
15
15
  import { renderViewerBusy, renderViewerUnreadable, renderViewerEnded, renderViewerGoal, renderViewerHome, renderViewerNeedsHttps, renderViewerSignin, renderViewerTeam } from "./viewer-pages.js";
16
16
  import { emailSenderFromEnv, maskEmail } from "./email.js";
17
+ import { viewerCodeEmailText, viewerCodeSubject, viewerInviteEmailText, viewerInviteSubject } from "./email-templates.js";
17
18
  import { Allowlist, RosterUnreadable } from "./roster-file.js";
18
19
  import { StateStore, ensurePrivateDir, setWaitForDisk, takeSlowestDiskWait, waitsForDisk } from "./store.js";
19
20
  import { countGoal, countMessage, emptyUsage, parseUsage, usageAnswer, USAGE_KEEP_DAYS, USAGE_SHOW_DAYS } from "./usage.js";
@@ -133,6 +134,30 @@ function forwardedProto(req) {
133
134
  const trusted = Math.max(1, Number(process.env.PANTHEON_TRUSTED_HOPS ?? 1) || 1);
134
135
  return hops.length ? hops[Math.max(0, hops.length - trusted)] : "";
135
136
  }
137
+ function requestOrigin(req) {
138
+ const host = String(req.headers.host ?? "").trim().toLowerCase();
139
+ if (!/^[a-z0-9.-]+(?::\d{1,5})?$|^\[[0-9a-f:]+\](?::\d{1,5})?$/.test(host))
140
+ return null;
141
+ const tls = forwardedProto(req) === "https" || !!req.socket.encrypted;
142
+ return `${tls ? "https" : "http"}://${host}`;
143
+ }
144
+ export function publicBase(operatorOrigin, env = process.env.PANTHEON_PUBLIC_URL) {
145
+ for (const pick of [env?.trim(), operatorOrigin]) {
146
+ if (!pick)
147
+ continue;
148
+ try {
149
+ const u = new URL(pick);
150
+ if (u.protocol !== "https:" && u.protocol !== "http:")
151
+ continue;
152
+ const h = u.hostname.replace(/^\[|\]$/g, "");
153
+ if (h === "0.0.0.0" || h === "::" || h === "")
154
+ continue;
155
+ return u.origin;
156
+ }
157
+ catch { }
158
+ }
159
+ return null;
160
+ }
136
161
  function secretEq(a, b) {
137
162
  const x = createHash("sha256").update(a).digest(), y = createHash("sha256").update(b).digest();
138
163
  return timingSafeEqualBuf(x, y);
@@ -190,16 +215,53 @@ const COLD_MAX = 2;
190
215
  const VIEW_INFLIGHT_PER_SESSION = 2;
191
216
  const SLEEPING_REPLAY_MAX = 2_000;
192
217
  const maxOrNull = (a, b) => (a === null ? b : b === null ? a : Math.max(a, b));
193
- function compactedFromGaps(records) {
218
+ function settledBlocked(g, obligations) {
219
+ if (g.state !== "BLOCKED")
220
+ return false;
221
+ for (const o of obligations.values())
222
+ if (o.kind === "HUMAN" && o.goal === g.id)
223
+ return false;
224
+ return true;
225
+ }
226
+ function unblocks(g, obligations, actInGoal = false) {
227
+ return settledBlocked(g, obligations) && (g.acts < g.budget || actInGoal);
228
+ }
229
+ function healBlocked(goals, obligations, stall) {
230
+ const reopened = [], stalled = [];
231
+ for (const g of goals.values()) {
232
+ if (!settledBlocked(g, obligations))
233
+ continue;
234
+ if (g.acts < g.budget) {
235
+ g.state = "OPEN";
236
+ reopened.push(g);
237
+ }
238
+ else if (stall?.(g))
239
+ stalled.push(g);
240
+ }
241
+ return { reopened, stalled };
242
+ }
243
+ function compactedFromGaps(records, after = 0) {
194
244
  let through = null;
195
245
  let prev = 0;
196
246
  for (const r of records) {
197
- if (r.seq > prev + 1 && (through === null || r.ts > through))
247
+ if (r.seq > prev + 1 && r.seq - 1 > after && (through === null || r.ts > through))
198
248
  through = r.ts;
199
249
  prev = r.seq;
200
250
  }
201
251
  return through;
202
252
  }
253
+ function compactedMark(stored, checked, records) {
254
+ let after = 0;
255
+ if (checked) {
256
+ let n = 0;
257
+ for (const r of records)
258
+ if (r.seq <= checked.seq)
259
+ n++;
260
+ if (n >= checked.kept)
261
+ after = checked.seq;
262
+ }
263
+ return maxOrNull(stored, compactedFromGaps(records, after));
264
+ }
203
265
  class UnboundTeam extends Error {
204
266
  team;
205
267
  constructor(team) {
@@ -1100,7 +1162,7 @@ export class Relay {
1100
1162
  if (url.pathname === "/admin/action" && req.method === "POST") {
1101
1163
  if (!authed)
1102
1164
  return this.json(res, 403, { error: "sign in at /admin" });
1103
- return this.readForm(req, res, (body) => this.adminAction(res, A0, body, ip, csrf));
1165
+ return this.readForm(req, res, (body) => this.adminAction(res, A0, body, ip, csrf, requestOrigin(req)));
1104
1166
  }
1105
1167
  if (url.pathname === "/admin/message") {
1106
1168
  if (req.method !== "POST") {
@@ -1870,7 +1932,7 @@ export class Relay {
1870
1932
  }
1871
1933
  return team.name;
1872
1934
  }
1873
- adminAction(res, A, body, ip, csrf) {
1935
+ adminAction(res, A, body, ip, csrf, origin = null) {
1874
1936
  if (!secretEq(body.csrf ?? "", csrf))
1875
1937
  return this.json(res, 403, { error: "stale form — reload the dashboard and try again" });
1876
1938
  const act = body.action ?? "", id = (body.id ?? "").trim();
@@ -2072,12 +2134,12 @@ export class Relay {
2072
2134
  const until = new Date(g.expires_at).toUTCString().slice(5, 16);
2073
2135
  A.audit({ event: "viewer_granted", space: ts.name, target: email, detail: `${days} days, until ${new Date(g.expires_at).toISOString().slice(0, 10)}, by the operator`, ip });
2074
2136
  this.noteViewerChange(ts.name, `${email} can now see this team's hand-offs, read-only (who asked whom, when, and what waits on whom; no message text, code or files). Given by the relay's operator, until ${until}.`, { email, state: "granted", until: g.expires_at });
2075
- if (this.email.sendNotice)
2076
- void this.email.sendNotice(email, `You can now see how the team "${ts.name}" works on Pantheon`, `The operator of the Pantheon relay ${this.opts.host ?? ""} gave you read-only access to the team "${ts.name}" until ${until}.
2077
-
2078
- You can see who handed work to whom, who picked it up and how long it took. Message text, code and files stay with the team. The team was told.
2079
-
2080
- Sign in with a code sent to this address at /view on the relay.`).catch(() => false);
2137
+ const base = publicBase(origin);
2138
+ const invite = { team: ts.name, until, viewUrl: base ? `${base}/view` : null, relayName: base ? new URL(base).host : null };
2139
+ if (this.email.sendViewerInvite)
2140
+ void this.email.sendViewerInvite(email, invite).catch(() => false);
2141
+ else if (this.email.sendNotice)
2142
+ void this.email.sendNotice(email, viewerInviteSubject(ts.name), viewerInviteEmailText(invite)).catch(() => false);
2081
2143
  this.log(`[admin] viewer ${email} granted on ${ts.name} for ${days}d from ${ip}`);
2082
2144
  return back(`${email} can see ${ts.name} until ${until}; the team was told`);
2083
2145
  }
@@ -3176,10 +3238,11 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3176
3238
  const started = A.startViewerCode(email, nonce);
3177
3239
  if (!started.ok)
3178
3240
  return;
3179
- const text = `Your code to see your team's work on Pantheon (read-only) is ${started.code}. It works for 10 minutes, in the browser that asked for it.\n\nIf you did not ask for it, ignore this email. Nobody can sign in without the code.`;
3180
- const sent = this.email.sendNotice
3181
- ? await this.email.sendNotice(email, `Your Pantheon team view code: ${started.code}`, text)
3182
- : await this.email.sendCode(email, started.code, "login");
3241
+ const sent = this.email.sendViewerCode
3242
+ ? await this.email.sendViewerCode(email, started.code)
3243
+ : this.email.sendNotice
3244
+ ? await this.email.sendNotice(email, viewerCodeSubject(started.code), viewerCodeEmailText(started.code))
3245
+ : await this.email.sendCode(email, started.code, "login");
3183
3246
  if (sent)
3184
3247
  this.noteEmailSent("login", email, ip, `viewer:${nonce}`, false);
3185
3248
  A.audit({ event: "viewer_code_sent", target: email, ip });
@@ -3212,7 +3275,7 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3212
3275
  }
3213
3276
  liveTeamState(sp) {
3214
3277
  const rec = sp.ledger.all();
3215
- return { name: sp.name, safe: safeName(sp.name), sp, records: rec, goals: sp.goals, obligations: sp.obligations, firstClaims: sp.store.firstClaims, usage: sp.store.usage, refusals: sp.store.refusals, allow: sp.allow, compactedThrough: maxOrNull(sp.store.compactedThrough, compactedFromGaps(rec)), stateNote: null };
3278
+ return { name: sp.name, safe: safeName(sp.name), sp, records: rec, goals: sp.goals, obligations: sp.obligations, firstClaims: sp.store.firstClaims, usage: sp.store.usage, refusals: sp.store.refusals, allow: sp.allow, compactedThrough: compactedMark(sp.store.compactedThrough, sp.store.gapsChecked, rec), stateNote: null };
3216
3279
  }
3217
3280
  sleepingOnDisk(name, safe) {
3218
3281
  if (this.leftoverState(safe).state === "covered")
@@ -3262,7 +3325,7 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3262
3325
  const woken = this.sleepingAsWoken(teamName, records, allow, loaded, savedAt, index);
3263
3326
  const out = {
3264
3327
  name: teamName, safe, sp: null, goals: woken.goals, obligations: woken.obligations, firstClaims: st.firstClaims, usage: st.usage, refusals: st.refusals, allow,
3265
- compactedThrough: maxOrNull(st.compactedThrough, compactedFromGaps(records)),
3328
+ compactedThrough: compactedMark(st.compactedThrough, st.gapsChecked, records),
3266
3329
  stateNote: woken.note,
3267
3330
  };
3268
3331
  this.sleepStates.set(safe, { sig, st: out });
@@ -3292,6 +3355,7 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3292
3355
  worker: w ? { state: w.state, ...(w.reason ? { reason: w.reason } : {}), at: w.at } : null,
3293
3356
  build, behind: !!build && stuckBehind(build, relayPkg, now - this.startedAt),
3294
3357
  lastSeen: present.length ? now : (m?.last_seen || e.last_seen || null), unseen,
3358
+ reportsSince: ts.sp ? ts.sp.createdAt : null,
3295
3359
  };
3296
3360
  });
3297
3361
  }
@@ -5854,6 +5918,38 @@ pantheon start</code></pre>
5854
5918
  default:
5855
5919
  break;
5856
5920
  }
5921
+ if ((rec.act === "ANSWER" || rec.act === "RETRACT") && rec.ref) {
5922
+ const settled = sp.ledger.find(rec.ref)?.goal ?? null;
5923
+ for (const id of new Set([rec.goal, settled])) {
5924
+ const g = id ? sp.goals.get(id) : undefined;
5925
+ if (!g)
5926
+ continue;
5927
+ if (unblocks(g, sp.obligations, g.id === rec.goal || !!ctx)) {
5928
+ g.state = "OPEN";
5929
+ this.broadcast(sp, { t: "goal", goal: g });
5930
+ }
5931
+ else if (settledBlocked(g, sp.obligations))
5932
+ this.stallSpent(sp, g);
5933
+ }
5934
+ }
5935
+ }
5936
+ stallSpent(sp, g) {
5937
+ let ref;
5938
+ const all = sp.ledger.all();
5939
+ for (let i = all.length - 1; i >= 0; i--) {
5940
+ const r = all[i];
5941
+ if (r.goal === g.id && r.act !== "ESCALATE" && r.act !== "HUMAN_REQUIRED") {
5942
+ ref = r;
5943
+ break;
5944
+ }
5945
+ }
5946
+ if (!ref)
5947
+ return false;
5948
+ g.state = "STALLED";
5949
+ this.oblige(sp, { kind: "HUMAN", owner: `human:${g.opened_by}`, ref: ref.id, goal: g.id,
5950
+ body: `"${g.title}" spent its act budget without closing` });
5951
+ this.broadcast(sp, { t: "goal", goal: g });
5952
+ return true;
5857
5953
  }
5858
5954
  oblige(sp, o) {
5859
5955
  const id = newId("o");
@@ -6111,6 +6207,21 @@ pantheon start</code></pre>
6111
6207
  this.noteStorageFailure(`[${name}] replayed snapshot`, e);
6112
6208
  }
6113
6209
  }
6210
+ {
6211
+ const { reopened, stalled } = healBlocked(sp.goals, sp.obligations, (g) => this.stallSpent(sp, g));
6212
+ if (reopened.length)
6213
+ this.log(`[${name}] ${reopened.length} goal(s) were still marked blocked with no decision waiting in them — open again: ${reopened.map((g) => g.id).join(", ")}`);
6214
+ if (stalled.length)
6215
+ this.log(`[${name}] ${stalled.length} goal(s) were still marked blocked with no decision waiting and no acts left — stalled, their opener asked: ${stalled.map((g) => g.id).join(", ")}`);
6216
+ if (reopened.length || stalled.length) {
6217
+ try {
6218
+ store.flush(sp.goals, sp.obligations, sp.profiles);
6219
+ }
6220
+ catch (e) {
6221
+ this.noteStorageFailure(`[${name}] reopened goals`, e);
6222
+ }
6223
+ }
6224
+ }
6114
6225
  this.spaces.set(spaceKey(name), sp);
6115
6226
  try {
6116
6227
  allow.recordName(name);
@@ -6190,10 +6301,13 @@ pantheon start</code></pre>
6190
6301
  if (loaded.unclean || ahead) {
6191
6302
  return { goals: loaded.unclean ? new Map() : loaded.goals, obligations: new Map(), note: { kind: "rebuild" } };
6192
6303
  }
6193
- if (loaded.rebuilt || !behind)
6304
+ if (loaded.rebuilt || !behind) {
6305
+ healBlocked(loaded.goals, loaded.obligations);
6194
6306
  return { goals: loaded.goals, obligations: loaded.obligations, note: null };
6307
+ }
6195
6308
  const missed = head - loaded.ledgerHead;
6196
6309
  if (missed > SLEEPING_REPLAY_MAX) {
6310
+ healBlocked(loaded.goals, loaded.obligations);
6197
6311
  return { goals: loaded.goals, obligations: loaded.obligations, note: { kind: "stale", asOf: savedAt ?? 0, behind: missed } };
6198
6312
  }
6199
6313
  const byId = index(records);
@@ -6204,6 +6318,7 @@ pantheon start</code></pre>
6204
6318
  lastActor: new Map(), contLocks: new Map(), createdAt: 0, lastTouch: 0,
6205
6319
  };
6206
6320
  this.replayMissed(sp, loaded.ledgerHead);
6321
+ healBlocked(sp.goals, sp.obligations);
6207
6322
  return { goals: sp.goals, obligations: sp.obligations, note: null };
6208
6323
  }
6209
6324
  rebuildFromLedger(sp) {
@@ -6288,9 +6403,15 @@ pantheon start</code></pre>
6288
6403
  };
6289
6404
  const referenced = new Set([...sp.obligations.values()].map((o) => o.ref));
6290
6405
  const before = sp.ledger.all().map((r) => r.id);
6291
- const { dropped, kept, newestDropped } = sp.ledger.compact({ keepRecent: this.opts.ledgerKeepRecent ?? LIMITS.ledgerKeepRecent, isLive, keep: (id) => referenced.has(id) });
6406
+ const fromGaps = compactedMark(null, sp.store.gapsChecked, sp.ledger.all());
6407
+ const { dropped, kept, newestDropped } = sp.ledger.compact({
6408
+ keepRecent: this.opts.ledgerKeepRecent ?? LIMITS.ledgerKeepRecent, isLive, keep: (id) => referenced.has(id),
6409
+ presence: { is: (r) => r.act === "JOIN" || r.act === "LEAVE", keepRecent: this.opts.ledgerKeepPresence ?? LIMITS.ledgerKeepPresence },
6410
+ });
6292
6411
  if (dropped) {
6412
+ sp.store.noteCompacted(fromGaps);
6293
6413
  sp.store.noteCompacted(newestDropped);
6414
+ sp.store.gapsChecked = { seq: sp.ledger.head, kept: sp.ledger.size };
6294
6415
  try {
6295
6416
  sp.store.flush(sp.goals, sp.obligations, sp.profiles);
6296
6417
  }
@@ -6307,7 +6428,7 @@ pantheon start</code></pre>
6307
6428
  d.set(id, now);
6308
6429
  }
6309
6430
  if (dropped)
6310
- this.log(`[${sp.name}] compacted ledger — dropped ${dropped} old act(s) from closed goals, ${kept} kept`);
6431
+ this.log(`[${sp.name}] compacted ledger — dropped ${dropped} old act(s) (closed goals' and arrivals/departures), ${kept} kept`);
6311
6432
  }
6312
6433
  attach(sp, id, display, agent, session, role, ws, pkg, quiet = false) {
6313
6434
  let m = sp.members.get(id);
package/dist/store.js CHANGED
@@ -106,6 +106,7 @@ export class StateStore {
106
106
  if (ts !== null && Number.isFinite(ts) && (this.compactedThrough === null || ts > this.compactedThrough))
107
107
  this.compactedThrough = ts;
108
108
  }
109
+ gapsChecked = null;
109
110
  firstClaims = new Map();
110
111
  noteFirstClaim(c) {
111
112
  if (this.firstClaims.has(c.ob))
@@ -192,8 +193,10 @@ export class StateStore {
192
193
  }
193
194
  for (const p of snap.profiles ?? [])
194
195
  profiles.set(p.member, p);
195
- const known = new Set(["v", "goals", "obligations", "profiles", "refusals", "ledger_head", "rebuilt", "first_claims", "compacted_through", "saved_at"]);
196
+ const known = new Set(["v", "goals", "obligations", "profiles", "refusals", "ledger_head", "rebuilt", "first_claims", "compacted_through", "gaps_checked", "saved_at"]);
196
197
  this.compactedThrough = typeof snap.compacted_through === "number" && Number.isFinite(snap.compacted_through) ? snap.compacted_through : null;
198
+ const gc = snap.gaps_checked;
199
+ this.gapsChecked = gc && typeof gc === "object" && Number.isSafeInteger(gc.seq) && Number.isSafeInteger(gc.kept) && gc.seq >= 0 && gc.kept >= 0 ? { seq: gc.seq, kept: gc.kept } : null;
197
200
  this.firstClaims = new Map();
198
201
  if (Array.isArray(snap.first_claims)) {
199
202
  for (const c of snap.first_claims) {
@@ -259,6 +262,7 @@ export class StateStore {
259
262
  ...(this.rebuilt ? { rebuilt: this.rebuilt } : {}),
260
263
  ...(this.firstClaims.size ? { first_claims: this.keptFirstClaims() } : {}),
261
264
  ...(this.compactedThrough !== null ? { compacted_through: this.compactedThrough } : {}),
265
+ ...(this.gapsChecked ? { gaps_checked: this.gapsChecked } : {}),
262
266
  saved_at: Date.now(),
263
267
  };
264
268
  writerFor(this.dir, this.stem).replace(this.file, JSON.stringify(snap, null, 2) + "\n");
@@ -1,4 +1,5 @@
1
- import { MARK, SEAL, cap, esc, head, pct, plural, rangeSeg, rangeWords, script, secbar, split, stackedColumns, when } from "./admin-ui.js";
1
+ import { MARK, SEAL, cap, esc, head, pct, plural, rangeSeg, rangeWords, script, secbar, when } from "./admin-ui.js";
2
+ import { carriedSection, handoffsRow } from "./flow-visuals.js";
2
3
  import { asOfHtml, signinShell, stateNoteHtml } from "./admin-pages.js";
3
4
  import { dur } from "./flow-stats.js";
4
5
  import { GOAL_CSS, goalDiagram, goalSummary } from "./goal-flow.js";
@@ -86,30 +87,7 @@ export function renderViewerUnreadable(o) {
86
87
  export function renderViewerTeam(d) {
87
88
  const f = d.flow, range = rangeWords(d.days);
88
89
  const people = f.members.length;
89
- const max = Math.max(1, ...Object.values(f.matrix.n).flatMap((r) => Object.values(r)));
90
- const cell = (n, from, to) => {
91
- if (!n)
92
- return `<td class="z" aria-label="${esc(cap(from))} asked ${esc(cap(to))}: none">·</td>`;
93
- const a = 0.18 + 0.82 * (n / max);
94
- return `<td class="h" tabindex="0" data-tip="${plural(n, "ask")}|${esc(cap(from))} asked ${esc(cap(to))}" aria-label="${esc(cap(from))} asked ${esc(cap(to))}: ${n}" style="--a:${a.toFixed(2)}">${n}</td>`;
95
- };
96
- let top = null, ties = 0;
97
- for (const [from, row] of Object.entries(f.matrix.n))
98
- for (const [to, n] of Object.entries(row)) {
99
- if (!top || n > top.n) {
100
- top = { from, to, n };
101
- ties = 0;
102
- }
103
- else if (n === top.n)
104
- ties++;
105
- }
106
- const matrix = f.matrix.from.length ? `<table class="matrix" aria-label="Who asked whom, ${range}">
107
- <thead><tr><th></th>${f.matrix.to.map((p) => `<th scope="col">${esc(cap(p))}</th>`).join("")}</tr></thead>
108
- <tbody>${f.matrix.from.map((from) => `<tr><th scope="row" class="rowh">${esc(cap(from))}</th>${f.matrix.to.map((to) => from === to ? `<td class="self" aria-hidden="true"></td>` : cell(f.matrix.n[from]?.[to] ?? 0, from, to)).join("")}</tr>`).join("")}</tbody>
109
- </table>` : `<p class="muted" style="margin:0">Nobody asked anyone ${range}.</p>`;
110
90
  const waiting = f.waiting.map((w) => `<li><div class="t"><b>${esc(cap(w.owner))}</b> to decide${w.from && w.from !== w.owner ? `, asked by ${esc(cap(w.from))}'s agent` : ", escalated by their own agent"} <span class="num">${dur(w.ageMs)}</span> ago<span class="sub">${w.goalTitle ? `in ${esc(w.goalTitle)}` : "not in a goal"}${w.blocksGoal ? " · the goal is blocked until they answer" : ""}</span></div></li>`).join("");
111
- const pron = (who) => cap(who);
112
- const carriedRows = f.carried.map((c) => `<tr><td class="span"><b class="who">${esc(cap(c.who))}</b><span class="sub">${esc(c.agent)}</span></td><td data-l="Asked" class="r num">${c.asked}</td><td data-l="Answered by" class="span">${split(c.byWorker, c.byPerson, c.asked, 140)}<span class="sub num">${c.byWorker} by their worker · ${c.byPerson} by ${esc(pron(c.who))} in person</span></td><td data-l="Median time to answer" class="r num">${c.medianMs !== null ? dur(c.medianMs) : `<span class="quiet">none yet</span>`}</td><td data-l="Open now" class="r num">${c.open || `<span class="quiet">0</span>`}</td></tr>`).join("");
113
91
  const goalRows = f.goals.filter((g) => g.state !== "CLOSED").map((g) => `<tr><td class="span"><b>${esc(g.title)}</b>${g.worklist ? ` <span class="chip plain">worklist</span>` : ""}${g.why ? `<span class="sub">${g.state === "BLOCKED" ? "blocked " : ""}${esc(g.why)}</span>` : ""}<a class="more seeflow" href="/view/goal?name=${encodeURIComponent(d.team)}&amp;id=${esc(encodeURIComponent(g.id))}">See how it moved</a></td><td data-l="State">${g.state === "OPEN" ? `<span class="chip">open</span>` : g.state === "STALLED" ? `<span class="chip line">${SEAL} out of acts</span>` : `<span class="chip line">${SEAL} blocked</span>`}</td><td data-l="Deadline">${g.deadline ? `${when(g.deadline, "full")}${g.overdueMs !== null ? ` <span class="chip line">overdue</span>` : ""}` : `<span class="quiet">none</span>`}</td><td data-l="Open items" class="r num">${g.open || `<span class="quiet">0</span>`}</td></tr>`).join("");
114
92
  const openGoals = f.goals.filter((g) => g.state !== "CLOSED").length;
115
93
  return shell({
@@ -150,25 +128,9 @@ export function renderViewerTeam(d) {
150
128
 
151
129
  ${stateNoteHtml(d.stateNote, true)}
152
130
  ${f.historyFrom ? `<p class="note">Partial: counts start ${when(f.historyFrom, "full")}. Older history in this range was compacted on the relay, so asks, answers and hand-offs before then are not counted.</p>` : ""}
153
- <div class="grid2 even sec" id="handoffs">
154
- <section class="card pad" aria-labelledby="h-who">
155
- <div class="sechead" style="margin-bottom:10px"><h2 id="h-who">Who asked whom</h2><p>rows asked, columns were asked</p></div>
156
- <div class="scroll">${matrix}</div>
157
- ${top ? `<p class="note">Stronger teal means more asks. ${ties ? `The most from one person to another ${range} is ${plural(top.n, "request")}, shared by ${ties + 1} pairs (${esc(cap(top.from))} to ${esc(cap(top.to))} is one).` : `${esc(cap(top.from))} handed ${plural(top.n, "request")} to ${esc(cap(top.to))} ${range}, the most of any pair.`}</p>` : ""}
158
- </section>
159
- <section class="card pad" aria-labelledby="h-daily">
160
- <div class="sechead" style="margin-bottom:4px"><h2 id="h-daily">Messages per day</h2><p>the last 14 UTC days</p></div>
161
- ${stackedColumns({ days: d.series14, width: 620, height: 190, step: 3, label: `Messages per day for 14 days. ${f.messages.total} ${range}, ${f.messages.worker} by workers.` })}
162
- </section>
163
- </div>
131
+ ${handoffsRow(f, d.series14, range)}
164
132
 
165
- <section class="sec" id="carried" aria-labelledby="h-carry">
166
- <div class="sechead"><h2 id="h-carry">Who carried the work</h2><p>requests each person was asked, and whether their worker or they answered</p></div>
167
- <div class="card"><table class="rt">
168
- <thead><tr><th>Asked of</th><th class="r">Asked</th><th>Answered by</th><th class="r">Median time to answer</th><th class="r">Open now</th></tr></thead>
169
- <tbody>${carriedRows || `<tr><td colspan="5" class="empty">Nobody was asked anything ${range}.</td></tr>`}</tbody>
170
- </table></div>
171
- </section>
133
+ ${carriedSection(f, range)}
172
134
 
173
135
  <section class="sec" id="goals" aria-labelledby="h-goals">
174
136
  <div class="sechead"><h2 id="h-goals">Goals in progress</h2><p>${openGoals} open · "See how it moved" draws who handed what to whom</p></div>