pi-crew 0.11.57 → 0.11.59

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.
@@ -130,9 +130,10 @@ export const PiTeamsRuntimeConfigSchema = Type.Object(
130
130
  ),
131
131
  ),
132
132
  excludeContextBash: Type.Optional(Type.Boolean()),
133
- // Handoff budget: est-token (chars/4) cap on the dynamic.dependencyContext
134
- // prompt layer. Matches parseHandoffBudgetTokens in config-validation.ts
135
- // (out-of-range values are dropped → render default 1800).
133
+ // Handoff budget: effective-token cap on the dynamic.dependencyContext
134
+ // prompt layer (CJK-aware countTokens, utils/token-counter.ts — the old
135
+ // chars/4 wording was drift). Matches parseHandoffBudgetTokens in
136
+ // config-validation.ts (out-of-range values are dropped → render default 1800).
136
137
  handoffBudgetTokens: Type.Optional(Type.Integer({ minimum: 1, maximum: 1_000_000 })),
137
138
  agentExtensions: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { sensitive: true })),
138
139
  // Mux-surface policy (spec v0.7 §8.2.4): no sensitive marks — surface
@@ -291,7 +291,7 @@ const sharedFields = {
291
291
  minimum: 1,
292
292
  maximum: 1_000_000,
293
293
  description:
294
- "Est-token (chars/4) budget cap on the dependency-context layer of worker prompts (default 1800). When exceeded, later dependencies are trimmed to summary head + artifact pointer. Out-of-range values are ignored.",
294
+ "Effective-token budget cap on the dependency-context layer of worker prompts (default 1800). Tokens are counted by the in-tree CJK-aware counter (utils/token-counter.ts countTokens, floored by measured worker usage) — NOT a chars/4 estimate. When exceeded, later dependencies are trimmed to summary head + artifact pointer. Out-of-range values are ignored here; env PI_CREW_HANDOFF_BUDGET_TOKENS overrides, and a RESOLVED value ≤0 or >1_000_000 disables the trim entirely.",
295
295
  }),
296
296
  ),
297
297
  budgetTotal: Type.Optional(
@@ -612,7 +612,7 @@ export interface TeamToolParamsValue {
612
612
  b?: number;
613
613
  /** Mark certain bash commands as excludeFromContext to reduce context tokens (default: false). */
614
614
  excludeContextBash?: boolean;
615
- /** Est-token (chars/4) budget cap on the dependency-context layer of worker prompts (default 1800). Later dependencies get trimmed to summary head + artifact pointer when exceeded. */
615
+ /** Effective-token budget cap on the dependency-context layer of worker prompts (default 1800; CJK-aware countTokens from utils/token-counter.ts — the old chars/4 wording was drift). Later dependencies get trimmed to summary head + artifact pointer when exceeded. */
616
616
  handoffBudgetTokens?: number;
617
617
  /** Total token budget for the run. When set, enables budget tracking (minimum 1000). */
618
618
  budgetTotal?: number;
@@ -1,7 +1,9 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { DEFAULT_PATHS } from "../../config/defaults.ts";
3
4
  import type { ManifestSummary } from "../../runtime/task-health.ts";
4
5
  import { computeRunHealth } from "../../runtime/task-health.ts";
6
+ import { logInternalError } from "../../utils/internal-error.ts";
5
7
  import { atomicWriteFile } from "../atomic-write.ts";
6
8
 
7
9
  // Relative to the crew root (`<cwd>/.crew`). BUG A fix (pts/2 hang
@@ -77,3 +79,76 @@ export class HealthStore {
77
79
  return snapshots;
78
80
  }
79
81
  }
82
+
83
+ /**
84
+ * FIX 1 (retention): delete one run's health snapshot. The snapshot lives
85
+ * OUTSIDE the run dir (`<crewRoot>/state/health/<runId>.json` vs stateRoot
86
+ * `<crewRoot>/state/runs/<runId>/`), so prune/forget paths that rmSync the
87
+ * stateRoot must call this too or the snapshot is orphaned forever — 2,322
88
+ * files / 9.3 MB accumulated that way (oldest 2026-06-18). Path knowledge
89
+ * stays in this module (HEALTH_DIR); runId trust matches saveSnapshot
90
+ * (both sides are pi-crew-authored manifest runIds).
91
+ */
92
+ export function removeHealthSnapshot(crewRoot: string, runId: string): boolean {
93
+ try {
94
+ fs.unlinkSync(path.join(crewRoot, HEALTH_DIR, `${runId}.json`));
95
+ return true;
96
+ } catch (error) {
97
+ const code = (error as NodeJS.ErrnoException)?.code;
98
+ if (code === "ENOENT") return false;
99
+ logInternalError("health-store.remove-snapshot", error, `runId=${runId}`);
100
+ return false;
101
+ }
102
+ }
103
+
104
+ /** Default bound for the orphan sweep: files examined per call. 2,322
105
+ * orphans existed on the dev box at discovery, so 5,000 leaves headroom
106
+ * while keeping the scan bounded on pathological dirs. */
107
+ export const SWEEP_ORPHAN_HEALTH_MAX_FILES = 5000;
108
+
109
+ /**
110
+ * FIX 1 (retention): sweep pre-existing orphaned health snapshots — files
111
+ * under `<crewRoot>/state/health/` whose `<runId>` has NO run dir under
112
+ * `<crewRoot>/state/runs/` (left behind by pre-fix prunes). CONSERVATIVE:
113
+ * a run dir that exists but is unreadable (stat error other than ENOENT)
114
+ * is KEPT — only a positively-confirmed-absent run dir proves the snapshot
115
+ * is garbage. Bounded + best-effort: never throws, malformed entries are
116
+ * skipped (kept).
117
+ */
118
+ export function sweepOrphanHealthSnapshots(crewRoot: string, opts: { maxFiles?: number } = {}): { removed: string[]; kept: number } {
119
+ const removed: string[] = [];
120
+ let kept = 0;
121
+ try {
122
+ const dir = path.join(crewRoot, HEALTH_DIR);
123
+ if (!fs.existsSync(dir)) return { removed, kept };
124
+ const files = fs
125
+ .readdirSync(dir)
126
+ .filter((f) => f.endsWith(".json"))
127
+ .slice(0, opts.maxFiles ?? SWEEP_ORPHAN_HEALTH_MAX_FILES);
128
+ for (const file of files) {
129
+ const runId = file.slice(0, -".json".length);
130
+ const runDir = path.join(crewRoot, DEFAULT_PATHS.state.runsSubdir, runId);
131
+ try {
132
+ fs.statSync(runDir);
133
+ kept++; // run dir exists → snapshot still owned
134
+ continue;
135
+ } catch (error) {
136
+ // ENOENT = positively absent → orphan candidate. ANY other error
137
+ // (EACCES, EPERM on a parent…) = exists-but-unreadable → KEEP.
138
+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
139
+ kept++;
140
+ continue;
141
+ }
142
+ }
143
+ try {
144
+ fs.unlinkSync(path.join(dir, file));
145
+ removed.push(runId);
146
+ } catch {
147
+ kept++; // unlink failed → not removed → still on disk
148
+ }
149
+ }
150
+ } catch (error) {
151
+ logInternalError("health-store.sweep-orphans", error, `crewRoot=${crewRoot}`);
152
+ }
153
+ return { removed, kept };
154
+ }
@@ -78,6 +78,17 @@ export function summarizeHeartbeats(snapshot: RunUiSnapshot, opts: HeartbeatSumm
78
78
  // carry "running" task statuses that lag the run manifest's terminal
79
79
  // transition. Defense-in-depth: skip ALL task counting when the run manifest
80
80
  // itself is terminal. Runs with a non-terminal manifest are unaffected.
81
+ //
82
+ // LABEL-GC invariant (FIX 2, 2026-11): this same gate is what stops a
83
+ // terminal run from RE-ADDING the {runId,taskId} / {runId,level} label
84
+ // values released by HeartbeatWatcher once the run stopped being active
85
+ // (run-scoped label values are live only while the run is active; durable
86
+ // detail lives in events.jsonl + health snapshot). The write predicate
87
+ // below (`!isTerminalRunStatus(manifest.status)` AND a running task) never
88
+ // admits a status the watcher releases on (watcher releases only when the
89
+ // status is neither running nor blocked, i.e. completed/failed/cancelled),
90
+ // so a released series cannot be re-added. Blocked runs are skipped on BOTH
91
+ // sides — retained, resumable.
81
92
  const runTerminal = isTerminalRunStatus(snapshot.manifest.status);
82
93
  for (const task of snapshot.tasks) {
83
94
  if (runTerminal || !isActiveTask(task)) continue;