@andares/pi-toolkits 0.13.0 → 1.0.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +123 -25
  3. package/README.zh-CN.md +75 -21
  4. package/package.json +14 -4
  5. package/src/features/ask/index.test.ts +15 -0
  6. package/src/features/ask/index.ts +17 -0
  7. package/src/features/init/audit.test.ts +19 -2
  8. package/src/features/init/audit.ts +117 -15
  9. package/src/features/init/index.test.ts +123 -1
  10. package/src/features/init/index.ts +156 -46
  11. package/src/features/init/parity.test.ts +176 -0
  12. package/src/features/init/parity.ts +229 -0
  13. package/src/features/init/plan.ts +25 -3
  14. package/src/features/init/refresh.test.ts +88 -1
  15. package/src/features/init/refresh.ts +43 -64
  16. package/src/features/init/spec.ts +11 -0
  17. package/src/features/init/templates/memory-readme.md +9 -2
  18. package/src/features/init/test-helpers.ts +1 -0
  19. package/src/features/init/workflow.ts +159 -0
  20. package/src/features/permission/policy.test.ts +10 -0
  21. package/src/features/permission/units.test.ts +157 -0
  22. package/src/features/permission/units.ts +317 -15
  23. package/src/features/plan/index.test.ts +51 -0
  24. package/src/features/plan/index.ts +24 -4
  25. package/src/features/quit-guard/constants.ts +18 -5
  26. package/src/features/quit-guard/index.ts +75 -29
  27. package/src/features/quit-guard/killer.test.ts +77 -0
  28. package/src/features/quit-guard/killer.ts +215 -0
  29. package/src/features/review/index.ts +14 -0
  30. package/src/features/review/review.test.ts +34 -2
  31. package/src/features/uat/index.test.ts +15 -0
  32. package/src/features/uat/index.ts +10 -7
  33. package/src/features/uat/record-tool.ts +3 -2
  34. package/src/features/uat/state.ts +13 -5
  35. package/src/features/whats-new/changelog.ts +104 -0
  36. package/src/features/whats-new/constants.ts +35 -0
  37. package/src/features/whats-new/index.ts +146 -0
  38. package/src/features/whats-new/notice.ts +68 -0
  39. package/src/features/whats-new/paths.ts +29 -0
  40. package/src/features/whats-new/store.ts +114 -0
  41. package/src/features/whats-new/version.ts +43 -0
  42. package/src/features/whats-new/whats-new.test.ts +460 -0
  43. package/src/index.ts +3 -0
  44. package/src/lib/phases.ts +37 -0
@@ -74,6 +74,21 @@ const DEVICE_SINKS = new Set(["/dev/null", "/dev/stdout", "/dev/stderr"]);
74
74
  */
75
75
  const NO_PATH_OPERANDS = new Set(["echo", "printf"]);
76
76
 
77
+ /**
78
+ * Flags whose value is data even when it looks like a path. `curl -w
79
+ * '%{http_code}\n'` contains a backslash, so the path heuristic claimed a
80
+ * write target inside the project (audit 2026-10-26: 2 asks). The table stays
81
+ * small on purpose: every entry widens the read blind spot for that flag.
82
+ */
83
+ const DATA_VALUE_OPTS: Record<string, ReadonlySet<string>> = {
84
+ curl: new Set([
85
+ "-w", "--write-out", "-H", "--header", "-d", "--data", "--data-raw",
86
+ "--data-binary", "--data-urlencode", "-X", "--request", "-A",
87
+ "--user-agent", "-e", "--referer", "-u", "--user", "-b", "--cookie",
88
+ "-F", "--form", "--form-string", "-x", "--proxy",
89
+ ]),
90
+ };
91
+
77
92
  /* -------------------------------------------------------------------------- */
78
93
  /* Read/write classification */
79
94
  /* -------------------------------------------------------------------------- */
@@ -232,6 +247,7 @@ export function commandEffect(command: string, args: readonly string[]): Effect
232
247
  const verb = args.find((arg) => /^[a-zA-Z]+$/.test(arg)) ?? "";
233
248
  return /[xc]/.test(verb) ? "write" : "read";
234
249
  }
250
+ if (command === "docker" || command === "podman") return containerEffect(args);
235
251
  if (READ_COMMANDS.has(command)) return "read";
236
252
  if (WRITE_COMMANDS.has(command)) return "write";
237
253
  return "write";
@@ -250,6 +266,42 @@ const REDIRECTS = new Set([
250
266
  const WRITE_REDIRECTS = new Set([">", ">>", ">|", "&>", "&>>", ">&", "<>"]);
251
267
  const PROCESS_SUBSTITUTION = new Set(["<(", ">("]);
252
268
 
269
+ /**
270
+ * Container subcommands that only inspect. `docker compose ps` in a directory
271
+ * outside the session roots used to ask as an "outside-project write" (audit
272
+ * 2026-10-29) although it touches no local file; anything not listed — `run`,
273
+ * `exec`, `rm`, `build`, … — stays a write. `exec` in particular runs an
274
+ * arbitrary command and must keep asking.
275
+ */
276
+ const CONTAINER_READ_SUBCOMMANDS = new Set([
277
+ "ps", "logs", "inspect", "images", "version", "info", "top", "stats",
278
+ "port", "diff", "history", "search", "events", "df",
279
+ ]);
280
+ const CONTAINER_VALUE_OPTS = new Set([
281
+ "-H", "--host", "--context", "-c", "--config", "--log-level",
282
+ "--tlscacert", "--tlscert", "--tlskey",
283
+ ]);
284
+ const COMPOSE_READ_SUBCOMMANDS = new Set([
285
+ "ps", "logs", "config", "top", "images", "version", "ls", "port",
286
+ ]);
287
+ const COMPOSE_VALUE_OPTS = new Set([
288
+ "-f", "--file", "-p", "--project-name", "--profile",
289
+ "--project-directory", "--env-file", "--ansi", "--progress",
290
+ ]);
291
+
292
+ function containerEffect(args: readonly string[]): Effect {
293
+ const top = firstNonOption(args, CONTAINER_VALUE_OPTS);
294
+ if (top < 0) return "write";
295
+ if (args[top] === "compose") {
296
+ const rest = args.slice(top + 1);
297
+ const inner = firstNonOption(rest, COMPOSE_VALUE_OPTS);
298
+ return inner >= 0 && COMPOSE_READ_SUBCOMMANDS.has(rest[inner])
299
+ ? "read"
300
+ : "write";
301
+ }
302
+ return CONTAINER_READ_SUBCOMMANDS.has(args[top]) ? "read" : "write";
303
+ }
304
+
253
305
  function opOf(entry: ParseEntry): string | undefined {
254
306
  if (typeof entry !== "object" || entry === null) return undefined;
255
307
  if (!("op" in entry)) return undefined;
@@ -319,6 +371,11 @@ export function stripHeredocs(input: string): string | undefined {
319
371
  * Replace `$(…)` and backtick substitutions with placeholder words and return
320
372
  * their payloads, so the outer command parses cleanly and each payload can be
321
373
  * analysed as a command of its own.
374
+ *
375
+ * Quote-aware: inside single quotes both forms are literal text, not commands
376
+ * (`grep -n ':title="x`' file` is a pattern, not an unterminated
377
+ * substitution — audit 2026-11-05). Inside double quotes they do expand, as in
378
+ * bash.
322
379
  */
323
380
  export function extractSubstitutions(input: string): {
324
381
  text: string;
@@ -327,26 +384,49 @@ export function extractSubstitutions(input: string): {
327
384
  const payloads: string[] = [];
328
385
  let out = "";
329
386
  let index = 0;
387
+ let quote: "'" | '"' | undefined;
388
+
389
+ const takeSubstitution = (start: number, end: number): void => {
390
+ payloads.push(input.slice(start, end));
391
+ out += `${SENTINEL}SUBST${payloads.length - 1}${SENTINEL}`;
392
+ };
393
+
330
394
  while (index < input.length) {
331
395
  const char = input[index];
332
- if (char === "\\") {
396
+ if (char === "\\" && quote !== "'") {
333
397
  out += input.slice(index, index + 2);
334
398
  index += 2;
335
399
  continue;
336
400
  }
401
+ if (quote === "'") {
402
+ out += char;
403
+ if (char === "'") quote = undefined;
404
+ index++;
405
+ continue;
406
+ }
407
+ if (char === "'" && quote === undefined) {
408
+ quote = "'";
409
+ out += char;
410
+ index++;
411
+ continue;
412
+ }
413
+ if (char === '"' ) {
414
+ quote = quote === '"' ? undefined : '"';
415
+ out += char;
416
+ index++;
417
+ continue;
418
+ }
337
419
  if (char === "`") {
338
420
  const end = input.indexOf("`", index + 1);
339
421
  if (end < 0) return undefined;
340
- payloads.push(input.slice(index + 1, end));
341
- out += `${SENTINEL}SUBST${payloads.length - 1}${SENTINEL}`;
422
+ takeSubstitution(index + 1, end);
342
423
  index = end + 1;
343
424
  continue;
344
425
  }
345
426
  if (char === "$" && input[index + 1] === "(") {
346
427
  const end = findClosingParen(input, index + 2);
347
428
  if (end < 0) return undefined;
348
- payloads.push(input.slice(index + 2, end));
349
- out += `${SENTINEL}SUBST${payloads.length - 1}${SENTINEL}`;
429
+ takeSubstitution(index + 2, end);
350
430
  index = end + 1;
351
431
  continue;
352
432
  }
@@ -357,12 +437,19 @@ export function extractSubstitutions(input: string): {
357
437
  }
358
438
 
359
439
  /**
360
- * Remove shell comments and verify quote balance in one pass.
440
+ * Remove shell comments, normalize line breaks, and verify quote balance in
441
+ * one pass.
361
442
  *
362
443
  * `shell-quote` silently accepts an unterminated quote, so the balance check
363
444
  * is what keeps malformed input from being parsed as a command we then judge.
364
445
  * Comments are dropped first because an apostrophe in `# it's fine` would
365
446
  * otherwise look like an opening quote. `undefined` means unbalanced.
447
+ *
448
+ * Unquoted newlines become `;`: shell-quote treats a newline as plain
449
+ * whitespace, so without this two commands on separate lines merged into one
450
+ * segment (`ls⏎rm -rf x` looked like `ls rm -rf x` — a missed write, and the
451
+ * common source of phantom "unresolved path" asks for multi-line scripts).
452
+ * A backslash-newline is a line continuation in bash and is removed instead.
366
453
  */
367
454
  function stripComments(input: string): string | undefined {
368
455
  let out = "";
@@ -371,6 +458,14 @@ function stripComments(input: string): string | undefined {
371
458
  const char = input[i];
372
459
  if (quote !== "'") {
373
460
  if (char === "\\") {
461
+ if (input[i + 1] === "\n") {
462
+ i++;
463
+ continue;
464
+ }
465
+ if (input[i + 1] === "\r" && input[i + 2] === "\n") {
466
+ i += 2;
467
+ continue;
468
+ }
374
469
  out += input.slice(i, i + 2);
375
470
  i++;
376
471
  continue;
@@ -388,10 +483,15 @@ function stripComments(input: string): string | undefined {
388
483
  }
389
484
  if (char === "#" && (i === 0 || /\s/.test(input[i - 1]))) {
390
485
  while (i < input.length && input[i] !== "\n") i++;
391
- out += "\n";
486
+ out += ";";
392
487
  continue;
393
488
  }
394
- out += char;
489
+ if (char === "\r" && input[i + 1] === "\n") {
490
+ out += ";";
491
+ i++;
492
+ continue;
493
+ }
494
+ out += char === "\n" ? ";" : char;
395
495
  }
396
496
  return quote === undefined ? out : undefined;
397
497
  }
@@ -435,6 +535,12 @@ function envFor(base: string | null): Record<string, string> {
435
535
  get(target, key) {
436
536
  if (typeof key !== "string") return undefined;
437
537
  if (Object.hasOwn(target, key)) return target[key];
538
+ // A lone `$` — end of a double-quoted string (`"</div>\s*$"`), or
539
+ // `$` before a character that cannot start a name — is literal in
540
+ // bash. shell-quote still calls the proxy with an empty key for that
541
+ // case; expanding it to the sentinel turned every such grep pattern
542
+ // into an "unresolved path" (audit 2026-11-12: 5 asks).
543
+ if (key === "") return "$";
438
544
  return `${SENTINEL}VAR${key}${SENTINEL}`;
439
545
  },
440
546
  });
@@ -539,13 +645,18 @@ function firstCommandWord(words: readonly string[]): string {
539
645
  /** Whether a word looks like a filesystem path. */
540
646
  export function looksLikePath(word: string): boolean {
541
647
  if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(word)) return false; // URL
648
+ if (/^[A-Za-z]:[\\/]/.test(word) || word.startsWith("\\\\")) return true; // Windows drive / UNC
542
649
  return (
543
650
  word === "." ||
544
651
  word === ".." ||
545
652
  word.startsWith("/") ||
546
653
  word.startsWith("~") ||
547
654
  word.includes("/") ||
548
- word.includes("\\") ||
655
+ // A bare backslash is *not* a path separator on POSIX: `\s*`, `\|`, and
656
+ // `%{http_code}\n` are regex/format text, and treating them as paths made
657
+ // read targets out of grep patterns (audit 2026-11-12). Relative Windows
658
+ // spellings (`dir\file`) join the read blind spot; the target host here is
659
+ // POSIX, and absolute Windows paths still match above.
549
660
  word.includes("*") ||
550
661
  word.includes("?") ||
551
662
  word.includes("[")
@@ -605,6 +716,21 @@ const WRITE_OPERAND_VALUE_OPTS = new Set([
605
716
  "--reference", "--mode",
606
717
  ]);
607
718
 
719
+ /**
720
+ * grep-family commands whose **first positional operand is the pattern**, not a
721
+ * path. `grep -n '</div>\s*$' src/a.vue` used to collect the pattern as a file
722
+ * target (and an unresolved `$`/`\` in a pattern as an opaque path — audit
723
+ * 2026-11-12: 5 asks). With `-e`/`-f` the pattern is named explicitly, so every
724
+ * positional is a file again.
725
+ */
726
+ const GREP_FAMILY = new Set(["grep", "egrep", "fgrep", "rg", "ag"]);
727
+ const GREP_VALUE_OPTS = new Set([
728
+ "-A", "-B", "-C", "-m", "-d", "-e", "--regexp", "-f", "--file",
729
+ "--after-context", "--before-context", "--context", "--max-count",
730
+ "--directories", "--include", "--exclude", "--exclude-dir", "--exclude-from",
731
+ "--label", "--color", "--colour",
732
+ ]);
733
+
608
734
  function dedupeTargets(targets: UnitTarget[]): UnitTarget[] {
609
735
  const seen = new Set<string>();
610
736
  const out: UnitTarget[] = [];
@@ -669,17 +795,38 @@ function analyzeSegment(
669
795
  if (words.length === 0) return { units: [], nextBase: base };
670
796
 
671
797
  // Leading `VAR=value` assignments belong to the segment's environment, not
672
- // to the command.
798
+ // to the command. A segment made only of assignments touches nothing, so it
799
+ // produces no unit (audit 2026-11-12: `f=…jsonl` asked as a write).
673
800
  let peeled = words.filter(() => true);
674
801
  while (peeled.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(peeled[0])) {
675
802
  peeled = peeled.slice(1);
676
803
  }
804
+ if (peeled.length === 0) return { units: [], nextBase: base };
677
805
 
678
806
  // Wrapper peeling: `sudo rm` is decided by `rm`, while `headWord` keeps the
679
807
  // wrapper visible for the danger table.
680
808
  for (let round = 0; round < 4; round++) {
681
809
  const step = peelOne(peeled);
682
810
  if (!step) break;
811
+ // A plain `env` / `env FOO=1` prints the environment: nothing to resolve,
812
+ // nothing to guard. Without this it was an opaque "wrapper runs no
813
+ // visible command" (audit 2026-11-12: 5 asks for `env | grep …`).
814
+ const rest = peeled.slice(step.inner);
815
+ if (step.wrapper === "env" && rest.every((word) => ASSIGNMENT_RE.test(word))) {
816
+ return {
817
+ units: [{
818
+ raw,
819
+ headWord,
820
+ command: "env",
821
+ args: rest,
822
+ effect: "read",
823
+ opaque: false,
824
+ base,
825
+ targets: [],
826
+ }],
827
+ nextBase: base,
828
+ };
829
+ }
683
830
  if (step.inner >= peeled.length) {
684
831
  return {
685
832
  units: [opaqueUnit(raw, headWord, step.wrapper, base, "wrapper runs no visible command")],
@@ -877,9 +1024,22 @@ function analyzeSegment(
877
1024
  }
878
1025
 
879
1026
  // Path-like arguments are targets for every command, except for commands
880
- // whose arguments are data (`echo`, `printf`) and device sinks.
1027
+ // whose arguments are data (`echo`, `printf`), declared data flags, and
1028
+ // device sinks.
881
1029
  if (!NO_PATH_OPERANDS.has(command)) {
882
- for (const arg of args) {
1030
+ const dataOpts = DATA_VALUE_OPTS[command];
1031
+ const patternIndex =
1032
+ GREP_FAMILY.has(command) &&
1033
+ !hasFlag(args, "-e", "--regexp", "-f", "--file")
1034
+ ? firstNonOption(args, GREP_VALUE_OPTS)
1035
+ : -1;
1036
+ for (let i = 0; i < args.length; i++) {
1037
+ const arg = args[i];
1038
+ if (dataOpts?.has(arg)) {
1039
+ i++;
1040
+ continue;
1041
+ }
1042
+ if (i === patternIndex) continue;
883
1043
  if (DEVICE_SINKS.has(arg)) continue;
884
1044
  if (!looksLikePath(arg)) continue;
885
1045
  // `sed -i` operands were already classified above; its script is not a path.
@@ -947,6 +1107,145 @@ function segmentTokens(entries: ParseEntry[]): string[][] {
947
1107
 
948
1108
  const PLACEHOLDER = /\u0000SUBST(\d+)\u0000/g;
949
1109
 
1110
+ /* -------------------------------------------------------------------------- */
1111
+ /* Literal for-loops */
1112
+ /* -------------------------------------------------------------------------- */
1113
+
1114
+ /**
1115
+ * `for f in a b; do grep x "$f"; done` is a common read-only inspection
1116
+ * shape. The tokenizer leaves `$f` as an unresolved sentinel, which made every
1117
+ * such command opaque (audit 2026-11-12: 29 of 61 asks). Expanding the literal
1118
+ * loop values is what bash does, so the per-unit judgement sees real paths.
1119
+ *
1120
+ * This deliberately does **not** persist ordinary `NAME=value` assignments:
1121
+ * without a control-flow graph, `false && d=/safe; rm "$d/x"` or
1122
+ * `d=/safe; read d; rm "$d/x"` would be judged against the wrong path. Such
1123
+ * uses stay opaque. Loop expansion likewise stops for a variable reassigned or
1124
+ * passed to a shell builtin that can mutate it.
1125
+ *
1126
+ * Anything not provably literal — a value from `$(…)`, a loop over an unknown
1127
+ * list, more than {@link MAX_EXPANSIONS} combinations, a value with whitespace
1128
+ * — is left untouched: the sentinel survives and the unit stays opaque.
1129
+ */
1130
+ const MAX_EXPANSIONS = 64;
1131
+ const ASSIGNMENT_RE = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
1132
+ const SUBST_PLACEHOLDER_RE = /\u0000SUBST\d+\u0000/;
1133
+
1134
+ interface LoopFrame {
1135
+ readonly name: string;
1136
+ /** Literal values; empty means "cannot expand, keep failing closed". */
1137
+ readonly values: readonly string[];
1138
+ }
1139
+
1140
+ interface ExpansionState {
1141
+ /** Open `for` loops, innermost last. */
1142
+ readonly loops: LoopFrame[];
1143
+ }
1144
+
1145
+ function variableMarker(name: string): string {
1146
+ return `${SENTINEL}VAR${name}${SENTINEL}`;
1147
+ }
1148
+
1149
+ /** A value that can be substituted without changing word splitting. */
1150
+ function isLiteralValue(value: string): boolean {
1151
+ return (
1152
+ value !== "" &&
1153
+ !hasSentinel(value) &&
1154
+ !SUBST_PLACEHOLDER_RE.test(value) &&
1155
+ !/\s/.test(value)
1156
+ );
1157
+ }
1158
+
1159
+ /** `for NAME in w1 w2 …`; any other header keeps an unexpandable frame. */
1160
+ function parseForHeader(words: readonly string[]): LoopFrame {
1161
+ const name = words[1] ?? "";
1162
+ if (words[2] !== "in") return { name, values: [] };
1163
+ const values = words.slice(3);
1164
+ return { name, values: values.every(isLiteralValue) ? values : [] };
1165
+ }
1166
+
1167
+ /** Stop expanding a loop variable after code may have changed its value. */
1168
+ function disableLoopVariable(state: ExpansionState, name: string): void {
1169
+ for (let i = 0; i < state.loops.length; i++) {
1170
+ if (state.loops[i].name === name) {
1171
+ state.loops[i] = { name, values: [] };
1172
+ }
1173
+ }
1174
+ }
1175
+
1176
+ const LOOP_MUTATING_COMMANDS = new Set([
1177
+ "read", "readarray", "mapfile", "unset", "export", "declare", "local",
1178
+ "typeset", "let", "printf",
1179
+ ]);
1180
+ const LOOP_DYNAMIC_COMMANDS = new Set(["eval", "source", "."]);
1181
+
1182
+ /** Conservative guard for builtins that can assign to a named variable. */
1183
+ function disableMutatedLoopVariables(
1184
+ words: readonly string[],
1185
+ state: ExpansionState,
1186
+ ): void {
1187
+ const command = words[0];
1188
+ if (LOOP_DYNAMIC_COMMANDS.has(command)) {
1189
+ for (const loop of state.loops) disableLoopVariable(state, loop.name);
1190
+ return;
1191
+ }
1192
+ if (!LOOP_MUTATING_COMMANDS.has(command)) return;
1193
+ for (const arg of words.slice(1)) {
1194
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)(?:=|$)/.exec(arg);
1195
+ if (match) disableLoopVariable(state, match[1]);
1196
+ }
1197
+ }
1198
+
1199
+ /**
1200
+ * Apply loop keywords and literal expansion to one segment.
1201
+ *
1202
+ * Returns zero segments for structural statements (`for …`, `done`, a bare
1203
+ * assignment) and one segment per literal loop value otherwise.
1204
+ */
1205
+ function expandSegment(
1206
+ words: readonly string[],
1207
+ state: ExpansionState,
1208
+ ): string[][] {
1209
+ let rest = [...words];
1210
+ if (rest[0] === "do") rest = rest.slice(1);
1211
+
1212
+ if (rest[0] === "done") {
1213
+ state.loops.pop();
1214
+ return [];
1215
+ }
1216
+ if (rest[0] === "for") {
1217
+ state.loops.push(parseForHeader(rest));
1218
+ return [];
1219
+ }
1220
+
1221
+ // A reassignment shadows the loop value from this point on. Do not substitute
1222
+ // the old literal into later commands; leave their variable marker opaque.
1223
+ while (rest.length > 0) {
1224
+ const match = ASSIGNMENT_RE.exec(rest[0]);
1225
+ if (!match) break;
1226
+ disableLoopVariable(state, match[1]);
1227
+ rest = rest.slice(1);
1228
+ }
1229
+ if (rest.length === 0) return [];
1230
+ disableMutatedLoopVariables(rest, state);
1231
+
1232
+ let variants: string[][] = [rest];
1233
+ // Innermost first: `for f in /a; do for f in /b; …` uses the inner binding.
1234
+ for (const loop of [...state.loops].reverse()) {
1235
+ if (loop.values.length === 0) continue;
1236
+ const marker = variableMarker(loop.name);
1237
+ const next: string[][] = [];
1238
+ for (const variant of variants) {
1239
+ for (const value of loop.values) {
1240
+ next.push(variant.map((word) => word.split(marker).join(value)));
1241
+ if (next.length > MAX_EXPANSIONS) return [rest];
1242
+ }
1243
+ }
1244
+ variants = next;
1245
+ }
1246
+ return variants;
1247
+ }
1248
+
950
1249
  /**
951
1250
  * Token-level walker: substitutions are analysed where their placeholder
952
1251
  * appears, so a payload after `cd /tmp` is judged against `/tmp`.
@@ -965,6 +1264,7 @@ function parseText(
965
1264
  }
966
1265
  const units: CommandUnit[] = [];
967
1266
  let currentBase = base;
1267
+ const expansion: ExpansionState = { loops: [] };
968
1268
  for (const segment of segmentTokens(entries)) {
969
1269
  const cleaned: string[] = [];
970
1270
  for (const word of segment) {
@@ -979,9 +1279,11 @@ function parseText(
979
1279
  if (rest !== "") cleaned.push(rest);
980
1280
  }
981
1281
  if (cleaned.length === 0) continue;
982
- const analyzed = analyzeSegment(cleaned, currentBase, depth);
983
- units.push(...analyzed.units);
984
- currentBase = analyzed.nextBase;
1282
+ for (const words of expandSegment(cleaned, expansion)) {
1283
+ const analyzed = analyzeSegment(words, currentBase, depth);
1284
+ units.push(...analyzed.units);
1285
+ currentBase = analyzed.nextBase;
1286
+ }
985
1287
  }
986
1288
  return units;
987
1289
  }
@@ -6,6 +6,7 @@
6
6
  * control are fakes.
7
7
  */
8
8
  import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
9
+ import { execFileSync } from "node:child_process";
9
10
  import { request } from "node:http";
10
11
  import { tmpdir } from "node:os";
11
12
  import { dirname, join } from "node:path";
@@ -155,6 +156,56 @@ describe("ask-plan command", () => {
155
156
  expect(h.control.restore).toHaveBeenCalled();
156
157
  expect(h.activeTools()).not.toContain(PLAN_SUBMIT_TOOL);
157
158
  });
159
+
160
+ it("refuses to start while ask-uat is open", async () => {
161
+ const h = harness();
162
+ h.pi.setActiveTools([...h.activeTools(), "uat_item"]);
163
+ await h.commands.get(PLAN_COMMAND)!.handler("topic", h.ctx);
164
+ expect(h.sendUserMessage).not.toHaveBeenCalled();
165
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("ask-uat"), "warning");
166
+ });
167
+
168
+ it("refuses to start while the agent is still running", async () => {
169
+ const h = harness();
170
+ const busy = { ...h.ctx, isIdle: () => false } as ExtensionContext;
171
+ await h.commands.get(PLAN_COMMAND)!.handler("topic", busy);
172
+ expect(h.sendUserMessage).not.toHaveBeenCalled();
173
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("still running"), "warning");
174
+ });
175
+
176
+ it("reads framework readiness from the main checkout in a linked worktree", async () => {
177
+ const main = mkdtempSync(join(tmpdir(), "plan-main-"));
178
+ const parent = mkdtempSync(join(tmpdir(), "plan-worktrees-"));
179
+ const linked = join(parent, "linked");
180
+ const git = (cwd: string, args: string[]) =>
181
+ execFileSync("git", ["-C", cwd, ...args], { stdio: "ignore" });
182
+ try {
183
+ git(main, ["init", "-q"]);
184
+ writeFileSync(join(main, "tracked.txt"), "one\n", "utf8");
185
+ git(main, ["add", "tracked.txt"]);
186
+ git(main, ["-c", "user.email=test@example.com", "-c", "user.name=test", "commit", "-qm", "init"]);
187
+ git(main, ["worktree", "add", "-qb", "plan-review", linked]);
188
+ mkdirSync(join(main, ".agents/framework"), { recursive: true });
189
+ writeFileSync(join(main, ".agents/framework/state.toml"), 'version = 1\ntool = "test"\n', "utf8");
190
+ writeFileSync(join(main, "AGENTS.md"), "# demo\n", "utf8");
191
+ mkdirSync(join(main, ".agents/memory"), { recursive: true });
192
+ writeFileSync(join(main, ".agents/memory/README.md"), "# contract\n", "utf8");
193
+ mkdirSync(join(main, ".agents/implementations"), { recursive: true });
194
+
195
+ const h = harness();
196
+ const linkedCtx = { ...h.ctx, cwd: linked } as ExtensionContext;
197
+ const handler = h.commands.get(PLAN_COMMAND)!.handler;
198
+ await handler("topic", linkedCtx);
199
+ expect(h.notify).not.toHaveBeenCalledWith(
200
+ expect.stringContaining("no complete agent framework"),
201
+ "info",
202
+ );
203
+ await handler("off", linkedCtx);
204
+ } finally {
205
+ rmSync(main, { recursive: true, force: true });
206
+ rmSync(parent, { recursive: true, force: true });
207
+ }
208
+ });
158
209
  });
159
210
 
160
211
  describe("phase integration", () => {
@@ -18,14 +18,17 @@
18
18
  * plannotator's habit of switching models silently is the reason this one
19
19
  * is written from scratch.
20
20
  */
21
- import { readFileSync, existsSync } from "node:fs";
22
- import { isAbsolute, join, relative, resolve } from "node:path";
21
+ import { readFileSync } from "node:fs";
22
+ import { isAbsolute, relative, resolve } from "node:path";
23
23
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
24
24
  import { Type } from "typebox";
25
25
  import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
26
26
  import type { GateHub } from "../../lib/gates.js";
27
27
  import { getPermissionControl, type PermissionSnapshot } from "../../lib/permission-control.js";
28
28
  import { getAskControl } from "../../lib/ask-control.js";
29
+ import { PLAN_PHASE_TOOL, UAT_PHASE_TOOL } from "../../lib/phases.js";
30
+ import { frameworkReadiness } from "../init/parity.js";
31
+ import { resolveProjectRoot } from "../uat/state.js";
29
32
  import { canonicalize, isWithin } from "../permission/paths.js";
30
33
  import { parseCommandUnits } from "../permission/units.js";
31
34
  import { buildFeedbackMarkdown } from "./feedback.js";
@@ -43,7 +46,7 @@ import {
43
46
  } from "./store.js";
44
47
 
45
48
  export const PLAN_COMMAND = "ask-plan";
46
- export const PLAN_SUBMIT_TOOL = "plan_submit";
49
+ export const PLAN_SUBMIT_TOOL = PLAN_PHASE_TOOL;
47
50
 
48
51
  /** Files the planning phase may write: project markdown, nothing else. */
49
52
  function isMarkdownPath(path: string): boolean {
@@ -173,7 +176,7 @@ export function registerPlan(pi: ExtensionAPI, gates: GateHub, options: PlanOpti
173
176
  // approval only when the project has the framework and the tool exists.
174
177
  recordTool:
175
178
  pi.getAllTools().some((tool) => tool.name === "record_change") &&
176
- existsSync(join(cwd, ".agents/framework/state.toml")),
179
+ frameworkReadiness(resolveProjectRoot(cwd)).ready,
177
180
  });
178
181
  }
179
182
 
@@ -240,6 +243,23 @@ export function registerPlan(pi: ExtensionAPI, gates: GateHub, options: PlanOpti
240
243
  return;
241
244
  }
242
245
 
246
+ if (!ctx.isIdle()) {
247
+ ctx.ui.notify("ask-plan: the agent is still running — finish or abort first.", "warning");
248
+ return;
249
+ }
250
+ if (pi.getActiveTools().includes(UAT_PHASE_TOOL)) {
251
+ ctx.ui.notify("ask-plan: ask-uat is open — /ask-uat off first.", "warning");
252
+ return;
253
+ }
254
+
255
+ const readiness = frameworkReadiness(resolveProjectRoot(cwd));
256
+ if (!readiness.ready) {
257
+ ctx.ui.notify(
258
+ `ask-plan: no complete agent framework (missing: ${readiness.missing.join(", ")}). The spec still works, but record_change and /ask-uat stay unavailable until /ask-init.`,
259
+ "info",
260
+ );
261
+ }
262
+
243
263
  const slug = planSlug(arg || "plan");
244
264
  specPath = `specs/${slug}.md`;
245
265
  session = undefined;
@@ -73,13 +73,26 @@ export const TEARDOWN_MARKERS = ["\x1b[?2004l", "\x1b[?1049l"] as const;
73
73
  export const SHUTDOWN_EVENT_MARKER = "session_shutdown";
74
74
 
75
75
  /**
76
- * Terminal restore written before a forced exit that never reached
77
- * `ui.stop()`: leave the alternate screen, disable bracketed paste, show the
78
- * cursor, reset attributes. Harmless when the TUI already restored (the
79
- * marker-armed path never writes it) and the only thing that makes the shell
80
- * usable when it did not.
76
+ * Terminal restore written before every forced exit (writeSync(1, …), which
77
+ * bypasses our own stdout wrapper and cannot re-arm the guard).
78
+ *
79
+ * The shutdown-event path needs it because nothing restored the terminal:
80
+ * without it the prompt comes back on the alternate screen, with bracketed
81
+ * paste on and the cursor hidden. The marker path gets it too (since
82
+ * 2026-11-13): `ui.stop()` can also hang between its two sequences —
83
+ * `?2004l` written, `?1049l` never — and an already-restored terminal
84
+ * simply ignores the extra sequences. Idempotent, unlike a frozen screen.
81
85
  */
82
86
  export const TERMINAL_RESTORE = "\x1b[?2004l\x1b[?1049l\x1b[?25h\x1b[0m\r\n";
83
87
 
88
+ /**
89
+ * Grace period for the kill fallbacks that run AFTER the report is on disk
90
+ * and "forcing exit" has been printed: `process.exit(0)` first, then, in
91
+ * layers, a same-loop `setTimeout` SIGKILL and the independent-thread
92
+ * SIGKILL from killer.ts (see there for why the timer alone is not enough:
93
+ * the main thread can deadlock inside `process.exit`, where no timer runs).
94
+ */
95
+ export const HARD_KILL_DELAY_MS = 500;
96
+
84
97
  /** Sequences that mean a TUI is starting (mode switch or suspend/resume). */
85
98
  export const RESTART_MARKERS = ["\x1b[?2004h", "\x1b[?1049h"] as const;