paseo-follow-up 1.4.0-beta.32 → 1.4.0-beta.33

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/README.md CHANGED
@@ -238,7 +238,7 @@ This replaces the separate **Wait** plugin (`paseo-wait`). While that plugin is
238
238
  Install the beta:
239
239
 
240
240
  ```sh
241
- paseo plugin update follow-through --version 1.4.0-beta.32
241
+ paseo plugin update follow-through --version 1.4.0-beta.33
242
242
  # or, for a fresh install:
243
243
  paseo plugin install npm:paseo-follow-up@beta
244
244
  ```
@@ -293,7 +293,7 @@ npm run test:install
293
293
  paseo plugin reload follow-through # after changes
294
294
  ```
295
295
 
296
- Integration checks use a separate Paseo home with synthetic agents.
296
+ Integration checks use a separate Paseo home with synthetic agents. Working on Follow-up with an agent? Start at [AGENTS.md](AGENTS.md): the architecture map, a file index per subsystem, the invariants, and the docs in [docs/](docs/).
297
297
 
298
298
  Release notes: a PR that changes something users see adds `changes/<branch>.md` with one to three plain-language bullets ([rules](changes/README.md)). Before a stable version bump, `npm run release:notes <version>` moves them into CHANGELOG.md (`-- --allow-empty` for a release with nothing user-facing). For a beta it writes nothing and the fragments wait for the next stable release. `npm run verify` fails if a stable package version has no notes.
299
299
 
package/index.server.ts CHANGED
@@ -59,6 +59,7 @@ import { inboxAnswer } from "./server/etag";
59
59
  import { AiJobs } from "./server/ai-jobs";
60
60
  import { liveRankSources, planningUrl, Ranker, RANKER_ROLE_DEFAULT } from "./server/ranker";
61
61
  import { AboutService, AboutStore, liveSources, rootHistory, type AboutContext } from "./server/about";
62
+ import { LinkedService, LinkedStore, liveLinkedSources } from "./server/linked";
62
63
  import { readTranscript } from "./server/transcript";
63
64
  import { AgentSettingsStore, ProviderCatalog, type CatalogSource } from "./server/agent-settings";
64
65
  import { labelsFor, providerName, resolveRole, roleSummary, type AgentSettingsView } from "./shared/agent-settings";
@@ -875,9 +876,10 @@ export default function contribute(server: PluginServerContext) {
875
876
  },
876
877
  };
877
878
  };
879
+ const aboutStore = new AboutStore(directory);
878
880
  const about = new AboutService({
879
881
  role: () => agentSettings.role("about"),
880
- store: new AboutStore(directory), jobs: aiJobs, sources: liveSources(),
882
+ store: aboutStore, jobs: aiJobs, sources: liveSources(),
881
883
  workspace: async id => (await store.snapshot()).workspaces.find(w => w.id === id && w.enable_tracking && !w.archived) ?? null,
882
884
  context: aboutContext, usage: () => usage.read(),
883
885
  firstMessage: async agentId => { await historyCache.load(); return historyCache.get(agentId)?.history.goal ?? null; }, roomForBackground: async () => governor.allowsBackground(), roomOnDemand: async () => governor.allowsExtras(),
@@ -898,6 +900,18 @@ export default function contribute(server: PluginServerContext) {
898
900
  if (!stopped) aboutTimer = setTimeout(() => void aboutLoop(), 10 * 60_000);
899
901
  };
900
902
  aboutTimer = setTimeout(() => void aboutLoop(), 60_000);
903
+ // Linked items (shared/linked.ts): carry over verified About links once, then drain the Linear check queue on the
904
+ // same 10-minute cadence. An empty queue (the steady state) costs one small file read and no MCP call.
905
+ const linked = new LinkedService({ store: new LinkedStore(directory), sources: liveLinkedSources(), roomForBackground: async () => governor.allowsBackground() });
906
+ let linkedTimer: ReturnType<typeof setTimeout> | null = null;
907
+ const linkedLoop = async () => {
908
+ await ready;
909
+ if (stopped || loadError) return;
910
+ await linked.migrate(async () => (await aboutStore.read()).entries).catch(() => undefined);
911
+ await linked.drain().catch(() => undefined);
912
+ if (!stopped) linkedTimer = setTimeout(() => void linkedLoop(), 10 * 60_000);
913
+ };
914
+ linkedTimer = setTimeout(() => void linkedLoop(), 90_000);
901
915
  // Developer RPCs as agent tools (server/agent-parity.ts): the same handler the button's RPC runs.
902
916
  const rpcBridge = {
903
917
  async validate(method: string, input: unknown) { const h = handlers.get(method); if (!h) throw new Error(`Unknown Follow-up method ${method}.`); return h.input.parseAsync(input); },
@@ -1158,7 +1172,7 @@ export default function contribute(server: PluginServerContext) {
1158
1172
  server.on("workspace.archived", async event => { await ready; if (!loadError && !stopped) await store.mutate(state => { const w = state.workspaces.find(w => w.id === event.workspace.id); if (w) w.archived = true; }); }),
1159
1173
  ];
1160
1174
  return async () => {
1161
- stopped = true; wait.close(); updater.stop(); governor.stop(); if (timer) clearTimeout(timer); if (aboutTimer) clearTimeout(aboutTimer); aiJobs.stop(); ranker = null; if (inboxTimer) clearTimeout(inboxTimer); inbox.stop(); if (hookTimer) clearInterval(hookTimer); removers.forEach(remove => remove());
1175
+ stopped = true; wait.close(); updater.stop(); governor.stop(); if (timer) clearTimeout(timer); if (aboutTimer) clearTimeout(aboutTimer); if (linkedTimer) clearTimeout(linkedTimer); aiJobs.stop(); ranker = null; if (inboxTimer) clearTimeout(inboxTimer); inbox.stop(); if (hookTimer) clearInterval(hookTimer); removers.forEach(remove => remove());
1162
1176
  await ready; if (hooksStarted) await agentHooks.stop().catch(() => {});
1163
1177
  await actions.close(); await closeConnections(); await engine.stop(); await ready; await store.flush().catch(() => undefined); await unlock?.();
1164
1178
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "paseo-follow-up",
3
3
  "private": false,
4
- "version": "1.4.0-beta.32",
4
+ "version": "1.4.0-beta.33",
5
5
  "description": "Follow every workspace PR stack in Paseo, answer agent questions, batch repairs for the main agent, and see what needs you.",
6
6
  "type": "module",
7
7
  "files": [
@@ -0,0 +1,120 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { liveSources, mcpproxyText } from "./about";
7
+ import { TEAMS_TTL_MS, applyCheck, setTeams, dueChecks, emptyLinkedFile, linkedFileSchema, migrateAboutLinks, takeBudget, type LinearIssueFacts, type LinkedFile } from "../shared/linked";
8
+
9
+ /**
10
+ * linked.json beside state.json (see shared/linked.ts). Read from disk on each use and never held whole in the worker:
11
+ * it is small and read rarely (a panel open, one drain per observe cycle). Writes are serialized and atomic.
12
+ */
13
+ export class LinkedStore {
14
+ private tail: Promise<unknown> = Promise.resolve();
15
+ constructor(private directory: string) {}
16
+ private get path() { return join(this.directory, "linked.json"); }
17
+ async read(): Promise<LinkedFile> {
18
+ try { return linkedFileSchema.parse(JSON.parse(await readFile(this.path, "utf8"))); } catch { return emptyLinkedFile(); }
19
+ }
20
+ mutate<T>(fn: (file: LinkedFile) => T): Promise<T> {
21
+ const next = this.tail.then(async () => {
22
+ const file = await this.read();
23
+ const result = fn(file);
24
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
25
+ const temporary = `${this.path}.${randomUUID()}`;
26
+ await writeFile(temporary, JSON.stringify(file), { mode: 0o600 });
27
+ await rename(temporary, this.path);
28
+ return result;
29
+ });
30
+ this.tail = next.catch(() => undefined);
31
+ return next;
32
+ }
33
+ }
34
+
35
+ /** Daemon-side Linear reads. `issue` returns null for "not found" and throws when Linear couldn't be read. */
36
+ export type LinkedSources = {
37
+ issue(key: string): Promise<LinearIssueFacts | null>;
38
+ teams(): Promise<string[]>;
39
+ };
40
+
41
+ /** `linear:list_teams` text: JSON with team objects carrying `key`, or anything with "key": "HER" pairs. */
42
+ export function parseLinearTeams(text: string): string[] {
43
+ const keys = new Set<string>();
44
+ const visit = (v: unknown) => {
45
+ if (Array.isArray(v)) { v.forEach(visit); return; }
46
+ if (!v || typeof v !== "object") return;
47
+ const k = (v as { key?: unknown }).key;
48
+ if (typeof k === "string" && /^[A-Z][A-Z0-9]{1,9}$/.test(k)) keys.add(k);
49
+ for (const x of Object.values(v)) if (x && typeof x === "object") visit(x);
50
+ };
51
+ try { visit(JSON.parse(text)); } catch { for (const m of text.matchAll(/"key"\s*:\s*"([A-Z][A-Z0-9]{1,9})"/g)) keys.add(m[1]); }
52
+ return [...keys].sort();
53
+ }
54
+
55
+ export type LinkedDeps = {
56
+ store: LinkedStore;
57
+ sources: LinkedSources;
58
+ /** The resource governor's background threshold: no checks while the VM is short of room. */
59
+ roomForBackground?(): Promise<boolean>;
60
+ now?: () => number;
61
+ };
62
+
63
+ /**
64
+ * The Linear check queue. Drained on the observe cadence: nothing to do (the steady state) costs one small file read;
65
+ * otherwise at most LIMITS.checksPerDrain reads, within a daily budget, plus the team list once a day.
66
+ */
67
+ export class LinkedService {
68
+ private draining: Promise<{ checked: number; skipped: string | null }> | null = null;
69
+ constructor(private deps: LinkedDeps) {}
70
+ private now() { return (this.deps.now ?? Date.now)(); }
71
+
72
+ drain(): Promise<{ checked: number; skipped: string | null }> {
73
+ this.draining ??= this.run().finally(() => { this.draining = null; });
74
+ return this.draining;
75
+ }
76
+
77
+ private async run(): Promise<{ checked: number; skipped: string | null }> {
78
+ const file = await this.deps.store.read();
79
+ const pending = Object.values(file.workspaces).some(w => w.candidates.length);
80
+ if (!pending) return { checked: 0, skipped: null };
81
+ if (this.deps.roomForBackground && !await this.deps.roomForBackground().catch(() => true)) return { checked: 0, skipped: "memory" };
82
+ const now = this.now();
83
+ if (!file.teams || now - Date.parse(file.teams.at) > TEAMS_TTL_MS) {
84
+ const keys = await this.deps.sources.teams().catch(() => null);
85
+ // An unreadable team list keeps the old one; without any, candidates wait (they never render meanwhile).
86
+ if (keys?.length) await this.deps.store.mutate(f => setTeams(f, keys, now));
87
+ }
88
+ const due = dueChecks(await this.deps.store.read(), now);
89
+ let checked = 0;
90
+ for (const { key } of due) {
91
+ if (!await this.deps.store.mutate(f => takeBudget(f, this.now()))) return { checked, skipped: "daily-cap" };
92
+ const result = await this.deps.sources.issue(key).then(found => ({ found }), (error: unknown) => ({ error: error instanceof Error ? error.message : String(error) }));
93
+ await this.deps.store.mutate(f => applyCheck(f, key, result, this.now()));
94
+ checked++;
95
+ }
96
+ return { checked, skipped: null };
97
+ }
98
+
99
+ /** One-time carry-over of verified Summary links (shared/linked.ts migrateAboutLinks). */
100
+ migrate(about: () => Promise<Record<string, { links: { kind: string; key: string; url: string | null; title: string | null; state?: string | null }[] }>>): Promise<{ items: number; candidates: number }> {
101
+ return this.deps.store.read().then(async file => {
102
+ if (file.migrations.includes("about-links-1")) return { items: 0, candidates: 0 };
103
+ const entries = await about().catch(() => ({}));
104
+ return this.deps.store.mutate(f => migrateAboutLinks(f, entries, this.now()));
105
+ });
106
+ }
107
+ }
108
+
109
+ const exec = promisify(execFile);
110
+ /** The live reads, through mcpproxy like the Summary: Linear's get_issue and list_teams. */
111
+ export function liveLinkedSources(run: (command: string, args: string[], timeoutMs: number) => Promise<string> = async (c, a, t) => (await exec(c, a, { timeout: t, maxBuffer: 4 * 1024 * 1024 })).stdout): LinkedSources {
112
+ const about = liveSources(run);
113
+ return {
114
+ async issue(key) { const i = await about.linear(key); return i ? { title: i.title, state: i.state, url: i.url } : null; },
115
+ async teams() {
116
+ const out = await run("mcpproxy", ["call", "tool-read", "--tool-name=linear:list_teams", "--json_args={}", "--reason=Follow-up: which Linear keys are real", "--log-level=error", "-o", "json"], 45_000);
117
+ return parseLinearTeams(mcpproxyText(out));
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,282 @@
1
+ import { z } from "zod";
2
+ import { classifyUrl } from "./about";
3
+
4
+ /**
5
+ * Linked items (1.4.0-beta.28): the verified things a workspace's work is about (Linear issues, Slack threads, Claude
6
+ * artifacts, docs, GitHub issues, other links), tracked per workspace like PRs. Kept in linked.json beside state.json,
7
+ * never in state.json's hot path. Pure: identity, dedupe, the cap, exclusions and the Linear check queue are all here.
8
+ *
9
+ * Precision over recall: a Linear key extracted from text is only a *candidate* until Linear confirms it, and only if
10
+ * its team prefix is a known Linear team; candidates never render. A key Linear says doesn't exist is remembered and
11
+ * never checked again. PRs are not linked items (they have their own card).
12
+ */
13
+
14
+ export const LINKED_KINDS = ["linear", "slack", "artifact", "doc", "issue", "link"] as const;
15
+ export type LinkedKind = typeof LINKED_KINDS[number];
16
+ export const LINKED_ORIGINS = ["registered", "manual", "spec", "published", "extracted"] as const;
17
+ export type LinkedOrigin = typeof LINKED_ORIGINS[number];
18
+ /** Who may overwrite whom when the same key arrives again: a later, more trusted origin upgrades the record. */
19
+ const TRUST: Record<LinkedOrigin, number> = { manual: 4, registered: 3, spec: 2, published: 2, extracted: 1 };
20
+ export const STATUS_TONES = ["done", "active", "todo", "cancelled"] as const;
21
+
22
+ export const LIMITS = { items: 50, excluded: 200, candidates: 40, rejected: 2000, checksPerDrain: 6, dailyChecks: 120 } as const;
23
+ /** A candidate whose check failed (Linear unreachable) waits 1h, 6h, then 24h, then is dropped. */
24
+ export const RETRY_MS = [3_600_000, 6 * 3_600_000, 24 * 3_600_000] as const;
25
+ export const TEAMS_TTL_MS = 24 * 3_600_000;
26
+
27
+ const short = (n: number) => z.string().max(n);
28
+ export const linkedItemSchema = z.object({
29
+ key: short(300),
30
+ kind: z.enum(LINKED_KINDS),
31
+ url: short(2000).nullable(),
32
+ title: short(200).nullable(),
33
+ status: short(60).nullable().default(null),
34
+ statusTone: z.enum(STATUS_TONES).nullable().default(null),
35
+ origin: z.enum(LINKED_ORIGINS),
36
+ by: short(120).nullable().default(null),
37
+ why: short(140).nullable().default(null),
38
+ firstSeen: z.string(),
39
+ lastSeen: z.string(),
40
+ checkedAt: z.string().nullable().default(null),
41
+ });
42
+ export type LinkedItem = z.infer<typeof linkedItemSchema>;
43
+ const exclusionSchema = z.object({ key: short(300), at: z.string(), by: short(120), reason: short(200).nullable().default(null) });
44
+ const candidateSchema = z.object({ key: short(40), seen: z.number().int().min(1), firstSeen: z.string(), retryAt: z.string().nullable().default(null), failures: z.number().int().min(0).default(0) });
45
+ export const workspaceLinksSchema = z.object({
46
+ items: z.array(linkedItemSchema).default([]),
47
+ excluded: z.array(exclusionSchema).default([]),
48
+ candidates: z.array(candidateSchema).default([]),
49
+ });
50
+ export type WorkspaceLinks = z.infer<typeof workspaceLinksSchema>;
51
+ export const linkedFileSchema = z.object({
52
+ version: z.literal(1),
53
+ workspaces: z.record(z.string(), workspaceLinksSchema).default({}),
54
+ /** Keys Linear said don't exist, with when: never checked again (oldest dropped past the cap). */
55
+ rejected: z.record(z.string(), z.string()).default({}),
56
+ /** Known Linear team prefixes ("HER"), read at most once a day. Null until read: candidates wait. */
57
+ teams: z.object({ keys: z.array(z.string()), at: z.string() }).nullable().default(null),
58
+ daily: z.object({ date: z.string(), count: z.number().int() }).nullable().default(null),
59
+ migrations: z.array(z.string()).default([]),
60
+ });
61
+ export type LinkedFile = z.infer<typeof linkedFileSchema>;
62
+ export const emptyLinkedFile = (): LinkedFile => ({ version: 1, workspaces: {}, rejected: {}, teams: null, daily: null, migrations: [] });
63
+ export const emptyWorkspaceLinks = (): WorkspaceLinks => ({ items: [], excluded: [], candidates: [] });
64
+
65
+ // ---------- identity ----------
66
+
67
+ const LINEAR_KEY = /^([A-Z][A-Z0-9]{1,9})-(\d{1,6})$/;
68
+ /** "her-1312" → "HER-1312"; null when it isn't key-shaped. */
69
+ export function linearKey(raw: string): string | null {
70
+ const m = LINEAR_KEY.exec(raw.trim().toUpperCase());
71
+ return m && Number(m[2]) > 0 ? `${m[1]}-${Number(m[2])}` : null;
72
+ }
73
+ export const teamOf = (key: string) => key.split("-")[0];
74
+
75
+ export type Classified = { kind: LinkedKind; key: string; url: string | null } | { kind: "pr"; key: string; url: string };
76
+ /**
77
+ * What a pasted or registered reference is. Linear keys and URLs, Slack threads (a reply collapses to its thread),
78
+ * claude.ai artifacts, Google and Notion docs, GitHub issues, a PR (refused by the caller), and, only when `explicit`
79
+ * (an agent or the developer linked it on purpose), any other http(s) URL.
80
+ */
81
+ export function classifyLink(raw: string, explicit = false): Classified | null {
82
+ const text = raw.trim();
83
+ const key = linearKey(text);
84
+ if (key) return { kind: "linear", key, url: null };
85
+ if (!/^https?:\/\//i.test(text)) return null;
86
+ const known = classifyUrl(text);
87
+ if (known?.kind === "pr") return { kind: "pr", key: known.key, url: known.url! };
88
+ if (known) return { kind: known.kind === "linear" ? "linear" : known.kind as LinkedKind, key: known.key, url: known.url };
89
+ let u: URL;
90
+ try { u = new URL(text.replace(/[.,;:!?*]+$/, "")); } catch { return null; }
91
+ const issue = u.hostname.toLowerCase() === "github.com" ? /^\/([\w.-]+)\/([\w.-]+)\/issues\/(\d+)/.exec(u.pathname) : null;
92
+ if (issue) return { kind: "issue", key: `${issue[1]}/${issue[2]}#${Number(issue[3])}`, url: `https://github.com/${issue[1]}/${issue[2]}/issues/${Number(issue[3])}` };
93
+ if (!explicit) return null;
94
+ u.hash = "";
95
+ return { kind: "link", key: u.toString(), url: u.toString() };
96
+ }
97
+
98
+ // ---------- upsert, exclusion, the cap ----------
99
+
100
+ export type ItemInput = Pick<LinkedItem, "key" | "kind" | "url"> & Partial<Pick<LinkedItem, "title" | "status" | "statusTone" | "by" | "why" | "checkedAt">> & { origin: LinkedOrigin };
101
+ export type UpsertResult = { ok: true; item: LinkedItem; created: boolean } | { ok: false; reason: "excluded" | "cap" };
102
+
103
+ /**
104
+ * Adds or refreshes one item. The same key from another origin merges into one record: fields fill in, and a more
105
+ * trusted origin (manual > registered > spec/published > extracted) takes over. An excluded key is refused unless the
106
+ * developer adds it by hand, which clears the exclusion. Past the cap the oldest extracted item makes room; registered,
107
+ * manual and derived items are never evicted silently, so adding past the cap with none to evict is refused.
108
+ */
109
+ export function upsertItem(ws: WorkspaceLinks, input: ItemInput, now: number): UpsertResult {
110
+ const at = new Date(now).toISOString();
111
+ const excluded = ws.excluded.findIndex(e => e.key === input.key);
112
+ if (excluded >= 0) {
113
+ if (input.origin !== "manual") return { ok: false, reason: "excluded" };
114
+ ws.excluded.splice(excluded, 1);
115
+ }
116
+ const prior = ws.items.find(i => i.key === input.key);
117
+ if (prior) {
118
+ const upgrade = TRUST[input.origin] > TRUST[prior.origin];
119
+ prior.url = input.url ?? prior.url;
120
+ prior.title = input.title ?? prior.title;
121
+ if (input.status !== undefined) { prior.status = input.status; prior.statusTone = input.statusTone ?? null; }
122
+ if (input.checkedAt !== undefined) prior.checkedAt = input.checkedAt;
123
+ if (upgrade) { prior.origin = input.origin; prior.by = input.by ?? prior.by; prior.why = input.why ?? prior.why; }
124
+ else { prior.why ??= input.why ?? null; prior.by ??= input.by ?? null; }
125
+ prior.lastSeen = at;
126
+ return { ok: true, item: prior, created: false };
127
+ }
128
+ if (ws.items.length >= LIMITS.items) {
129
+ const evictable = ws.items.filter(i => i.origin === "extracted").sort((a, b) => a.lastSeen.localeCompare(b.lastSeen))[0];
130
+ if (!evictable) return { ok: false, reason: "cap" };
131
+ ws.items.splice(ws.items.indexOf(evictable), 1);
132
+ }
133
+ const item: LinkedItem = linkedItemSchema.parse({
134
+ key: input.key, kind: input.kind, url: input.url, title: input.title?.slice(0, 200) ?? null, status: input.status ?? null, statusTone: input.statusTone ?? null,
135
+ origin: input.origin, by: input.by ?? null, why: input.why?.slice(0, 140) ?? null, firstSeen: at, lastSeen: at, checkedAt: input.checkedAt ?? null,
136
+ });
137
+ ws.items.push(item);
138
+ ws.candidates = ws.candidates.filter(c => c.key !== input.key);
139
+ return { ok: true, item, created: true };
140
+ }
141
+
142
+ /** Removes an item (developer or agent) and remembers it, so no origin brings it back. Returns the removed item. */
143
+ export function excludeItem(ws: WorkspaceLinks, key: string, by: string, reason: string | null, now: number): LinkedItem | null {
144
+ const at = new Date(now).toISOString();
145
+ const i = ws.items.findIndex(x => x.key === key);
146
+ const removed = i >= 0 ? ws.items.splice(i, 1)[0] : null;
147
+ ws.candidates = ws.candidates.filter(c => c.key !== key);
148
+ if (!ws.excluded.some(e => e.key === key)) ws.excluded.push({ key, at, by, reason: reason?.slice(0, 200) ?? null });
149
+ if (ws.excluded.length > LIMITS.excluded) ws.excluded.splice(0, ws.excluded.length - LIMITS.excluded);
150
+ return removed;
151
+ }
152
+ /** Undo: the exclusion goes, and the removed item (when given) comes back as it was. */
153
+ export function unexcludeItem(ws: WorkspaceLinks, key: string, restore: LinkedItem | null): void {
154
+ ws.excluded = ws.excluded.filter(e => e.key !== key);
155
+ if (restore && !ws.items.some(i => i.key === key)) ws.items.push(restore);
156
+ }
157
+
158
+ // ---------- Linear candidates and the check queue ----------
159
+
160
+ /**
161
+ * An extracted Linear-shaped key. Known items refresh their lastSeen; excluded and rejected keys, and keys whose team
162
+ * prefix isn't a known Linear team, are dropped on the spot. Returns whether it is (now) a candidate.
163
+ */
164
+ export function noteCandidate(file: LinkedFile, workspaceId: string, raw: string, now: number): boolean {
165
+ const key = linearKey(raw);
166
+ if (!key || file.rejected[key]) return false;
167
+ const ws = file.workspaces[workspaceId] ??= emptyWorkspaceLinks();
168
+ if (ws.excluded.some(e => e.key === key)) return false;
169
+ const item = ws.items.find(i => i.key === key);
170
+ if (item) { item.lastSeen = new Date(now).toISOString(); return false; }
171
+ if (file.teams && !file.teams.keys.includes(teamOf(key))) return false;
172
+ const c = ws.candidates.find(c => c.key === key);
173
+ if (c) { c.seen++; return true; }
174
+ ws.candidates.push({ key, seen: 1, firstSeen: new Date(now).toISOString(), retryAt: null, failures: 0 });
175
+ if (ws.candidates.length > LIMITS.candidates) ws.candidates.splice(0, ws.candidates.length - LIMITS.candidates);
176
+ return true;
177
+ }
178
+
179
+ /** The team list arrived: candidates whose prefix isn't a Linear team ("STATUS-1025", "REVISION-2026") go for good. */
180
+ export function setTeams(file: LinkedFile, keys: string[], now: number): void {
181
+ file.teams = { keys: [...new Set(keys)].sort(), at: new Date(now).toISOString() };
182
+ for (const ws of Object.values(file.workspaces)) ws.candidates = ws.candidates.filter(c => keys.includes(teamOf(c.key)));
183
+ }
184
+
185
+ /** Up to `max` candidates due for a Linear check, oldest first. Nothing while the team list is unknown. */
186
+ export function dueChecks(file: LinkedFile, now: number, max: number = LIMITS.checksPerDrain): { workspaceId: string; key: string }[] {
187
+ if (!file.teams) return [];
188
+ const due: { workspaceId: string; key: string; firstSeen: string }[] = [];
189
+ const seen = new Set<string>();
190
+ for (const [workspaceId, ws] of Object.entries(file.workspaces)) for (const c of ws.candidates) {
191
+ if (c.retryAt && Date.parse(c.retryAt) > now) continue;
192
+ if (!file.teams.keys.includes(teamOf(c.key))) continue;
193
+ due.push({ workspaceId, key: c.key, firstSeen: c.firstSeen });
194
+ }
195
+ return due.sort((a, b) => a.firstSeen.localeCompare(b.firstSeen)).filter(d => !seen.has(d.key) && seen.add(d.key)).slice(0, max).map(({ workspaceId, key }) => ({ workspaceId, key }));
196
+ }
197
+
198
+ export type LinearIssueFacts = { title: string; state: string | null; url: string | null };
199
+ /** "In Progress" → active; "Done"/"Merged" → done; "Canceled"/"Duplicate" → cancelled; else todo. */
200
+ export function toneOf(state: string | null): LinkedItem["statusTone"] {
201
+ if (!state) return null;
202
+ const s = state.toLowerCase();
203
+ if (/cancel|duplicate|won.?t/.test(s)) return "cancelled";
204
+ if (/done|complete|merged|released|closed/.test(s)) return "done";
205
+ if (/progress|review|started|doing|active|testing/.test(s)) return "active";
206
+ return "todo";
207
+ }
208
+
209
+ /**
210
+ * One check's result, for every workspace holding the key as a candidate. Found: it becomes an extracted item with
211
+ * Linear's title, state and URL. Not found: rejected for good. A failure: retried with back-off, then dropped.
212
+ */
213
+ export function applyCheck(file: LinkedFile, key: string, result: { found: LinearIssueFacts | null } | { error: string }, now: number): void {
214
+ const at = new Date(now).toISOString();
215
+ if ("found" in result && !result.found) {
216
+ file.rejected[key] = at;
217
+ const keys = Object.keys(file.rejected);
218
+ if (keys.length > LIMITS.rejected) for (const k of keys.sort((a, b) => file.rejected[a].localeCompare(file.rejected[b])).slice(0, keys.length - LIMITS.rejected)) delete file.rejected[k];
219
+ }
220
+ for (const ws of Object.values(file.workspaces)) {
221
+ const c = ws.candidates.find(c => c.key === key);
222
+ if (!c) continue;
223
+ if ("error" in result) {
224
+ c.failures++;
225
+ if (c.failures > RETRY_MS.length) ws.candidates = ws.candidates.filter(x => x !== c);
226
+ else c.retryAt = new Date(now + RETRY_MS[c.failures - 1]).toISOString();
227
+ continue;
228
+ }
229
+ ws.candidates = ws.candidates.filter(x => x !== c);
230
+ if (result.found) upsertItem(ws, { key, kind: "linear", url: result.found.url, title: result.found.title, status: result.found.state, statusTone: toneOf(result.found.state), origin: "extracted", checkedAt: at }, now);
231
+ }
232
+ }
233
+
234
+ /** The daily check budget, shared by every workspace. */
235
+ export function takeBudget(file: LinkedFile, now: number, cap: number = LIMITS.dailyChecks): boolean {
236
+ const date = new Date(now).toISOString().slice(0, 10);
237
+ const count = file.daily?.date === date ? file.daily.count : 0;
238
+ if (count >= cap) return false;
239
+ file.daily = { date, count: count + 1 };
240
+ return true;
241
+ }
242
+
243
+ // ---------- what the panel shows ----------
244
+
245
+ /** Per-kind counts for the chip: verified items only, without the spec (its own chip sits beside it). */
246
+ export function linkedCounts(ws: WorkspaceLinks | undefined, specUrl: string | null = null): Partial<Record<LinkedKind, number>> {
247
+ const counts: Partial<Record<LinkedKind, number>> = {};
248
+ for (const i of ws?.items ?? []) {
249
+ if (i.origin === "spec" || specUrl && i.url === specUrl) continue;
250
+ counts[i.kind] = (counts[i.kind] ?? 0) + 1;
251
+ }
252
+ return counts;
253
+ }
254
+
255
+ // ---------- migration from Summary links ----------
256
+
257
+ export const ABOUT_MIGRATION = "about-links-1";
258
+ type AboutLinkLike = { kind: string; key: string; url: string | null; title: string | null; state?: string | null };
259
+ /**
260
+ * One-time: carries over only what was verified. A Linear link with a title was confirmed by Linear; Slack threads with
261
+ * a channel, artifacts and docs are URL-shaped. Bare Linear keys (today's "couldn't be read" rows) become candidates
262
+ * and go through the normal check queue; PRs and generic links are dropped.
263
+ */
264
+ export function migrateAboutLinks(file: LinkedFile, about: Record<string, { links: AboutLinkLike[] }>, now: number): { items: number; candidates: number } {
265
+ let items = 0, candidates = 0;
266
+ if (file.migrations.includes(ABOUT_MIGRATION)) return { items, candidates };
267
+ for (const [workspaceId, record] of Object.entries(about)) {
268
+ for (const l of record.links ?? []) {
269
+ const ws = file.workspaces[workspaceId] ??= emptyWorkspaceLinks();
270
+ if (l.kind === "linear") {
271
+ const key = linearKey(l.key);
272
+ if (!key) continue;
273
+ if (l.title) { if (upsertItem(ws, { key, kind: "linear", url: l.url, title: l.title, status: l.state ?? null, statusTone: toneOf(l.state ?? null), origin: "extracted" }, now).ok) items++; }
274
+ else if (noteCandidate(file, workspaceId, key, now)) candidates++;
275
+ } else if (l.kind === "slack" && l.title || l.kind === "artifact" || l.kind === "doc") {
276
+ if (upsertItem(ws, { key: l.key, kind: l.kind as LinkedKind, url: l.url, title: l.title, origin: "extracted" }, now).ok) items++;
277
+ }
278
+ }
279
+ }
280
+ file.migrations.push(ABOUT_MIGRATION);
281
+ return { items, candidates };
282
+ }