@andares/pi-toolkits 0.11.3 → 0.12.1

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.
@@ -35,6 +35,7 @@ import {
35
35
  IMPLEMENTATIONS_DIR,
36
36
  MEMORY_DIR,
37
37
  PLAN_FILE,
38
+ PLANS_DIR,
38
39
  REPORTS_DIR,
39
40
  SIGNPOST_FILE,
40
41
  SPECS_DIR,
@@ -374,7 +375,6 @@ export function stateToToml(state: FrameworkState): string {
374
375
  updated: state.updated,
375
376
  profile: state.profile,
376
377
  modules: state.modules,
377
- lang: state.lang,
378
378
  budgets: state.budgets
379
379
  ? compact({
380
380
  agents_md_soft_chars: state.budgets.agentsMdSoftChars,
@@ -618,6 +618,7 @@ export function applyPlan(plan: Plan, options: ApplyOptions = {}): ApplyResult {
618
618
  ? writeCoverageFile(plan, plan.artifacts.coverage)
619
619
  : undefined;
620
620
  const planPath = !ctx.dryRun && plan.artifacts.plan ? writeWorkOrder(plan, ctx) : undefined;
621
+ const scrubbedPlans = planPath ? scrubPlanArtifacts(join(plan.root, PLANS_DIR), false) : 0;
621
622
 
622
623
  const summary: string[] = [];
623
624
  if (ctx.snapshot) summary.push(`snapshot: ${ctx.snapshot.dir} (${ctx.snapshot.files} files)`);
@@ -628,6 +629,7 @@ export function applyPlan(plan: Plan, options: ApplyOptions = {}): ApplyResult {
628
629
  if (ctx.created.length > 0) summary.push(`created ${ctx.created.length} files`);
629
630
  if (coverageWritten) summary.push(`coverage worklist: ${coverageWritten}`);
630
631
  if (planPath) summary.push(`work order: ${planPath}`);
632
+ if (scrubbedPlans > 0) summary.push(`removed obsolete fields from ${scrubbedPlans} plan artifact(s)`);
631
633
  if (ctx.skipped.length > 0) summary.push(`skipped ${ctx.skipped.length} (see report)`);
632
634
 
633
635
  return {
@@ -666,6 +668,102 @@ function writeWorkOrder(plan: Plan, ctx: ApplyContext): string | undefined {
666
668
  return plan.artifacts.plan;
667
669
  }
668
670
 
671
+ /**
672
+ * Remove retired language directives from every plan artifact in a directory.
673
+ * Covers the top-level `language` key and the retired survey-task line that old
674
+ * runs serialized into `tasks[].detail`. Local-only run artefacts; unreadable
675
+ * files are left untouched. Returns how many files were (or would be) rewritten.
676
+ */
677
+ const RETIRED_DETAIL_LINES = [
678
+ "Language for everything you write: en.",
679
+ "Language for everything you write: zh.",
680
+ ];
681
+
682
+ function scrubPlanArtifacts(dir: string, dryRun: boolean): number {
683
+ if (!existsSync(dir)) return 0;
684
+ let scrubbed = 0;
685
+ for (const name of readdirSync(dir).sort()) {
686
+ if (!name.endsWith(".json")) continue;
687
+ const file = join(dir, name);
688
+ try {
689
+ const value = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown> | null;
690
+ if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
691
+ let changed = false;
692
+ if ("language" in value) {
693
+ delete value.language;
694
+ changed = true;
695
+ }
696
+ if (Array.isArray(value.tasks)) {
697
+ for (const task of value.tasks) {
698
+ if (task === null || typeof task !== "object") continue;
699
+ const record = task as Record<string, unknown>;
700
+ if (typeof record.detail !== "string") continue;
701
+ const kept = record.detail
702
+ .split("\n")
703
+ .filter((line) => !RETIRED_DETAIL_LINES.includes(line))
704
+ .join("\n");
705
+ if (kept === record.detail) continue;
706
+ record.detail = kept;
707
+ changed = true;
708
+ }
709
+ }
710
+ if (!changed) continue;
711
+ scrubbed += 1;
712
+ if (!dryRun) writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
713
+ } catch {
714
+ // Not ours to fix: malformed artifacts stay as they are.
715
+ }
716
+ }
717
+ return scrubbed;
718
+ }
719
+
720
+ /**
721
+ * A retired `lang` key, in the shapes TOML accepts. Only the top-level region of
722
+ * the state file is filtered: an identically named key inside a table belongs to
723
+ * that table, not to us.
724
+ */
725
+ const RETIRED_STATE_LINE = /^\s*lang\s*=\s*["'](?:zh|en)["']\s*(?:#.*)?$/;
726
+
727
+ function scrubStateLang(raw: string): string {
728
+ const lines = raw.split("\n");
729
+ const firstTable = lines.findIndex((line) => /^\s*\[/.test(line));
730
+ const limit = firstTable === -1 ? lines.length : firstTable;
731
+ return lines.filter((line, index) => index >= limit || !RETIRED_STATE_LINE.test(line)).join("\n");
732
+ }
733
+
734
+ export interface ScrubOptions {
735
+ /** Report what would change without touching the files. */
736
+ readonly dryRun?: boolean;
737
+ }
738
+
739
+ export interface ScrubResult {
740
+ /** state.toml lost (in a dry run: would lose) the retired key. */
741
+ readonly stateScrubbed: boolean;
742
+ /** Plan artifacts that were (in a dry run: would be) rewritten. */
743
+ readonly plansScrubbed: number;
744
+ }
745
+
746
+ /**
747
+ * Maintenance entry: remove retired language fields from an installed
748
+ * framework (the `lang` line in state.toml, the `language` key and the retired
749
+ * survey line in plan artifacts). Idempotent — a second call reports nothing to
750
+ * do. Files outside the three retired shapes are not rewritten.
751
+ */
752
+ export function scrubRetiredFields(root: string, options: ScrubOptions = {}): ScrubResult {
753
+ const dryRun = options.dryRun === true;
754
+ const stateFile = join(root, STATE_FILE);
755
+ let stateScrubbed = false;
756
+ if (existsSync(stateFile)) {
757
+ const raw = readFileSync(stateFile, "utf8");
758
+ const kept = scrubStateLang(raw);
759
+ if (kept !== raw) {
760
+ stateScrubbed = true;
761
+ if (!dryRun) writeFileSync(stateFile, kept, "utf8");
762
+ }
763
+ }
764
+ return { stateScrubbed, plansScrubbed: scrubPlanArtifacts(join(root, PLANS_DIR), dryRun) };
765
+ }
766
+
669
767
  /** Write state, refreshing the hashes of files this framework manages. */
670
768
  function writeState(root: string, state: FrameworkState): string {
671
769
  const managedPaths = [CONTRACT_FILE, SIGNPOST_FILE, STATE_GITIGNORE];
@@ -192,7 +192,7 @@ describe("detect", () => {
192
192
  it("parses a deliberately partial state file", () => {
193
193
  const state = parseState('version = 1\nroots = []\n');
194
194
  expect(state.version).toBe(1);
195
- expect(state.lang).toBe("en");
195
+ expect(Object.keys(state)).not.toContain("lang");
196
196
  expect(state.profile).toBe("core");
197
197
  });
198
198
  });
@@ -220,7 +220,6 @@ describe("review regressions", () => {
220
220
  updated: "2026-01-01T00:00:00+08:00",
221
221
  profile: "core",
222
222
  modules: [],
223
- lang: "en",
224
223
  budgets: {
225
224
  agentsMdSoftChars: 9000,
226
225
  agentsMdHardChars: 16000,
@@ -389,7 +389,6 @@ export function parseState(raw: string): FrameworkState {
389
389
  const updated = String(data.updated ?? created);
390
390
  const profile = data.profile === "full" ? "full" : "core";
391
391
  const modules = Array.isArray(data.modules) ? data.modules.map(String) : [];
392
- const lang = data.lang === "zh" ? "zh" : "en";
393
392
  const budgets = data.budgets as Record<string, unknown> | undefined;
394
393
  const roots = Array.isArray(data.roots)
395
394
  ? (data.roots as Array<Record<string, unknown>>).map((entry) => ({
@@ -429,7 +428,6 @@ export function parseState(raw: string): FrameworkState {
429
428
  updated,
430
429
  profile,
431
430
  modules,
432
- lang,
433
431
  budgets: budgets
434
432
  ? {
435
433
  agentsMdSoftChars: numberOrUndefined(
@@ -798,7 +796,7 @@ export function detect(root: string, options: DetectOptions = {}): Facts {
798
796
  modulesPresent: readModulesPresent(root, memory),
799
797
  refs: scanRefs(root),
800
798
  project: detectProject(root),
801
- language: options.lang ?? state?.lang ?? detectLanguage(root),
799
+ language: options.lang ?? detectLanguage(root),
802
800
  roots: mergeRoots(root, state?.roots ?? [], options.addedRoots ?? []),
803
801
  warnings: contextWarnings(context, state, stateError),
804
802
  };
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { buildWorkOrder, serializeWorkOrder } from "./dispatch.js";
3
+ import { buildPlan } from "./plan.js";
4
+ import { detect } from "./detect.js";
5
+ import { project } from "./test-helpers.js";
6
+
7
+ const NOW = new Date("2026-10-26T10:00:00Z");
8
+
9
+ function planFor(files: Record<string, string>) {
10
+ return buildPlan(detect(project(files)), { toolVersion: "test", now: NOW });
11
+ }
12
+
13
+ describe("buildWorkOrder", () => {
14
+ it("contains no language directive at all", () => {
15
+ const order = buildWorkOrder({ plan: planFor({ "README.md": "# demo\n" }) });
16
+ // The work order must not tell the model which language to write or reply in —
17
+ // it works that out from the project's own docs. Rendering language for the
18
+ // framework's own files is computed in code and never appears here.
19
+ expect(order).not.toMatch(/prose language/i);
20
+ expect(order).not.toMatch(/\blanguage\b/i);
21
+ expect(order).not.toMatch(/\b(English|Chinese)\b/);
22
+ expect(order).toContain("Repository:");
23
+ expect(order).toContain("Plan (machine-readable):");
24
+ });
25
+
26
+ it("keeps the project language out of the survey task detail", () => {
27
+ const plan = planFor({ "README.md": "# 演示\n\n本项目只做演示,说明保持中文。\n" });
28
+ expect(plan.language).toBe("zh");
29
+ const order = buildWorkOrder({ plan });
30
+ expect(order).not.toMatch(/\blanguage\b/i);
31
+ const survey = plan.tasks.find((task) => task.id === "survey");
32
+ expect(survey?.detail).not.toMatch(/\blanguage\b/i);
33
+ });
34
+
35
+ it("persists no language field in the serialized work order", () => {
36
+ const plan = planFor({ "README.md": "# demo\n" });
37
+ const raw = serializeWorkOrder(plan);
38
+ expect(raw).not.toMatch(/\blanguage\b/i);
39
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
40
+ expect("language" in parsed).toBe(false);
41
+ });
42
+ });
@@ -26,7 +26,6 @@ const MODE_LABEL: Record<Plan["mode"], string> = {
26
26
 
27
27
  export function buildWorkOrder(input: WorkOrderInput): string {
28
28
  const { plan, applied } = input;
29
- const language = plan.language === "zh" ? "Chinese" : "English";
30
29
 
31
30
  const done: string[] = [];
32
31
  if (applied) {
@@ -65,7 +64,6 @@ export function buildWorkOrder(input: WorkOrderInput): string {
65
64
  `AGENT FRAMEWORK v${plan.frameworkVersion} — ${MODE_LABEL[plan.mode]}`,
66
65
  "",
67
66
  `Repository: ${plan.root}`,
68
- `Prose language for anything you write: ${language}.`,
69
67
  `Plan (machine-readable): ${input.planPath ?? plan.artifacts.plan ?? "(see the plan task)"}`,
70
68
  "",
71
69
  "The deterministic half has already run. Do not repeat it, and do not move, rename or scaffold directories yourself unless a task says so.",
@@ -112,7 +110,6 @@ export function serializeWorkOrder(plan: Plan, applied?: ApplyResult): string {
112
110
  version: plan.frameworkVersion,
113
111
  mode: plan.mode,
114
112
  root: plan.root,
115
- language: plan.language,
116
113
  createdAt: plan.createdAt,
117
114
  tool: plan.toolVersion,
118
115
  artifacts: plan.artifacts,
@@ -83,6 +83,7 @@ describe("parseInitArgs", () => {
83
83
  expect(parseInitArgs("").sub).toBe("run");
84
84
  expect(parseInitArgs("check").sub).toBe("check");
85
85
  expect(parseInitArgs("roots").sub).toBe("roots");
86
+ expect(parseInitArgs("scrub").sub).toBe("scrub");
86
87
  expect(parseInitArgs("plan --deep").sub).toBe("plan");
87
88
  });
88
89
 
@@ -328,4 +329,44 @@ describe("review regressions", () => {
328
329
  remove(root);
329
330
  }
330
331
  });
332
+
333
+ it("scrubs retired language fields, once, and honours --dry-run", async () => {
334
+ const state = [
335
+ "version = 1",
336
+ 'tool = "0.11.0"',
337
+ 'created = "2026-01-01T00:00:00+08:00"',
338
+ 'updated = "2026-01-01T00:00:00+08:00"',
339
+ 'profile = "core"',
340
+ "modules = []",
341
+ 'lang = "zh"',
342
+ "",
343
+ ].join("\n");
344
+ const plan = `${JSON.stringify({ framework: "agent-framework", language: "zh", tasks: [] }, null, 2)}\n`;
345
+ const root = project({
346
+ ".agents/framework/state.toml": state,
347
+ ".agents/framework/plans/plan-old.json": plan,
348
+ });
349
+ try {
350
+ const dry = harness(root);
351
+ registerInit(dry.pi, { now: NOW, toolVersion: "test" });
352
+ await dry.run("scrub --dry-run");
353
+ expect(dry.messages.at(-1)?.message).toMatch(/would clean/);
354
+ expect(readFileSync(join(root, ".agents/framework/state.toml"), "utf8")).toBe(state);
355
+ expect(readFileSync(join(root, ".agents/framework/plans/plan-old.json"), "utf8")).toBe(plan);
356
+
357
+ const h = harness(root);
358
+ registerInit(h.pi, { now: NOW, toolVersion: "test" });
359
+ await h.run("scrub");
360
+ expect(h.messages.at(-1)?.message).toMatch(/cleaned/);
361
+ expect(readFileSync(join(root, ".agents/framework/state.toml"), "utf8")).not.toMatch(/^\s*lang\s*=/m);
362
+ expect(readFileSync(join(root, ".agents/framework/plans/plan-old.json"), "utf8")).not.toMatch(/"language"/);
363
+
364
+ const again = harness(root);
365
+ registerInit(again.pi, { now: NOW, toolVersion: "test" });
366
+ await again.run("scrub");
367
+ expect(again.messages.at(-1)?.message).toMatch(/nothing to scrub/);
368
+ } finally {
369
+ remove(root);
370
+ }
371
+ });
331
372
  });
@@ -31,7 +31,7 @@ import type {
31
31
  } from "@earendil-works/pi-coding-agent";
32
32
  import { Text } from "@earendil-works/pi-tui";
33
33
  import { stateToToml } from "./apply.js";
34
- import { applyPlan } from "./apply.js";
34
+ import { applyPlan, scrubRetiredFields } from "./apply.js";
35
35
  import { audit, countFindings, renderFindings } from "./audit.js";
36
36
  import { detect } from "./detect.js";
37
37
  import { buildWorkOrder } from "./dispatch.js";
@@ -60,7 +60,7 @@ export interface InitOptions {
60
60
  }
61
61
 
62
62
  export interface ParsedInitArgs {
63
- readonly sub: "run" | "plan" | "check" | "roots" | "help";
63
+ readonly sub: "run" | "plan" | "check" | "roots" | "scrub" | "help";
64
64
  readonly dryRun: boolean;
65
65
  readonly deep: boolean;
66
66
  readonly yes: boolean;
@@ -74,9 +74,9 @@ const USAGE = [
74
74
  "/ask-init plan [--deep] show the plan only (writes nothing)",
75
75
  "/ask-init check audit the installed framework (read-only)",
76
76
  "/ask-init roots sync pi-add-dir roots into the framework state",
77
- "/ask-init --dry-run same as plan",
77
+ "/ask-init --dry-run report only, write nothing (same as plan)",
78
78
  "/ask-init --yes skip the confirmation panel",
79
- "/ask-init --lang zh|en language for generated prose",
79
+ "/ask-init --lang zh|en rendering language for framework-generated files",
80
80
  ].join("\n");
81
81
 
82
82
  export function parseInitArgs(input: string): ParsedInitArgs {
@@ -89,7 +89,7 @@ export function parseInitArgs(input: string): ParsedInitArgs {
89
89
  const unknown: string[] = [];
90
90
  for (let index = 0; index < tokens.length; index += 1) {
91
91
  const token = tokens[index];
92
- if (token === "plan" || token === "check" || token === "roots" || token === "help") {
92
+ if (token === "plan" || token === "check" || token === "roots" || token === "scrub" || token === "help") {
93
93
  sub = token;
94
94
  continue;
95
95
  }
@@ -231,7 +231,7 @@ function planText(plan: Plan): string {
231
231
  const lines = [
232
232
  `/ask-init — ${plan.mode}`,
233
233
  `root: ${plan.root}`,
234
- `framework: v${plan.frameworkVersion} · language: ${plan.language}`,
234
+ `framework: v${plan.frameworkVersion}`,
235
235
  "",
236
236
  "## plan",
237
237
  ...plan.summary.map((line) => `- ${line}`),
@@ -443,6 +443,27 @@ function createRunHandler(
443
443
  return;
444
444
  }
445
445
 
446
+ // Hidden maintenance subcommand (not in USAGE): removes retired fields
447
+ // from an installed framework. Documented in AGENTS.md only; obeys
448
+ // `--dry-run` because that flag promises "nothing is written".
449
+ if (parsed.sub === "scrub") {
450
+ const result = scrubRetiredFields(root, { dryRun: parsed.dryRun });
451
+ const parts: string[] = [];
452
+ if (result.stateScrubbed) parts.push(".agents/framework/state.toml");
453
+ if (result.plansScrubbed > 0) {
454
+ parts.push(`${result.plansScrubbed} plan artifact(s)`);
455
+ }
456
+ const verb = parsed.dryRun ? "would clean" : "cleaned";
457
+ const suffix = parsed.dryRun ? " — nothing was written." : "";
458
+ ctx.ui.notify(
459
+ parts.length > 0
460
+ ? `ask-init scrub: ${verb} ${parts.join(" · ")}${suffix}`
461
+ : "ask-init scrub: nothing to scrub — state and plan artifacts are already clean.",
462
+ "info",
463
+ );
464
+ return;
465
+ }
466
+
446
467
  const toolVersion = options.toolVersion ?? packageVersion();
447
468
  const now = options.now ?? new Date();
448
469
  const addedRoots = options.addedRoots ?? addedRootsFromBranch(ctx);
@@ -558,11 +579,11 @@ export function registerInit(pi0: ExtensionAPI, options: InitOptions = {}): void
558
579
  { value: "plan", label: "plan", description: "show the plan only (writes nothing)" },
559
580
  { value: "check", label: "check", description: "audit the installed framework" },
560
581
  { value: "roots", label: "roots", description: "sync pi-add-dir roots into state" },
561
- { value: "--dry-run", label: "--dry-run", description: "same as plan" },
582
+ { value: "--dry-run", label: "--dry-run", description: "report only, write nothing" },
562
583
  { value: "--deep", label: "--deep", description: "allow structural rewrites" },
563
584
  { value: "--yes", label: "--yes", description: "skip the confirmation panel" },
564
- { value: "--lang zh", label: "--lang zh", description: "Chinese prose" },
565
- { value: "--lang en", label: "--lang en", description: "English prose" },
585
+ { value: "--lang zh", label: "--lang zh", description: "render framework text in Chinese" },
586
+ { value: "--lang en", label: "--lang en", description: "render framework text in English" },
566
587
  ].filter((item) => item.value.startsWith(prefix)),
567
588
  handler: createRunHandler(pi, options, runtime),
568
589
  });
@@ -216,7 +216,6 @@ function buildState(
216
216
  updated: iso(now),
217
217
  profile: "core",
218
218
  modules: [...new Set(modules)],
219
- lang: facts.language,
220
219
  budgets: previous?.budgets,
221
220
  roots: facts.roots.length > 0 ? facts.roots : (previous?.roots ?? []),
222
221
  managed: previous?.managed ?? [],
@@ -249,7 +248,6 @@ function surveyTask(facts: Facts): Task {
249
248
  "Read the project and record only evidence; anything you cannot verify is `TBD`.",
250
249
  `Read: ${read.join(", ") || "(no manifests found — walk the tree)"}`,
251
250
  `Also: directory tree (depth 2-3, skip build dirs), \`git log --oneline -20\`, README.`,
252
- `Language for everything you write: ${facts.language}.`,
253
251
  ].join("\n"),
254
252
  acceptance: [
255
253
  "every command in AGENTS.md was read from a manifest/CI/script, not guessed",
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * init feature — markdown fragments shared by the plan, the scaffold and the
3
- * work order. Kept language-aware: the framework's own text is English, but
4
- * anything written into a project follows that project's language.
3
+ * work order. Language-aware only for the framework's own rendered text — never
4
+ * a directive to the model about which language to use.
5
5
  */
6
6
  import {
7
7
  MEMORY_DIR,
@@ -308,9 +308,11 @@ export type AuditCode = (typeof AUDIT_CODES)[keyof typeof AUDIT_CODES];
308
308
  /* -------------------------------------------------------------------------- */
309
309
 
310
310
  /**
311
- * Framework-owned text (contract, plan headers, audit codes) ships in English:
312
- * it is read by models and published on npm. Text *written into a project*
313
- * follows that project's language (`zh` when its docs are mostly CJK).
311
+ * Rendering language for framework-generated files (skeleton, seeds, index
312
+ * tables). This is our own output choice, never a directive to the model:
313
+ * nothing in this package tells the model which language to write or reply in —
314
+ * the model judges that itself from the project's own docs. The value is
315
+ * computed per run and is never persisted to state or plan artifacts.
314
316
  */
315
317
  export type ProjectLanguage = "zh" | "en";
316
318
 
@@ -60,7 +60,6 @@ export interface FrameworkState {
60
60
  updated: string;
61
61
  profile: "core" | "full";
62
62
  modules: string[];
63
- lang: ProjectLanguage;
64
63
  budgets?: {
65
64
  agentsMdSoftChars?: number;
66
65
  agentsMdHardChars?: number;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * quit-guard feature — constants and the rationale behind them.
3
+ *
4
+ * WHY a terminal-sequence trigger instead of `session_shutdown`: pi runs
5
+ * extension shutdown handlers one after another without a timeout. If a
6
+ * handler loaded BEFORE ours never settles, our own `session_shutdown` never
7
+ * runs, so a watchdog armed from that event would miss exactly the hangs it
8
+ * is meant to catch. The teardown sequence below is written by the TUI
9
+ * before that phase starts, so it arms the guard regardless of extension
10
+ * load order (and even when the host's own writes are what hangs).
11
+ *
12
+ * Teardown markers (arm):
13
+ * - `\x1b[?2004l` — bracketed paste off, written by `ProcessTerminal.stop()`
14
+ * (both `regular` and `fullscreen` modes);
15
+ * - `\x1b[?1049l` — alternate-screen exit, written by the fullscreen
16
+ * renderer's `afterTerminalStop()`.
17
+ *
18
+ * Restart markers (disarm): a TUI that re-enters must never be killed by a
19
+ * timer meant for a process that is leaving:
20
+ * - `\x1b[?2004h` — bracketed paste on, `ProcessTerminal.start()`;
21
+ * - `\x1b[?1049h` — alternate-screen enter, fullscreen `beforeTerminalStart()`.
22
+ *
23
+ * These cover the two legitimate teardown-then-restart paths: an interactive
24
+ * TUI mode switch (`switchTuiMode()` stops the old renderer with
25
+ * `preserveScreen`, then starts the new one) and Ctrl+Z suspend/resume
26
+ * (`handleCtrlZ()` calls `ui.stop()`, then `ui.start()` on SIGCONT). The
27
+ * SIGCONT listener in index.ts disarms synchronously as well, so an expired
28
+ * timer cannot win a race against a resume.
29
+ *
30
+ * Scope: interactive TUI only. Print/JSON/RPC sessions never write these
31
+ * sequences, so the guard stays inert there (documented boundary).
32
+ */
33
+ export const QUIT_GUARD_FILE = "pi-toolkits-quit-guard.json";
34
+
35
+ /** Directory holding the JSON reports written when the guard fires. */
36
+ export const QUIT_GUARD_REPORT_DIR = "quit-guard";
37
+
38
+ /**
39
+ * Default watchdog deadline, measured from the terminal teardown write.
40
+ *
41
+ * Measured on a 20-extension setup (2026-11-05): a healthy `/quit` spends
42
+ * ~0.1–3 s between the teardown write and `process.exit(0)` (the whole
43
+ * `runtimeHost.dispose()` / extension-shutdown phase), and 0.12 s with
44
+ * `pi -ne`. 10 s leaves a wide margin for a slow-but-finishing shutdown
45
+ * (e.g. a memory flush or an MCP server close) while still returning the
46
+ * prompt quickly when something never settles.
47
+ */
48
+ export const DEFAULT_TIMEOUT_MS = 10_000;
49
+
50
+ /** Floor for `/quit-guard <ms>`: below this, a healthy slow quit would be cut. */
51
+ export const MIN_TIMEOUT_MS = 2_000;
52
+
53
+ /** Ceiling for `/quit-guard <ms>`: beyond this the user is better off with `kill -9`. */
54
+ export const MAX_TIMEOUT_MS = 60_000;
55
+
56
+ /** Sequences after which the interactive TUI has begun tearing down. */
57
+ export const TEARDOWN_MARKERS = ["\x1b[?2004l", "\x1b[?1049l"] as const;
58
+
59
+ /** Sequences that mean a TUI is starting (mode switch or suspend/resume). */
60
+ export const RESTART_MARKERS = ["\x1b[?2004h", "\x1b[?1049h"] as const;