neurastream 0.3.20 → 0.3.21
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/package.json +1 -1
- package/src/adapters/index.ts +3 -2
- package/src/adapters/omp/adapter.ts +2 -1
- package/src/adapters/omp/auto-close.ts +64 -0
- package/src/adapters/omp/chat-commands.ts +161 -0
- package/src/adapters/omp/inbox.ts +221 -0
- package/src/adapters/omp/index.ts +115 -1039
- package/src/adapters/omp/launch.ts +31 -3
- package/src/adapters/omp/rate-limit-controller.ts +196 -0
- package/src/adapters/omp/rollover-controller.ts +334 -0
- package/src/adapters/omp/types.ts +143 -0
- package/src/cli/commands.ts +33 -2
- package/src/cli/dispatch.ts +37 -16
- package/src/cli/recall.ts +3 -2
- package/src/cli/results-build.ts +1 -1
- package/src/cli/workspace.ts +13 -2
- package/src/core/adapter.ts +16 -0
- package/src/core/blockers.ts +326 -30
- package/src/core/file-lock.ts +71 -12
- package/src/core/guards/plan-edit.ts +338 -0
- package/src/core/guards/planner.ts +70 -0
- package/src/core/guards/review.ts +391 -0
- package/src/core/guards/spawn.ts +699 -0
- package/src/core/guards/state.ts +581 -0
- package/src/core/guards/stop.ts +235 -0
- package/src/core/guards/tool.ts +541 -0
- package/src/core/guards.ts +12 -2658
- package/src/core/incidents.ts +125 -91
- package/src/core/machine-guard.ts +23 -5
- package/src/core/main-start.ts +10 -8
- package/src/core/owner-topics.ts +2 -13
- package/src/core/owner-ui/auth.ts +164 -0
- package/src/core/owner-ui/data.ts +437 -0
- package/src/core/owner-ui/handlers.ts +250 -0
- package/src/core/owner-ui/messages.ts +209 -0
- package/src/core/owner-ui/render.ts +714 -0
- package/src/core/owner-ui/results.ts +266 -0
- package/src/core/owner-ui/server.ts +142 -0
- package/src/core/owner-ui.ts +11 -2121
- package/src/core/page-notes.ts +25 -0
- package/src/core/pages.ts +452 -77
- package/src/core/plan-approval.ts +12 -14
- package/src/core/queue/lib.ts +88 -39
- package/src/core/queue-cancel.ts +21 -17
- package/src/core/queue-close.ts +48 -23
- package/src/core/secret-redact.ts +65 -14
- package/src/core/tailscale.ts +79 -3
- package/src/core/team-client.ts +13 -2
- package/src/core/uninstall.ts +2 -0
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
// Page data builders: one pure typed-row builder per source; rendering reads only these.
|
|
2
|
+
|
|
3
|
+
import { readFileSync, statfsSync, statSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import { basename } from "node:path";
|
|
6
|
+
import type { RunSource } from "../adapter.ts";
|
|
7
|
+
import type { Unreachable } from "../claims.ts";
|
|
8
|
+
import { nowSec } from "../clock.ts";
|
|
9
|
+
import type { Config } from "../config.ts";
|
|
10
|
+
import { cpuCount } from "../host.ts";
|
|
11
|
+
import { isFindingKind, openIncidents } from "../incidents.ts";
|
|
12
|
+
import { knowledgeManifest, urlValue, type KnowledgeEntry } from "../knowledge.ts";
|
|
13
|
+
import { readMetricEvents } from "../metrics.ts";
|
|
14
|
+
import { publishedPages } from "../pages-expiry.ts";
|
|
15
|
+
import { activePlans, expandHome, type Plan, type QueuePaths } from "../queue/lib.ts";
|
|
16
|
+
import { summaryHolder, teamPlans, teamViews, type TeamPlanRow, type TeamView } from "../team-client.ts";
|
|
17
|
+
import { recheckHolds, staleFiles, type HoldRunner } from "../waiting-check.ts";
|
|
18
|
+
import { inboxPath, recentOwnerMessages, type MessageRow } from "./messages.ts";
|
|
19
|
+
import { noopResultsBuild, resultsView, type ResultsBuild, type ResultsView } from "./results.ts";
|
|
20
|
+
|
|
21
|
+
export interface QuestionRow {
|
|
22
|
+
plan: string;
|
|
23
|
+
title: string;
|
|
24
|
+
repo: string;
|
|
25
|
+
waitingLine: string;
|
|
26
|
+
/** What to do, from the WAITING line. */
|
|
27
|
+
waitingAsk: string;
|
|
28
|
+
/** What stays stuck until then, or null. */
|
|
29
|
+
waitingBlocked: string | null;
|
|
30
|
+
/** Why Main cannot do it, or null. */
|
|
31
|
+
waitingWhy: string | null;
|
|
32
|
+
/** Titles of other open plans whose Waits on names this plan. */
|
|
33
|
+
unblocks: string[];
|
|
34
|
+
goal: string[];
|
|
35
|
+
waitingMin: number;
|
|
36
|
+
/** The last answer this plan already got (from the owner inbox, so the card can say so; for a team plan, the newest server answer). */
|
|
37
|
+
answered: { answer: string; at: number; login?: string } | null;
|
|
38
|
+
/** The team this card belongs to; `plan` is then the server plan id, not a local path (P4). */
|
|
39
|
+
team?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The newest inbox record that carries an answer for this plan, if any. A missing or torn inbox is simply "no answer". */
|
|
43
|
+
function lastAnswerFor(plan: string, paths: Pick<QueuePaths, "queue_state">): { answer: string; at: number } | null {
|
|
44
|
+
let lines: string[];
|
|
45
|
+
try {
|
|
46
|
+
lines = readFileSync(inboxPath(paths), "utf8").split("\n");
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
51
|
+
const line = lines[i]!.trim();
|
|
52
|
+
if (!line) continue;
|
|
53
|
+
try {
|
|
54
|
+
const rec = JSON.parse(line) as Record<string, unknown>;
|
|
55
|
+
if (rec.plan === plan && typeof rec.answer === "string" && rec.answer) return { answer: rec.answer, at: Number(rec.ts) || 0 };
|
|
56
|
+
} catch {}
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface AgentRow {
|
|
62
|
+
id: string;
|
|
63
|
+
model: string;
|
|
64
|
+
detail: string;
|
|
65
|
+
minutes: number;
|
|
66
|
+
status: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface QueueRow {
|
|
70
|
+
repo: string;
|
|
71
|
+
file: string;
|
|
72
|
+
title: string;
|
|
73
|
+
status: string;
|
|
74
|
+
waiting: boolean;
|
|
75
|
+
/** `Summary:` header, else the first Goal bullet with a leading Owner/INCIDENT prefix cut off. */
|
|
76
|
+
summary: string | null;
|
|
77
|
+
/** The Main id holding this plan's claim, else null (P5 multi-main). */
|
|
78
|
+
holder: string | null;
|
|
79
|
+
/** Chip text: waits you, waits on a plan, not started, phase K of N, or all N done. */
|
|
80
|
+
state: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface CiRow {
|
|
84
|
+
mr: string;
|
|
85
|
+
tries: number;
|
|
86
|
+
ts: number;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface IncidentRow {
|
|
90
|
+
id: string;
|
|
91
|
+
kind: string;
|
|
92
|
+
summary: string;
|
|
93
|
+
count: number;
|
|
94
|
+
/** Main's latest written reason for a finding incident; null when none or not a finding. */
|
|
95
|
+
proposal: string | null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** A markdown table from the ranking board plus every non-table line, kept in order. */
|
|
99
|
+
export interface ScoresData {
|
|
100
|
+
header: string[];
|
|
101
|
+
rows: string[][];
|
|
102
|
+
text: string[];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface MachineRow {
|
|
106
|
+
freeGb: number;
|
|
107
|
+
diskMin: number;
|
|
108
|
+
load: number;
|
|
109
|
+
loadMax: number;
|
|
110
|
+
cores: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function questionRows(cfg: Config, run?: HoldRunner): QuestionRow[] {
|
|
114
|
+
const now = Date.now();
|
|
115
|
+
const plans = activePlans(cfg.paths);
|
|
116
|
+
const stale = staleFiles(recheckHolds(cfg, plans, run));
|
|
117
|
+
return plans
|
|
118
|
+
.filter(p => p.waiting && p.status === "open" && p.waitingLine && !stale.has(p.file))
|
|
119
|
+
.map(p => {
|
|
120
|
+
let waitingMin = 0;
|
|
121
|
+
try {
|
|
122
|
+
waitingMin = Math.max(0, Math.round((now - statSync(p.file).mtimeMs) / 60_000));
|
|
123
|
+
} catch {}
|
|
124
|
+
return {
|
|
125
|
+
plan: p.file,
|
|
126
|
+
title: p.title,
|
|
127
|
+
repo: basename(p.repo),
|
|
128
|
+
waitingLine: p.waitingLine ?? "",
|
|
129
|
+
waitingAsk: p.waitingAsk ?? p.waitingLine ?? "",
|
|
130
|
+
waitingBlocked: p.waitingBlocked,
|
|
131
|
+
waitingWhy: p.waitingWhy,
|
|
132
|
+
unblocks: plans.filter(o => o.status === "open" && o.file !== p.file && o.waitsOn.includes(p.file)).map(o => o.title),
|
|
133
|
+
goal: p.goal,
|
|
134
|
+
waitingMin,
|
|
135
|
+
answered: lastAnswerFor(p.file, cfg.paths),
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function agentRows(cfg: Config, source: RunSource): AgentRow[] {
|
|
141
|
+
const cut = nowSec() - cfg.ledger.default_hours * 3600;
|
|
142
|
+
return source
|
|
143
|
+
.listRuns(cut)
|
|
144
|
+
.filter(r => r.status === "running" || r.status === "waiting")
|
|
145
|
+
.map(r => ({
|
|
146
|
+
id: r.id,
|
|
147
|
+
model: r.model.slice(r.model.lastIndexOf("/") + 1),
|
|
148
|
+
detail: r.statusDetail,
|
|
149
|
+
minutes: r.startedAt === null ? 0 : Math.max(0, Math.round((nowSec() - r.startedAt) / 60)),
|
|
150
|
+
status: r.status,
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Cut a leading `Owner (…):` or `INCIDENT <id>` prefix off a Goal bullet used as the card line. */
|
|
155
|
+
function goalSummary(line: string): string {
|
|
156
|
+
let s = line.trim();
|
|
157
|
+
for (;;) {
|
|
158
|
+
const next = s.replace(/^Owner\s*\([^)]*\):\s*/, "").replace(/^INCIDENT\s+\S+\.?\s*/, "").trim();
|
|
159
|
+
if (next === s) return s;
|
|
160
|
+
s = next;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function queueState(p: Plan, plans: Plan[]): string {
|
|
165
|
+
if (p.waiting) return "waits you";
|
|
166
|
+
const target = p.waitsOn[0];
|
|
167
|
+
if (target) {
|
|
168
|
+
const title = plans.find(w => w.file === target)?.title ?? target.split("/").pop()?.replace(/\.md$/, "") ?? target;
|
|
169
|
+
return `waits on ${title}`;
|
|
170
|
+
}
|
|
171
|
+
const { done, total } = p.phases;
|
|
172
|
+
if (done === total && total > 0) return `all ${total} done · checking`;
|
|
173
|
+
if (!p.started) return `not started · 0/${total}`;
|
|
174
|
+
return `phase ${Math.min(done + 1, total)} of ${total}`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function queueRows(cfg: Config, views?: Map<string, TeamView | Unreachable>): QueueRow[] {
|
|
178
|
+
const plans = activePlans(cfg.paths).filter(p => p.status === "open");
|
|
179
|
+
const claims = summaryHolder(cfg, {}, views);
|
|
180
|
+
return plans.map(p => {
|
|
181
|
+
const holder = claims.holder(p.file);
|
|
182
|
+
return {
|
|
183
|
+
repo: basename(p.repo),
|
|
184
|
+
file: p.file,
|
|
185
|
+
title: p.title,
|
|
186
|
+
status: p.status ?? "?",
|
|
187
|
+
waiting: p.waiting,
|
|
188
|
+
summary: p.summary ?? (goalSummary(p.goal[0] ?? "") || null),
|
|
189
|
+
state: queueState(p, plans),
|
|
190
|
+
holder: holder === null ? null : "unreachable" in holder ? "team server unreachable" : holder.main,
|
|
191
|
+
};
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** One team's card on the phone page: its plans as queue rows and its open WAITING lines. */
|
|
196
|
+
export interface TeamSection {
|
|
197
|
+
name: string;
|
|
198
|
+
server: string;
|
|
199
|
+
/** False when the team server did not answer: the card says so instead of listing plans. */
|
|
200
|
+
reachable: boolean;
|
|
201
|
+
rows: QueueRow[];
|
|
202
|
+
questions: QuestionRow[];
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The team half of the phone page (P4): each team's already-read view mapped to the page's own
|
|
207
|
+
* row types, so the render stays one shape. A plan is a QueueRow whose `file` is the server id
|
|
208
|
+
* (team order is not INDEX order, so no drag and no /reorder) and whose state is queueState over
|
|
209
|
+
* the team's own parsed plans; each open plan with a WAITING line is a QuestionRow whose newest
|
|
210
|
+
* server answer fills `answered`. Sends nothing.
|
|
211
|
+
*/
|
|
212
|
+
export function teamSections(cfg: Config, views: Map<string, TeamView | Unreachable>): TeamSection[] {
|
|
213
|
+
return cfg.teams.map(team => {
|
|
214
|
+
const view = views.get(team.name);
|
|
215
|
+
if (view === undefined || "unreachable" in view) return { name: team.name, server: team.server, reachable: false, rows: [], questions: [] };
|
|
216
|
+
return teamSection(team.name, team.server, teamPlans(cfg, team, view));
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** One reachable team's card from its parsed plans: the phone page and the team page both build it here. */
|
|
221
|
+
export function teamSection(name: string, server: string, plans: TeamPlanRow[]): TeamSection {
|
|
222
|
+
const parsed = plans.map(p => p.plan);
|
|
223
|
+
const rows: QueueRow[] = plans.map(p => ({
|
|
224
|
+
repo: p.relPath,
|
|
225
|
+
file: p.id,
|
|
226
|
+
title: p.plan.title,
|
|
227
|
+
status: p.plan.status ?? "?",
|
|
228
|
+
waiting: p.plan.waiting,
|
|
229
|
+
summary: p.plan.summary ?? (goalSummary(p.plan.goal[0] ?? "") || null),
|
|
230
|
+
holder: p.holder ? `${p.holder.main} (${p.holder.login})` : null,
|
|
231
|
+
state: queueState(p.plan, parsed),
|
|
232
|
+
}));
|
|
233
|
+
const questions: QuestionRow[] = plans
|
|
234
|
+
.filter(p => p.plan.status === "open" && p.plan.waiting && p.plan.waitingLine)
|
|
235
|
+
.map(p => {
|
|
236
|
+
const first = p.answered;
|
|
237
|
+
return {
|
|
238
|
+
plan: p.id,
|
|
239
|
+
team: name,
|
|
240
|
+
title: p.plan.title,
|
|
241
|
+
repo: p.relPath,
|
|
242
|
+
waitingLine: p.plan.waitingLine ?? "",
|
|
243
|
+
waitingAsk: p.plan.waitingAsk ?? p.plan.waitingLine ?? "",
|
|
244
|
+
waitingBlocked: p.plan.waitingBlocked,
|
|
245
|
+
waitingWhy: p.plan.waitingWhy,
|
|
246
|
+
unblocks: [],
|
|
247
|
+
goal: p.plan.goal,
|
|
248
|
+
waitingMin: 0,
|
|
249
|
+
answered: first ? { answer: first.answer, at: first.time, login: first.login } : null,
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
return { name, server, reachable: true, rows, questions };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function ciRows(cfg: Config): CiRow[] {
|
|
256
|
+
return readMetricEvents(cfg)
|
|
257
|
+
.filter(e => e.type === "ci")
|
|
258
|
+
.slice(-10)
|
|
259
|
+
.reverse()
|
|
260
|
+
.map(e => ({ mr: String(e.mr), tries: Number(e.tries), ts: Number(e.ts) }));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function incidentRows(cfg: Config): IncidentRow[] {
|
|
264
|
+
return openIncidents(cfg).map(i => ({
|
|
265
|
+
id: i.id,
|
|
266
|
+
kind: i.kind,
|
|
267
|
+
summary: i.summary,
|
|
268
|
+
count: i.count,
|
|
269
|
+
proposal: isFindingKind(i.kind) ? (i.proposal?.why ?? null) : null,
|
|
270
|
+
}));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function scoresData(cfg: Config): ScoresData {
|
|
274
|
+
const out: ScoresData = { header: [], rows: [], text: [] };
|
|
275
|
+
for (const raw of readFileSync(cfg.paths.ranking_board, "utf8").split("\n")) {
|
|
276
|
+
const line = raw.trim();
|
|
277
|
+
if (line.startsWith("|") && line.endsWith("|")) {
|
|
278
|
+
const cells = line.slice(1, -1).split("|").map(c => c.trim());
|
|
279
|
+
if (cells.every(c => /^:?-{2,}:?$/.test(c))) continue;
|
|
280
|
+
if (!out.header.length) out.header = cells;
|
|
281
|
+
else out.rows.push(cells);
|
|
282
|
+
} else if (line) {
|
|
283
|
+
out.text.push(line);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return out;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function machineRow(cfg: Config): MachineRow {
|
|
290
|
+
const st = statfsSync(expandHome(cfg.machine.disk_path));
|
|
291
|
+
const freeGb = (Number(st.bavail) * Number(st.bsize)) / 1e9;
|
|
292
|
+
const load = os.loadavg()[0] ?? 0;
|
|
293
|
+
const cores = cpuCount();
|
|
294
|
+
const loadMax = cfg.machine.load_max > 0 ? cfg.machine.load_max : cores + cfg.machine.load_over_cores;
|
|
295
|
+
return { freeGb, diskMin: cfg.machine.disk_min_gb, load, loadMax, cores };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The numbers behind the top tiles: everything in the last 24 h plus the open-plan count. */
|
|
299
|
+
export interface NowStats {
|
|
300
|
+
/** Total list-price spend over the last 24 h. */
|
|
301
|
+
spend24: number;
|
|
302
|
+
/** The "main" kind's share of spend24. */
|
|
303
|
+
mainSpend: number;
|
|
304
|
+
/** The "sub" kind's share of spend24. */
|
|
305
|
+
agentSpend: number;
|
|
306
|
+
/** Runs seen in the last 24 h. */
|
|
307
|
+
runs24: number;
|
|
308
|
+
/** Of those, the ones still running. */
|
|
309
|
+
running: number;
|
|
310
|
+
/** Of those, the ones that died. */
|
|
311
|
+
died: number;
|
|
312
|
+
/** Spend per hour over the last 24 h: 24 buckets, oldest → newest. */
|
|
313
|
+
spendByHour: number[];
|
|
314
|
+
/** Runs started per hour over the last 24 h: 24 buckets, oldest → newest. */
|
|
315
|
+
runsByHour: number[];
|
|
316
|
+
/** Spend and run count per short model name (after the last /), costliest first. */
|
|
317
|
+
byModel: { model: string; spend: number; runs: number }[];
|
|
318
|
+
/** Open plans in INDEX.md. */
|
|
319
|
+
openPlans: number;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Pure tile math over `source.listRuns(now - 86400)`: a run is in the window when its
|
|
324
|
+
* bucket time — `startedAt`, else `lastWriteAt` — is newer than exactly 24 h ago, and it
|
|
325
|
+
* counts in the hourly bucket of that time. The run source pre-filters by its own mtime,
|
|
326
|
+
* so the strict window check here is the one rule that decides.
|
|
327
|
+
*/
|
|
328
|
+
export function nowStats(cfg: Config, source: RunSource, now: number): NowStats {
|
|
329
|
+
const cut = now - 86400;
|
|
330
|
+
const spendByHour = Array.from({ length: 24 }, () => 0);
|
|
331
|
+
const runsByHour = Array.from({ length: 24 }, () => 0);
|
|
332
|
+
const models = new Map<string, { spend: number; runs: number }>();
|
|
333
|
+
let spend24 = 0;
|
|
334
|
+
let mainSpend = 0;
|
|
335
|
+
let agentSpend = 0;
|
|
336
|
+
let runs24 = 0;
|
|
337
|
+
let running = 0;
|
|
338
|
+
let died = 0;
|
|
339
|
+
for (const r of source.listRuns(cut)) {
|
|
340
|
+
const ts = r.startedAt ?? r.lastWriteAt;
|
|
341
|
+
if (ts <= cut) continue;
|
|
342
|
+
spend24 += r.cost;
|
|
343
|
+
runs24++;
|
|
344
|
+
if (r.kind === "main") mainSpend += r.cost;
|
|
345
|
+
else agentSpend += r.cost;
|
|
346
|
+
if (r.status === "running") running++;
|
|
347
|
+
if (r.status === "died") died++;
|
|
348
|
+
// A future clock (skew) clamps into the newest bucket, never out of the array.
|
|
349
|
+
const hoursAgo = Math.min(23, Math.max(0, Math.floor((now - ts) / 3600)));
|
|
350
|
+
const at = 23 - hoursAgo;
|
|
351
|
+
spendByHour[at]! += r.cost;
|
|
352
|
+
runsByHour[at]! += 1;
|
|
353
|
+
const short = r.model.slice(r.model.lastIndexOf("/") + 1);
|
|
354
|
+
const m = models.get(short) ?? { spend: 0, runs: 0 };
|
|
355
|
+
m.spend += r.cost;
|
|
356
|
+
m.runs += 1;
|
|
357
|
+
models.set(short, m);
|
|
358
|
+
}
|
|
359
|
+
const byModel = [...models.entries()].map(([model, v]) => ({ model, spend: v.spend, runs: v.runs })).sort((a, b) => b.spend - a.spend);
|
|
360
|
+
// The tile counts the open plans the queue card renders; a holder read here would ask every
|
|
361
|
+
// team server a second time on a page that already read one view per team (P4).
|
|
362
|
+
return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: activePlans(cfg.paths).filter(p => p.status === "open").length };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// ---- page assembly: one unreadable source never takes the page down ----
|
|
366
|
+
|
|
367
|
+
/** One published page row for the Base tab: the pages-server link is built once, at data build. */
|
|
368
|
+
export interface PublishedPageRow { name: string; repo: string; published: string; url: string }
|
|
369
|
+
|
|
370
|
+
export interface PageData {
|
|
371
|
+
questions: QuestionRow[] | null;
|
|
372
|
+
agents: AgentRow[] | null;
|
|
373
|
+
queue: QueueRow[] | null;
|
|
374
|
+
ci: CiRow[] | null;
|
|
375
|
+
incidents: IncidentRow[] | null;
|
|
376
|
+
scores: ScoresData | null;
|
|
377
|
+
machine: MachineRow | null;
|
|
378
|
+
/** Repo-local HTML explainers from the knowledge manifest; null when unreadable. */
|
|
379
|
+
knowledge: KnowledgeEntry[] | null;
|
|
380
|
+
/** Published pages (plan 20261029_1436 P2), newest first, with their pages-server URL; null when unreadable. */
|
|
381
|
+
pages: PublishedPageRow[] | null;
|
|
382
|
+
/** The 24 h tile numbers; null when the run source is unreadable. */
|
|
383
|
+
stats: NowStats | null;
|
|
384
|
+
/** Each team's card, built from one already-read view per team (P4); absent or null when the views could not be read. */
|
|
385
|
+
teams?: TeamSection[] | null;
|
|
386
|
+
/** The Results tab's saved numbers and build state; absent on every other tab. The numbers come from a background process (computeResults), never from the request. */
|
|
387
|
+
results?: ResultsView | null;
|
|
388
|
+
/** The owner's messages newer than the keep window, newest first; null when unreadable. */
|
|
389
|
+
messages: MessageRow[] | null;
|
|
390
|
+
/** Minutes left in the guard unlock; null = locked. */
|
|
391
|
+
lockMinutesLeft: number | null;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function safe<T>(build: () => T): T | null {
|
|
395
|
+
try {
|
|
396
|
+
return build();
|
|
397
|
+
} catch {
|
|
398
|
+
// One unreadable source must never take the page down.
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function publishedRows(cfg: Config, host: string): PublishedPageRow[] {
|
|
404
|
+
return publishedPages(cfg.pages.dir, new Date()).map(p => ({ ...p, url: `http://${host}:${cfg.pages.port}/${urlValue(p.name)}` }));
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function lockMinutesLeft(cfg: Config): number | null {
|
|
408
|
+
try {
|
|
409
|
+
const end = statSync(cfg.paths.unlock).mtimeMs + cfg.guards.unlock_minutes * 60_000;
|
|
410
|
+
const left = Math.round((end - Date.now()) / 60_000);
|
|
411
|
+
return left > 0 ? left : null;
|
|
412
|
+
} catch {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = noopResultsBuild, pagesHost = "tailnet"): PageData {
|
|
418
|
+
// P4: one GET /view per team, read once and handed to the queue rows' holder and the team
|
|
419
|
+
// cards, so a render makes no second request per team.
|
|
420
|
+
const views = safe(() => teamViews(cfg));
|
|
421
|
+
return {
|
|
422
|
+
questions: safe(() => questionRows(cfg)),
|
|
423
|
+
agents: safe(() => agentRows(cfg, source)),
|
|
424
|
+
queue: safe(() => queueRows(cfg, views ?? undefined)),
|
|
425
|
+
ci: safe(() => ciRows(cfg)),
|
|
426
|
+
incidents: safe(() => incidentRows(cfg)),
|
|
427
|
+
scores: safe(() => scoresData(cfg)),
|
|
428
|
+
machine: safe(() => machineRow(cfg)),
|
|
429
|
+
knowledge: safe(() => knowledgeManifest(cfg)),
|
|
430
|
+
pages: safe(() => publishedRows(cfg, pagesHost)),
|
|
431
|
+
stats: safe(() => nowStats(cfg, source, nowSec())),
|
|
432
|
+
teams: views === null ? null : safe(() => teamSections(cfg, views)),
|
|
433
|
+
results: tab === "results" ? safe(() => resultsView(nowSec(), build, cfg.paths)) : undefined,
|
|
434
|
+
messages: safe(() => recentOwnerMessages(nowSec(), cfg.paths)),
|
|
435
|
+
lockMinutesLeft: lockMinutesLeft(cfg),
|
|
436
|
+
};
|
|
437
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// Owner UI POST action handlers: answer, team answer, incident, unlock, lock, tier, and queue reorder.
|
|
2
|
+
|
|
3
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import type { RunSource } from "../adapter.ts";
|
|
6
|
+
import { chatTier, type Tier } from "../autonomy.ts";
|
|
7
|
+
import { nowSec, strftime } from "../clock.ts";
|
|
8
|
+
import type { Config } from "../config.ts";
|
|
9
|
+
import { dismissIncident, isFindingKind, openIncidents } from "../incidents.ts";
|
|
10
|
+
import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, updateIndex, type Plan, type QueuePaths } from "../queue/lib.ts";
|
|
11
|
+
import { postTeamAnswer, type TeamEarlier } from "../team-client.ts";
|
|
12
|
+
import { ANSWER_MAX, jsonFail, jsonSent, receiptText, redirect, sentTo, textRes } from "./auth.ts";
|
|
13
|
+
import { inboxPath, storeOwnerMessage } from "./messages.ts";
|
|
14
|
+
import { pageRes } from "./render.ts";
|
|
15
|
+
|
|
16
|
+
/** The last answer appended per plan, for the double-press guard (P8c): memory only, no file. */
|
|
17
|
+
const lastAnswerByPlan = new Map<string, { answer: string; ts: number }>();
|
|
18
|
+
const DOUBLE_PRESS_SEC = 10;
|
|
19
|
+
|
|
20
|
+
/** Clears per-server answer deduplication memory when a fresh UI server starts. */
|
|
21
|
+
export function clearAnswerDedupe(): void {
|
|
22
|
+
lastAnswerByPlan.clear();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Appends the answer to the owner inbox unless this plan got the same trimmed answer in the last 10 s (P8c). */
|
|
26
|
+
function appendAnswer(plan: string, question: string, answer: string, login: string, paths: Pick<QueuePaths, "queue_state">): void {
|
|
27
|
+
const now = nowSec();
|
|
28
|
+
const last = lastAnswerByPlan.get(plan);
|
|
29
|
+
if (last !== undefined && last.answer === answer && now - last.ts < DOUBLE_PRESS_SEC) return;
|
|
30
|
+
mkdirSync(paths.queue_state, { recursive: true });
|
|
31
|
+
appendFileSync(inboxPath(paths), `${JSON.stringify({ ts: now, plan, question, answer, login })}\n`);
|
|
32
|
+
lastAnswerByPlan.set(plan, { answer, ts: now });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string, wantsJson: boolean, pagesHost: string): Response {
|
|
36
|
+
const planFile = (fields.plan ?? "").trim();
|
|
37
|
+
const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
|
|
38
|
+
if (!planFile || !answer) return wantsJson ? jsonFail("plan and answer are required", 400) : textRes("plan and answer are required", 400);
|
|
39
|
+
if (answer.length > ANSWER_MAX) return wantsJson ? jsonFail(`answer is longer than ${ANSWER_MAX} chars`, 400) : textRes(`answer is longer than ${ANSWER_MAX} chars`, 400);
|
|
40
|
+
// P4: a team plan is answered on its server, never in this machine's inbox; the branch sits
|
|
41
|
+
// before the INDEX lookup, which knows only this machine's own plans.
|
|
42
|
+
if ((fields.team ?? "").trim()) return handleTeamAnswer(cfg, fields, planFile, answer, wantsJson);
|
|
43
|
+
const plan = activePlans(cfg.paths).find(p => p.file === planFile);
|
|
44
|
+
if (!plan) return wantsJson ? jsonFail("plan is not open and waiting", 409) : textRes("plan is not open and waiting", 409);
|
|
45
|
+
if (plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
|
|
46
|
+
// Stale answer (P8b): Main cleared the question before the answer arrived; pass it on anyway.
|
|
47
|
+
appendAnswer(planFile, "(already cleared)", answer, login, cfg.paths);
|
|
48
|
+
if (wantsJson) return jsonSent("stale", receiptText("stale", new URLSearchParams()));
|
|
49
|
+
return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }), undefined, pagesHost);
|
|
50
|
+
}
|
|
51
|
+
appendAnswer(planFile, plan.waitingLine, answer, login, cfg.paths);
|
|
52
|
+
if (wantsJson) return jsonSent("answer", receiptText("answer", new URLSearchParams()));
|
|
53
|
+
return redirect(sentTo(fields.tab ?? "", "sent=answer"));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* An answer to a team plan (P4): `POST /answer/<id>` on that team's server with the answer
|
|
58
|
+
* alone — the server stores the whois login — and nothing is written to this machine's inbox,
|
|
59
|
+
* which belongs to its own Main. The double-press guard is the page's own memory, keyed
|
|
60
|
+
* `<team>/<id>`; a repeated press within 10 s sends nothing again.
|
|
61
|
+
*/
|
|
62
|
+
export function handleTeamAnswer(cfg: Config, fields: Record<string, string>, planId: string, answer: string, wantsJson: boolean): Response {
|
|
63
|
+
const name = (fields.team ?? "").trim();
|
|
64
|
+
const team = cfg.teams.find(t => t.name === name);
|
|
65
|
+
if (!team) return wantsJson ? jsonFail("unknown team", 400) : textRes("unknown team", 400);
|
|
66
|
+
const key = `${team.name}/${planId}`;
|
|
67
|
+
const now = nowSec();
|
|
68
|
+
const last = lastAnswerByPlan.get(key);
|
|
69
|
+
const repeat = last !== undefined && last.answer === answer && now - last.ts < DOUBLE_PRESS_SEC;
|
|
70
|
+
let earlier: TeamEarlier | null = null;
|
|
71
|
+
if (!repeat) {
|
|
72
|
+
const out = postTeamAnswer(team, planId, answer);
|
|
73
|
+
if ("unreachable" in out) return wantsJson ? jsonFail(`team server ${out.unreachable} unreachable`, 503) : textRes(`team server ${out.unreachable} unreachable`, 503);
|
|
74
|
+
if (!out.ok) {
|
|
75
|
+
const error = out.status === 404 ? "plan is not on the team server" : out.error;
|
|
76
|
+
return wantsJson ? jsonFail(error, out.status === 404 ? 409 : out.status) : textRes(error, out.status === 404 ? 409 : out.status);
|
|
77
|
+
}
|
|
78
|
+
lastAnswerByPlan.set(key, { answer, ts: now });
|
|
79
|
+
earlier = out.earlier;
|
|
80
|
+
}
|
|
81
|
+
const note = earlier ? `answer kept; an earlier answer by ${earlier.login} at ${strftime(earlier.time, "%H:%M")} won: "${earlier.answer}"` : null;
|
|
82
|
+
if (wantsJson) return jsonSent("team-answer", note ?? receiptText("team-answer", new URLSearchParams({ team: team.name })));
|
|
83
|
+
if (note) return textRes(note, 200);
|
|
84
|
+
return redirect(sentTo(fields.tab ?? "", `sent=team-answer&team=${encodeURIComponent(team.name)}`));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---- POST /incident (plan P3): the owner's tap on a finding: "false alarm" closes it, "bug" plans it ----
|
|
88
|
+
export function handleIncident(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
89
|
+
const id = (fields.id ?? "").trim();
|
|
90
|
+
const choice = (fields.choice ?? "").trim();
|
|
91
|
+
const fail = (error: string, status: number): Response => (wantsJson ? jsonFail(error, status) : textRes(error, status));
|
|
92
|
+
if (choice !== "bug" && choice !== "false") return fail("choice must be bug or false", 400);
|
|
93
|
+
const view = openIncidents(cfg).find(i => i.id === id);
|
|
94
|
+
if (!view) return fail("incident is not open", 409);
|
|
95
|
+
if (!isFindingKind(view.kind)) return fail("only a finding is tapped here", 409);
|
|
96
|
+
if (choice === "false") {
|
|
97
|
+
const why = `owner tapped "false alarm" on the phone page (${login}): ${view.proposal?.why ?? "no reason given"}`;
|
|
98
|
+
const err = dismissIncident(cfg, id, why, undefined, login);
|
|
99
|
+
if (err) return fail(err, 409);
|
|
100
|
+
if (wantsJson) return jsonSent("incident-closed", receiptText("incident-closed", new URLSearchParams()));
|
|
101
|
+
return redirect(sentTo(fields.tab ?? "", "sent=incident-closed"));
|
|
102
|
+
}
|
|
103
|
+
storeOwnerMessage(`${id}: it's a bug — plan it`, login, [], "", cfg.paths);
|
|
104
|
+
if (wantsJson) return jsonSent("incident-bug", receiptText("incident-bug", new URLSearchParams()));
|
|
105
|
+
return redirect(sentTo(fields.tab ?? "", "sent=incident-bug"));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function handleUnlock(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
109
|
+
const minutes = fields.minutes ?? "";
|
|
110
|
+
if (minutes !== "" && !/^\d+$/.test(minutes)) return wantsJson ? jsonFail("minutes must be a number", 400) : textRes("minutes must be a number", 400);
|
|
111
|
+
const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
|
|
112
|
+
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
113
|
+
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
114
|
+
appendFileSync(
|
|
115
|
+
inboxPath(cfg.paths),
|
|
116
|
+
`${JSON.stringify({ ts: nowSec(), kind: "unlock", minutes: result.minutes, until: result.until, login })}\n`,
|
|
117
|
+
);
|
|
118
|
+
if (wantsJson) return jsonSent("unlock", receiptText("unlock", new URLSearchParams({ minutes: String(result.minutes) })));
|
|
119
|
+
return redirect(sentTo(fields.tab ?? "", `sent=unlock&minutes=${result.minutes}`));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function handleLock(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
123
|
+
const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
|
|
124
|
+
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
125
|
+
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
126
|
+
appendFileSync(inboxPath(cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
|
|
127
|
+
if (wantsJson) return jsonSent("lock", receiptText("lock", new URLSearchParams()));
|
|
128
|
+
return redirect(sentTo(fields.tab ?? "", "sent=lock"));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const TIERS: readonly Tier[] = ["strict", "opinionated", "full"];
|
|
132
|
+
|
|
133
|
+
// Autonomy tier from the phone page (plan 20261025_1940 P3): behind the same auth as every other
|
|
134
|
+
// route, written by the core chatTier with the owner's tapped name; a bad name is a 400 before
|
|
135
|
+
// the core is called, and the chat gate off redirects to the plain-words note like unlock/lock.
|
|
136
|
+
export function handleTier(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
137
|
+
const name = (fields.tier ?? "").trim().toLowerCase();
|
|
138
|
+
if (!(TIERS as readonly string[]).includes(name)) return wantsJson ? jsonFail("tier must be strict, opinionated or full", 400) : textRes("tier must be strict, opinionated or full", 400);
|
|
139
|
+
const result = chatTier(`tier ${name}`, cfg, `ui:${login}`, "ui");
|
|
140
|
+
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
141
|
+
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
142
|
+
appendFileSync(inboxPath(cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "tier", tier: result.tier, login })}\n`);
|
|
143
|
+
if (wantsJson) return jsonSent("tier");
|
|
144
|
+
return redirect(sentTo(fields.tab ?? "", `sent=tier&tier=${result.tier}`));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ---- queue reorder (plan P4): the owner drags a card; INDEX.md is rewritten atomically ----
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* The index text with its open-plan groups reordered: a group is a plan line plus the non-plan
|
|
151
|
+
* lines (blank or `<!--` comment) attached above it, and the open groups — the first line of
|
|
152
|
+
* each path in `openPaths`, in file order — are replaced by the groups of `order`, so every open
|
|
153
|
+
* plan moves with its comment lines while every other plan line keeps its slot (a path listed
|
|
154
|
+
* twice keeps both lines). Lines after the last plan keep the file's end. Returns null when an
|
|
155
|
+
* order path is no longer in the file.
|
|
156
|
+
*/
|
|
157
|
+
export function reorderedIndexText(text: string, order: string[], openPaths: ReadonlySet<string>): string | null {
|
|
158
|
+
if (!text) return null;
|
|
159
|
+
const groups: { path: string; lines: string[] }[] = [];
|
|
160
|
+
let pending: string[] = [];
|
|
161
|
+
for (const raw of text.split("\n")) {
|
|
162
|
+
const norm = raw
|
|
163
|
+
.trim()
|
|
164
|
+
.replace(/^[-*]\s+/, "")
|
|
165
|
+
.trim();
|
|
166
|
+
if (!norm || norm.startsWith("<!--")) {
|
|
167
|
+
pending.push(raw);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
groups.push({ path: resolve(process.cwd(), expandHome(norm.replace(/`/g, ""))), lines: [...pending, raw] });
|
|
171
|
+
pending = [];
|
|
172
|
+
}
|
|
173
|
+
// The open slots in file order: the first line of each open path; a later duplicate of the
|
|
174
|
+
// same path keeps its place like a non-open line, so a path listed twice keeps both lines.
|
|
175
|
+
const byPath = new Map<string, number>();
|
|
176
|
+
const slots: number[] = [];
|
|
177
|
+
const seen = new Set<string>();
|
|
178
|
+
for (const [i, g] of groups.entries()) {
|
|
179
|
+
if (!byPath.has(g.path)) byPath.set(g.path, i);
|
|
180
|
+
if (openPaths.has(g.path) && !seen.has(g.path)) {
|
|
181
|
+
seen.add(g.path);
|
|
182
|
+
slots.push(i);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (slots.length !== order.length) return null;
|
|
186
|
+
const parts: string[] = [];
|
|
187
|
+
let k = 0;
|
|
188
|
+
for (let i = 0; i < groups.length; i++) {
|
|
189
|
+
if (slots[k] === i) {
|
|
190
|
+
const at = byPath.get(order[k] ?? "");
|
|
191
|
+
if (at === undefined) return null;
|
|
192
|
+
parts.push(...groups[at]!.lines);
|
|
193
|
+
k++;
|
|
194
|
+
} else {
|
|
195
|
+
parts.push(...groups[i]!.lines);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
parts.push(...pending);
|
|
199
|
+
return parts.join("\n");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function handleReorder(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
203
|
+
const index = cfg.paths.queue_index;
|
|
204
|
+
const order = (fields.order ?? "")
|
|
205
|
+
.split("\n")
|
|
206
|
+
.map(l => l.trim())
|
|
207
|
+
.filter(l => l.length > 0);
|
|
208
|
+
const before = (fields.before ?? "")
|
|
209
|
+
.split("\n")
|
|
210
|
+
.map(l => l.trim())
|
|
211
|
+
.filter(l => l.length > 0);
|
|
212
|
+
const moved = (fields.moved ?? "").trim();
|
|
213
|
+
// The page's drag and arrow buttons send this over fetch (accept: application/json) and read
|
|
214
|
+
// the JSON reply; a no-JS form post still gets the 303. Errors follow the same split.
|
|
215
|
+
const fail = (error: string, status: number): Response =>
|
|
216
|
+
wantsJson ? Response.json({ ok: false, error }, { status }) : textRes(error, status);
|
|
217
|
+
// One source of truth for the reorderable set: the open plans, the same list queueRows renders.
|
|
218
|
+
const openPlans = activePlans(cfg.paths).filter(p => p.status === "open");
|
|
219
|
+
const openPaths = openPlans.map(p => p.file);
|
|
220
|
+
const openPlan: Record<string, Plan> = Object.fromEntries(openPlans.map(p => [p.file, p]));
|
|
221
|
+
if (!moved || !order.length) return fail("order and moved are required", 400);
|
|
222
|
+
// 400: the posted order must be exactly the open plans the page renders now — no adds, drops or duplicates.
|
|
223
|
+
if (new Set(order).size !== order.length) return fail("order lists a plan more than once", 400);
|
|
224
|
+
const sortedOrder = [...order].sort();
|
|
225
|
+
const sortedOpen = [...openPaths].sort();
|
|
226
|
+
const sameSet = order.length === openPaths.length && sortedOrder.every((p, i) => p === sortedOpen[i]);
|
|
227
|
+
if (!sameSet) return fail("order is not exactly the plans now on the page", 400);
|
|
228
|
+
// 409: the order the page was rendered with must still be the open plans' current order.
|
|
229
|
+
const stale = before.length !== openPaths.length || before.some((p, i) => p !== openPaths[i]);
|
|
230
|
+
if (stale) return fail("the queue changed since the page loaded — reload and drag again", 409);
|
|
231
|
+
// 409: the index is priority (I-20261025-208), so the posted order itself may not put a plan
|
|
232
|
+
// above the open plan it waits on. Checked before any write: the index file and the reorder
|
|
233
|
+
// inbox stay untouched, and the page's 409 branch shows the message and reloads the real order.
|
|
234
|
+
const firstBlock = dependencyOrderProblems(order.map(o => openPlan[o]!))[0];
|
|
235
|
+
if (firstBlock) return fail(`blocked: ${firstBlock}`, 409);
|
|
236
|
+
const from = openPaths.indexOf(moved);
|
|
237
|
+
const to = order.indexOf(moved);
|
|
238
|
+
if (from === -1 || to === -1) return fail("moved is not one of the page's plans", 400);
|
|
239
|
+
// The queue library owns every index write (plan 20261031_0911 P2): a reorder is the same plan
|
|
240
|
+
// set, so no removal reason, and the locked RMW write lands temp + chmod 0444 + rename.
|
|
241
|
+
const wrote = updateIndex(index, undefined, (currentText) => {
|
|
242
|
+
const newText = reorderedIndexText(currentText, order, new Set(openPaths));
|
|
243
|
+
return newText === null ? null : newText.trimEnd().split("\n");
|
|
244
|
+
});
|
|
245
|
+
if (!wrote) return fail("the queue index no longer lists every open plan", 400);
|
|
246
|
+
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
247
|
+
appendFileSync(inboxPath(cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "reorder", plan: moved, from: from + 1, to: to + 1, login })}\n`);
|
|
248
|
+
if (wantsJson) return Response.json({ ok: true, to: to + 1 });
|
|
249
|
+
return redirect(sentTo(fields.tab ?? "", `sent=reorder&to=${to + 1}`));
|
|
250
|
+
}
|