pi-daddy 0.49.4 → 0.50.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 (149) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/README.md +218 -28
  3. package/dist/governance/initiative-coordinator.d.ts +58 -0
  4. package/dist/governance/initiative-coordinator.d.ts.map +1 -0
  5. package/dist/governance/initiative-coordinator.js +348 -0
  6. package/dist/governance/initiative-coordinator.js.map +1 -0
  7. package/dist/governance/initiative-effects.d.ts +20 -0
  8. package/dist/governance/initiative-effects.d.ts.map +1 -0
  9. package/dist/governance/initiative-effects.js +108 -0
  10. package/dist/governance/initiative-effects.js.map +1 -0
  11. package/dist/governance/initiative-state.d.ts +13 -0
  12. package/dist/governance/initiative-state.d.ts.map +1 -0
  13. package/dist/governance/initiative-state.js +122 -0
  14. package/dist/governance/initiative-state.js.map +1 -0
  15. package/dist/governance/operation-artifact-io.d.ts +8 -0
  16. package/dist/governance/operation-artifact-io.d.ts.map +1 -0
  17. package/dist/governance/operation-artifact-io.js +95 -0
  18. package/dist/governance/operation-artifact-io.js.map +1 -0
  19. package/dist/governance/operation-artifact-scan.d.ts +13 -0
  20. package/dist/governance/operation-artifact-scan.d.ts.map +1 -0
  21. package/dist/governance/operation-artifact-scan.js +71 -0
  22. package/dist/governance/operation-artifact-scan.js.map +1 -0
  23. package/dist/governance/operation-artifacts.d.ts +53 -0
  24. package/dist/governance/operation-artifacts.d.ts.map +1 -0
  25. package/dist/governance/operation-artifacts.js +309 -0
  26. package/dist/governance/operation-artifacts.js.map +1 -0
  27. package/dist/governance/runtime-settlement.d.ts +2 -0
  28. package/dist/governance/runtime-settlement.d.ts.map +1 -1
  29. package/dist/governance/runtime-settlement.js +26 -0
  30. package/dist/governance/runtime-settlement.js.map +1 -1
  31. package/dist/governance/workspace-acceptance.d.ts +5 -0
  32. package/dist/governance/workspace-acceptance.d.ts.map +1 -1
  33. package/dist/governance/workspace-acceptance.js +16 -0
  34. package/dist/governance/workspace-acceptance.js.map +1 -1
  35. package/dist/index.d.ts +8 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +8 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/kernel/dashboard-observation.d.ts +76 -0
  40. package/dist/kernel/dashboard-observation.d.ts.map +1 -0
  41. package/dist/kernel/dashboard-observation.js +49 -0
  42. package/dist/kernel/dashboard-observation.js.map +1 -0
  43. package/dist/kernel/dispatch-operation.d.ts +2 -0
  44. package/dist/kernel/dispatch-operation.d.ts.map +1 -1
  45. package/dist/kernel/dispatch-operation.js.map +1 -1
  46. package/dist/kernel/initiative.d.ts +94 -0
  47. package/dist/kernel/initiative.d.ts.map +1 -0
  48. package/dist/kernel/initiative.js +38 -0
  49. package/dist/kernel/initiative.js.map +1 -0
  50. package/dist/kernel/operation-artifact.d.ts +49 -0
  51. package/dist/kernel/operation-artifact.d.ts.map +1 -0
  52. package/dist/kernel/operation-artifact.js +4 -0
  53. package/dist/kernel/operation-artifact.js.map +1 -0
  54. package/dist/kernel/principal-binding.d.ts +4 -0
  55. package/dist/kernel/principal-binding.d.ts.map +1 -0
  56. package/dist/kernel/principal-binding.js +94 -0
  57. package/dist/kernel/principal-binding.js.map +1 -0
  58. package/dist/kernel/project-paths.d.ts +6 -0
  59. package/dist/kernel/project-paths.d.ts.map +1 -1
  60. package/dist/kernel/project-paths.js +12 -0
  61. package/dist/kernel/project-paths.js.map +1 -1
  62. package/dist/kernel/selected-definitions.d.ts.map +1 -1
  63. package/dist/kernel/selected-definitions.js +5 -91
  64. package/dist/kernel/selected-definitions.js.map +1 -1
  65. package/dist/kernel/workspace-diagnostics.d.ts +24 -0
  66. package/dist/kernel/workspace-diagnostics.d.ts.map +1 -0
  67. package/dist/kernel/workspace-diagnostics.js +81 -0
  68. package/dist/kernel/workspace-diagnostics.js.map +1 -0
  69. package/dist/products/activity-storage.d.ts +2 -0
  70. package/dist/products/activity-storage.d.ts.map +1 -0
  71. package/dist/products/activity-storage.js +119 -0
  72. package/dist/products/activity-storage.js.map +1 -0
  73. package/dist/products/activity-timeline.d.ts +4 -0
  74. package/dist/products/activity-timeline.d.ts.map +1 -1
  75. package/dist/products/activity-timeline.js +12 -0
  76. package/dist/products/activity-timeline.js.map +1 -1
  77. package/dist/products/dashboard-cli.d.ts +2 -0
  78. package/dist/products/dashboard-cli.d.ts.map +1 -1
  79. package/dist/products/dashboard-cli.js +41 -9
  80. package/dist/products/dashboard-cli.js.map +1 -1
  81. package/dist/products/dashboard-display-controls.d.ts.map +1 -1
  82. package/dist/products/dashboard-display-controls.js +30 -0
  83. package/dist/products/dashboard-display-controls.js.map +1 -1
  84. package/dist/products/dashboard-file-cache.d.ts +10 -0
  85. package/dist/products/dashboard-file-cache.d.ts.map +1 -0
  86. package/dist/products/dashboard-file-cache.js +38 -0
  87. package/dist/products/dashboard-file-cache.js.map +1 -0
  88. package/dist/products/dashboard-panels.d.ts +6 -0
  89. package/dist/products/dashboard-panels.d.ts.map +1 -0
  90. package/dist/products/dashboard-panels.js +179 -0
  91. package/dist/products/dashboard-panels.js.map +1 -0
  92. package/dist/products/dashboard-screen.d.ts +8 -0
  93. package/dist/products/dashboard-screen.d.ts.map +1 -1
  94. package/dist/products/dashboard-screen.js +86 -15
  95. package/dist/products/dashboard-screen.js.map +1 -1
  96. package/dist/products/dashboard-session-client.d.ts +16 -2
  97. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  98. package/dist/products/dashboard-session-client.js +64 -11
  99. package/dist/products/dashboard-session-client.js.map +1 -1
  100. package/dist/products/dashboard-settings.d.ts.map +1 -1
  101. package/dist/products/dashboard-settings.js +4 -6
  102. package/dist/products/dashboard-settings.js.map +1 -1
  103. package/dist/products/ecosystem-versions.d.ts +1 -1
  104. package/dist/products/ecosystem-versions.d.ts.map +1 -1
  105. package/extensions/activity-timeline.ts +3 -1
  106. package/extensions/artifact-bridge.ts +130 -0
  107. package/extensions/dashboard-live.ts +63 -0
  108. package/extensions/dashboard-observation.ts +39 -0
  109. package/extensions/dashboard-session-server.ts +45 -3
  110. package/extensions/dashboard-sources.ts +124 -0
  111. package/extensions/delegation-artifacts.ts +125 -0
  112. package/extensions/delegation-operations.ts +100 -42
  113. package/extensions/ecosystem-versions.ts +12 -5
  114. package/extensions/grants-command.ts +34 -6
  115. package/extensions/grants.ts +9 -20
  116. package/extensions/initiative-dashboard.ts +143 -0
  117. package/extensions/initiative-runtime.ts +406 -0
  118. package/extensions/runtime-snapshot.ts +121 -2
  119. package/extensions/session-environment.ts +13 -1
  120. package/extensions/session.ts +28 -10
  121. package/extensions/workspace-diagnostics.ts +90 -0
  122. package/package.json +1 -1
  123. package/src/governance/initiative-coordinator.ts +400 -0
  124. package/src/governance/initiative-effects.ts +146 -0
  125. package/src/governance/initiative-state.ts +144 -0
  126. package/src/governance/operation-artifact-io.ts +103 -0
  127. package/src/governance/operation-artifact-scan.ts +77 -0
  128. package/src/governance/operation-artifacts.ts +363 -0
  129. package/src/governance/runtime-settlement.ts +28 -0
  130. package/src/governance/workspace-acceptance.ts +18 -0
  131. package/src/index.ts +13 -0
  132. package/src/kernel/dashboard-observation.ts +109 -0
  133. package/src/kernel/dispatch-operation.ts +2 -0
  134. package/src/kernel/initiative.ts +126 -0
  135. package/src/kernel/operation-artifact.ts +46 -0
  136. package/src/kernel/principal-binding.ts +104 -0
  137. package/src/kernel/project-paths.ts +16 -0
  138. package/src/kernel/selected-definitions.ts +5 -100
  139. package/src/kernel/workspace-diagnostics.ts +110 -0
  140. package/src/products/activity-storage.ts +128 -0
  141. package/src/products/activity-timeline.ts +11 -0
  142. package/src/products/dashboard-cli.ts +44 -9
  143. package/src/products/dashboard-display-controls.ts +27 -0
  144. package/src/products/dashboard-file-cache.ts +38 -0
  145. package/src/products/dashboard-panels.ts +217 -0
  146. package/src/products/dashboard-screen.ts +107 -17
  147. package/src/products/dashboard-session-client.ts +78 -14
  148. package/src/products/dashboard-settings.ts +4 -6
  149. package/src/products/ecosystem-versions.ts +2 -1
@@ -0,0 +1,128 @@
1
+ /** Initialize default activity storage once per recorder, before observing product identity. */
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, realpath } from "node:fs/promises";
4
+ import { execFile } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import {
8
+ ACTIVITY_GITIGNORE_CONTENT,
9
+ activityTimelinePath,
10
+ piProjectDir,
11
+ projectGitignorePath,
12
+ projectStateDir,
13
+ } from "../kernel/project-paths.ts";
14
+
15
+ const execute = promisify(execFile);
16
+ const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === "ENOENT";
17
+
18
+ async function ordinaryDirectory(path: string): Promise<void> {
19
+ try {
20
+ await mkdir(path, { mode: 0o700 });
21
+ } catch (error) {
22
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
23
+ }
24
+ const info = await lstat(path);
25
+ if (!info.isDirectory() || info.isSymbolicLink())
26
+ throw Error("activity storage path is not an ordinary directory; nothing followed or replaced");
27
+ }
28
+
29
+ /** Without Git, allow ordinary non-repository roles but never guess that a marked repo is safe. */
30
+ async function markerFreeNonRepository(cwd: string): Promise<boolean> {
31
+ if (["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE"].some((key) => process.env[key]?.trim()))
32
+ return false;
33
+ let current = await realpath(cwd);
34
+ for (let depth = 0; depth < 128; depth++) {
35
+ try {
36
+ await lstat(join(current, ".git"));
37
+ return false;
38
+ } catch (error) {
39
+ if (!missing(error)) throw error;
40
+ }
41
+ const parent = dirname(current);
42
+ if (parent === current) return true;
43
+ current = parent;
44
+ }
45
+ return false;
46
+ }
47
+
48
+ export async function prepareDefaultActivityStorage(cwd: string, path: string): Promise<void> {
49
+ // Configured and transported locations retain their explicit existing policy.
50
+ if (resolve(path) !== activityTimelinePath(cwd)) return;
51
+ const root = resolve(cwd),
52
+ ignore = projectGitignorePath(root),
53
+ state = projectStateDir(root);
54
+ const git = (...args: string[]) =>
55
+ execute(
56
+ "git",
57
+ ["--no-optional-locks", ...(args[0] === "ls-files" ? ["--literal-pathspecs"] : []), "-C", root, ...args],
58
+ {
59
+ encoding: "utf8",
60
+ maxBuffer: 64 * 1024,
61
+ timeout: 2000,
62
+ env: { ...process.env, LC_ALL: "C" },
63
+ },
64
+ );
65
+ let repository = true;
66
+ try {
67
+ await git("rev-parse", "--show-toplevel");
68
+ } catch (error) {
69
+ const result = error as { code?: number | string; stderr?: string };
70
+ if (
71
+ (result.code === "ENOENT" || (result.code === 128 && result.stderr?.includes("not a git repository"))) &&
72
+ (await markerFreeNonRepository(root))
73
+ )
74
+ repository = false;
75
+ else throw Error("activity Git policy could not be checked; recording unavailable");
76
+ }
77
+ if (repository) {
78
+ const tracked = await git("ls-files", "-z", "--", path, `${path}.lock`, join(state, "content"));
79
+ if (tracked.stdout.length)
80
+ throw Error("activity runtime files are already tracked; no index or ignore policy was changed");
81
+ }
82
+ await ordinaryDirectory(piProjectDir(root));
83
+ await ordinaryDirectory(state);
84
+ let present = true;
85
+ try {
86
+ const info = await lstat(ignore);
87
+ if (!info.isFile() || info.isSymbolicLink())
88
+ throw Error("activity ignore path is not an ordinary file; nothing followed or replaced");
89
+ } catch (error) {
90
+ if (missing(error)) present = false;
91
+ else throw error;
92
+ }
93
+ if (!present) {
94
+ if (repository && (await git("ls-files", "-z", "--", ignore)).stdout.length)
95
+ throw Error("tracked ignore file is missing; recording did not recreate it");
96
+ try {
97
+ const file = await open(
98
+ ignore,
99
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0),
100
+ 0o600,
101
+ );
102
+ try {
103
+ await file.writeFile(ACTIVITY_GITIGNORE_CONTENT, "utf8");
104
+ } finally {
105
+ await file.close();
106
+ }
107
+ } catch (error) {
108
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
109
+ // Another cooperating initializer won. Preserve its file and validate its policy below.
110
+ }
111
+ }
112
+ const installed = await lstat(ignore);
113
+ if (!installed.isFile() || installed.isSymbolicLink())
114
+ throw Error("activity ignore path changed; recording unavailable");
115
+ if (repository) {
116
+ // Require the directory itself to be excluded: one sample digest cannot prove that
117
+ // custom rules cover every digest and temporary filename.
118
+ for (const probe of [path, `${path}.lock`, `${join(state, "content")}/`]) {
119
+ try {
120
+ await git("check-ignore", "-q", "--", probe);
121
+ } catch {
122
+ throw Error(
123
+ "existing Git policy does not exclude default activity storage; existing rules were preserved and recording is unavailable",
124
+ );
125
+ }
126
+ }
127
+ }
128
+ }
@@ -4,6 +4,7 @@ import { constants } from "node:fs";
4
4
  import { appendFile, mkdir, open, readFile, realpath, rename, writeFile } from "node:fs/promises";
5
5
  import { dirname, join, resolve, sep } from "node:path";
6
6
  import { activityTimelinePath } from "../kernel/project-paths.ts";
7
+ import { prepareDefaultActivityStorage } from "./activity-storage.ts";
7
8
  import { isEpisodeId, newEpisodeId } from "../kernel/episode-id.ts";
8
9
  import { ENV_EPISODE_ID } from "../kernel/env-names.ts";
9
10
  import { appendRecord, readRecords } from "../governance/record.ts";
@@ -572,7 +573,10 @@ export class ActivityTimelineRecorder {
572
573
  readonly rootId: string;
573
574
  readonly episodeId: string;
574
575
  private taskId?: string;
576
+ private storageReady?: Promise<void>;
577
+ private readonly cwd: string;
575
578
  constructor(cwd: string, env: NodeJS.ProcessEnv = process.env) {
579
+ this.cwd = cwd;
576
580
  const configured = env[ENV_ACTIVITY_TIMELINE]?.trim();
577
581
  this.enabled = configured !== "off" && configured !== "0";
578
582
  this.contentEnabled =
@@ -584,6 +588,11 @@ export class ActivityTimelineRecorder {
584
588
  this.episodeId = isEpisodeId(inheritedEpisodeId) ? inheritedEpisodeId : newEpisodeId();
585
589
  this.taskId = identity.taskId;
586
590
  }
591
+ /** Await during session_start. Direct recorder users also pass this before any write. */
592
+ prepareStorage(): Promise<void> {
593
+ if (!this.enabled) return Promise.resolve();
594
+ return (this.storageReady ??= prepareDefaultActivityStorage(this.cwd, this.path));
595
+ }
587
596
  get task(): string | undefined {
588
597
  return this.taskId;
589
598
  }
@@ -660,6 +669,7 @@ export class ActivityTimelineRecorder {
660
669
  fields: Omit<Partial<ActivityEvent>, "version" | "id" | "kind" | "at" | "rootId" | "taskId">,
661
670
  ): Promise<void> {
662
671
  if (!this.enabled || !this.taskId) return;
672
+ await this.prepareStorage();
663
673
  const event: ActivityEvent = {
664
674
  version: 1,
665
675
  id: randomUUID(),
@@ -676,6 +686,7 @@ export class ActivityTimelineRecorder {
676
686
  await appendRecord(this.path, "activity", event); // ADR-0076 PR 3d: envelope, lock, damage refusal
677
687
  }
678
688
  private async content(value: string): Promise<ContentReference> {
689
+ await this.prepareStorage();
679
690
  const digest = sha(value),
680
691
  bytes = Buffer.byteLength(value);
681
692
  if (!this.contentEnabled || bytes > MAX_CONTENT_BYTES) return { digest, bytes };
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { dashboardFile, dashboardTimeline, dashboardSelectedDetail } from "./dashboard-file-cache.ts";
2
3
  /**
3
4
  * `pi-daddy-dashboard` — the view of one ledger or activity timeline plus session model controls.
4
5
  *
@@ -64,6 +65,8 @@ export interface DashboardFrameOptions {
64
65
  screen?: DashboardScreenState;
65
66
  notice?: string;
66
67
  pending?: boolean;
68
+ connected?: boolean;
69
+ acknowledgment?: string;
67
70
  command?: string;
68
71
  }
69
72
 
@@ -147,9 +150,12 @@ async function compactFrame(options: DashboardFrameOptions): Promise<string> {
147
150
  problem: "INCOMPATIBLE dashboard protocol; relink this package.",
148
151
  });
149
152
  try {
150
- const text = await readFile(path, "utf8");
153
+ const text = options.session?.observation ? await dashboardFile(path) : await readFile(path, "utf8");
151
154
  if (!options.ledgerPath || isActivityTimelineText(text)) {
152
- const timeline = parseActivityTimeline(text);
155
+ const parsed = dashboardTimeline(path, text);
156
+ const timeline = options.session?.observation
157
+ ? { ...parsed, tasks: parsed.tasks.filter((task) => task.rootId === options.session!.activity?.rootId) }
158
+ : parsed;
153
159
  items = activityDashboardItems(timeline, aliases, options.now ?? new Date()).map((item) => ({
154
160
  ...item,
155
161
  timelinePath: path,
@@ -157,6 +163,22 @@ async function compactFrame(options: DashboardFrameOptions): Promise<string> {
157
163
  problem = timeline.refusals[0];
158
164
  } else {
159
165
  const projection = parseDashboardLedger(text, { now: options.now });
166
+ if (options.session?.observation) {
167
+ const owner = options.session.observation.logicalOwnerId;
168
+ const admitted = new Set(
169
+ projection.nodes.filter((node) => owner && node.logicalParentId === owner).map((node) => node.executionId),
170
+ );
171
+ for (let pass = 0; pass < projection.nodes.length; pass++) {
172
+ let changed = false;
173
+ for (const node of projection.nodes)
174
+ if (node.parentExecutionId && admitted.has(node.parentExecutionId) && !admitted.has(node.executionId)) {
175
+ admitted.add(node.executionId);
176
+ changed = true;
177
+ }
178
+ if (!changed) break;
179
+ }
180
+ projection.nodes = projection.nodes.filter((node) => admitted.has(node.executionId));
181
+ }
160
182
  items = ledgerDashboardItems(projection);
161
183
  if (projection.corrupt.length) problem = `Ledger unavailable: ${projection.corrupt.length} corrupt line(s)`;
162
184
  }
@@ -172,15 +194,22 @@ async function compactFrame(options: DashboardFrameOptions): Promise<string> {
172
194
  const key = activityTaskKey(activity.rootId, activity.taskId);
173
195
  current = `Task ${activity.taskId}`;
174
196
  try {
175
- const timeline = parseActivityTimeline(await readFile(activity.path, "utf8"));
176
- timeline.tasks = timeline.tasks.filter((task) => activityTaskKey(task.rootId, task.id) === key);
197
+ const text = options.session?.observation
198
+ ? await dashboardFile(activity.path)
199
+ : await readFile(activity.path, "utf8");
200
+ const parsed = dashboardTimeline(activity.path, text);
201
+ const timeline = {
202
+ ...parsed,
203
+ tasks: parsed.tasks.filter((task) => activityTaskKey(task.rootId, task.id) === key),
204
+ };
177
205
  const item = activityDashboardItems(timeline, aliases, options.now ?? new Date())[0];
178
206
  if (item) {
179
207
  current = item.label;
180
208
  currentStatus = item.status;
181
209
  if (!items.some((existing) => existing.key === key)) items.unshift({ ...item, timelinePath: activity.path });
182
210
  try {
183
- current = (await detailForTimeline(activity.path, key, "prompt")).text.slice(0, 600);
211
+ if (!options.session?.observation)
212
+ current = (await detailForTimeline(activity.path, key, "prompt")).text.slice(0, 600);
184
213
  } catch {
185
214
  /* Metadata-only/off and unavailable retained content retain the exact task identity. */
186
215
  }
@@ -198,8 +227,10 @@ async function compactFrame(options: DashboardFrameOptions): Promise<string> {
198
227
  const source = items.find((value) => value.taskKey === key)?.timelinePath;
199
228
  if (!source) throw Error("task has no retained activity source");
200
229
  content = {
201
- title: `PRIVATE ${options.activityDetail.field.toUpperCase()}`,
202
- text: (await detailForTimeline(source, key, options.activityDetail.field)).text,
230
+ title: `PRIVATE ${options.activityDetail.field.toUpperCase()} · selected snapshot`,
231
+ text: options.session?.observation
232
+ ? (await dashboardSelectedDetail(options.activityDetail, source, key)).text
233
+ : (await detailForTimeline(source, key, options.activityDetail.field)).text,
203
234
  };
204
235
  } catch (error) {
205
236
  problem = `Activity detail unavailable: ${error instanceof Error ? error.message : String(error)}`;
@@ -328,7 +359,11 @@ export async function runDashboard(argv = process.argv.slice(2), env: NodeJS.Pro
328
359
  width: process.stdout.columns || 80,
329
360
  ...display.state,
330
361
  activityAliases: display.aliases,
331
- session: connection.state.snapshot,
362
+ session: connection.state.snapshot ?? connection.state.lastObserved,
363
+ connected: Boolean(connection.state.snapshot),
364
+ acknowledgment: connection.state.acknowledgment
365
+ ? `${connection.state.acknowledgment.action}: ${connection.state.acknowledgment.state} · ${connection.state.acknowledgment.effect}`
366
+ : undefined,
332
367
  ...(interactive
333
368
  ? {
334
369
  height: process.stdout.rows || 24,
@@ -414,7 +449,7 @@ export async function runDashboard(argv = process.argv.slice(2), env: NodeJS.Pro
414
449
  let action = display.key(
415
450
  key.name === "return"
416
451
  ? "return"
417
- : ["up", "down", "escape", "tab"].includes(key.name || "")
452
+ : ["up", "down", "pageup", "pagedown", "escape", "tab"].includes(key.name || "")
418
453
  ? key.name!
419
454
  : text || "",
420
455
  );
@@ -1,3 +1,4 @@
1
+ import { DASHBOARD_DESTINATIONS } from "./dashboard-panels.ts";
1
2
  import { DASHBOARD_SETTING_KEYS } from "./dashboard-settings.ts";
2
3
  /** Local display controls; these never dispatch actions to an owner or change ledger state. */
3
4
  import { dashboardScreenState } from "./dashboard-screen.ts";
@@ -18,22 +19,44 @@ export function createDashboardDisplayControls(details: boolean, ledger: boolean
18
19
  state,
19
20
  screen,
20
21
  key(key: string): "auto" | "quit" | "command" | "setting" | undefined {
22
+ if (/^[1-6]$/.test(key)) {
23
+ screen.selections ??= {};
24
+ if (screen.selectedKey) screen.selections[screen.destination ?? "now"] = screen.selectedKey;
25
+ screen.destination = DASHBOARD_DESTINATIONS[Number(key) - 1];
26
+ screen.selectedKey = screen.selections[screen.destination!];
27
+ screen.view = screen.destination === "settings" ? "settings" : "main";
28
+ screen.offset = 0;
29
+ state.activityDetail = undefined;
30
+ return;
31
+ }
32
+ if (key === "pageup" || key === "pagedown") {
33
+ screen.manualScroll = true;
34
+ screen.offset = Math.max(0, screen.offset + (key === "pageup" ? -8 : 8));
35
+ return;
36
+ }
37
+ if (key === "x") {
38
+ screen.expanded = !screen.expanded;
39
+ return;
40
+ }
21
41
  if (key === "a") return "auto";
22
42
  if (key === "q" || key === "ctrl-c") return "quit";
23
43
  if (key === ":") return "command";
24
44
  if (screen.view === "settings" && (key === "return" || key === "d")) return "setting";
25
45
  if (key === "escape") {
26
46
  screen.view = screen.view === "version-details" ? "versions" : "main";
47
+ if (screen.view === "main" && screen.destination === "settings") screen.destination = "now";
27
48
  state.activityDetail = undefined;
28
49
  screen.offset = 0;
29
50
  } else if (key === "?" || key === "m" || key === "v" || key === "s") {
30
51
  screen.view = key === "?" ? "help" : key === "v" ? "versions" : key === "s" ? "settings" : "models";
52
+ if (key === "s") screen.destination = "settings";
31
53
  state.activityDetail = undefined;
32
54
  screen.offset = 0;
33
55
  } else if (key === "return" || key === "d") {
34
56
  screen.view = screen.view === "versions" ? "version-details" : "details";
35
57
  screen.offset = 0;
36
58
  } else if (["up", "down", "j", "k"].includes(key)) {
59
+ screen.manualScroll = false;
37
60
  const delta = key === "up" || key === "k" ? -1 : 1;
38
61
  if (screen.view === "settings") {
39
62
  const index = DASHBOARD_SETTING_KEYS.indexOf(screen.settingKey ?? "auto");
@@ -53,8 +76,12 @@ export function createDashboardDisplayControls(details: boolean, ledger: boolean
53
76
  state.activityDetail = undefined;
54
77
  }
55
78
  } else if (key === "tab") {
79
+ screen.selections ??= {};
80
+ if (screen.selectedKey)
81
+ screen.selections[`${screen.destination ?? "now"}:${state.filter ?? "everything"}`] = screen.selectedKey;
56
82
  const filters = ["everything", "agents", "skills", "needs-you"] as const;
57
83
  state.filter = filters[(filters.indexOf(state.filter ?? "everything") + 1) % filters.length];
84
+ screen.selectedKey = screen.selections[`${screen.destination ?? "now"}:${state.filter}`];
58
85
  screen.view = "main";
59
86
  state.activityDetail = undefined;
60
87
  } else if (key === "p" || key === "f") {
@@ -0,0 +1,38 @@
1
+ /** Small display cache: bounded metadata reads, no filesystem traversal or durable writes. */
2
+ import { stat } from "node:fs/promises";
3
+ import { readBoundedTextSync } from "../kernel/bounded-read-sync.ts";
4
+ import { parseActivityTimeline, detailForTimeline } from "./activity-timeline.ts";
5
+ const MAX_BYTES = 2 * 1024 * 1024;
6
+ const files = new Map<
7
+ string,
8
+ { checked: number; identity: string; text: string; timeline?: ReturnType<typeof parseActivityTimeline> }
9
+ >();
10
+ export async function dashboardFile(path: string, now = Date.now()): Promise<string> {
11
+ const cached = files.get(path);
12
+ if (cached && now - cached.checked < 1000) return cached.text;
13
+ const s = await stat(path);
14
+ if (!s.isFile() || s.size > MAX_BYTES)
15
+ throw Error("Dashboard metadata file unavailable or exceeds 2 MiB; no full-history restore");
16
+ const identity = `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}`;
17
+ if (cached?.identity === identity) {
18
+ cached.checked = now;
19
+ return cached.text;
20
+ }
21
+ const text = readBoundedTextSync(path, { maxBytes: MAX_BYTES }).text;
22
+ files.set(path, { checked: now, identity, text });
23
+ while (files.size > 4) files.delete(files.keys().next().value!);
24
+ return text;
25
+ }
26
+ export function dashboardTimeline(path: string, text: string) {
27
+ const cached = files.get(path);
28
+ if (cached?.text === text) return (cached.timeline ??= parseActivityTimeline(text));
29
+ return parseActivityTimeline(text);
30
+ }
31
+
32
+ // One explicit selection, read once. A fresh p/f selection obtains a new checked snapshot.
33
+ let detail: { selection: object; source: string; key: string; value: ReturnType<typeof detailForTimeline> } | undefined;
34
+ export function dashboardSelectedDetail(selection: { field: "prompt" | "final" }, source: string, key: string) {
35
+ if (detail?.selection !== selection || detail.source !== source || detail.key !== key)
36
+ detail = { selection, source, key, value: detailForTimeline(source, key, selection.field) };
37
+ return detail.value;
38
+ }
@@ -0,0 +1,217 @@
1
+ /** Six current-session destinations share stable row identities; contributions are labels, never authority. */
2
+ import type { DashboardContribution } from "../kernel/dashboard-observation.ts";
3
+ import type { DashboardItem, DashboardScreenOptions } from "./dashboard-screen.ts";
4
+ import { dashboardText } from "./dashboard-screen.ts";
5
+ import { activityTaskKey } from "./activity-timeline.ts";
6
+ import { truncate, cellWidth } from "./dashboard-render.ts";
7
+ export type DashboardDestination = "now" | "work" | "reviews" | "activity" | "evidence" | "settings";
8
+ export const DASHBOARD_DESTINATIONS: DashboardDestination[] = [
9
+ "now",
10
+ "work",
11
+ "reviews",
12
+ "activity",
13
+ "evidence",
14
+ "settings",
15
+ ];
16
+ const clean = (s: string) => dashboardText(s).replace(/\s+/g, " ").trim();
17
+ const row = (item: DashboardContribution, key: string, source: string, stale = false): DashboardItem => ({
18
+ key,
19
+ label: item.label,
20
+ status: stale ? "last-observed" : item.state,
21
+ elapsed: "",
22
+ agent: item.kind === "work",
23
+ details: [
24
+ `Source: ${source}`,
25
+ `Observed state: ${item.state}${stale ? " (stale/disconnected)" : ""}`,
26
+ ...(item.details ?? []),
27
+ ...(item.reference ? [`Reference: ${item.reference}`] : []),
28
+ ...(item.kind === "review" ? ["A reported judgment is not execution authority or overall task acceptance."] : []),
29
+ "Reported observations do not grant execution authority or task approval.",
30
+ ...(stale ? ["Current liveness/applicability unknown; no automatic retry."] : []),
31
+ ],
32
+ });
33
+ export function sessionDashboardItems(options: DashboardScreenOptions): DashboardItem[] {
34
+ const observed = options.session!.observation!;
35
+ const destination = options.screen.destination ?? "now";
36
+ const staleOwner = options.connected === false;
37
+ const now = options.now?.getTime() ?? Date.now();
38
+ const wanted =
39
+ destination === "work"
40
+ ? ["work"]
41
+ : destination === "reviews"
42
+ ? ["review"]
43
+ : destination === "evidence"
44
+ ? ["evidence"]
45
+ : destination === "activity"
46
+ ? ["status"]
47
+ : ["work", "status"];
48
+ const published = observed.sources.flatMap((source) =>
49
+ source.items
50
+ .filter(
51
+ (item) =>
52
+ wanted.includes(item.kind) &&
53
+ !(source.producer === "daddy-initiative" && item.id === "scope" && ["now", "work"].includes(destination)),
54
+ )
55
+ .map((item) =>
56
+ row(
57
+ item,
58
+ `source:${source.producer}:${source.generation}:${item.id}`,
59
+ `${source.producer}@${source.producerVersion} · seq ${source.sequence} · ${source.observedAt}`,
60
+ staleOwner || source.availability === "closed" || now - Date.parse(source.observedAt) > source.staleAfterMs,
61
+ ),
62
+ ),
63
+ );
64
+ if (destination === "reviews") return published;
65
+ if (destination === "evidence")
66
+ return [
67
+ ...(observed.artifacts ?? []).map((a) => ({
68
+ key: `artifact:${a.executionId}`,
69
+ label: a.operationId,
70
+ status: "retained",
71
+ elapsed: "",
72
+ details: [
73
+ `Producer: pi-daddy`,
74
+ `Execution: ${a.executionId}`,
75
+ `Manifest SHA-256: ${a.sha256}`,
76
+ "Producer reference observed in this session; payload not loaded by the dashboard.",
77
+ "Retained is not reviewed, applicable or approved. Use the authorized artifact resolver for content.",
78
+ ],
79
+ })),
80
+ ...published,
81
+ ];
82
+ if (destination === "activity")
83
+ return [
84
+ ...(observed.activity ?? [])
85
+ .slice()
86
+ .reverse()
87
+ .map((item) =>
88
+ row(item, `activity:${observed.generation}:${item.id}`, `Pi owner · ${observed.sessionId}`, staleOwner),
89
+ ),
90
+ ...published,
91
+ ];
92
+ const native = options.items.map((item) =>
93
+ staleOwner
94
+ ? {
95
+ ...item,
96
+ status: "last-observed",
97
+ details: [...item.details, "Owner disconnected; current child liveness is unknown."],
98
+ }
99
+ : item,
100
+ );
101
+ const activity = options.session?.activity;
102
+ const parentShown =
103
+ activity && native.some((item) => item.taskKey === activityTaskKey(activity.rootId, activity.taskId));
104
+ return [
105
+ ...(observed.turn && !parentShown
106
+ ? [row(observed.turn, `owner:${observed.generation}:${observed.turn.id}`, "Pi owner", staleOwner)]
107
+ : []),
108
+ ...native,
109
+ ...published,
110
+ ];
111
+ }
112
+ export function sessionPanelLines(options: DashboardScreenOptions, items: DashboardItem[], width: number): string[] {
113
+ const observation = options.session!.observation!,
114
+ screen = options.screen;
115
+ const destination = screen.destination ?? "now";
116
+ const sourceRows = observation.sources.flatMap((s) => s.items.map((item) => ({ source: s, item })));
117
+ const lines: string[] = [`${destination.toUpperCase()} · CURRENT SESSION`];
118
+ const staleSource = (source: (typeof observation.sources)[number]) =>
119
+ options.connected === false ||
120
+ source.availability === "closed" ||
121
+ (options.now?.getTime() ?? Date.now()) - Date.parse(source.observedAt) > source.staleAfterMs;
122
+ const initiative = observation.sources.find((source) => source.producer === "daddy-initiative");
123
+ const scope = initiative?.items.find((item) => item.id === "scope");
124
+ if (scope && (destination === "now" || destination === "work")) {
125
+ lines.push(`SELECTED ${scope.label}${staleSource(initiative!) ? " (last observed)" : ""}`);
126
+ if (destination === "work" && scope.details?.[1]) lines.push(scope.details[1]);
127
+ }
128
+ if (destination === "now") {
129
+ const goal = sourceRows.find((x) => x.item.kind === "goal");
130
+ lines.push(
131
+ "GOAL",
132
+ goal
133
+ ? `${goal.item.label} (${goal.source.producer}${staleSource(goal.source) ? "; stale" : ""})`
134
+ : (options.current ?? "Goal not reported; no inference from a finished step."),
135
+ );
136
+ const next = sourceRows.find((x) => x.item.kind === "next");
137
+ const nextStale =
138
+ next &&
139
+ (options.connected === false ||
140
+ next.source.availability === "closed" ||
141
+ (options.now?.getTime() ?? Date.now()) - Date.parse(next.source.observedAt) > next.source.staleAfterMs);
142
+ lines.push(
143
+ "NEXT",
144
+ next
145
+ ? `${next.item.label} (${next.source.producer}${nextStale ? "; stale" : ""})`
146
+ : "No coordinator recommendation reported.",
147
+ );
148
+ const attention = items.filter((x) =>
149
+ [
150
+ "failed",
151
+ "refused",
152
+ "incomplete",
153
+ "unknown",
154
+ "unavailable",
155
+ "needs-you",
156
+ "approval-wait",
157
+ "dependency-wait",
158
+ "cancel-requested",
159
+ ].includes(x.status),
160
+ );
161
+ if (attention.length) {
162
+ lines.push(`ATTENTION · ${attention.length}`);
163
+ for (const item of attention.slice(0, 3)) lines.push(`${item.label} · ${item.status}`);
164
+ }
165
+ const result = [...items].reverse().find((x) => ["settled", "finished", "completed"].includes(x.status));
166
+ if (result) lines.push(`LATEST UPDATE · ${result.label} (${result.status})`);
167
+ }
168
+
169
+ if (!items.length)
170
+ lines.push(
171
+ destination === "reviews"
172
+ ? "No review producer observations available."
173
+ : destination === "evidence"
174
+ ? "No current-session result references observed."
175
+ : "No observations for this view.",
176
+ );
177
+ const selected = items.find((x) => x.key === screen.selectedKey);
178
+ const rows = items.map(
179
+ (x) =>
180
+ `${x.key === screen.selectedKey ? ">" : " "} ${clean(x.label)} · ${clean(x.status)}${x.elapsed ? " " + x.elapsed : ""}`,
181
+ );
182
+ const expanded = screen.expanded && width >= 96;
183
+ if (expanded && rows.length) {
184
+ const left = Math.floor(width * 0.45),
185
+ right = width - left - 3;
186
+ const details = [selected ? `DETAIL · ${clean(selected.label)}` : "DETAIL", ...(selected?.details ?? [])];
187
+ const length = Math.max(rows.length, details.length);
188
+ for (let i = 0; i < length; i++) {
189
+ const a = truncate(clean(rows[i] ?? ""), left);
190
+ lines.push(a + " ".repeat(Math.max(0, left - cellWidth(a))) + " | " + truncate(clean(details[i] ?? ""), right));
191
+ }
192
+ } else {
193
+ lines.push(...rows);
194
+ if (screen.expanded) lines.push("Expanded layout needs 96 columns; same selection retained.");
195
+ }
196
+ if (destination === "now") {
197
+ lines.push("COMPONENTS");
198
+ for (const producer of ["principal", "bookie", "scout", "skill-harness"]) {
199
+ const streams = observation.sources.filter(
200
+ (x) => x.producer === producer || (producer === "scout" && x.producer.startsWith("scout-")),
201
+ );
202
+ const stale = streams.filter(
203
+ (s) =>
204
+ options.connected === false ||
205
+ s.availability === "closed" ||
206
+ (options.now?.getTime() ?? Date.now()) - Date.parse(s.observedAt) > s.staleAfterMs,
207
+ ).length;
208
+ const status = !streams.length
209
+ ? "status adapter unavailable"
210
+ : `${streams.length - stale} observed${stale ? `; ${stale} last observed / stale` : ""}`;
211
+ lines.push(`${producer}: ${status}`);
212
+ }
213
+ const resource = observation.resources;
214
+ lines.push(`Parent RSS: ${(resource.rssBytes / 1024 / 1024).toFixed(1)} MiB`, "Host and child memory: unknown");
215
+ }
216
+ return lines;
217
+ }