neurastream 0.2.86 → 0.3.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.
- package/README.md +22 -7
- package/package.json +1 -1
- package/src/adapters/omp/doctor.ts +10 -3
- package/src/adapters/omp/index.ts +21 -5
- package/src/cli/claim.ts +48 -17
- package/src/cli/dispatch.ts +23 -8
- package/src/cli/setup.ts +3 -3
- package/src/cli/team.ts +311 -0
- package/src/cli/workspace.ts +235 -0
- package/src/core/claims.ts +29 -11
- package/src/core/config.ts +16 -5
- package/src/core/guards.ts +182 -46
- package/src/core/incident-detectors.ts +1 -1
- package/src/core/mr-sweep.ts +33 -6
- package/src/core/owner-ui.ts +353 -132
- package/src/core/pages.ts +1 -1
- package/src/core/queue/lib.ts +23 -9
- package/src/core/queue-check.ts +5 -3
- package/src/core/queue-close.ts +3 -3
- package/src/core/team-client.ts +813 -0
- package/src/core/team-labels.ts +127 -0
- package/src/core/team-server.ts +1008 -0
- package/src/core/ui-setup.ts +186 -41
- package/templates/config.yml +5 -3
- package/templates/queue/TEMPLATE.md +2 -0
- package/templates/systemd/neurastream-workspace.service +17 -0
- package/src/cli/ui.ts +0 -104
- package/templates/systemd/neurastream-ui.service +0 -16
|
@@ -0,0 +1,813 @@
|
|
|
1
|
+
// Team client (plan 20261027_1305 P3): the ClaimStore over a team server, the chooser that
|
|
2
|
+
// routes each plan to the file or the team store, the summary holder, and team sync. The
|
|
3
|
+
// guards are synchronous, so every request runs in one blocking child: spawnSync of this same
|
|
4
|
+
// file — the request entry below runs when team-client.ts is the process entry — with the JSON
|
|
5
|
+
// request on stdin, no shell, argv carries no request data, 5 s timeout. A server that did not
|
|
6
|
+
// answer is the typed `Unreachable` value (never null) and memoizes per team for 60 s, so a
|
|
7
|
+
// down team server costs one 5 s wait per process per minute. Write requests carry
|
|
8
|
+
// `Origin: http://<host:port>` (the server's Origin check); no request carries a token — whois
|
|
9
|
+
// is the auth. Requests carry plan ids, never plan text or paths (Forbidden).
|
|
10
|
+
|
|
11
|
+
import { spawnSync } from "node:child_process";
|
|
12
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync, writeSync } from "node:fs";
|
|
13
|
+
import { hostname } from "node:os";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { claimExpired, fileClaimStore, heldByOther, type Claim, type ClaimStore, type Unreachable } from "./claims.ts";
|
|
17
|
+
import { nowSec, strftime } from "./clock.ts";
|
|
18
|
+
import type { Config } from "./config.ts";
|
|
19
|
+
import { lock } from "./file-lock.ts";
|
|
20
|
+
import { mainId } from "./guards.ts";
|
|
21
|
+
import { jaccard } from "./incident-detectors.ts";
|
|
22
|
+
import { defaultRunner, listOpenMrs, remotePath, type CommandRunner } from "./mr-sweep.ts";
|
|
23
|
+
import { activePlans, headerField, parsePlan, planRepo, sha, SUMMARY_CAP, type Plan } from "./queue/lib.ts";
|
|
24
|
+
import { teamPlanId, type TeamView } from "./team-server.ts";
|
|
25
|
+
import { planShare, remoteListed, repoTeam } from "./team-labels.ts";
|
|
26
|
+
|
|
27
|
+
/** The server's one-read view, as the server defines it: every client consumer reads it from here. */
|
|
28
|
+
export type { TeamView };
|
|
29
|
+
|
|
30
|
+
/** One `cfg.teams` entry. */
|
|
31
|
+
export type TeamEntry = Config["teams"][number];
|
|
32
|
+
|
|
33
|
+
/** One request for the request entry. */
|
|
34
|
+
export interface WireRequest {
|
|
35
|
+
url: string;
|
|
36
|
+
method: string;
|
|
37
|
+
headers?: Record<string, string>;
|
|
38
|
+
body?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One answer from the request entry; `error` set means the server did not answer. */
|
|
42
|
+
export interface WireResponse {
|
|
43
|
+
status?: number;
|
|
44
|
+
body?: unknown;
|
|
45
|
+
error?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type Send = (req: WireRequest) => WireResponse | null;
|
|
49
|
+
|
|
50
|
+
export interface RemoteStoreOpts {
|
|
51
|
+
/** Clock in unix seconds; defaults to the NEURASTREAM_NOW-aware nowSec. */
|
|
52
|
+
clock?: () => number;
|
|
53
|
+
/** The transport; defaults to one spawnSync child per request (the request entry). */
|
|
54
|
+
send?: Send;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface RawOpts {
|
|
58
|
+
clock?: () => number;
|
|
59
|
+
send?: Send;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One wire claim row (`GET /claims`, claim answers); `plan` is the plan id on the wire. */
|
|
63
|
+
interface WireRow {
|
|
64
|
+
id?: string;
|
|
65
|
+
plan?: string;
|
|
66
|
+
sha?: string;
|
|
67
|
+
main?: string;
|
|
68
|
+
host?: string;
|
|
69
|
+
pid?: number;
|
|
70
|
+
since?: number;
|
|
71
|
+
beat?: number;
|
|
72
|
+
mine?: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A sync record entry: where this plan lives locally and which version this machine last saw. */
|
|
76
|
+
interface RecEntry {
|
|
77
|
+
path: string;
|
|
78
|
+
sha: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type TeamRecord = Record<string, RecEntry>;
|
|
82
|
+
|
|
83
|
+
const OUTAGE_MEMO_SEC = 60;
|
|
84
|
+
/** One request may block the calling process this long (the guards are synchronous). */
|
|
85
|
+
const REQUEST_TIMEOUT_MS = 5_000;
|
|
86
|
+
|
|
87
|
+
function isObj(v: unknown): v is Record<string, unknown> {
|
|
88
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** `Origin` header value for a write to this server (the server compares it to its Host header). */
|
|
92
|
+
function originOf(server: string): string {
|
|
93
|
+
return `http://${server.replace(/^https?:\/\//, "")}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// --- the outage memo: per team server, lives exactly as long as one process ---
|
|
97
|
+
|
|
98
|
+
const downUntil = new Map<string, number>();
|
|
99
|
+
|
|
100
|
+
function memoDown(name: string, clock: () => number): boolean {
|
|
101
|
+
const until = downUntil.get(name);
|
|
102
|
+
return until !== undefined && clock() < until;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function markDown(name: string, clock: () => number): void {
|
|
106
|
+
downUntil.set(name, clock() + OUTAGE_MEMO_SEC);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** One request through the send seam, with the memo: down answers at once; transport failures and 5xx mark the team down. Returns "down" when the server did not answer. */
|
|
110
|
+
function askRaw(team: TeamEntry, req: WireRequest, opts: RawOpts = {}): WireResponse | "down" {
|
|
111
|
+
const clock = opts.clock ?? nowSec;
|
|
112
|
+
const send = opts.send ?? defaultSend;
|
|
113
|
+
if (memoDown(team.name, clock)) return "down";
|
|
114
|
+
const res = send(req);
|
|
115
|
+
if (res === null || res.error !== undefined || typeof res.status !== "number" || res.status >= 500) {
|
|
116
|
+
markDown(team.name, clock);
|
|
117
|
+
return "down";
|
|
118
|
+
}
|
|
119
|
+
return res;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// --- the request entry (this file as a process) ---
|
|
123
|
+
|
|
124
|
+
/** Read one JSON request from stdin, perform the HTTP request, write one JSON answer to stdout. */
|
|
125
|
+
async function runRequestEntry(): Promise<void> {
|
|
126
|
+
let req: WireRequest;
|
|
127
|
+
try {
|
|
128
|
+
req = JSON.parse(readFileSync(0, "utf8")) as WireRequest;
|
|
129
|
+
} catch (err) {
|
|
130
|
+
writeEntry({ error: `bad request: ${(err as Error).message}` });
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
const res = await fetch(req.url, { method: req.method, headers: req.headers, body: req.body });
|
|
135
|
+
const text = await res.text();
|
|
136
|
+
let body: unknown = text;
|
|
137
|
+
try {
|
|
138
|
+
body = JSON.parse(text);
|
|
139
|
+
} catch {
|
|
140
|
+
// keep the raw text
|
|
141
|
+
}
|
|
142
|
+
writeEntry({ status: res.status, body });
|
|
143
|
+
} catch (err) {
|
|
144
|
+
writeEntry({ error: String(err) });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function writeEntry(out: WireResponse): void {
|
|
149
|
+
writeSync(1, JSON.stringify(out));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (import.meta.main) {
|
|
153
|
+
void runRequestEntry().then(
|
|
154
|
+
() => process.exit(0),
|
|
155
|
+
(err) => {
|
|
156
|
+
try {
|
|
157
|
+
writeEntry({ error: String(err) });
|
|
158
|
+
} catch {}
|
|
159
|
+
process.exit(0);
|
|
160
|
+
},
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The default transport: one synchronous child, JSON request on stdin, JSON answer on stdout. */
|
|
165
|
+
function defaultSend(req: WireRequest): WireResponse | null {
|
|
166
|
+
const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url)], {
|
|
167
|
+
input: JSON.stringify(req),
|
|
168
|
+
timeout: REQUEST_TIMEOUT_MS,
|
|
169
|
+
encoding: "utf8",
|
|
170
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
171
|
+
});
|
|
172
|
+
if (r.error || r.status !== 0 || !r.stdout) return { error: r.error ? String(r.error) : `request entry exited ${r.status}` };
|
|
173
|
+
try {
|
|
174
|
+
const out = JSON.parse(r.stdout) as WireResponse;
|
|
175
|
+
return isObj(out) ? (out as WireResponse) : { error: "unparseable answer" };
|
|
176
|
+
} catch {
|
|
177
|
+
return { error: "unparseable answer" };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// --- records: <queue_state>/team/<team>/record.json, every read-modify-write under the lock ---
|
|
182
|
+
|
|
183
|
+
export function teamDir(cfg: Config, team: TeamEntry): string {
|
|
184
|
+
return path.join(cfg.paths.queue_state, "team", team.name);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function readRecord(cfg: Config, team: TeamEntry): TeamRecord {
|
|
188
|
+
try {
|
|
189
|
+
const parsed: unknown = JSON.parse(readFileSync(path.join(teamDir(cfg, team), "record.json"), "utf8"));
|
|
190
|
+
if (isObj(parsed)) return parsed as TeamRecord;
|
|
191
|
+
} catch {}
|
|
192
|
+
return {};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A plan id as the server makes it: the sha256 hex of the origin and path. Any other string names no file, so it is never joined into a path or used as a record key. */
|
|
196
|
+
const PLAN_ID_RE = /^[0-9a-f]{64}$/;
|
|
197
|
+
function validId(id: unknown): id is string {
|
|
198
|
+
return typeof id === "string" && PLAN_ID_RE.test(id);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* One read-modify-write of the sync record, under the file lock the claims store uses
|
|
203
|
+
* (fileClaimStore's run() convention): the lock sits beside the data, the write is tmp + rename
|
|
204
|
+
* inside, released in finally. Unlocked, two racing processes each read the old record and the
|
|
205
|
+
* later rename drops the other's entry — a dropped entry is exactly the record rule's fail-open.
|
|
206
|
+
*/
|
|
207
|
+
function writeRecord(cfg: Config, team: TeamEntry, mutate: (rec: TeamRecord) => void): void {
|
|
208
|
+
const dir = teamDir(cfg, team);
|
|
209
|
+
mkdirSync(dir, { recursive: true });
|
|
210
|
+
const held = lock(path.join(dir, "record.lock"));
|
|
211
|
+
try {
|
|
212
|
+
const rec = readRecord(cfg, team);
|
|
213
|
+
mutate(rec);
|
|
214
|
+
const file = path.join(dir, "record.json");
|
|
215
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
216
|
+
writeFileSync(tmp, JSON.stringify(rec));
|
|
217
|
+
renameSync(tmp, file);
|
|
218
|
+
} finally {
|
|
219
|
+
held.release();
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// --- path -> id mapping (P2b (2)): the record's id when recorded, else the origin hash ---
|
|
224
|
+
|
|
225
|
+
const originCache = new Map<string, string>();
|
|
226
|
+
|
|
227
|
+
function gitOrigin(repo: string, run: CommandRunner): string {
|
|
228
|
+
const hit = originCache.get(repo);
|
|
229
|
+
if (hit !== undefined) return hit;
|
|
230
|
+
const r = run(["git", "-C", repo, "remote", "get-url", "origin"], {});
|
|
231
|
+
const url = r.code === 0 ? r.stdout.trim() : "";
|
|
232
|
+
originCache.set(repo, url);
|
|
233
|
+
return url;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** The origin as the wire carries it: host/path under https, so no userinfo, port or scheme from the git config. The server stores remotePath of what it gets, so the plan id is the same either way. */
|
|
237
|
+
function wireRemote(origin: string): string {
|
|
238
|
+
return `https://${remotePath(origin) ?? ""}`;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** The server's id for this plan file: the sync record's id for the path when recorded, else the hash of the repo origin and the repo-relative path. Null when neither names a plan. */
|
|
242
|
+
export function pathId(team: TeamEntry, cfg: Config, file: string, run: CommandRunner): string | null {
|
|
243
|
+
for (const [id, entry] of Object.entries(readRecord(cfg, team))) if (entry.path === file) return id;
|
|
244
|
+
const repo = planRepo(file);
|
|
245
|
+
return teamPlanId(gitOrigin(repo, run), path.relative(repo, file));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** The wire claim as a local Claim: the plan is this machine's path, `mine` rides along. */
|
|
249
|
+
function toClaim(row: WireRow, plan: string): Claim {
|
|
250
|
+
return {
|
|
251
|
+
plan,
|
|
252
|
+
main: String(row.main ?? ""),
|
|
253
|
+
host: String(row.host ?? ""),
|
|
254
|
+
pid: Number(row.pid ?? 0),
|
|
255
|
+
since: Number(row.since ?? 0),
|
|
256
|
+
beat: Number(row.beat ?? 0),
|
|
257
|
+
...(row.mine === undefined ? {} : { mine: row.mine }),
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// --- the remote claim store ---
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The ClaimStore over one team server (U = Unreachable). The plan ids ride the wire; every
|
|
265
|
+
* returned Claim names the local path, and ids with no recorded path are dropped from list().
|
|
266
|
+
* On a timeout, a refused connection, a 5xx or an unparseable answer the store answers
|
|
267
|
+
* Unreachable for the next 60 s without sending a request; heartbeat answers false and release
|
|
268
|
+
* sends nothing (the claim lapses at the TTL).
|
|
269
|
+
*/
|
|
270
|
+
export function remoteClaimStore(team: TeamEntry, queueState: string, opts: RemoteStoreOpts = {}): ClaimStore {
|
|
271
|
+
const optsRaw: RawOpts = opts;
|
|
272
|
+
const cfgLike = { paths: { queue_state: queueState } } as Config;
|
|
273
|
+
|
|
274
|
+
function claimHeaders(): Record<string, string> {
|
|
275
|
+
return { "content-type": "application/json", origin: originOf(team.server) };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return {
|
|
279
|
+
claim(plan, main) {
|
|
280
|
+
const id = pathId(team, cfgLike, plan, defaultRunner);
|
|
281
|
+
if (id === null) return { unreachable: team.server };
|
|
282
|
+
const res = askRaw(team, { url: `${team.server}/claims/${encodeURIComponent(id)}`, method: "POST", headers: claimHeaders(), body: JSON.stringify({ main, host: hostname(), pid: process.pid }) }, optsRaw);
|
|
283
|
+
if (res === "down") return { unreachable: team.server };
|
|
284
|
+
if (res.status === 409 && isObj(res.body) && isObj(res.body.heldBy)) return { heldBy: toClaim(res.body.heldBy as WireRow, plan) };
|
|
285
|
+
if (res.status === 200 && isObj(res.body) && isObj(res.body.claim)) return toClaim(res.body.claim as WireRow, plan);
|
|
286
|
+
// 404 (no such plan), 429, 403: no claim can be taken — fail closed, not null.
|
|
287
|
+
return { unreachable: team.server };
|
|
288
|
+
},
|
|
289
|
+
heartbeat(plan, main) {
|
|
290
|
+
const id = pathId(team, cfgLike, plan, defaultRunner);
|
|
291
|
+
if (id === null) return false;
|
|
292
|
+
const res = askRaw(team, { url: `${team.server}/claims/${encodeURIComponent(id)}/beat`, method: "POST", headers: claimHeaders(), body: JSON.stringify({ main }) }, optsRaw);
|
|
293
|
+
return res !== "down" && res.status === 200;
|
|
294
|
+
},
|
|
295
|
+
holder(plan) {
|
|
296
|
+
const id = pathId(team, cfgLike, plan, defaultRunner);
|
|
297
|
+
if (id === null) return { unreachable: team.server };
|
|
298
|
+
const res = askRaw(team, { url: `${team.server}/claims/${encodeURIComponent(id)}`, method: "GET" }, optsRaw);
|
|
299
|
+
if (res === "down") return { unreachable: team.server };
|
|
300
|
+
if (res.status === 404) return null; // the plan is not stored on the server: free
|
|
301
|
+
if (res.status === 200 && isObj(res.body)) return isObj(res.body.claim) ? toClaim(res.body.claim as WireRow, plan) : null;
|
|
302
|
+
return { unreachable: team.server };
|
|
303
|
+
},
|
|
304
|
+
release(plan, main) {
|
|
305
|
+
const id = pathId(team, cfgLike, plan, defaultRunner);
|
|
306
|
+
if (id === null) return;
|
|
307
|
+
// Void on any answer: an unreachable release sends nothing and the claim lapses at the TTL.
|
|
308
|
+
askRaw(team, { url: `${team.server}/claims/${encodeURIComponent(id)}`, method: "DELETE", headers: claimHeaders(), body: JSON.stringify({ main }) }, optsRaw);
|
|
309
|
+
},
|
|
310
|
+
list() {
|
|
311
|
+
const res = askRaw(team, { url: `${team.server}/claims`, method: "GET" }, optsRaw);
|
|
312
|
+
if (res === "down") return { unreachable: team.server };
|
|
313
|
+
if (res.status !== 200 || !isObj(res.body) || !Array.isArray(res.body.claims)) return { unreachable: team.server };
|
|
314
|
+
const rec = readRecord(cfgLike, team);
|
|
315
|
+
const out: Claim[] = [];
|
|
316
|
+
for (const row of res.body.claims as WireRow[]) {
|
|
317
|
+
const planId = typeof row?.plan === "string" ? row.plan : typeof row?.id === "string" ? row.id : undefined;
|
|
318
|
+
const local = planId !== undefined ? rec[planId]?.path : undefined;
|
|
319
|
+
if (local !== undefined) out.push(toClaim(row, local)); // ids with no recorded path are dropped
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// --- the chooser's module map: one remote store per cfg.teams entry per process ---
|
|
327
|
+
|
|
328
|
+
const stores = new Map<string, ClaimStore>();
|
|
329
|
+
|
|
330
|
+
/** The team's remote store from the process-wide map; test seams may inject clock and send. */
|
|
331
|
+
export function remoteStoreFor(team: TeamEntry, cfg: Config, opts: RemoteStoreOpts = {}): ClaimStore {
|
|
332
|
+
const hit = stores.get(team.name);
|
|
333
|
+
if (hit && !opts.clock && !opts.send) return hit;
|
|
334
|
+
const built = remoteClaimStore(team, cfg.paths.queue_state, opts);
|
|
335
|
+
stores.set(team.name, built);
|
|
336
|
+
return built;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Clears the process-wide remote stores, the outage memo and the origin cache. A test seam: the memo lives exactly one process, and a scenario must not inherit a down mark. */
|
|
340
|
+
export function resetTeamStores(): void {
|
|
341
|
+
stores.clear();
|
|
342
|
+
downUntil.clear();
|
|
343
|
+
originCache.clear();
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** The team this plan's claims belong to: a `Queue: team` plan goes to the repo's team (the order planShare uses); a headerless plan whose path sits in some team's sync record goes there anyway — the record is a local JSON read, no git. */
|
|
347
|
+
export function routeTeam(file: string, cfg: Config, text: string | undefined, run: CommandRunner): TeamEntry | null {
|
|
348
|
+
const header = headerField(text ?? readText(file) ?? "", "Queue");
|
|
349
|
+
if (header === "team") {
|
|
350
|
+
const name = repoTeam(planRepo(file), cfg, run);
|
|
351
|
+
const entry = name ? cfg.teams.find((t) => t.name === name) : undefined;
|
|
352
|
+
if (entry) return entry;
|
|
353
|
+
}
|
|
354
|
+
for (const team of cfg.teams) {
|
|
355
|
+
for (const entry of Object.values(readRecord(cfg, team))) if (entry.path === file) return team;
|
|
356
|
+
}
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function readText(file: string): string | null {
|
|
361
|
+
try {
|
|
362
|
+
return readFileSync(file, "utf8");
|
|
363
|
+
} catch {
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* The claim store for one plan: the team's remote store when the plan is a team plan (by
|
|
370
|
+
* header, or by the sync record when the header was stripped on disk outside the edit gate),
|
|
371
|
+
* else the local file store. Personal plans never run git and never send.
|
|
372
|
+
*/
|
|
373
|
+
export function claimStoreFor(file: string, cfg: Config, text?: string, run: CommandRunner = defaultRunner): ClaimStore {
|
|
374
|
+
const team = routeTeam(file, cfg, text, run);
|
|
375
|
+
if (team) return remoteStoreFor(team, cfg);
|
|
376
|
+
return fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// --- the summary holder: one GET /claims per team per summary ---
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* A holder-only store for one queue summary (checkInject, queue-check, the owner page's rows):
|
|
383
|
+
* a plan the chooser sends to the file store is answered locally; a plan of team T is answered
|
|
384
|
+
* from that team's claims, fetched once on first use within this summary (one child, one
|
|
385
|
+
* request) — or, when the caller already read a team view (P4's `teamViews`), from that view's
|
|
386
|
+
* `claims`, which are the same rows `GET /claims` sends, so one render stays one request per
|
|
387
|
+
* team. Matching is by plan id, never by recorded path, so a never-synced `Queue: team` plan
|
|
388
|
+
* still shows its server holder. Liveness uses this member's claim_ttl_min; it only colours the
|
|
389
|
+
* summary, every decision still asks the server per plan.
|
|
390
|
+
*/
|
|
391
|
+
export function summaryHolder(cfg: Config, opts: RawOpts = {}, views?: Map<string, TeamView | Unreachable>): Pick<ClaimStore, "holder"> {
|
|
392
|
+
const clock = opts.clock ?? nowSec;
|
|
393
|
+
const byTeam = new Map<string, Map<string, WireRow> | "down">();
|
|
394
|
+
|
|
395
|
+
function rowsFor(team: TeamEntry): Map<string, WireRow> | "down" {
|
|
396
|
+
const hit = byTeam.get(team.name);
|
|
397
|
+
if (hit) return hit;
|
|
398
|
+
let out: Map<string, WireRow> | "down";
|
|
399
|
+
const seen = views?.get(team.name);
|
|
400
|
+
if (seen !== undefined) {
|
|
401
|
+
out = "unreachable" in seen ? "down" : new Map(seen.claims.map(row => [row.plan, row] as const));
|
|
402
|
+
} else {
|
|
403
|
+
const res = askRaw(team, { url: `${team.server}/claims`, method: "GET" }, opts);
|
|
404
|
+
if (res !== "down" && res.status === 200 && isObj(res.body) && Array.isArray(res.body.claims)) {
|
|
405
|
+
const rows = new Map<string, WireRow>();
|
|
406
|
+
for (const row of res.body.claims as WireRow[]) {
|
|
407
|
+
const planId = typeof row?.plan === "string" ? row.plan : typeof row?.id === "string" ? row.id : undefined;
|
|
408
|
+
if (isObj(row) && planId) rows.set(planId, row);
|
|
409
|
+
}
|
|
410
|
+
out = rows;
|
|
411
|
+
} else {
|
|
412
|
+
out = "down";
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
byTeam.set(team.name, out);
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return {
|
|
420
|
+
holder(plan) {
|
|
421
|
+
const team = routeTeam(plan, cfg, undefined, defaultRunner);
|
|
422
|
+
if (!team) return fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min).holder(plan);
|
|
423
|
+
const rows = rowsFor(team);
|
|
424
|
+
if (rows === "down") return { unreachable: team.server };
|
|
425
|
+
const id = pathId(team, cfg, plan, defaultRunner);
|
|
426
|
+
const row = id === null ? undefined : rows.get(id);
|
|
427
|
+
if (!row) return null;
|
|
428
|
+
return claimExpired({ beat: Number(row.beat ?? 0) }, clock(), cfg.queue.claim_ttl_min) ? null : toClaim(row, plan);
|
|
429
|
+
},
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// --- team sync ---
|
|
434
|
+
|
|
435
|
+
/** One GET /plans/:id pulled into this machine: the read copy is written unless the record maps the id to a repo path (then the repo file is left alone and only the sha is noted for the next push's base). */
|
|
436
|
+
function pullPlan(team: TeamEntry, cfg: Config, id: string): void {
|
|
437
|
+
if (!validId(id)) return; // a server id that is not a plan id is never fetched, joined into a path, or read as a record key
|
|
438
|
+
const res = askRaw(team, { url: `${team.server}/plans/${encodeURIComponent(id)}`, method: "GET" });
|
|
439
|
+
if (res === "down" || res.status !== 200 || !isObj(res.body) || typeof res.body.text !== "string" || typeof res.body.sha !== "string") return;
|
|
440
|
+
const text = res.body.text;
|
|
441
|
+
const nextSha = res.body.sha;
|
|
442
|
+
const copyDir = path.join(teamDir(cfg, team), "plans");
|
|
443
|
+
const entry = readRecord(cfg, team)[id];
|
|
444
|
+
if (entry && !entry.path.startsWith(`${copyDir}/`)) {
|
|
445
|
+
// A repo path: the local repo file is left alone, only the sha is noted.
|
|
446
|
+
writeRecord(cfg, team, (rec) => {
|
|
447
|
+
rec[id] = { path: entry.path, sha: nextSha };
|
|
448
|
+
});
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
mkdirSync(copyDir, { recursive: true });
|
|
452
|
+
const copy = path.join(copyDir, `${id}.md`);
|
|
453
|
+
writeFileSync(copy, text);
|
|
454
|
+
writeRecord(cfg, team, (rec) => {
|
|
455
|
+
rec[id] = { path: entry?.path ?? copy, sha: nextSha };
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* One plan's push (share's one-plan push and syncTeam's loop run this): never without the
|
|
461
|
+
* `Queue: team` marker on the text, never while another member's login holds it (the server's
|
|
462
|
+
* PUT has no claim check), with the record's sha as the base. A 409 pulls that id — with the
|
|
463
|
+
* server sha it re-reads, with `sha: null` the plan is absent on the server and the record
|
|
464
|
+
* entry stays, so every later sync conflicts again until the plan is unshared and shared anew.
|
|
465
|
+
*/
|
|
466
|
+
export function pushTeamPlan(team: TeamEntry, cfg: Config, file: string, text?: string, run: CommandRunner = defaultRunner, distinct?: string): void {
|
|
467
|
+
const body = text ?? readText(file) ?? "";
|
|
468
|
+
if (headerField(body, "Queue") !== "team") return; // a plan without the marker is never pushed
|
|
469
|
+
// The server refuses a repo its team does not list; checking here keeps the text on this machine.
|
|
470
|
+
const repo = planRepo(file);
|
|
471
|
+
if (!remoteListed(gitOrigin(repo, run), team.repos)) {
|
|
472
|
+
console.log(`team sync: ${file} not pushed: its repo is not in team ${team.name}`);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const id = pathId(team, cfg, file, run);
|
|
476
|
+
if (id === null) {
|
|
477
|
+
console.log(`team sync: ${file} not pushed: its repo origin does not parse`);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
const holder = remoteStoreFor(team, cfg).holder(file);
|
|
481
|
+
if (holder !== null && "unreachable" in holder) {
|
|
482
|
+
console.log(`team sync: ${file} not pushed: team server ${team.server} unreachable`);
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (heldByOther(holder, mainId())) {
|
|
486
|
+
console.log(`team sync: ${file} not pushed: held by another member's Main`);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const base = readRecord(cfg, team)[id]?.sha ?? null;
|
|
490
|
+
const res = askRaw(team, {
|
|
491
|
+
url: `${team.server}/plans/${encodeURIComponent(id)}`,
|
|
492
|
+
method: "PUT",
|
|
493
|
+
headers: { "content-type": "application/json", origin: originOf(team.server) },
|
|
494
|
+
body: JSON.stringify({ remote: wireRemote(gitOrigin(repo, run)), rel_path: path.relative(repo, file), text: body, base_sha: base, distinct }),
|
|
495
|
+
});
|
|
496
|
+
if (res === "down") {
|
|
497
|
+
console.log(`team sync: ${file} not pushed: team server ${team.server} unreachable`);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (res.status === 200 && isObj(res.body) && typeof res.body.sha === "string") {
|
|
501
|
+
const nextSha = res.body.sha;
|
|
502
|
+
writeRecord(cfg, team, (rec) => {
|
|
503
|
+
rec[id] = { path: file, sha: nextSha };
|
|
504
|
+
});
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
if (res.status === 409) {
|
|
508
|
+
const serverSha = isObj(res.body) && typeof res.body.sha === "string" ? res.body.sha : null;
|
|
509
|
+
if (serverSha !== null) pullPlan(team, cfg, id);
|
|
510
|
+
console.log(`team sync: ${file} conflict: the server has a newer version (${serverSha}); merge it and run team sync again`);
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
console.log(`team sync: ${file} not pushed: the server refused (${res.status})`);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Team sync for one team: pull (GET /plans, then each id whose sha differs from the record),
|
|
518
|
+
* then push every INDEX plan this team shares whose text sha differs from the record. Each
|
|
519
|
+
* request may block its caller up to 5 s; no hook and no heartbeat tick runs sync.
|
|
520
|
+
*/
|
|
521
|
+
export function syncTeam(team: TeamEntry, cfg: Config, run: CommandRunner = defaultRunner): number {
|
|
522
|
+
const res = askRaw(team, { url: `${team.server}/plans`, method: "GET" });
|
|
523
|
+
if (res === "down" || res.status !== 200 || !isObj(res.body) || !Array.isArray(res.body.plans)) {
|
|
524
|
+
console.log(`team sync: team server ${team.server} unreachable`);
|
|
525
|
+
} else {
|
|
526
|
+
const rec = readRecord(cfg, team);
|
|
527
|
+
for (const row of res.body.plans as WireRow[]) {
|
|
528
|
+
if (typeof row?.id === "string" && typeof row.sha === "string" && rec[row.id]?.sha !== row.sha) pullPlan(team, cfg, row.id);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
for (const plan of activePlans(cfg.paths.queue_index)) {
|
|
532
|
+
if (planShare(plan, cfg, run) !== team.name) continue;
|
|
533
|
+
const id = pathId(team, cfg, plan.file, run);
|
|
534
|
+
if (id === null) continue;
|
|
535
|
+
if (readRecord(cfg, team)[id]?.sha === sha(plan.text)) continue;
|
|
536
|
+
pushTeamPlan(team, cfg, plan.file, plan.text, run);
|
|
537
|
+
}
|
|
538
|
+
return 0;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Deletes this plan's record entries (by path and by plan id) from every team's record — `team unshare` runs it after rewriting the header. */
|
|
542
|
+
export function deleteRecordEntries(cfg: Config, file: string, run: CommandRunner = defaultRunner): void {
|
|
543
|
+
for (const team of cfg.teams) {
|
|
544
|
+
const rec = readRecord(cfg, team);
|
|
545
|
+
const id = pathId(team, cfg, file, run);
|
|
546
|
+
const hits = Object.entries(rec).filter(([entryId, entry]) => entry.path === file || entryId === id);
|
|
547
|
+
if (!hits.length) continue;
|
|
548
|
+
writeRecord(cfg, team, (next) => {
|
|
549
|
+
for (const [entryId] of hits) delete next[entryId];
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// --- team views: one GET /view per team per render or summary (P4) ---
|
|
555
|
+
|
|
556
|
+
/** One plan of a team's view, as every team section reads it. */
|
|
557
|
+
export interface TeamPlanRow {
|
|
558
|
+
/** The server's plan id. */
|
|
559
|
+
id: string;
|
|
560
|
+
/** This machine's path for the plan: the sync record's path, else the read copy `team sync` writes. Display only. */
|
|
561
|
+
file: string;
|
|
562
|
+
/** The server text parsed with `localPaths` false, its worktree and appliesTo blanked: nothing stats a team-chosen path. */
|
|
563
|
+
plan: Plan;
|
|
564
|
+
/** The repo-relative path on the server: the plan's identity in a team card. */
|
|
565
|
+
relPath: string;
|
|
566
|
+
/** The live claim on the server; `login` is the member holding it. */
|
|
567
|
+
holder: (Claim & { login: string }) | null;
|
|
568
|
+
approvals: string[];
|
|
569
|
+
/** The plan's answers, newest first (the view's own order). */
|
|
570
|
+
answers: TeamView["answers"];
|
|
571
|
+
/** The first answer to the plan's current WAITING question (the server's), or null when none. */
|
|
572
|
+
answered: TeamEarlier | null;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** True when the body carries the arrays `readTeamView` sends. */
|
|
576
|
+
function isView(body: unknown): body is TeamView {
|
|
577
|
+
return (
|
|
578
|
+
isObj(body) &&
|
|
579
|
+
Array.isArray(body.plans) &&
|
|
580
|
+
Array.isArray(body.claims) &&
|
|
581
|
+
Array.isArray(body.approvals) &&
|
|
582
|
+
Array.isArray(body.votes) &&
|
|
583
|
+
Array.isArray(body.paused) &&
|
|
584
|
+
Array.isArray(body.answers) &&
|
|
585
|
+
Array.isArray(body.first) &&
|
|
586
|
+
typeof body.me_paused === "boolean"
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** One team's view (`GET /view`): the TeamView, or the typed Unreachable. teamViews is this over every team. */
|
|
591
|
+
export function teamView(team: TeamEntry, opts: RawOpts = {}): TeamView | Unreachable {
|
|
592
|
+
const res = askRaw(team, { url: `${team.server}/view`, method: "GET" }, opts);
|
|
593
|
+
return res === "down" || res.status !== 200 || !isView(res.body) ? { unreachable: team.server } : res.body;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* One `GET /view` per `cfg.teams` entry: plan text, claims and the P2c tables in one request, so
|
|
598
|
+
* a render costs one child per team instead of one per table. The outage memo and the 5 s bound
|
|
599
|
+
* are askRaw's, and a non-200 or a body of the wrong shape is Unreachable — the same answer
|
|
600
|
+
* remoteClaimStore.list() gives its own read.
|
|
601
|
+
*/
|
|
602
|
+
export function teamViews(cfg: Config, opts: RawOpts = {}): Map<string, TeamView | Unreachable> {
|
|
603
|
+
const out = new Map<string, TeamView | Unreachable>();
|
|
604
|
+
for (const team of cfg.teams) out.set(team.name, teamView(team, opts));
|
|
605
|
+
return out;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const GOAL_STOP = new Set(
|
|
609
|
+
"a an the and or but of to in on for with by at from into onto is are was be been being it its this that these those as so not no we our you your they their can will should must all any each per via vs then than when where which who what how do does done make add use new".split(" "),
|
|
610
|
+
);
|
|
611
|
+
|
|
612
|
+
/** Lowercase word tokens of the given lines: one-letter words and the stopwords above are dropped. */
|
|
613
|
+
function goalTokens(lines: string[]): Set<string> {
|
|
614
|
+
const out = new Set<string>();
|
|
615
|
+
for (const t of lines.join(" ").toLowerCase().split(/[^a-z0-9]+/)) if (t.length > 1 && !GOAL_STOP.has(t)) out.add(t);
|
|
616
|
+
return out;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** The share of a title's tokens that the Goal also has: |G∩T| / |T|. */
|
|
620
|
+
function coverage(goal: Set<string>, title: Set<string>): number {
|
|
621
|
+
let shared = 0;
|
|
622
|
+
for (const t of title) if (goal.has(t)) shared++;
|
|
623
|
+
return shared / title.size;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** One same-goal hit: `item` names the plan, finished plan or MR; `score` is the overlap that blocked. */
|
|
627
|
+
export interface GoalOverlap {
|
|
628
|
+
item: string;
|
|
629
|
+
score: number;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* The same-goal check (plan P6b2 rule a), pure. A plan not yet complete is compared Goal to Goal
|
|
634
|
+
* (Jaccard >= 0.5); a finished plan and an open MR are compared Goal to title (|G∩T| / |T| >= 0.6,
|
|
635
|
+
* titles of 3+ tokens only). Only the first 6 Goal bullets count. The plan's own id is skipped.
|
|
636
|
+
*/
|
|
637
|
+
export function goalOverlaps(goal: string[], view: TeamView, mrs: { token: string; title: string }[], selfId: string | null): GoalOverlap[] {
|
|
638
|
+
const g = goalTokens(goal);
|
|
639
|
+
const out: GoalOverlap[] = [];
|
|
640
|
+
const titleHit = (title: string, item: string): void => {
|
|
641
|
+
const t = goalTokens([title]);
|
|
642
|
+
if (t.size < 3) return;
|
|
643
|
+
const score = coverage(g, t);
|
|
644
|
+
if (score >= 0.6) out.push({ item, score });
|
|
645
|
+
};
|
|
646
|
+
for (const p of view.plans) {
|
|
647
|
+
if (p.id === selfId) continue;
|
|
648
|
+
const plan = parsePlan(".", p.rel_path, p.text, undefined, [], false);
|
|
649
|
+
if (plan.status === "complete") {
|
|
650
|
+
titleHit(plan.title, `finished ${plan.title}`);
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
const score = jaccard(g, goalTokens(plan.goal));
|
|
654
|
+
if (score >= 0.5) out.push({ item: `plan ${p.rel_path}`, score });
|
|
655
|
+
}
|
|
656
|
+
for (const mr of mrs) titleHit(mr.title, `MR ${mr.token} ${mr.title}`);
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* `team share`'s same-goal gate: the team's view and the repo's open MRs, then goalOverlaps. A view
|
|
662
|
+
* the server did not answer, or an MR list that failed, refuses (`refused`): the check fails closed.
|
|
663
|
+
*/
|
|
664
|
+
export function sameGoalCheck(team: TeamEntry, cfg: Config, file: string, text: string, run: CommandRunner = defaultRunner, opts: RawOpts = {}): { overlaps: GoalOverlap[] } | { refused: string } {
|
|
665
|
+
const view = teamView(team, opts);
|
|
666
|
+
if ("unreachable" in view) return { refused: `team server ${team.server} unreachable` };
|
|
667
|
+
const repo = planRepo(file);
|
|
668
|
+
const mrs = listOpenMrs(repo, run);
|
|
669
|
+
if (!mrs.ok) return { refused: `open MRs of ${repo} not listed (${mrs.why})` };
|
|
670
|
+
const plan = parsePlan(repo, file, text, undefined, [], false);
|
|
671
|
+
return { overlaps: goalOverlaps(plan.goal, view, mrs.mrs, pathId(team, cfg, file, run)) };
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* The plans of one team's view in the server's order (`ORDER BY rel_path, id`), as every team
|
|
676
|
+
* section reads them. The text is the server's; the path is the record's, else the read copy.
|
|
677
|
+
* `parsePlan` runs with `localPaths` false: team text names paths on its author's machine, so no
|
|
678
|
+
* blocker is executed and no reuse citation is stat'ed. Worktree and appliesTo are blanked for
|
|
679
|
+
* the same reason — later code that stats or runs git on them must never see a team-chosen path.
|
|
680
|
+
*/
|
|
681
|
+
export function teamPlans(cfg: Config, team: TeamEntry, view: TeamView): TeamPlanRow[] {
|
|
682
|
+
const rec = readRecord(cfg, team);
|
|
683
|
+
const copyDir = path.join(teamDir(cfg, team), "plans");
|
|
684
|
+
return viewPlanRows({ ...view, plans: view.plans.filter(p => validId(p.id)) }, cfg.queue.claim_ttl_min, nowSec(), id => rec[id]?.path ?? path.join(copyDir, `${id}.md`));
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** A plan's sort key: [tier, value]. Tier 0 is the leader's override (value: its position); tier 1 a voted plan (value: its rank sum); tier 2 no vote. */
|
|
688
|
+
function planOrderKey(id: string, overridePos: Map<string, number>, scores: Map<string, number>): [number, number] {
|
|
689
|
+
const pos = overridePos.get(id);
|
|
690
|
+
if (pos !== undefined) return [0, pos];
|
|
691
|
+
const score = scores.get(id);
|
|
692
|
+
return score === undefined ? [2, 0] : [1, score];
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* The plan rows of one view, each parsed under the file `fileOf` names for it. The phone section
|
|
697
|
+
* (teamPlans) and the team page (P5) share this body. Reads no path and runs no git.
|
|
698
|
+
* Order: the leader's override first, in its order; then the voted plans by rank sum, lowest first
|
|
699
|
+
* (ranked 1 by one member and 2 by another scores 3); then the plans nobody voted on. Ties keep
|
|
700
|
+
* `rel_path, id`. `answered` is the server's first answer to the current WAITING question.
|
|
701
|
+
*/
|
|
702
|
+
export function viewPlanRows(view: TeamView, ttlMin: number, now: number, fileOf: (id: string) => string): TeamPlanRow[] {
|
|
703
|
+
const claims = new Map(view.claims.map(row => [row.plan, row] as const));
|
|
704
|
+
const approvals = new Map<string, string[]>();
|
|
705
|
+
for (const a of view.approvals) approvals.set(a.plan, [...(approvals.get(a.plan) ?? []), a.login]);
|
|
706
|
+
const answers = new Map<string, TeamView["answers"]>();
|
|
707
|
+
for (const a of view.answers) answers.set(a.plan, [...(answers.get(a.plan) ?? []), a]);
|
|
708
|
+
const answered = new Map(view.first.map(a => [a.plan, { login: a.login, time: a.time, answer: a.answer }] as const));
|
|
709
|
+
const overridePos = new Map((view.override?.plan_ids ?? []).map((id, i) => [id, i] as const));
|
|
710
|
+
const scores = new Map<string, number>();
|
|
711
|
+
for (const v of view.votes) scores.set(v.plan_id, (scores.get(v.plan_id) ?? 0) + v.rank);
|
|
712
|
+
const ordered = view.plans.toSorted((a, b) => {
|
|
713
|
+
const [tierA, valueA] = planOrderKey(a.id, overridePos, scores);
|
|
714
|
+
const [tierB, valueB] = planOrderKey(b.id, overridePos, scores);
|
|
715
|
+
if (tierA !== tierB) return tierA - tierB;
|
|
716
|
+
if (valueA !== valueB) return valueA - valueB;
|
|
717
|
+
if (a.rel_path !== b.rel_path) return a.rel_path < b.rel_path ? -1 : 1;
|
|
718
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
719
|
+
});
|
|
720
|
+
return ordered.map(row => {
|
|
721
|
+
const file = fileOf(row.id);
|
|
722
|
+
const claim = claims.get(row.id);
|
|
723
|
+
const live = claim !== undefined && !claimExpired(claim, now, ttlMin) ? { ...toClaim(claim, file), login: claim.login } : null;
|
|
724
|
+
return {
|
|
725
|
+
id: row.id,
|
|
726
|
+
file,
|
|
727
|
+
plan: { ...parsePlan(path.dirname(file), file, row.text, undefined, [], false), worktree: null, appliesTo: [] },
|
|
728
|
+
relPath: row.rel_path,
|
|
729
|
+
holder: live,
|
|
730
|
+
approvals: approvals.get(row.id) ?? [],
|
|
731
|
+
answers: answers.get(row.id) ?? [],
|
|
732
|
+
answered: answered.get(row.id) ?? null,
|
|
733
|
+
};
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* The team half of the queue summary and `main-start`: per team one line, then up to `cap`
|
|
739
|
+
* plans in queueSummary's line form — rel_path, the holder with its login, the WAITING ask, the
|
|
740
|
+
* approvals, the first Goal bullet. A team whose view is Unreachable prints one line and no
|
|
741
|
+
* plans. Sends nothing: the caller built `views` once.
|
|
742
|
+
*/
|
|
743
|
+
export function teamSummaryLines(cfg: Config, views: Map<string, TeamView | Unreachable>, cap = SUMMARY_CAP): string[] {
|
|
744
|
+
const lines: string[] = [];
|
|
745
|
+
for (const team of cfg.teams) {
|
|
746
|
+
const view = views.get(team.name);
|
|
747
|
+
if (view === undefined || "unreachable" in view) {
|
|
748
|
+
lines.push(`Team ${team.name}: team server ${team.server} unreachable`);
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
const rows = teamPlans(cfg, team, view);
|
|
752
|
+
lines.push(`Team ${team.name}: ${rows.length} plan(s)`);
|
|
753
|
+
rows.slice(0, cap).forEach((row, i) => {
|
|
754
|
+
const flags = [
|
|
755
|
+
row.holder ? `held by ${row.holder.main} (${row.holder.login}) since ${strftime(row.holder.since, "%H:%M")}` : "free",
|
|
756
|
+
row.plan.waiting ? `WAITING on owner: ${(row.plan.waitingLine ?? "").slice(0, 80)}` : "",
|
|
757
|
+
row.approvals.length ? `approved by ${row.approvals.join(", ")}` : "",
|
|
758
|
+
]
|
|
759
|
+
.filter(Boolean)
|
|
760
|
+
.join(", ");
|
|
761
|
+
lines.push(` T${i + 1}. ${row.relPath} [${flags}] ${(row.plan.goal[0] ?? "").slice(0, 100)}`);
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
return lines;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** An answer to a WAITING question: the first one to it (a plan's `answered`), or the earlier one a later answer lost to. */
|
|
768
|
+
export interface TeamEarlier {
|
|
769
|
+
login: string;
|
|
770
|
+
time: number;
|
|
771
|
+
answer: string;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** What `POST /answer/<id>` answered: stored (with the earlier answer to the same question, when one won), the server's refusal, or a team that did not answer. */
|
|
775
|
+
export type TeamAnswerOutcome = { ok: true; earlier: TeamEarlier | null } | { ok: false; status: number; error: string } | Unreachable;
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* One member's answer to a team plan's WAITING line: `POST /answer/<id>` with `{ answer }` only.
|
|
779
|
+
* The body carries no login — the server stores the whois login. Built as pushTeamPlan builds
|
|
780
|
+
* its write (content-type and Origin), with the id percent-encoded like every other route id.
|
|
781
|
+
*/
|
|
782
|
+
export function postTeamAnswer(team: TeamEntry, id: string, answer: string, opts: RawOpts = {}): TeamAnswerOutcome {
|
|
783
|
+
const res = askRaw(
|
|
784
|
+
team,
|
|
785
|
+
{ url: `${team.server}/answer/${encodeURIComponent(id)}`, method: "POST", headers: { "content-type": "application/json", origin: originOf(team.server) }, body: JSON.stringify({ answer }) },
|
|
786
|
+
opts,
|
|
787
|
+
);
|
|
788
|
+
if (res === "down" || res.status === undefined) return { unreachable: team.server };
|
|
789
|
+
if (res.status === 200) {
|
|
790
|
+
const e = isObj(res.body) ? res.body.earlier : null;
|
|
791
|
+
const earlier = isObj(e) && typeof e.login === "string" && typeof e.time === "number" && typeof e.answer === "string" ? { login: e.login, time: e.time, answer: e.answer } : null;
|
|
792
|
+
return { ok: true, earlier };
|
|
793
|
+
}
|
|
794
|
+
return { ok: false, status: res.status, error: isObj(res.body) && typeof res.body.error === "string" ? res.body.error : `team server answered ${res.status}` };
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** `team pause|resume`: the server's POST /pause or /resume for this login. Ok only on a 200; any other answer carries the server's error text. */
|
|
798
|
+
export function postTeamPause(team: TeamEntry, paused: boolean, opts: RawOpts = {}): { ok: true } | { ok: false; error: string } {
|
|
799
|
+
const res = askRaw(team, { url: `${team.server}/${paused ? "pause" : "resume"}`, method: "POST", headers: { "content-type": "application/json", origin: originOf(team.server) }, body: "{}" }, opts);
|
|
800
|
+
if (res === "down" || res.status === undefined) return { ok: false, error: `team server ${team.server} unreachable` };
|
|
801
|
+
if (res.status === 200) return { ok: true };
|
|
802
|
+
return { ok: false, error: isObj(res.body) && typeof res.body.error === "string" ? res.body.error : `team server answered ${res.status}` };
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** `team pause` releases this Main's own claims by plan id, so a plan with no local copy is released too. Void on any answer, as the store's release is. */
|
|
806
|
+
export function releaseTeamClaim(team: TeamEntry, id: string, main: string, opts: RawOpts = {}): void {
|
|
807
|
+
askRaw(team, { url: `${team.server}/claims/${encodeURIComponent(id)}`, method: "DELETE", headers: { "content-type": "application/json", origin: originOf(team.server) }, body: JSON.stringify({ main }) }, opts);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** This machine's file for a plan as the sync record names it; undefined when the record has no entry for the id. */
|
|
811
|
+
export function recordPath(cfg: Config, team: TeamEntry, id: string): string | undefined {
|
|
812
|
+
return readRecord(cfg, team)[id]?.path;
|
|
813
|
+
}
|