neurastream 0.2.29 → 0.2.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.29",
3
+ "version": "0.2.30",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -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);
@@ -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): Decision {
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): Decision {
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(e.after, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
1052
- if (!problems.length) return ALLOW;
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 section = READ_SECTION.exec(text)?.[1] ?? "";
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 (!(Date.parse(reads[abs] ?? "") >= Date.now() - maxMs)) problems.push(`${p} was not read by Main within ${cfg.guards.plan_read_max_hours} h`);
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.has(abs) || !isFile(abs)) continue;
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
- const roots = wt && wt !== "-" ? [wt, repo] : [repo];
1097
- const root = roots.find(r => isFile(path.join(r, home))) ?? repo;
1098
- return path.join(root, home);
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 {
@@ -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
- window.addEventListener("pointermove",function(e){if(!drag||e.pointerId!==drag.id)return;var card=drag.card,list=drag.list;card.style.transform="translateY("+(e.clientY-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);}
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
- 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;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;};
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 openPaths = activePlans(index)
1224
- .filter(p => p.status === "open")
1225
- .map(p => p.file);
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);
@@ -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 readPlans(readIndex(index), blockersDir)) {
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
- const flags = [status, hold, p.priorityId ?? ""].filter(Boolean).join(", ");
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
  });