neurastream 0.2.29 → 0.2.31
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 +3 -2
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +13 -1
- package/src/core/guards.ts +142 -11
- package/src/core/main-start.ts +11 -1
- package/src/core/mr-sweep.ts +266 -0
- package/src/core/owner-ui.ts +36 -8
- package/src/core/queue/lib.ts +39 -2
- package/src/core/queue-check.ts +13 -1
- package/templates/AGENTS.md +2 -2
package/README.md
CHANGED
|
@@ -95,7 +95,8 @@ Green is both exiting 0.
|
|
|
95
95
|
Owner rule: never write a plan when another agent is doing the research or reading for you. When Main writes a plan, Main reads the relevant code itself and lists those files in the plan.
|
|
96
96
|
|
|
97
97
|
- Logged: every non-`task` call Main makes adds the paths it touches to `main-reads.json` in the queue state dir (`paths.queue_state`), with the time. A `grep -n` result adds each file it names (`path:line:` at a line start), resolved against the call's directory.
|
|
98
|
-
- Window: `guards.plan_read_max_hours` (default 24, `docs/config.md`). Every file listed under `## Code read by Main` must exist and have a logged read within that many hours. A backticked path cited elsewhere in the plan, outside `docs/plans/`, must also be listed there.
|
|
98
|
+
- Window: `guards.plan_read_max_hours` (default 24, `docs/config.md`). Every file listed under `## Code read by Main` must exist and have a logged read within that many hours. A backticked path cited elsewhere in the plan, outside `docs/plans/`, must also be listed there. A logged read counts in any checkout: the file read at the plan's worktree path or at the same repo-relative path under the main checkout both pass.
|
|
99
|
+
- Auto-list: a cited file Main did read within the window but that is missing from the list is added to `## Code read by Main` when the edit is allowed (`plan-guard: added <n> file(s) to "## Code read by Main": …`) instead of refusing the edit; a file Main never read in any checkout is still refused. Reading a plan runs the same check early and appends `plan-guard: before you edit this plan, re-read: <paths>` to the read result when a listed entry would fail now, so Main re-reads before drafting instead of losing the edit at save time.
|
|
99
100
|
- Cutoff: plans whose filename stamp is `20261021_0100` or later must carry a non-empty `## Code read by Main` section. Older plans are grandfathered.
|
|
100
101
|
- Retention: entries older than 7 days are dropped on each write.
|
|
101
102
|
- Spawn briefs: a brief must name an unticked phase id of the plan (for example `P4`). A brief that asks for research for a plan to be written is refused, quoting the owner rule.
|
|
@@ -107,7 +108,7 @@ A plan parked for the owner has one line: `WAITING on owner: <what>`. That line
|
|
|
107
108
|
|
|
108
109
|
## Queue priority
|
|
109
110
|
|
|
110
|
-
`INDEX.md` order is priority: the top line is rank 1. The queue summary lists plans in that order (`N. <file> [flags] <goal>`). Before a spawn, the guard checks every plan above each plan the brief names. A higher plan that is idle — open, no `WAITING on owner:`, not awaiting merge, still has an unticked phase, and not itself waiting on another open indexed plan via a `Waits on: <plan>` line — and not staffed by a running job blocks the spawn unless the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`, at least four words that appear in an owner message of the last 24 h (`<queue_state>/owner-messages.jsonl`, recorded from Main's prompts); any other skip line is refused. `Waits on:` lines are Main-only, like `WAITING on owner:`. Staffing is `<queue_state>/staffing.json` (each plan's newest spawn's task names) matched against omp's running job labels. The owner reorders the queue by dragging cards on the phone page.
|
|
111
|
+
`INDEX.md` order is priority: the top line is rank 1. The queue summary lists plans in that order (`N. <file> [flags] <goal>`). Before a spawn, the guard checks every plan above each plan the brief names. A higher plan that is idle — open, no `WAITING on owner:`, not awaiting merge, still has an unticked phase, and not itself waiting on another open indexed plan via a `Waits on: <plan>` line — and not staffed by a running job blocks the spawn unless the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`, at least four words that appear in an owner message of the last 24 h (`<queue_state>/owner-messages.jsonl`, recorded from Main's prompts); any other skip line is refused. `Waits on:` lines are Main-only, like `WAITING on owner:`. Staffing is `<queue_state>/staffing.json` (each plan's newest spawn's task names) matched against omp's running job labels. The owner reorders the queue by dragging cards on the phone page — a drag held near the screen edge autoscrolls the page, so the end of a queue taller than the screen is reachable. The order must respect the dependencies: an open plan may not sit above the open plan its `Waits on:` line names — `queue-check` lists one problem per misranked plan and exits 1, the summary shows the target as a `waits on #N` flag on the plan, and a drag that would create such an order is refused with that reason (`blocked: #N <plan> waits on #M …`) before the index or the reorder inbox change. A `Waits on:` target that is complete or gone from the index imposes no order.
|
|
111
112
|
|
|
112
113
|
## Autonomy tiers
|
|
113
114
|
|
package/package.json
CHANGED
|
@@ -23,7 +23,7 @@ import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
|
|
|
23
23
|
import { loadConfig, type Config } from "../../core/config.ts";
|
|
24
24
|
import { nowSec, strftime } from "../../core/clock.ts";
|
|
25
25
|
import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
|
|
26
|
-
import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
|
|
26
|
+
import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
|
|
27
27
|
import { rateLimitWait } from "../../core/rate-limit.ts";
|
|
28
28
|
import { notifyProviders, postReply } from "../../core/notify.ts";
|
|
29
29
|
import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
|
|
@@ -794,6 +794,14 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
794
794
|
revertMainEdit(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), cfg);
|
|
795
795
|
return { isError: true, content: [{ type: "text", text: d.reason }] };
|
|
796
796
|
}
|
|
797
|
+
// Plan-guard auto-listing (I-20261025-208): the allowed edit's file is amended to name
|
|
798
|
+
// the cited files Main did read; the note tells Main what moved into the list.
|
|
799
|
+
if (d.allow && d.rewrite) {
|
|
800
|
+
try {
|
|
801
|
+
writeFileSync(d.rewrite.path, d.rewrite.text);
|
|
802
|
+
} catch {}
|
|
803
|
+
if (d.note) notes.push(d.note);
|
|
804
|
+
}
|
|
797
805
|
if (d.allow && (!c.hasAgent || c.kind === "main") && q.doneCount(after) > q.doneCount(before) && q.planAt(file, q.activePlans())) {
|
|
798
806
|
const note = trimProgress(file);
|
|
799
807
|
if (note) notes.push(note);
|
|
@@ -808,6 +816,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
808
816
|
if ((!c.hasAgent || c.kind === "main") && !e.isError) {
|
|
809
817
|
const text = content.map(p => asString(asRecord(p).text)).join("\n");
|
|
810
818
|
recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
|
|
819
|
+
// After the reads are recorded: a fresh hit clears its own warning, a stale list warns
|
|
820
|
+
// before Main drafts an edit the plan-read guard would refuse (I-20261025-208 P3).
|
|
821
|
+
const readNote = planReadNote(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text, cfg);
|
|
822
|
+
if (readNote) notes.push(readNote);
|
|
811
823
|
}
|
|
812
824
|
if ((!c.hasAgent || c.kind === "main") && e.isError) {
|
|
813
825
|
revertMainEdit(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), cfg);
|
package/src/core/guards.ts
CHANGED
|
@@ -35,6 +35,18 @@ import type { Plan } from "./queue/lib.ts";
|
|
|
35
35
|
import { nowSec } from "./clock.ts";
|
|
36
36
|
const ALLOW: Decision = { allow: true, reason: "" };
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* The plan-edit decision: a Decision plus the allow-with-amendment fields of the plan-read guard
|
|
40
|
+
* (I-20261025-208). On allow, `rewrite` names the file the caller writes back (the auto-listed
|
|
41
|
+
* read section) and `note` is the receipt for the tool result; both travel through the guard
|
|
42
|
+
* CLI's JSON output. They live here, not on the shared Decision, so every other check keeps the
|
|
43
|
+
* plain shape.
|
|
44
|
+
*/
|
|
45
|
+
export interface PlanEditDecision extends Decision {
|
|
46
|
+
rewrite?: { path: string; text: string };
|
|
47
|
+
note?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
38
50
|
function deny(reason: string): Decision {
|
|
39
51
|
return { allow: false, reason };
|
|
40
52
|
}
|
|
@@ -860,6 +872,36 @@ export function recordMainResult(tool: string, input: Record<string, unknown>, c
|
|
|
860
872
|
recordMainReads([...text.matchAll(GREP_LINE)].map(m => path.resolve(dir, m[1] ?? "")));
|
|
861
873
|
}
|
|
862
874
|
|
|
875
|
+
/**
|
|
876
|
+
* The pre-draft warning (I-20261025-208): when Main reads a plan file (the read tool, or a result
|
|
877
|
+
* whose first `path:line:` hit is the plan), the tool result gains one note naming the plan's
|
|
878
|
+
* listed files that would fail the read check right now — before Main drafts an edit the guard
|
|
879
|
+
* would refuse and throw away. Silence when every listed file is fresh in some checkout.
|
|
880
|
+
*/
|
|
881
|
+
export function planReadNote(tool: string, input: Record<string, unknown>, cwd: string, text: string, cfg: Config): string | undefined {
|
|
882
|
+
let planPath = "";
|
|
883
|
+
if (tool === "read" && typeof input.path === "string") planPath = path.resolve(cwd, q.expandHome(input.path));
|
|
884
|
+
else {
|
|
885
|
+
const first = [...text.matchAll(GREP_LINE)][0];
|
|
886
|
+
if (first) {
|
|
887
|
+
const base = typeof input.cwd === "string" ? path.resolve(cwd, q.expandHome(input.cwd)) : cwd;
|
|
888
|
+
planPath = path.resolve(q.shellCwd(String(input.command ?? input.code ?? ""), base), first[1] ?? "");
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (!planPath || !MAIN_PLAN_FILE.test(planPath)) return undefined;
|
|
892
|
+
let plan: string;
|
|
893
|
+
try {
|
|
894
|
+
plan = readFileSync(planPath, "utf8");
|
|
895
|
+
} catch {
|
|
896
|
+
return undefined;
|
|
897
|
+
}
|
|
898
|
+
const stale = planReadProblems(plan, planPath, cfg)
|
|
899
|
+
.filter(p => p.includes(" was not read by Main within "))
|
|
900
|
+
.map(p => p.slice(0, p.indexOf(" was not read by Main within ")));
|
|
901
|
+
if (!stale.length) return undefined;
|
|
902
|
+
return `plan-guard: before you edit this plan, re-read: ${stale.join(", ")}`;
|
|
903
|
+
}
|
|
904
|
+
|
|
863
905
|
/**
|
|
864
906
|
* spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
|
|
865
907
|
* original paths (the extension spawn event and a `task` tool call); the brief names the plan.
|
|
@@ -965,7 +1007,7 @@ function mainOnlyLines(text: string): string {
|
|
|
965
1007
|
* `restore` hands back the untouched text for the caller to write (the original restored the
|
|
966
1008
|
* file itself before reporting).
|
|
967
1009
|
*/
|
|
968
|
-
export function checkPlanEdit(e: PlanEditEvent, cfg: Config):
|
|
1010
|
+
export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
969
1011
|
if (e.agent === "main") return checkMainPlan(e, cfg);
|
|
970
1012
|
if (q.outsideProgress(e.after) !== q.outsideProgress(e.before) || mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
|
|
971
1013
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path}`);
|
|
@@ -1043,13 +1085,27 @@ export function findingsValue(block: string): string | null {
|
|
|
1043
1085
|
|
|
1044
1086
|
// Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
|
|
1045
1087
|
// An empty `before` means the plan file did not exist yet; a refusal then deletes it.
|
|
1046
|
-
function checkMainPlan(e: PlanEditEvent, cfg: Config):
|
|
1088
|
+
function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
1047
1089
|
if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) return ALLOW;
|
|
1090
|
+
// A cited file Main did read lands in the list instead of the refusal (I-20261025-208): fix the
|
|
1091
|
+
// text first, then judge the fixed text like any other edit.
|
|
1092
|
+
const fix = autoListReads(e.after, e.path, cfg);
|
|
1093
|
+
const fixed = fix ? fix.text : e.after;
|
|
1048
1094
|
// Refuse only what this edit adds: a problem the plan already had is not Main's doing now.
|
|
1049
1095
|
// The missing-section problem is always refused: a plan with no read list has no evidence behind its text.
|
|
1050
1096
|
const known = new Set(e.before ? planReadProblems(e.before, e.path, cfg) : []);
|
|
1051
|
-
const problems = planReadProblems(
|
|
1052
|
-
if (!problems.length)
|
|
1097
|
+
const problems = planReadProblems(fixed, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
|
|
1098
|
+
if (!problems.length) {
|
|
1099
|
+
if (!fix) return ALLOW;
|
|
1100
|
+
const list = fix.paths.join(", ");
|
|
1101
|
+
log(cfg.paths.plan_guard_log, `AUTO-LIST ${e.path}: ${list}`);
|
|
1102
|
+
return {
|
|
1103
|
+
allow: true,
|
|
1104
|
+
reason: "",
|
|
1105
|
+
rewrite: { path: e.path, text: fix.text },
|
|
1106
|
+
note: `plan-guard: added ${fix.paths.length} file(s) to "## Code read by Main": ${list}`,
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1053
1109
|
log(cfg.paths.plan_guard_log, `REFUSE-READ ${e.path}: ${problems.join("; ")}`);
|
|
1054
1110
|
return {
|
|
1055
1111
|
allow: false,
|
|
@@ -1066,8 +1122,7 @@ const NO_SECTION = `no "## Code read by Main" section lists a file (list each fi
|
|
|
1066
1122
|
|
|
1067
1123
|
/** Read evidence behind a plan edit: section present, each listed path read within the window, no unlisted cited path. */
|
|
1068
1124
|
function planReadProblems(text: string, planPath: string, cfg: Config): string[] {
|
|
1069
|
-
const
|
|
1070
|
-
const listed = [...section.matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, ""));
|
|
1125
|
+
const listed = [...(READ_SECTION.exec(text)?.[1] ?? "").matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, ""));
|
|
1071
1126
|
if (!listed.length) return [NO_SECTION];
|
|
1072
1127
|
const reads = readMainReads();
|
|
1073
1128
|
const maxMs = cfg.guards.plan_read_max_hours * 3_600_000;
|
|
@@ -1077,11 +1132,11 @@ function planReadProblems(text: string, planPath: string, cfg: Config): string[]
|
|
|
1077
1132
|
const abs = planFile(p, planPath, text);
|
|
1078
1133
|
named.add(abs);
|
|
1079
1134
|
if (!isFile(abs)) problems.push(`${p} does not exist`);
|
|
1080
|
-
else if (!(
|
|
1135
|
+
else if (!readWithin(abs, planPath, text, reads, maxMs)) problems.push(`${p} was not read by Main within ${cfg.guards.plan_read_max_hours} h`);
|
|
1081
1136
|
}
|
|
1082
1137
|
for (const [, cited = ""] of q.outsideProgress(text).matchAll(CITED_PATH)) {
|
|
1083
1138
|
const abs = planFile(cited, planPath, text);
|
|
1084
|
-
if (abs.includes("/docs/plans/") || named
|
|
1139
|
+
if (abs.includes("/docs/plans/") || namedOrTwin(named, abs, planPath, text) || !isFile(abs)) continue;
|
|
1085
1140
|
problems.push(`${cited} is cited but not listed under "## Code read by Main"`);
|
|
1086
1141
|
}
|
|
1087
1142
|
return problems;
|
|
@@ -1091,11 +1146,87 @@ function planReadProblems(text: string, planPath: string, cfg: Config): string[]
|
|
|
1091
1146
|
function planFile(p: string, planPath: string, text: string): string {
|
|
1092
1147
|
const home = q.expandHome(p);
|
|
1093
1148
|
if (path.isAbsolute(home)) return home;
|
|
1149
|
+
const roots = planRoots(planPath, text);
|
|
1150
|
+
const root = roots.find(r => isFile(path.join(r, home))) ?? roots[roots.length - 1]!;
|
|
1151
|
+
return path.join(root, home);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/** The roots a plan-relative path resolves against: the plan's Worktree (when set), then its repo (dirname³ of the plan file). */
|
|
1155
|
+
function planRoots(planPath: string, text: string): string[] {
|
|
1094
1156
|
const wt = /^Worktree:\s*(\S+)/m.exec(text)?.[1];
|
|
1095
1157
|
const repo = path.dirname(path.dirname(path.dirname(planPath)));
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1158
|
+
return wt && wt !== "-" ? [wt, repo] : [repo];
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
/** The same repo-relative file under the plan's other root (Worktree ↔ main checkout), or null when `abs` sits under neither. */
|
|
1162
|
+
function twinFile(abs: string, planPath: string, text: string): string | null {
|
|
1163
|
+
const roots = planRoots(planPath, text);
|
|
1164
|
+
for (const root of roots) {
|
|
1165
|
+
const prefixed = root.endsWith("/") ? root : `${root}/`;
|
|
1166
|
+
if (!abs.startsWith(prefixed)) continue;
|
|
1167
|
+
for (const other of roots) {
|
|
1168
|
+
if (other === root) continue;
|
|
1169
|
+
return `${other.endsWith("/") ? other : `${other}/`}${abs.slice(prefixed.length)}`;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/** Main read this file within the window — at the resolved path or at its twin under the plan's other root (I-20261025-208 evidence: the same file read in the main checkout must cover its Worktree copy). */
|
|
1176
|
+
function readWithin(abs: string, planPath: string, text: string, reads: Record<string, string>, maxMs: number): boolean {
|
|
1177
|
+
const cutoff = Date.now() - maxMs;
|
|
1178
|
+
const fresh = (f: string) => Date.parse(reads[f] ?? "") >= cutoff;
|
|
1179
|
+
if (fresh(abs)) return true;
|
|
1180
|
+
const twin = twinFile(abs, planPath, text);
|
|
1181
|
+
return twin !== null && fresh(twin);
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/** The resolved path, or its twin under the plan's other root, is already in the set (cited-vs-listed matches files, not spellings). */
|
|
1185
|
+
function namedOrTwin(named: Set<string>, abs: string, planPath: string, text: string): boolean {
|
|
1186
|
+
if (named.has(abs)) return true;
|
|
1187
|
+
const twin = twinFile(abs, planPath, text);
|
|
1188
|
+
return twin !== null && named.has(twin);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
/**
|
|
1192
|
+
* Cited paths (outside Progress) Main read within the window but the list omits: returns the plan
|
|
1193
|
+
* text with one `- \`<path as cited>\`` line appended to "## Code read by Main" (the section is
|
|
1194
|
+
* created before "## Progress" when missing), or null when nothing qualifies. Never-read citations
|
|
1195
|
+
* stay out: they are refused like today.
|
|
1196
|
+
*/
|
|
1197
|
+
function autoListReads(text: string, planPath: string, cfg: Config): { text: string; paths: string[] } | null {
|
|
1198
|
+
const reads = readMainReads();
|
|
1199
|
+
const maxMs = cfg.guards.plan_read_max_hours * 3_600_000;
|
|
1200
|
+
const covered = new Set<string>();
|
|
1201
|
+
for (const p of [...(READ_SECTION.exec(text)?.[1] ?? "").matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, "")))
|
|
1202
|
+
covered.add(planFile(p, planPath, text));
|
|
1203
|
+
const added: string[] = [];
|
|
1204
|
+
const seen = new Set<string>();
|
|
1205
|
+
for (const [, cited = ""] of q.outsideProgress(text).matchAll(CITED_PATH)) {
|
|
1206
|
+
const abs = planFile(cited, planPath, text);
|
|
1207
|
+
if (abs.includes("/docs/plans/") || seen.has(cited) || !isFile(abs)) continue;
|
|
1208
|
+
if (namedOrTwin(covered, abs, planPath, text)) continue;
|
|
1209
|
+
if (!readWithin(abs, planPath, text, reads, maxMs)) continue;
|
|
1210
|
+
seen.add(cited);
|
|
1211
|
+
covered.add(abs);
|
|
1212
|
+
added.push(cited);
|
|
1213
|
+
}
|
|
1214
|
+
if (!added.length) return null;
|
|
1215
|
+
const lines = added.map(p => `- \`${p}\``);
|
|
1216
|
+
const m = READ_SECTION.exec(text);
|
|
1217
|
+
let out: string;
|
|
1218
|
+
if (m && m[1] !== undefined) {
|
|
1219
|
+
// Append after the section's last entry, ahead of the blank lines before the next heading.
|
|
1220
|
+
const bodyStart = m.index + m[0].length - m[1].length;
|
|
1221
|
+
const at = bodyStart + m[1].replace(/\s+$/, "").length;
|
|
1222
|
+
out = `${text.slice(0, at)}\n${lines.join("\n")}${text.slice(at)}`;
|
|
1223
|
+
} else {
|
|
1224
|
+
// No section yet: create it right before "## Progress" (or at the end when that is missing too).
|
|
1225
|
+
const at = text.search(/^## Progress\b/m);
|
|
1226
|
+
const block = `## Code read by Main\n${lines.join("\n")}\n\n`;
|
|
1227
|
+
out = at === -1 ? `${text}${block}` : `${text.slice(0, at)}${block}${text.slice(at)}`;
|
|
1228
|
+
}
|
|
1229
|
+
return { text: out, paths: added };
|
|
1099
1230
|
}
|
|
1100
1231
|
|
|
1101
1232
|
function isFile(file: string): boolean {
|
package/src/core/main-start.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { log as logGuard } from "./guards.ts";
|
|
|
12
12
|
import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
|
|
13
13
|
import { buildReport } from "./report.ts";
|
|
14
14
|
import { loadavgLine } from "./host.ts";
|
|
15
|
+
import { mrSweep } from "./mr-sweep.ts";
|
|
15
16
|
|
|
16
17
|
function bin(name: string, cfg: Config): string {
|
|
17
18
|
return join(cfg.paths.home, ".local/bin", name);
|
|
@@ -134,7 +135,7 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
134
135
|
out.push(health.stdout + health.stderr);
|
|
135
136
|
say("");
|
|
136
137
|
say("=== queue");
|
|
137
|
-
const check = await run(bin("queue-check", cfg), [], { stdin: childStdin, stderr: childStderr });
|
|
138
|
+
const check = await run(bin("queue-check", cfg), ["--no-mr-sweep"], { stdin: childStdin, stderr: childStderr });
|
|
138
139
|
out.push(check.stdout + check.stderr);
|
|
139
140
|
say("");
|
|
140
141
|
say("=== heavy-run lock");
|
|
@@ -151,6 +152,15 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
151
152
|
const text = `${doctor.stdout}${doctor.stderr}`;
|
|
152
153
|
out.push(text.endsWith("\n") || text === "" ? text : `${text}\n`);
|
|
153
154
|
if (doctor.error) say(doctor.error.message);
|
|
155
|
+
try {
|
|
156
|
+
const sweep = mrSweep({ index: cfg.paths.queue_index });
|
|
157
|
+
if (sweep.lines.length) {
|
|
158
|
+
say("=== mr-sweep");
|
|
159
|
+
for (const line of sweep.lines) say(line);
|
|
160
|
+
}
|
|
161
|
+
} catch {
|
|
162
|
+
say("mr-sweep: skipped (forge unreachable)");
|
|
163
|
+
}
|
|
154
164
|
return out.join("");
|
|
155
165
|
}
|
|
156
166
|
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Reconcile open forge MRs with open plans. The forge is the source of truth; a missing CLI,
|
|
2
|
+
// auth failure, unknown host or absent origin skips that repo and never fails the sweep.
|
|
3
|
+
// Host-neutral: forge CLIs are invoked through a command runner. No harness imports.
|
|
4
|
+
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { cmd } from "./proc.ts";
|
|
8
|
+
import { activePlans, gitTop } from "./queue/lib.ts";
|
|
9
|
+
|
|
10
|
+
export const MR_SWEEP_NO_CLI = "mr-sweep: skipped (no forge CLI)";
|
|
11
|
+
const UNTRACKED_TAIL = "— no open plan mentions it";
|
|
12
|
+
const PAGE = 100;
|
|
13
|
+
const MAX_PAGES = 20;
|
|
14
|
+
|
|
15
|
+
export type Forge = "gitlab" | "github";
|
|
16
|
+
|
|
17
|
+
export interface CommandResult {
|
|
18
|
+
code: number;
|
|
19
|
+
stdout: string;
|
|
20
|
+
stderr: string;
|
|
21
|
+
/** The executable was not on PATH. Distinct from a non-zero exit (auth, network, usage). */
|
|
22
|
+
missing?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type CommandRunner = (args: string[], opts: { cwd?: string; env?: NodeJS.ProcessEnv }) => CommandResult;
|
|
26
|
+
|
|
27
|
+
export interface SweepMr {
|
|
28
|
+
forge: Forge;
|
|
29
|
+
number: number;
|
|
30
|
+
token: string;
|
|
31
|
+
branch: string;
|
|
32
|
+
repo: string;
|
|
33
|
+
tracked: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface SweepResult {
|
|
37
|
+
lines: string[];
|
|
38
|
+
mrs: SweepMr[];
|
|
39
|
+
/** True only when a reachable forge listed at least one untracked MR. A skip is never a failure. */
|
|
40
|
+
fail: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface SweepOpts {
|
|
44
|
+
index?: string;
|
|
45
|
+
env?: NodeJS.ProcessEnv;
|
|
46
|
+
runner?: CommandRunner;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function defaultRunner(args: string[], opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {}): CommandResult {
|
|
50
|
+
const bin = args[0];
|
|
51
|
+
if (!bin) return { code: 127, stdout: "", stderr: "missing command", missing: true };
|
|
52
|
+
const r = spawnSync(bin, args.slice(1), {
|
|
53
|
+
cwd: opts.cwd,
|
|
54
|
+
env: opts.env ?? process.env,
|
|
55
|
+
encoding: "utf8",
|
|
56
|
+
timeout: 20_000,
|
|
57
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
58
|
+
});
|
|
59
|
+
const err = r.error as NodeJS.ErrnoException | undefined;
|
|
60
|
+
if (err?.code === "ENOENT") return { code: 127, stdout: "", stderr: err.message, missing: true };
|
|
61
|
+
if (err) return { code: 1, stdout: r.stdout ?? "", stderr: `${r.stderr ?? ""}${err.message}` };
|
|
62
|
+
return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Host of an origin URL (`git@host:path`, `ssh://`, `https://`). Null when it does not parse. */
|
|
66
|
+
export function remoteHost(url: string): string | null {
|
|
67
|
+
const u = url.trim();
|
|
68
|
+
if (!u.includes("://")) {
|
|
69
|
+
const scp = /^[^@\s]+@([^:\s]+):/.exec(u);
|
|
70
|
+
if (scp?.[1]) return scp[1].toLowerCase();
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
if (u.includes("://")) {
|
|
74
|
+
const host = new URL(u).hostname.toLowerCase();
|
|
75
|
+
return host || null;
|
|
76
|
+
}
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** `gitlab` in the host → gitlab; `github` in the host → github; anything else is unknown. */
|
|
84
|
+
export function forgeOf(host: string): Forge | null {
|
|
85
|
+
const h = host.toLowerCase();
|
|
86
|
+
if (h.includes("gitlab")) return "gitlab";
|
|
87
|
+
if (h.includes("github")) return "github";
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** `!N` / `#N` as a whole token, or the source branch name, in any of the texts. `MR !N: ignored` matches the token. */
|
|
92
|
+
export function mentioned(token: string, branch: string, texts: string[]): boolean {
|
|
93
|
+
const re = new RegExp(`(?:^|[^0-9])${token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![0-9])`);
|
|
94
|
+
for (const text of texts) {
|
|
95
|
+
if (re.test(text)) return true;
|
|
96
|
+
if (branch && text.includes(branch)) return true;
|
|
97
|
+
}
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function asRecord(v: unknown): Record<string, unknown> | null {
|
|
102
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function asNumber(v: unknown): number | null {
|
|
106
|
+
if (typeof v === "number" && Number.isInteger(v) && v > 0) return v;
|
|
107
|
+
if (typeof v === "string" && /^[0-9]+$/.test(v)) return Number(v);
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Parse a JSON list. Null means the CLI answered but not with a list — treat as unreachable, never as "no MRs". */
|
|
112
|
+
function parseList(stdout: string): Record<string, unknown>[] | null {
|
|
113
|
+
const t = stdout.trim();
|
|
114
|
+
if (!t) return [];
|
|
115
|
+
const from = (v: unknown): Record<string, unknown>[] | null => {
|
|
116
|
+
if (Array.isArray(v)) return v.map(asRecord).filter((x): x is Record<string, unknown> => x !== null);
|
|
117
|
+
const rec = asRecord(v);
|
|
118
|
+
if (!rec) return null;
|
|
119
|
+
for (const key of ["merge_requests", "items", "pull_requests"]) {
|
|
120
|
+
const inner = rec[key];
|
|
121
|
+
if (Array.isArray(inner)) return inner.map(asRecord).filter((x): x is Record<string, unknown> => x !== null);
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
};
|
|
125
|
+
try {
|
|
126
|
+
return from(JSON.parse(t));
|
|
127
|
+
} catch {
|
|
128
|
+
const at = t.indexOf("[");
|
|
129
|
+
const end = t.lastIndexOf("]");
|
|
130
|
+
if (at < 0 || end <= at) return null;
|
|
131
|
+
try {
|
|
132
|
+
return from(JSON.parse(t.slice(at, end + 1)));
|
|
133
|
+
} catch {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
interface Listed {
|
|
140
|
+
missing?: boolean;
|
|
141
|
+
fail?: boolean;
|
|
142
|
+
items: { number: number; branch: string }[];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function takeItems(parsed: Record<string, unknown>[], numberKey: "iid" | "number", branchKeys: string[]): { number: number; branch: string }[] {
|
|
146
|
+
const items: { number: number; branch: string }[] = [];
|
|
147
|
+
const seen = new Set<number>();
|
|
148
|
+
for (const item of parsed) {
|
|
149
|
+
const n = asNumber(item[numberKey] ?? item.number);
|
|
150
|
+
if (n === null || seen.has(n)) continue;
|
|
151
|
+
const state = typeof item.state === "string" ? item.state : "";
|
|
152
|
+
// The list command already asks for open MRs. Skip only an explicit closed/merged row,
|
|
153
|
+
// so an unexpected state label cannot hide an open MR.
|
|
154
|
+
if (state === "closed" || state === "merged") continue;
|
|
155
|
+
seen.add(n);
|
|
156
|
+
let branch = "";
|
|
157
|
+
for (const key of branchKeys) {
|
|
158
|
+
const value = item[key];
|
|
159
|
+
if (typeof value === "string") {
|
|
160
|
+
branch = value;
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
items.push({ number: n, branch });
|
|
165
|
+
}
|
|
166
|
+
return items;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function listGitlab(repo: string, run: CommandRunner, env?: NodeJS.ProcessEnv): Listed {
|
|
170
|
+
const items: { number: number; branch: string }[] = [];
|
|
171
|
+
const seen = new Set<number>();
|
|
172
|
+
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
173
|
+
const r = run(["glab", "mr", "list", "-F", "json", "-P", String(PAGE), "-p", String(page)], { cwd: repo, env });
|
|
174
|
+
if (r.missing) return { missing: true, items: [] };
|
|
175
|
+
if (r.code !== 0) return { fail: true, items: [] };
|
|
176
|
+
const parsed = parseList(r.stdout);
|
|
177
|
+
if (parsed === null) return { fail: true, items: [] };
|
|
178
|
+
for (const item of takeItems(parsed, "iid", ["source_branch", "sourceBranch"])) {
|
|
179
|
+
if (seen.has(item.number)) continue;
|
|
180
|
+
seen.add(item.number);
|
|
181
|
+
items.push(item);
|
|
182
|
+
}
|
|
183
|
+
if (parsed.length < PAGE) break;
|
|
184
|
+
}
|
|
185
|
+
return { items };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function listGithub(repo: string, run: CommandRunner, env?: NodeJS.ProcessEnv): Listed {
|
|
189
|
+
const r = run(["gh", "pr", "list", "--state", "open", "--limit", "1000", "--json", "number,headRefName,title"], { cwd: repo, env });
|
|
190
|
+
if (r.missing) return { missing: true, items: [] };
|
|
191
|
+
if (r.code !== 0) return { fail: true, items: [] };
|
|
192
|
+
const parsed = parseList(r.stdout);
|
|
193
|
+
if (parsed === null) return { fail: true, items: [] };
|
|
194
|
+
return { items: takeItems(parsed, "number", ["headRefName", "head_ref_name"]) };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function skip(repo: string, why: string): string {
|
|
198
|
+
return `mr-sweep: skipped ${repo} (${why})`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Open MRs of every repo in the index, marked tracked when an open plan of that repo contains
|
|
203
|
+
* the `!N` / `#N` token (including `MR !N: ignored`) or the source branch name.
|
|
204
|
+
*/
|
|
205
|
+
export function mrSweep(opts: SweepOpts = {}): SweepResult {
|
|
206
|
+
const run = opts.runner ?? defaultRunner;
|
|
207
|
+
const plans = activePlans(opts.index);
|
|
208
|
+
const repos: string[] = [];
|
|
209
|
+
for (const p of plans) if (!repos.includes(p.repo)) repos.push(p.repo);
|
|
210
|
+
const lines: string[] = [];
|
|
211
|
+
const mrs: SweepMr[] = [];
|
|
212
|
+
let missingCli = false;
|
|
213
|
+
let fail = false;
|
|
214
|
+
for (const repo of repos) {
|
|
215
|
+
if (!gitTop(repo)) {
|
|
216
|
+
lines.push(skip(repo, "not a git repo"));
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const remote = cmd(["git", "-C", repo, "remote", "get-url", "origin"], { env: opts.env });
|
|
220
|
+
const url = remote.code === 0 ? remote.stdout.trim() : "";
|
|
221
|
+
if (!url) {
|
|
222
|
+
lines.push(skip(repo, "no origin remote"));
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const host = remoteHost(url);
|
|
226
|
+
const forge = host ? forgeOf(host) : null;
|
|
227
|
+
if (!forge) {
|
|
228
|
+
lines.push(skip(repo, "unknown forge"));
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
const listed = forge === "gitlab" ? listGitlab(repo, run, opts.env) : listGithub(repo, run, opts.env);
|
|
232
|
+
if (listed.missing) {
|
|
233
|
+
missingCli = true;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (listed.fail) {
|
|
237
|
+
lines.push(skip(repo, "forge unreachable"));
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const texts = plans.filter(p => p.repo === repo && p.status === "open").map(p => p.text);
|
|
241
|
+
const found = listed.items
|
|
242
|
+
.map(item => {
|
|
243
|
+
const token = forge === "gitlab" ? `!${item.number}` : `#${item.number}`;
|
|
244
|
+
const mr: SweepMr = {
|
|
245
|
+
forge,
|
|
246
|
+
number: item.number,
|
|
247
|
+
token,
|
|
248
|
+
branch: item.branch,
|
|
249
|
+
repo,
|
|
250
|
+
tracked: mentioned(token, item.branch, texts),
|
|
251
|
+
};
|
|
252
|
+
return mr;
|
|
253
|
+
})
|
|
254
|
+
.sort((a, b) => a.number - b.number);
|
|
255
|
+
for (const mr of found) {
|
|
256
|
+
mrs.push(mr);
|
|
257
|
+
if (mr.tracked) lines.push(`tracked MR ${mr.token} ${path.basename(mr.repo)} ${mr.repo} (${mr.branch})`);
|
|
258
|
+
else {
|
|
259
|
+
lines.push(`UNTRACKED MR ${mr.token} ${path.basename(mr.repo)} ${mr.repo} (${mr.branch}) ${UNTRACKED_TAIL}`);
|
|
260
|
+
fail = true;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (missingCli) lines.unshift(MR_SWEEP_NO_CLI);
|
|
265
|
+
return { lines, mrs, fail };
|
|
266
|
+
}
|
package/src/core/owner-ui.ts
CHANGED
|
@@ -19,7 +19,7 @@ import { cpuCount } from "./host.ts";
|
|
|
19
19
|
import { openIncidents } from "./incidents.ts";
|
|
20
20
|
import { log } from "./guards.ts";
|
|
21
21
|
import { readMetricEvents } from "./metrics.ts";
|
|
22
|
-
import { activePlans, chatUnlock, expandHome, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
|
|
22
|
+
import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
|
|
23
23
|
import type { Tailscale } from "./tailscale.ts";
|
|
24
24
|
|
|
25
25
|
const ANSWER_MAX = 2000;
|
|
@@ -711,8 +711,25 @@ export function dropSlot(mids: number[], mid: number): number {
|
|
|
711
711
|
return mids.length;
|
|
712
712
|
}
|
|
713
713
|
|
|
714
|
+
/**
|
|
715
|
+
* Autoscroll speed in px/frame while a drag is held near the screen edge (P5b): 0 outside a
|
|
716
|
+
* 72 px band, negative in the top band, positive in the bottom band, growing toward the edge,
|
|
717
|
+
* capped at 24 px/frame. Pure and exported so the page script — which inlines this exact
|
|
718
|
+
* source via toString() — and the test run the same code.
|
|
719
|
+
*/
|
|
720
|
+
export function edgeScrollStep(y: number, viewportH: number): number {
|
|
721
|
+
const BAND = 72;
|
|
722
|
+
const CAP = 24;
|
|
723
|
+
const fromTop = BAND - y;
|
|
724
|
+
const fromBottom = y - (viewportH - BAND);
|
|
725
|
+
if (fromTop > 0) return -Math.min(CAP, Math.ceil((CAP * fromTop) / BAND));
|
|
726
|
+
if (fromBottom > 0) return Math.min(CAP, Math.ceil((CAP * fromBottom) / BAND));
|
|
727
|
+
return 0;
|
|
728
|
+
}
|
|
729
|
+
|
|
714
730
|
const SCRIPT = `(function(){
|
|
715
731
|
var dropSlot=${dropSlot.toString()};
|
|
732
|
+
var edgeScrollStep=${edgeScrollStep.toString()};
|
|
716
733
|
// Keep only the tab in the address bar: receipts are one-time DOM, not a reloadable URL.
|
|
717
734
|
if(location.search){var keep=new URLSearchParams(location.search).get("tab");history.replaceState(null,"",location.pathname+(keep?"?tab="+keep:""));}
|
|
718
735
|
function store(d,v){var k="nsui:"+d.id;if(v===undefined)return sessionStorage.getItem(k);sessionStorage.setItem(k,v?"1":"0");}
|
|
@@ -746,10 +763,16 @@ function navigate(href){swapMain(href,true,true).catch(function(){showNetErr();}
|
|
|
746
763
|
function refreshNow(){if(swapping)return;swapping=true;swapMain(location.href,false,false).catch(function(){}).then(function(){swapping=false;});}
|
|
747
764
|
function showNetErr(){var d=showReceipt("Couldn't reach the page — tap to retry");if(d)d.setAttribute("data-js","neterr");}
|
|
748
765
|
var drag=null;
|
|
749
|
-
|
|
766
|
+
// One drag move: place the floating card at pointer Y and drop the placeholder between the
|
|
767
|
+
// cards around it. Also re-run after every autoscroll step, since scrolling moved the midpoints.
|
|
768
|
+
function dragMove(y){if(!drag)return;var card=drag.card,list=drag.list;card.style.transform="translateY("+(y-drag.y0)+"px)";var r=card.getBoundingClientRect();var mid=r.top+r.height/2;var mids=[];var els=[];var ch=list.children;for(var i=0;i<ch.length;i++){var el=ch[i];if(el===card||el===drag.ph)continue;var er=el.getBoundingClientRect();mids.push(er.top+er.height/2);els.push(el);}
|
|
750
769
|
var k=dropSlot(mids,mid);
|
|
751
|
-
if(k<mids.length){if(els[k].previousElementSibling!==drag.ph)list.insertBefore(drag.ph,els[k]);}else if(mids.length&&els[mids.length-1].nextElementSibling!==drag.ph){list.insertBefore(drag.ph,els[mids.length-1].nextSibling);}}
|
|
752
|
-
|
|
770
|
+
if(k<mids.length){if(els[k].previousElementSibling!==drag.ph)list.insertBefore(drag.ph,els[k]);}else if(mids.length&&els[mids.length-1].nextElementSibling!==drag.ph){list.insertBefore(drag.ph,els[mids.length-1].nextSibling);}}
|
|
771
|
+
window.addEventListener("pointermove",function(e){if(!drag||e.pointerId!==drag.id)return;drag.y=e.clientY;dragMove(drag.y);});
|
|
772
|
+
// P5b: a finger held still at the screen edge fires no pointermove, so a rAF loop keeps
|
|
773
|
+
// scrolling by edgeScrollStep and re-drops the placeholder while it scrolls; endDrag stops it.
|
|
774
|
+
function dragFrame(){if(!drag)return;var dy=edgeScrollStep(drag.y,window.innerHeight);if(dy){window.scrollBy(0,dy);dragMove(drag.y);}requestAnimationFrame(dragFrame);}
|
|
775
|
+
var endDrag=function(e,submitIt){if(!drag||(e&&e.pointerId!==undefined&&e.pointerId!==drag.id))return;var card=drag.card,ph=drag.ph,list=drag.list;if(drag.raf)cancelAnimationFrame(drag.raf);card.classList.remove("dragging");card.style.transform="";card.style.width="";card.style.left="";card.style.top="";list.insertBefore(card,ph);list.removeChild(ph);drag=null;if(submitIt)sendReorder(card.getAttribute("data-plan"),list);else dragging=false;};
|
|
753
776
|
window.addEventListener("pointerup",function(e){endDrag(e,true);});
|
|
754
777
|
window.addEventListener("pointercancel",function(e){endDrag(e,false);});
|
|
755
778
|
// Every POST form goes over fetch and swaps main in place (P11b); a no-JS browser still submits for real and gets the 303s.
|
|
@@ -782,7 +805,7 @@ var qlist=main.querySelector("#qlist");
|
|
|
782
805
|
if(qlist){
|
|
783
806
|
var moveCard=function(card,how){if(how==="top"){var f=qlist.querySelector(".qcard");if(f&&f!==card)qlist.insertBefore(card,f);}else if(how==="up"){var p=card.previousElementSibling;if(p&&p.classList.contains("qcard"))qlist.insertBefore(card,p);}else if(how==="down"){var n=card.nextElementSibling;if(n&&n.classList.contains("qcard"))qlist.insertBefore(card,n.nextSibling);}};
|
|
784
807
|
qlist.addEventListener("click",function(e){var t=e.target;if(!t||!t.closest)return;var b=t.closest(".qmove");if(!b)return;var card=t.closest(".qcard");if(!card)return;moveCard(card,b.getAttribute("data-move"));sendReorder(card.getAttribute("data-plan"),qlist);});
|
|
785
|
-
qlist.addEventListener("pointerdown",function(e){var t=e.target;if(!t||!t.closest)return;var h=t.closest(".qhandle");if(h&&!drag){var card=t.closest(".qcard");if(card){e.preventDefault();dragging=true;var r=card.getBoundingClientRect();var ph=document.createElement("li");ph.className="qph";ph.style.height=r.height+"px";qlist.insertBefore(ph,card);card.classList.add("dragging");card.style.width=r.width+"px";card.style.left=r.left+"px";card.style.top=r.top+"px";drag={card:card,ph:ph,y0:e.clientY,id:e.pointerId,list:qlist};try{h.setPointerCapture(e.pointerId);}catch(_){}}}});
|
|
808
|
+
qlist.addEventListener("pointerdown",function(e){var t=e.target;if(!t||!t.closest)return;var h=t.closest(".qhandle");if(h&&!drag){var card=t.closest(".qcard");if(card){e.preventDefault();dragging=true;var r=card.getBoundingClientRect();var ph=document.createElement("li");ph.className="qph";ph.style.height=r.height+"px";qlist.insertBefore(ph,card);card.classList.add("dragging");card.style.width=r.width+"px";card.style.left=r.left+"px";card.style.top=r.top+"px";drag={card:card,ph:ph,y0:e.clientY,y:e.clientY,id:e.pointerId,list:qlist,raf:0};try{h.setPointerCapture(e.pointerId);}catch(_){}requestAnimationFrame(dragFrame);}}}});
|
|
786
809
|
}
|
|
787
810
|
}
|
|
788
811
|
function busy(){if(dragging)return true;var els=document.querySelectorAll("input:not([type=hidden]), textarea");for(var k=0;k<els.length;k++){if(els[k]===document.activeElement||els[k].value)return true;}return false;}
|
|
@@ -1220,9 +1243,9 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
|
|
|
1220
1243
|
const fail = (error: string, status: number): Response =>
|
|
1221
1244
|
wantsJson ? Response.json({ ok: false, error }, { status }) : textRes(error, status);
|
|
1222
1245
|
// One source of truth for the reorderable set: the open plans, the same list queueRows renders.
|
|
1223
|
-
const
|
|
1224
|
-
|
|
1225
|
-
|
|
1246
|
+
const openPlans = activePlans(index).filter(p => p.status === "open");
|
|
1247
|
+
const openPaths = openPlans.map(p => p.file);
|
|
1248
|
+
const openPlan: Record<string, Plan> = Object.fromEntries(openPlans.map(p => [p.file, p]));
|
|
1226
1249
|
if (!moved || !order.length) return fail("order and moved are required", 400);
|
|
1227
1250
|
// 400: the posted order must be exactly the open plans the page renders now — no adds, drops or duplicates.
|
|
1228
1251
|
if (new Set(order).size !== order.length) return fail("order lists a plan more than once", 400);
|
|
@@ -1233,6 +1256,11 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
|
|
|
1233
1256
|
// 409: the order the page was rendered with must still be the open plans' current order.
|
|
1234
1257
|
const stale = before.length !== openPaths.length || before.some((p, i) => p !== openPaths[i]);
|
|
1235
1258
|
if (stale) return fail("the queue changed since the page loaded — reload and drag again", 409);
|
|
1259
|
+
// 409: the index is priority (I-20261025-208), so the posted order itself may not put a plan
|
|
1260
|
+
// above the open plan it waits on. Checked before any write: the index file and the reorder
|
|
1261
|
+
// inbox stay untouched, and the page's 409 branch shows the message and reloads the real order.
|
|
1262
|
+
const firstBlock = dependencyOrderProblems(order.map(o => openPlan[o]!))[0];
|
|
1263
|
+
if (firstBlock) return fail(`blocked: ${firstBlock}`, 409);
|
|
1236
1264
|
const from = openPaths.indexOf(moved);
|
|
1237
1265
|
const to = order.indexOf(moved);
|
|
1238
1266
|
if (from === -1 || to === -1) return fail("moved is not one of the page's plans", 400);
|
package/src/core/queue/lib.ts
CHANGED
|
@@ -807,6 +807,28 @@ export function awaitingMerge(p: Plan): boolean {
|
|
|
807
807
|
return p.status === "complete" && /^queue-close: AWAITING merge/.test(lastCloseResult(p.file) ?? "");
|
|
808
808
|
}
|
|
809
809
|
|
|
810
|
+
/**
|
|
811
|
+
* I-20261025-208: index order is priority, so an open plan must never sit above an open plan of
|
|
812
|
+
* this list it waits on. A "Waits on" target that is not an open plan of the list (complete,
|
|
813
|
+
* cancelled, gone from the index) imposes no order. Pure: queueProblems, queueSummary and the
|
|
814
|
+
* page's /reorder refusal all read it.
|
|
815
|
+
*/
|
|
816
|
+
export function dependencyOrderProblems(plans: Plan[]): string[] {
|
|
817
|
+
const rank = new Map(plans.map((p, i) => [p.file, i] as const));
|
|
818
|
+
const open = new Map(plans.filter(p => p.status === "open").map(p => [p.file, p] as const));
|
|
819
|
+
const problems: string[] = [];
|
|
820
|
+
plans.forEach((p, i) => {
|
|
821
|
+
if (p.status !== "open") return;
|
|
822
|
+
for (const f of p.waitsOn) {
|
|
823
|
+
const j = rank.get(f);
|
|
824
|
+
const target = open.get(f);
|
|
825
|
+
if (j === undefined || j <= i || !target) continue;
|
|
826
|
+
problems.push(`#${i + 1} ${p.title} waits on #${j + 1} ${target.title}; it cannot sit above it — move #${j + 1} up first or remove the "Waits on" line`);
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
return problems;
|
|
830
|
+
}
|
|
831
|
+
|
|
810
832
|
export interface QueueProblem {
|
|
811
833
|
where: string;
|
|
812
834
|
problem: string;
|
|
@@ -815,8 +837,9 @@ export interface QueueProblem {
|
|
|
815
837
|
export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR): QueueProblem[] {
|
|
816
838
|
const probs: QueueProblem[] = [];
|
|
817
839
|
if (!existsSync(index)) probs.push({ where: index, problem: "main index missing: create it (empty = no open work)" });
|
|
840
|
+
const plans = readPlans(readIndex(index), blockersDir);
|
|
818
841
|
const byWorktree = new Map<string, Plan[]>();
|
|
819
|
-
for (const p of
|
|
842
|
+
for (const p of plans) {
|
|
820
843
|
for (const e of p.errors) probs.push({ where: p.file, problem: e });
|
|
821
844
|
if ((p.status === "complete" || p.status === "cancelled") && !awaitingMerge(p)) {
|
|
822
845
|
const last = lastCloseResult(p.file);
|
|
@@ -833,6 +856,11 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR): QueueP
|
|
|
833
856
|
for (const [wt, ps] of byWorktree)
|
|
834
857
|
if (ps.length > 1)
|
|
835
858
|
probs.push({ where: wt, problem: `${ps.length} open plans name this worktree (${ps.map(p => p.file).join(", ")}); one plan = one worktree` });
|
|
859
|
+
// I-20261025-208: one problem per misranked plan, so queue-check exits 1 and the summary lists it.
|
|
860
|
+
for (const m of dependencyOrderProblems(plans)) {
|
|
861
|
+
const i = Number(/^#(\d+) /.exec(m)?.[1] ?? 0);
|
|
862
|
+
probs.push({ where: plans[i - 1]?.file ?? index, problem: m });
|
|
863
|
+
}
|
|
836
864
|
return probs;
|
|
837
865
|
}
|
|
838
866
|
|
|
@@ -840,12 +868,21 @@ export function queueSummary(index = INDEX): string {
|
|
|
840
868
|
// Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
|
|
841
869
|
// rank 1 = the index's top line; repos only surface through each plan's own path.
|
|
842
870
|
const plans = activePlans(index);
|
|
871
|
+
const rank = new Map(plans.map((p, i) => [p.file, i + 1] as const));
|
|
843
872
|
const repos = [...new Set(plans.map(p => p.repo))];
|
|
844
873
|
const lines = [`Queue (${index}): ${plans.length ? `${plans.length} plan(s) in ${repos.length} repo(s)` : "empty, no open work"}`];
|
|
845
874
|
plans.forEach((p, i) => {
|
|
846
875
|
const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
|
|
847
876
|
const hold = p.waiting ? `WAITING on owner: ${(p.waitingLine ?? "").slice(0, 80)}` : "";
|
|
848
|
-
|
|
877
|
+
// I-20261025-208: an open plan waiting on an open plan of the queue shows the target's rank.
|
|
878
|
+
const waits: string[] = [];
|
|
879
|
+
if (p.status === "open")
|
|
880
|
+
for (const f of p.waitsOn) {
|
|
881
|
+
const at = rank.get(f);
|
|
882
|
+
if (at === undefined || plans[at - 1]!.status !== "open") continue;
|
|
883
|
+
waits.push(`waits on #${at}`);
|
|
884
|
+
}
|
|
885
|
+
const flags = [status, hold, ...waits, p.priorityId ?? ""].filter(Boolean).join(", ");
|
|
849
886
|
const goal = items(sections(p.text).get("goal") ?? "")[0]?.slice(0, 100) ?? "";
|
|
850
887
|
lines.push(` ${i + 1}. ${p.file} [${flags}] ${goal}`);
|
|
851
888
|
});
|
package/src/core/queue-check.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Config } from "./config.ts";
|
|
2
2
|
import { applyQueueEnv } from "./queue/env.ts";
|
|
3
3
|
import { activePlans, queueProblems, queueSummary } from "./queue/lib.ts";
|
|
4
|
+
import { mrSweep } from "./mr-sweep.ts";
|
|
4
5
|
|
|
5
6
|
// One index (20261024_1400_one_index): the main index lists plan files directly, so there are no
|
|
6
7
|
// repo INDEX.md files to git-check and no work_roots scan; the queue problems carry the
|
|
@@ -12,5 +13,16 @@ export function queueCheck(args: string[], cfg: Config): number {
|
|
|
12
13
|
return 0;
|
|
13
14
|
}
|
|
14
15
|
console.log(queueSummary());
|
|
15
|
-
|
|
16
|
+
// main-start prints the sweep itself and passes this so the child bin does not print it twice.
|
|
17
|
+
let fail = queueProblems().length > 0;
|
|
18
|
+
if (!args.includes("--no-mr-sweep")) {
|
|
19
|
+
try {
|
|
20
|
+
const sweep = mrSweep();
|
|
21
|
+
for (const line of sweep.lines) console.log(line);
|
|
22
|
+
if (sweep.fail) fail = true;
|
|
23
|
+
} catch {
|
|
24
|
+
console.log("mr-sweep: skipped (forge unreachable)");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return fail ? 1 : 0;
|
|
16
28
|
}
|
package/templates/AGENTS.md
CHANGED
|
@@ -15,8 +15,8 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
|
|
|
15
15
|
## Scripts (run at the stated moment)
|
|
16
16
|
|Script|When|
|
|
17
17
|
|---|---|
|
|
18
|
-
|`main-start`|session start, after an abort, before every status report|
|
|
19
|
-
|`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first|
|
|
18
|
+
|`main-start`|session start, after an abort, before every status report; prints the MR sweep (open forge MRs vs open plans)|
|
|
19
|
+
|`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first; also fails when a reachable forge lists an open MR no open plan mentions (`MR !N: ignored <reason>` in a plan marks it tracked)|
|
|
20
20
|
|`agent-ledger --cap`|before every spawn|
|
|
21
21
|
|`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
|
|
22
22
|
|`brief-lint <plan.md>`|before every spawn on that plan|
|