@danypops/papyrus 0.29.5 → 0.29.7

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.
@@ -95,7 +95,7 @@ export function renderTaskWidgetLines(theme: Theme, projection: TaskWidgetProjec
95
95
  return lines;
96
96
  }
97
97
 
98
- class TaskOverlay {
98
+ export class TaskOverlay {
99
99
  private uiCtx: ExtensionUIContext | undefined;
100
100
  private registered = false;
101
101
  private tui: any | undefined;
@@ -116,6 +116,12 @@ class TaskOverlay {
116
116
  // concurrent agent's focused task never shows as active in this session's widget.
117
117
  setSessionId(sessionId: string): void { this.sessionId = sessionId; }
118
118
 
119
+ /**
120
+ * Never throws: called from several pi.on(...) handlers, some of which (session_compact,
121
+ * session_tree, tool_execution_end) don't wrap it themselves -- Pi's event emitter does not
122
+ * guarantee catching a handler's rejection, so an unguarded throw here would become an
123
+ * unhandled rejection at the call site instead of a stability issue contained to this widget.
124
+ */
119
125
  async refresh(): Promise<void> {
120
126
  if (!this.projectRoot) return;
121
127
  try {
@@ -123,7 +129,11 @@ class TaskOverlay {
123
129
  } catch {
124
130
  this.snapshot = { nodes: [], rootIds: [] };
125
131
  }
126
- this.render();
132
+ try {
133
+ this.render();
134
+ } catch {
135
+ // A rendering bug must not crash the extension host over a best-effort status widget.
136
+ }
127
137
  }
128
138
 
129
139
  private render(): void {
@@ -519,7 +529,7 @@ export default async function (pi: ExtensionAPI) {
519
529
  const usage = ctx.getContextUsage?.();
520
530
  // Real tree (not just the linear current-branch path): surfaces content sitting in an
521
531
  // abandoned /tree branch, which cost real tokens to generate but isn't in context now.
522
- const tree = ctx.sessionManager.getTree() as unknown as SessionTreeNodeLike[];
532
+ const tree = ctx.sessionManager.getTree() as SessionTreeNodeLike[];
523
533
  // buildContextEntries(), NOT getBranch(): getBranch() returns every raw entry on the
524
534
  // current path including everything a real compaction has already summarized away.
525
535
  // A session with 3 real compactions confirmed this made "active" message-history
@@ -528,8 +538,8 @@ export default async function (pi: ExtensionAPI) {
528
538
  // LLM"); buildContextEntries() is the compaction-aware entry list matching what the
529
539
  // LLM actually sees (the latest compaction entry itself, plus kept entries from its
530
540
  // firstKeptEntryId onward, plus everything after -- older summarized entries omitted).
531
- const activeEntryIds = new Set((ctx.sessionManager.buildContextEntries() as unknown as SessionEntryLike[]).map((entry) => entry.id));
532
- const branchEntryIds = new Set((ctx.sessionManager.getBranch() as unknown as SessionEntryLike[]).map((entry) => entry.id));
541
+ const activeEntryIds = new Set((ctx.sessionManager.buildContextEntries() as SessionEntryLike[]).map((entry) => entry.id));
542
+ const branchEntryIds = new Set((ctx.sessionManager.getBranch() as SessionEntryLike[]).map((entry) => entry.id));
533
543
  const messageHistory = buildMessageHistoryTree(tree, activeEntryIds, branchEntryIds);
534
544
  const breakdown = buildContextBreakdown({
535
545
  totalTokens: usage?.tokens ?? null,
@@ -120,7 +120,8 @@ export async function showTasks(ctx: ExtensionCommandContext): Promise<void> {
120
120
  if (action.type === "graph") { await showTaskGraph(ctx, graph); continue; }
121
121
  if (action.type !== "action" || !action.row) continue;
122
122
 
123
- const node = graph.nodes.find((entry) => entry.task.id === action.row!.id);
123
+ const rowId = action.row.id;
124
+ const node = graph.nodes.find((entry) => entry.task.id === rowId);
124
125
  const active = node?.active === true;
125
126
  const focusStatus = node?.focusStatus;
126
127
  const choices = [
@@ -136,8 +137,8 @@ export async function showTasks(ctx: ExtensionCommandContext): Promise<void> {
136
137
  const choice = await ctx.ui.select(action.row.title, choices);
137
138
  if (!choice) continue;
138
139
 
139
- if (choice === "Remove dependency" || choice === "Remove from parent") {
140
- const relatedIds = choice === "Remove dependency" ? node!.dependencyIds : node!.parentIds;
140
+ if ((choice === "Remove dependency" || choice === "Remove from parent") && node) {
141
+ const relatedIds = choice === "Remove dependency" ? node.dependencyIds : node.parentIds;
141
142
  const relatedTasks = relatedIds.map((relatedId) => graph.nodes.find((entry) => entry.task.id === relatedId)?.task).filter((task): task is Artifact => task !== undefined);
142
143
  const relatedTitles = taskChoiceLabels(relatedTasks);
143
144
  const selected = await ctx.ui.select(choice === "Remove dependency" ? "Remove which dependency?" : "Remove from which parent?", relatedTitles);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danypops/papyrus",
3
- "version": "0.29.5",
3
+ "version": "0.29.7",
4
4
  "description": "Daemon-backed graph artifacts, evidence-bearing tasks, rules, skills, and native TUI workflows for Pi",
5
5
  "type": "module",
6
6
  "keywords": ["pi-package"],
package/src/daemon.ts CHANGED
@@ -52,7 +52,11 @@ export function serveMain(): void {
52
52
  clearInterval(purgeTrashTimer);
53
53
  clearDaemonPort(stateDir);
54
54
  service.close();
55
- void server.stop(true).finally(() => process.exit(0));
55
+ // .finally() re-throws rather than handling a rejection -- catching it first turns a bare
56
+ // unhandled-rejection warning into a real, queryable shutdown-failure log line.
57
+ void server.stop(true)
58
+ .catch((error) => logEvent("error", "server_stop_failed", { message: error instanceof Error ? error.message : String(error) }))
59
+ .finally(() => process.exit(0));
56
60
  };
57
61
  process.on("SIGINT", shutdown);
58
62
  process.on("SIGTERM", shutdown);
package/src/db.ts CHANGED
@@ -12,13 +12,23 @@ import { SQLITE_BUSY_TIMEOUT_MS, SQLITE_SCHEMA_VERSION } from "./constants.ts";
12
12
 
13
13
  const require_ = createRequire(import.meta.url);
14
14
  const IS_BUN = typeof (globalThis as { Bun?: unknown }).Bun !== "undefined";
15
- const backend = IS_BUN
16
- ? (require_("bun:sqlite") as typeof import("bun:sqlite"))
17
- : (require_("node:sqlite") as unknown as typeof import("bun:sqlite"));
18
15
 
19
- const DatabaseCtor = (
20
- "DatabaseSync" in backend ? (backend as { DatabaseSync: unknown }).DatabaseSync : backend.Database
21
- ) as new (path: string, opts?: { create?: boolean }) => Db;
16
+ /** Bun's bun:sqlite exports Database; Node's node:sqlite exports DatabaseSync -- neither module is
17
+ * actually the other, but both satisfy this shape at the methods Papyrus calls through Db/DbStatement. */
18
+ interface SqliteBackendModule {
19
+ Database?: new (path: string, opts?: { create?: boolean }) => Db;
20
+ DatabaseSync?: new (path: string, opts?: { create?: boolean }) => Db;
21
+ }
22
+
23
+ const backend = require_(IS_BUN ? "bun:sqlite" : "node:sqlite") as SqliteBackendModule;
24
+ // IIFE + explicit return type, not a bare `const DatabaseCtor = backend.DatabaseSync ?? backend.Database`
25
+ // with a following throw-guard: that guard's narrowing wouldn't propagate into openDb() below, a
26
+ // separate function closing over this module-level binding.
27
+ const DatabaseCtor: new (path: string, opts?: { create?: boolean }) => Db = (() => {
28
+ const ctor = backend.DatabaseSync ?? backend.Database;
29
+ if (!ctor) throw new Error("no compatible sqlite backend found (expected bun:sqlite's Database or node:sqlite's DatabaseSync)");
30
+ return ctor;
31
+ })();
22
32
 
23
33
  export interface DbStatement {
24
34
  /** changes: number of rows the statement affected. Both bun:sqlite and node:sqlite's real run() return this at runtime; declared here so callers (e.g. reapStale) can rely on it without an unsafe cast. */
package/src/ops.ts CHANGED
@@ -507,53 +507,38 @@ function readBoundedGateFile(path: string): string {
507
507
  return readFileSync(path, "utf-8") as string;
508
508
  }
509
509
 
510
+ /** Shared by the sync and async process-gate runners so "test" is never a second, independently
511
+ * maintained copy of "command"'s own command-template/timeout selection. */
512
+ function processGateCommand(gate: Gate): { command: string; timeout: number } {
513
+ if (gate.type === "test") return { command: `npx vitest run ${gate.target} --reporter=dot`, timeout: GATE_TEST_TIMEOUT_MS };
514
+ return { command: gate.target, timeout: GATE_COMMAND_TIMEOUT_MS };
515
+ }
516
+
517
+ /**
518
+ * spawnSync + manual stdout/stderr concatenation, not execSync: execSync's return value is stdout
519
+ * only. Many real commands (bun test's own per-test lines and its pass/fail summary among them, and
520
+ * vitest's own "test" gate output) write their actual output to stderr, so an execSync-based match
521
+ * against gate.expect saw only the first line of a banner and never the result -- every such gate
522
+ * failed regardless of whether the command actually passed. This one function now serves both
523
+ * "command" and "test" gates; previously "test" was a second, separately-maintained execSync path
524
+ * that never checked gate.expect at all.
525
+ */
526
+ function runProcessGateSync(gate: Gate, cwd?: string): GateResult {
527
+ const { spawnSync } = require_("node:child_process");
528
+ const { command, timeout } = processGateCommand(gate);
529
+ const result = spawnSync(command, { shell: true, encoding: "utf-8", timeout, ...(cwd ? { cwd } : {}) });
530
+ if (result.error) return { gate, passed: false, output: result.error.message.slice(0, GATE_OUTPUT_LIMIT) };
531
+ const combined = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
532
+ const passed = result.status === 0 && (gate.expect ? combined.includes(gate.expect) : true);
533
+ return { gate, passed, output: combined.slice(0, GATE_OUTPUT_LIMIT) || (result.status === 0 ? "ok" : `command exited with code ${result.status}`) };
534
+ }
535
+
510
536
  export function runGates(db: Db, artifactId: string, options: GateRunOptions = {}): GateResult[] {
511
537
  const art = getArtifact(db, artifactId);
512
538
  if (!art) throw new Error("artifact not found");
513
539
  const gates = (art.extra["gates"] as Gate[]) ?? [];
514
540
  const cwd = options.cwd;
515
- return gates.map((gate) => {
516
- switch (gate.type) {
517
- case "file-exists": {
518
- const { existsSync } = require_("node:fs");
519
- const exists = existsSync(gate.target);
520
- return { gate, passed: exists, output: exists ? "exists" : "not found" };
521
- }
522
- case "contains": {
523
- try {
524
- const content = readBoundedGateFile(gate.target);
525
- const found = gate.expect ? content.includes(gate.expect) : content.length > 0;
526
- return { gate, passed: found, output: found ? "found" : `"${gate.expect ?? ""}" not found` };
527
- } catch {
528
- return { gate, passed: false, output: "file not readable" };
529
- }
530
- }
531
- case "command": {
532
- // spawnSync + manual stdout/stderr concatenation, not execSync: execSync's return value is
533
- // stdout only. Many real commands (bun test's own per-test lines and its pass/fail summary
534
- // among them) write their actual output to stderr, so an execSync-based match against
535
- // gate.expect saw only the first line of a banner and never the result -- every such gate
536
- // failed regardless of whether the command actually passed.
537
- const { spawnSync } = require_("node:child_process");
538
- const result = spawnSync(gate.target, { shell: true, encoding: "utf-8", timeout: GATE_COMMAND_TIMEOUT_MS, ...(cwd ? { cwd } : {}) });
539
- if (result.error) return { gate, passed: false, output: result.error.message.slice(0, GATE_OUTPUT_LIMIT) };
540
- const combined = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
541
- const passed = result.status === 0 && (gate.expect ? combined.includes(gate.expect) : true);
542
- return { gate, passed, output: combined.slice(0, GATE_OUTPUT_LIMIT) || (result.status === 0 ? "ok" : `command exited with code ${result.status}`) };
543
- }
544
- case "test": {
545
- const { execSync } = require_("node:child_process");
546
- try {
547
- execSync(`npx vitest run ${gate.target} --reporter=dot`, { encoding: "utf-8", timeout: GATE_TEST_TIMEOUT_MS, stdio: ["pipe", "pipe", "pipe"], ...(cwd ? { cwd } : {}) });
548
- return { gate, passed: true, output: "tests passed" };
549
- } catch (e) {
550
- return { gate, passed: false, output: e instanceof Error ? e.message.slice(0, GATE_OUTPUT_LIMIT) : "tests failed" };
551
- }
552
- }
553
- default:
554
- return { gate, passed: false, output: `unknown gate type: ${String(gate.type)}` };
555
- }
556
- });
541
+ return gates.map((gate) => (gate.type === "command" || gate.type === "test") ? runProcessGateSync(gate, cwd) : runNonProcessGate(gate));
557
542
  }
558
543
 
559
544
  /**
@@ -652,8 +637,7 @@ export async function runGatesAsync(db: Db, artifactId: string, options: GateRun
652
637
  continue;
653
638
  }
654
639
  if (gate.type === "command" || gate.type === "test") {
655
- const command = gate.type === "test" ? `npx vitest run ${gate.target} --reporter=dot` : gate.target;
656
- const configuredTimeout = gate.type === "test" ? GATE_TEST_TIMEOUT_MS : GATE_COMMAND_TIMEOUT_MS;
640
+ const { command, timeout: configuredTimeout } = processGateCommand(gate);
657
641
  const timeout = remainingMs === undefined ? configuredTimeout : Math.max(1, Math.min(configuredTimeout, remainingMs));
658
642
  const executed = await executeGateCommand(command, timeout, options.cwd);
659
643
  results.push({
@@ -286,10 +286,11 @@ export class Tasks {
286
286
  const byId = new Map(tasks.map((task) => [task.id, task]));
287
287
  const focus = this.focusStore.get(filter.sessionId);
288
288
  const focusedId = focus?.taskId;
289
+ const focusStatus = focus?.status;
289
290
  const nodes = new Map(tasks.map((task) => [task.id, {
290
291
  task,
291
292
  active: task.id === focusedId,
292
- ...(task.id === focusedId ? { focusStatus: focus!.status } : {}),
293
+ ...(task.id === focusedId ? { focusStatus } : {}),
293
294
  parentIds: [] as string[],
294
295
  childIds: [] as string[],
295
296
  dependencyIds: [] as string[],