kankaku 0.6.5 → 0.7.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.
@@ -0,0 +1,384 @@
1
+ /**
2
+ * The `/kankaku` panel's `target` screen (see odd/tasks/kankaku-panel.md):
3
+ * billing client, project, hub task and the legacy label, all editable from
4
+ * one `SettingsList`. A subagent session never resolves its own target
5
+ * (see AGENTS.md "Measurement rules"), so it gets a read-only note instead.
6
+ */
7
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
+ import type { Component, SelectItem, SettingItem, SettingsListTheme, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui";
9
+ import { Input, SelectList, SettingsList, Text } from "@earendil-works/pi-tui";
10
+ import { isValidClient } from "../../../domain/client-label.ts";
11
+ import { buildTargetRows } from "../../../domain/panel-model.ts";
12
+ import type { PanelRow } from "../../../domain/panel-model.ts";
13
+ import type { WorkRole } from "../../../domain/work-record.ts";
14
+ import type { HubTask, WorkTargetSourceName } from "../../../domain/work-target.ts";
15
+ import type { Catalog } from "../../../ports/catalog.ts";
16
+ import type { SessionClient } from "../../session-client.ts";
17
+ import type { SessionTarget } from "../../session-target.ts";
18
+ import type { PanelHost, PanelScreenFactory } from "../kankaku-panel.ts";
19
+ import { actionItem } from "../panel-items.ts";
20
+ import { buildSelectListTheme, buildSettingsListTheme } from "../panel-theme.ts";
21
+
22
+ export interface TargetScreenDeps {
23
+ pi: ExtensionAPI;
24
+ ctx: ExtensionContext;
25
+ role: WorkRole;
26
+ /** Present only when the hub (PocketBase) is configured; see `PiTrackerDeps.sessionTarget`. */
27
+ sessionTarget?: SessionTarget;
28
+ sessionClient: SessionClient;
29
+ /** Present only when the hub is configured. */
30
+ catalog?: Catalog;
31
+ refreshIdleStatus: (ctx: ExtensionContext) => void;
32
+ }
33
+
34
+ const SUBAGENT_NOTE = "Subagent session: the billing target is inherited from the orchestrator and cannot be changed here.";
35
+ const USE_DEFAULTS_VALUE = "__kankaku_use_defaults__";
36
+ const NO_PROJECT_VALUE = "__kankaku_no_project__";
37
+ const NO_TASK_VALUE = "__kankaku_no_task__";
38
+ const MAX_VISIBLE = 10;
39
+
40
+ /** `WorkTargetSourceName` ("session" | "project" | "repoPaths"), formatted for the read-only `source` row ("session" | "config" | "repoPaths"). */
41
+ function formatTargetSource(source: WorkTargetSourceName | undefined): string | undefined {
42
+ if (source === undefined) return undefined;
43
+ return source === "project" ? "config" : source;
44
+ }
45
+
46
+ /** Sort by `name`, ascending; never mutates the input. */
47
+ function sortByName<T extends { name: string }>(items: T[]): T[] {
48
+ return [...items].sort((a, b) => a.name.localeCompare(b.name));
49
+ }
50
+
51
+ /**
52
+ * Build `label -> task` options for the task submenu, sorted by title. When
53
+ * two tasks share the same title, disambiguate every colliding label with
54
+ * the task's `externalRef` when it has one, or its bare id otherwise —
55
+ * mirrors `adapters/target-picker.ts`'s private `labelTaskOptions` (not
56
+ * exported, so this is a small self-contained equivalent rather than a
57
+ * cross-module reach for a private helper).
58
+ */
59
+ function labelTasks(tasks: HubTask[]): Array<{ label: string; task: HubTask }> {
60
+ const sorted = [...tasks].sort((a, b) => a.title.localeCompare(b.title));
61
+ const titleCounts = new Map<string, number>();
62
+ for (const task of sorted) titleCounts.set(task.title, (titleCounts.get(task.title) ?? 0) + 1);
63
+ return sorted.map((task) => {
64
+ const collides = (titleCounts.get(task.title) ?? 0) > 1;
65
+ const label = collides ? `${task.title} (${task.externalRef ?? task.id})` : task.title;
66
+ return { label, task };
67
+ });
68
+ }
69
+
70
+ /** A one-line note shown as a submenu; closes back to the row that opened it on any key, without touching anything. */
71
+ class NoteComponent implements Component {
72
+ private readonly theme: SettingsListTheme;
73
+ private readonly text: string;
74
+ private readonly done: (selectedValue?: string, options?: { navigateTo?: string }) => void;
75
+
76
+ constructor(theme: SettingsListTheme, text: string, done: (selectedValue?: string, options?: { navigateTo?: string }) => void) {
77
+ this.theme = theme;
78
+ this.text = text;
79
+ this.done = done;
80
+ }
81
+
82
+ invalidate(): void {}
83
+
84
+ render(_width: number): string[] {
85
+ return [this.theme.hint(this.text)];
86
+ }
87
+
88
+ handleInput(_data: string): void {
89
+ this.done();
90
+ }
91
+ }
92
+
93
+ /**
94
+ * The legacy-label submenu: a pi-tui `Input` prefilled with the current
95
+ * label. While open, the panel shell must forward `q` as ordinary input
96
+ * (never close-on-q) — `PanelHost.setBodyWantsText` is set on construction
97
+ * and cleared whenever this component closes, on every path.
98
+ */
99
+ class LegacyLabelComponent implements Component {
100
+ private readonly theme: SettingsListTheme;
101
+ private readonly host: PanelHost;
102
+ private readonly onValid: (value: string | undefined) => void;
103
+ private readonly done: (selectedValue?: string, options?: { navigateTo?: string }) => void;
104
+ private readonly input: Input;
105
+ private invalidLabel: string | undefined;
106
+
107
+ constructor(
108
+ theme: SettingsListTheme,
109
+ initialValue: string,
110
+ host: PanelHost,
111
+ onValid: (value: string | undefined) => void,
112
+ done: (selectedValue?: string, options?: { navigateTo?: string }) => void,
113
+ ) {
114
+ this.theme = theme;
115
+ this.host = host;
116
+ this.onValid = onValid;
117
+ this.done = done;
118
+ this.input = new Input();
119
+ this.input.setValue(initialValue);
120
+ this.input.onSubmit = (value) => this.handleSubmit(value);
121
+ this.input.onEscape = () => this.handleEscape();
122
+ this.host.setBodyWantsText(true);
123
+ }
124
+
125
+ private handleSubmit(rawValue: string): void {
126
+ const trimmed = rawValue.trim();
127
+ if (trimmed.length > 0 && !isValidClient(trimmed)) {
128
+ this.invalidLabel = trimmed;
129
+ return;
130
+ }
131
+ this.close();
132
+ this.onValid(trimmed.length > 0 ? trimmed : undefined);
133
+ }
134
+
135
+ private handleEscape(): void {
136
+ this.close();
137
+ }
138
+
139
+ private close(): void {
140
+ this.host.setBodyWantsText(false);
141
+ // No `navigateTo`: the "legacy" row's own `SettingItem.submenu` would
142
+ // otherwise make `SettingsList.closeSubmenu()` reactivate it right back
143
+ // open (its `navigateAfterClose` mechanism reopens the target item's
144
+ // submenu when it has one — see settings-list.js). A successful submit
145
+ // rebuilds the list from scratch via `applyChange`, which already
146
+ // repositions the cursor on "legacy" itself; a cancel needs no
147
+ // rebuild at all — plain `done()` just restores the row selection.
148
+ this.done();
149
+ }
150
+
151
+ invalidate(): void {
152
+ this.input.invalidate();
153
+ }
154
+
155
+ render(width: number): string[] {
156
+ const lines = this.input.render(width);
157
+ if (this.invalidLabel === undefined) return lines;
158
+ return [...lines, this.theme.hint(`error: invalid label "${this.invalidLabel}"`)];
159
+ }
160
+
161
+ handleInput(data: string): void {
162
+ this.invalidLabel = undefined;
163
+ this.input.handleInput(data);
164
+ }
165
+ }
166
+
167
+ class TargetScreenComponent implements Component {
168
+ readonly searchable = false;
169
+ private readonly deps: TargetScreenDeps;
170
+ private readonly host: PanelHost;
171
+ private readonly settingsTheme: SettingsListTheme;
172
+ private list: SettingsList;
173
+
174
+ constructor(deps: TargetScreenDeps, host: PanelHost) {
175
+ this.deps = deps;
176
+ this.host = host;
177
+ this.settingsTheme = buildSettingsListTheme(host.theme);
178
+ this.list = this.buildList();
179
+ }
180
+
181
+ private currentRows(): PanelRow[] {
182
+ const sessionTarget = this.deps.sessionTarget;
183
+ const target = sessionTarget?.effectiveTarget();
184
+ const source = sessionTarget ? formatTargetSource(sessionTarget.effectiveSource()) : undefined;
185
+ const legacyLabel = this.deps.sessionClient.effectiveClient();
186
+ const legacySource = this.deps.sessionClient.effectiveSource();
187
+ return buildTargetRows({
188
+ hubConfigured: sessionTarget !== undefined,
189
+ target,
190
+ source,
191
+ legacyLabel,
192
+ legacySource,
193
+ });
194
+ }
195
+
196
+ private buildList(): SettingsList {
197
+ const items = this.currentRows().map((row) => this.buildItem(row));
198
+ return new SettingsList(
199
+ items,
200
+ MAX_VISIBLE,
201
+ this.settingsTheme,
202
+ () => {},
203
+ () => this.host.back(),
204
+ { enableSearch: false },
205
+ );
206
+ }
207
+
208
+ /** Rebuild the list from fresh state after a mutation, keep the cursor on `navigateToId`, and notify the host — see the feature doc's "After EVERY change" rule. */
209
+ private applyChange(navigateToId: string): void {
210
+ this.list = this.buildList();
211
+ this.list.selectItem(navigateToId);
212
+ this.deps.refreshIdleStatus(this.deps.ctx);
213
+ this.host.requestRender();
214
+ }
215
+
216
+ private buildItem(row: PanelRow): SettingItem {
217
+ switch (row.id) {
218
+ case "client":
219
+ return this.rowItem(row, (done) => this.buildClientSubmenu(done));
220
+ case "project":
221
+ return this.rowItem(row, (done) => this.buildProjectSubmenu(done));
222
+ case "task":
223
+ return this.rowItem(row, (done) => this.buildTaskSubmenu(done));
224
+ case "remember":
225
+ return this.buildRememberItem(row);
226
+ case "legacy":
227
+ return this.rowItem(row, (done) => this.buildLegacySubmenu(done));
228
+ case "source":
229
+ default:
230
+ return this.plainItem(row);
231
+ }
232
+ }
233
+
234
+ private plainItem(row: PanelRow): SettingItem {
235
+ return { id: row.id, label: row.label, currentValue: row.value, ...(row.description !== undefined ? { description: row.description } : {}) };
236
+ }
237
+
238
+ /**
239
+ * Wraps a row's submenu factory so opening it sets
240
+ * `PanelHost.setBodyCapturesEscape(true)` (the shell forwards Escape/←
241
+ * to this screen instead of popping it while the submenu — or the
242
+ * legacy-label `Input`, which also uses this via `buildLegacySubmenu` —
243
+ * is open) and clears it again right before the submenu's own `done` is
244
+ * invoked, on every close path (a pick, "— use defaults —"/"— none —",
245
+ * cancel, or a disabled note closing on any key).
246
+ */
247
+ private rowItem(row: PanelRow, submenu: (done: (selectedValue?: string, options?: { navigateTo?: string }) => void) => Component): SettingItem {
248
+ return {
249
+ ...this.plainItem(row),
250
+ submenu: (_currentValue, done) => {
251
+ this.host.setBodyCapturesEscape(true);
252
+ return submenu((selectedValue, options) => {
253
+ this.host.setBodyCapturesEscape(false);
254
+ done(selectedValue, options);
255
+ });
256
+ },
257
+ };
258
+ }
259
+
260
+ private buildClientSubmenu(done: (selectedValue?: string, options?: { navigateTo?: string }) => void): Component {
261
+ const clients = (this.deps.catalog?.read()?.clients ?? []).filter((client) => client.active && !client.unassigned);
262
+ const items: SelectItem[] = [
263
+ ...sortByName(clients).map((client) => ({ value: client.id, label: `${client.name} (${client.code})` })),
264
+ { value: USE_DEFAULTS_VALUE, label: "— use defaults —" },
265
+ ];
266
+ const list = new SelectList(items, MAX_VISIBLE, buildSelectListTheme(this.host.theme));
267
+ list.onSelect = (item) => {
268
+ if (item.value === USE_DEFAULTS_VALUE) {
269
+ this.deps.sessionTarget?.clear(this.deps.pi);
270
+ } else {
271
+ this.deps.sessionTarget?.setExplicit(this.deps.pi, { clientId: item.value });
272
+ }
273
+ done();
274
+ this.applyChange("client");
275
+ };
276
+ list.onCancel = () => done();
277
+ return list;
278
+ }
279
+
280
+ private buildProjectSubmenu(done: (selectedValue?: string, options?: { navigateTo?: string }) => void): Component {
281
+ const target = this.deps.sessionTarget?.effectiveTarget();
282
+ if (!target) {
283
+ return new NoteComponent(this.settingsTheme, "Pick a client first.", done);
284
+ }
285
+
286
+ const projects = (this.deps.catalog?.read()?.projects ?? []).filter((project) => project.active && project.clientId === target.clientId);
287
+ const items: SelectItem[] = [
288
+ ...sortByName(projects).map((project) => ({ value: project.id, label: project.name })),
289
+ { value: NO_PROJECT_VALUE, label: "(no project)" },
290
+ ];
291
+ const list = new SelectList(items, MAX_VISIBLE, buildSelectListTheme(this.host.theme));
292
+ list.onSelect = (item) => {
293
+ const projectId = item.value === NO_PROJECT_VALUE ? undefined : item.value;
294
+ this.deps.sessionTarget?.setExplicit(this.deps.pi, { clientId: target.clientId, ...(projectId !== undefined ? { projectId } : {}) });
295
+ done();
296
+ this.applyChange("project");
297
+ };
298
+ list.onCancel = () => done();
299
+ return list;
300
+ }
301
+
302
+ private buildTaskSubmenu(done: (selectedValue?: string, options?: { navigateTo?: string }) => void): Component {
303
+ const target = this.deps.sessionTarget?.effectiveTarget();
304
+ if (!target || target.projectId === undefined) {
305
+ return new NoteComponent(this.settingsTheme, "Pick a project first.", done);
306
+ }
307
+
308
+ const tasks = (this.deps.catalog?.read()?.tasks ?? []).filter((task) => task.status !== "done" && task.projectId === target.projectId);
309
+ if (tasks.length === 0) {
310
+ return new NoteComponent(this.settingsTheme, "No open tasks for this project in the hub", done);
311
+ }
312
+
313
+ const options = labelTasks(tasks);
314
+ const items: SelectItem[] = [...options.map((option) => ({ value: option.task.id, label: option.label })), { value: NO_TASK_VALUE, label: "— none —" }];
315
+ const list = new SelectList(items, MAX_VISIBLE, buildSelectListTheme(this.host.theme));
316
+ list.onSelect = (item) => {
317
+ if (item.value === NO_TASK_VALUE) {
318
+ this.deps.sessionTarget?.clearTask(this.deps.pi);
319
+ } else {
320
+ this.deps.sessionTarget?.setTask(this.deps.pi, item.value);
321
+ }
322
+ done();
323
+ this.applyChange("task");
324
+ };
325
+ list.onCancel = () => done();
326
+ return list;
327
+ }
328
+
329
+ private buildRememberItem(row: PanelRow): SettingItem {
330
+ const item = actionItem(this.settingsTheme, {
331
+ id: row.id,
332
+ label: row.label,
333
+ description: row.description,
334
+ run: () => {
335
+ const saved = this.deps.sessionTarget?.rememberTarget() ?? false;
336
+ return [saved ? "saved clientId/projectId to config.json" : "nothing to save"];
337
+ },
338
+ onOpen: () => this.host.setBodyCapturesEscape(true),
339
+ onClose: () => this.host.setBodyCapturesEscape(false),
340
+ onDone: () => this.host.requestRender(),
341
+ });
342
+ return { ...item, currentValue: row.value };
343
+ }
344
+
345
+ private buildLegacySubmenu(done: (selectedValue?: string, options?: { navigateTo?: string }) => void): Component {
346
+ const initial = this.deps.sessionClient.effectiveClient() ?? "";
347
+ return new LegacyLabelComponent(
348
+ this.settingsTheme,
349
+ initial,
350
+ this.host,
351
+ (value) => {
352
+ this.deps.sessionClient.set(this.deps.pi, value);
353
+ this.applyChange("legacy");
354
+ },
355
+ done,
356
+ );
357
+ }
358
+
359
+ invalidate(): void {
360
+ this.list.invalidate();
361
+ }
362
+
363
+ render(width: number): string[] {
364
+ return this.list.render(width);
365
+ }
366
+
367
+ handleInput(data: string): void {
368
+ this.list.handleInput(data);
369
+ }
370
+
371
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
372
+ return this.list.handleMouse?.(event);
373
+ }
374
+ }
375
+
376
+ /** `openKankakuPanel`'s `screens.target` factory; see {@link TargetScreenDeps}. */
377
+ export function createTargetScreen(deps: TargetScreenDeps): PanelScreenFactory {
378
+ return (host: PanelHost) => {
379
+ if (deps.role !== "orchestrator") {
380
+ return new Text(host.theme.fg("muted", SUBAGENT_NOTE));
381
+ }
382
+ return new TargetScreenComponent(deps, host);
383
+ };
384
+ }
@@ -3,7 +3,7 @@ import { isValidClient } from "../domain/client-label.ts";
3
3
  import { formatWorkTargetLabel } from "../domain/work-target.ts";
4
4
  import type { RegistryClassification } from "../domain/registry-health.ts";
5
5
  import type { SubagentProfile } from "../domain/subagent-profile.ts";
6
- import type { RejectedChildEnvMarker } from "../config.ts";
6
+ import type { KankakuConfig, RejectedChildEnvMarker } from "../config.ts";
7
7
  import type { OrchestratorRef, WorkRecord, WorkRecordCore, WorkRole } from "../domain/work-record.ts";
8
8
  import type { WorkTracker } from "../domain/work-tracker.ts";
9
9
  import type { Catalog } from "../ports/catalog.ts";
@@ -13,8 +13,15 @@ import { createSessionClient } from "./session-client.ts";
13
13
  import { readNonDefaultSessionDir } from "./session-dir.ts";
14
14
  import type { SessionTarget } from "./session-target.ts";
15
15
  import { createStatusBar } from "./status-bar.ts";
16
- import { notifyError, registerKankakuCommand } from "./kankaku-command.ts";
17
- import type { SyncCommandDeps } from "./kankaku-command.ts";
16
+ import { appendReportEntry, notifyError, registerKankakuCommand } from "./kankaku-command.ts";
17
+ import type { KankakuCommandDeps, SyncCommandDeps } from "./kankaku-command.ts";
18
+ import { openKankakuPanel } from "./panel/kankaku-panel.ts";
19
+ import { createAboutScreen } from "./panel/screens/about.ts";
20
+ import { createDoctorScreen } from "./panel/screens/doctor.ts";
21
+ import { createExportScreen } from "./panel/screens/export.ts";
22
+ import { createReportScreen } from "./panel/screens/report.ts";
23
+ import { createSyncScreen } from "./panel/screens/sync.ts";
24
+ import { createTargetScreen } from "./panel/screens/target.ts";
18
25
  import type { SyncTrigger } from "./sync-runner.ts";
19
26
 
20
27
  export type { KankakuReportData } from "./kankaku-command.ts";
@@ -174,11 +181,37 @@ export interface PiTrackerDeps {
174
181
  * real timer.
175
182
  */
176
183
  shutdownSyncTimeoutMs?: number;
184
+ /**
185
+ * The full active kankaku configuration (`config.ts#loadConfig`), for the
186
+ * panel's `about` screen (P3). Optional so every existing direct
187
+ * `createPiTracker` caller (e.g. `tests/pi-tracker.test.ts`) keeps
188
+ * working unchanged — falls back to {@link FALLBACK_ABOUT_CONFIG} (an
189
+ * empty configuration) when absent. `extension.ts` always supplies the
190
+ * real one.
191
+ */
192
+ config?: KankakuConfig;
193
+ /** This session's resolved kankaku directory (`adapters/kankaku-dir.ts#resolveKankakuDir`), for the `about` screen. */
194
+ kankakuDir?: string;
195
+ /** pi's version (`adapters/agent-info.ts#resolveAgentVersion`), for the `about` screen. */
196
+ agentVersion?: string;
197
+ /** kankaku's own version (`adapters/agent-info.ts#resolvePluginVersion`), for the `about` screen. */
198
+ pluginVersion?: string;
199
+ /** The hub (PocketBase) URL, when configured, for the `about` screen. */
200
+ hubUrl?: string;
177
201
  }
178
202
 
179
203
  /** Default for {@link PiTrackerDeps.shutdownSyncTimeoutMs}. */
180
204
  const DEFAULT_SHUTDOWN_SYNC_TIMEOUT_MS = 3000;
181
205
 
206
+ /** {@link PiTrackerDeps.config}'s fallback for a caller that has not wired the real one yet. */
207
+ const FALLBACK_ABOUT_CONFIG: KankakuConfig = {
208
+ dir: ".kankaku",
209
+ interactiveTools: [],
210
+ subagentProfiles: [],
211
+ segmentRules: [],
212
+ rejectedSubagentChildEnvMarkers: [],
213
+ };
214
+
182
215
  /** Default `isAlive`: probe with signal 0 — no signal is sent, only existence/permission is checked. */
183
216
  function defaultIsAlive(pid: number): boolean {
184
217
  try {
@@ -252,10 +285,19 @@ export function createPiTracker(pi: ExtensionAPI, deps: PiTrackerDeps): void {
252
285
  resolveIdleClient: idleDisplayLabel,
253
286
  });
254
287
 
255
- const kankakuCommand = registerKankakuCommand(pi, {
288
+ const refreshIdleStatus = (ctx: ExtensionContext) => statusBar.showIdle(ctx);
289
+
290
+ // Built as a named const (rather than inlined into `registerKankakuCommand`
291
+ // below) so `openPanel`'s doctor screen can reuse the exact same
292
+ // `KankakuCommandDeps` `buildDoctorLines` needs — the panel and
293
+ // `/kankaku doctor` can then never drift. Safe to reference `commandDeps`
294
+ // from within its own `openPanel` closure: the closure body only runs
295
+ // once `/kankaku` (no args) is actually invoked, long after this `const`
296
+ // has finished initializing.
297
+ const commandDeps: KankakuCommandDeps = {
256
298
  log,
257
299
  sessionClient,
258
- refreshIdleStatus: (ctx) => statusBar.showIdle(ctx),
300
+ refreshIdleStatus,
259
301
  writeExportFile: deps.writeExportFile,
260
302
  sessionTarget: deps.sessionTarget,
261
303
  catalog: deps.catalog,
@@ -270,7 +312,67 @@ export function createPiTracker(pi: ExtensionAPI, deps: PiTrackerDeps): void {
270
312
  rejectedSubagentChildEnvMarkers: deps.rejectedSubagentChildEnvMarkers,
271
313
  workLogRouting: deps.workLogRouting,
272
314
  subagentProfiles: deps.subagentProfiles,
273
- });
315
+ // The hub is configured exactly when a session target is wired (see
316
+ // PiTrackerDeps.sessionTarget's doc comment): the panel's root menu
317
+ // uses the same signal to decide whether to offer `sync` — `target`
318
+ // itself is offered either way, since the legacy `/kankaku client
319
+ // <name>` label lives on that same screen and works with no hub at
320
+ // all (see `domain/panel-model.ts#rootMenu`'s `target` row).
321
+ openPanel: (ctx) =>
322
+ openKankakuPanel(ctx, {
323
+ hubConfigured: deps.sessionTarget !== undefined,
324
+ screens: {
325
+ target: createTargetScreen({
326
+ pi,
327
+ ctx,
328
+ role,
329
+ sessionTarget: deps.sessionTarget,
330
+ sessionClient,
331
+ catalog: deps.catalog,
332
+ refreshIdleStatus,
333
+ }),
334
+ report: createReportScreen({
335
+ log,
336
+ ctx,
337
+ pi,
338
+ sessionId: () => ctx.sessionManager.getSessionId(),
339
+ pinReport: (report) => appendReportEntry(pi, ctx, report),
340
+ }),
341
+ doctor: createDoctorScreen({
342
+ commandDeps,
343
+ ctx,
344
+ pinReport: (report) => appendReportEntry(pi, ctx, report),
345
+ }),
346
+ about: createAboutScreen({
347
+ config: deps.config ?? FALLBACK_ABOUT_CONFIG,
348
+ kankakuDir: deps.kankakuDir ?? deps.config?.dir ?? FALLBACK_ABOUT_CONFIG.dir,
349
+ agentVersion: deps.agentVersion,
350
+ pluginVersion: deps.pluginVersion,
351
+ hubUrl: deps.hubUrl,
352
+ }),
353
+ // Present only when the hub is configured — mirrors `sync`'s own
354
+ // hub-only root-menu row (`domain/panel-model.ts#rootMenu`).
355
+ ...(deps.sync
356
+ ? {
357
+ sync: createSyncScreen({
358
+ sync: deps.sync,
359
+ catalog: deps.catalog,
360
+ ctx,
361
+ refreshIdleStatus,
362
+ pinReport: (report) => appendReportEntry(pi, ctx, report),
363
+ }),
364
+ }
365
+ : {}),
366
+ export: createExportScreen({
367
+ log,
368
+ writeExportFile: deps.writeExportFile,
369
+ ctx,
370
+ pinReport: (report) => appendReportEntry(pi, ctx, report),
371
+ }),
372
+ },
373
+ }),
374
+ };
375
+ const kankakuCommand = registerKankakuCommand(pi, commandDeps);
274
376
 
275
377
  /** At most one quiet auto-sync failure notification per session; never notified on success. Shared by the fire-and-forget `triggerAutoSync` and the awaited shutdown sync below. */
276
378
  let autoSyncErrorNotified = false;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The five `/kankaku` report views (summary/tasks/sessions/clients/
3
+ * projects), each as one pure `WorkRecord[] -> KankakuReportData` builder.
4
+ * Extracted from `kankaku-command.ts`'s subcommand handlers (see
5
+ * odd/tasks/kankaku-panel.md P3) so the `/kankaku` subcommands and the
6
+ * panel's report screen (`panel/screens/report.ts`) always compute the
7
+ * exact same lines — neither ever re-implements the other's logic.
8
+ */
9
+ import { buildSessions, buildTasks } from "../domain/task-view.ts";
10
+ import { exportRows, toCsv, toJson } from "../domain/export.ts";
11
+ import type { WorkRecord } from "../domain/work-record.ts";
12
+ import type { KankakuReportData } from "./kankaku-command.ts";
13
+ import { countUncertain, formatClients, formatProjects, formatReport, formatSessions, formatTasks, localDay, summarize, summarizeByClient, summarizeByProject } from "./report.ts";
14
+
15
+ /** Shared by every view except `buildTasksView`: `all` includes every day, otherwise only today's local day. */
16
+ export interface ReportViewOptions {
17
+ all: boolean;
18
+ }
19
+
20
+ /** `buildTasksView`'s own options: `all` scopes to every session instead of local-day range (tasks are never day-filtered — see `kankaku-command.ts`'s original `tasks` handler). */
21
+ export interface TasksViewOptions {
22
+ all: boolean;
23
+ sessionId: string | undefined;
24
+ }
25
+
26
+ /** The plain-text summary view (`/kankaku` with no view token): role/task totals, plus a one-line hint when uncertain records were excluded (SUBAGENT-REQ-017). */
27
+ export function buildSummaryView(records: WorkRecord[], options: ReportViewOptions): KankakuReportData {
28
+ const { all } = options;
29
+ const summary = summarize(records, { all });
30
+ const lines = formatReport(summary).split(" | ");
31
+ const uncertainCount = countUncertain(records, { all });
32
+ if (uncertainCount > 0) {
33
+ lines.push(`kankaku: ${uncertainCount} uncertain record(s) excluded from tasks — run /kankaku doctor`);
34
+ }
35
+ return { title: all ? "summary (all days)" : "summary (today)", lines };
36
+ }
37
+
38
+ /** `/kankaku clients [all]`: per-client totals. */
39
+ export function buildClientsView(records: WorkRecord[], options: ReportViewOptions): KankakuReportData {
40
+ const { all } = options;
41
+ const today = localDay(new Date().toISOString());
42
+ const tasks = buildTasks(records).filter((task) => all || localDay(task.startedAt) === today);
43
+ return { title: all ? "clients (all days)" : "clients (today)", lines: formatClients(summarizeByClient(tasks)).split("\n") };
44
+ }
45
+
46
+ /** `/kankaku projects [all]`: per-project totals. */
47
+ export function buildProjectsView(records: WorkRecord[], options: ReportViewOptions): KankakuReportData {
48
+ const { all } = options;
49
+ const today = localDay(new Date().toISOString());
50
+ const tasks = buildTasks(records).filter((task) => all || localDay(task.startedAt) === today);
51
+ return { title: all ? "projects (all days)" : "projects (today)", lines: formatProjects(summarizeByProject(tasks)).split("\n") };
52
+ }
53
+
54
+ /** `/kankaku sessions [all]`: per-session totals. */
55
+ export function buildSessionsView(records: WorkRecord[], options: ReportViewOptions): KankakuReportData {
56
+ const { all } = options;
57
+ const today = localDay(new Date().toISOString());
58
+ const tasks = buildTasks(records).filter((task) => all || localDay(task.startedAt) === today);
59
+ return { title: all ? "sessions (all days)" : "sessions (today)", lines: formatSessions(buildSessions(tasks)).split("\n") };
60
+ }
61
+
62
+ /**
63
+ * `/kankaku tasks [all]`: one line per task. Unlike every other view, tasks
64
+ * are never restricted by local day — `all` (or a missing `sessionId`)
65
+ * instead scopes from "this session" to "every session".
66
+ */
67
+ export function buildTasksView(records: WorkRecord[], options: TasksViewOptions): KankakuReportData {
68
+ const { all, sessionId } = options;
69
+ const scoped = all || !sessionId;
70
+ const tasks = buildTasks(records).filter((task) => scoped || task.sessionId === sessionId);
71
+ return { title: scoped ? "tasks (every session)" : "tasks (this session)", lines: formatTasks(tasks).split("\n") };
72
+ }
73
+
74
+ /** {@link buildExportContent}'s options: `format` picks csv/json, `all` includes every day instead of just today's local day (mirrors every other view except `buildTasksView`). */
75
+ export interface ExportContentOptions {
76
+ format: "csv" | "json";
77
+ all: boolean;
78
+ }
79
+
80
+ /**
81
+ * `/kankaku export [csv|json] [all]`'s file content: the flat export rows
82
+ * for today's (or every) task, rendered as csv or json, with the file name
83
+ * `/kankaku export` and the panel's export screen (`panel/screens/
84
+ * export.ts`) both use. Extracted from `kankaku-command.ts`'s
85
+ * `handleExportCommand` (see odd/tasks/kankaku-panel.md P4) so the
86
+ * subcommand and the panel never drift. `rowCount` is exposed only for the
87
+ * subcommand's "wrote N row(s) to <path>" confirmation line — the panel's
88
+ * own confirmation is simpler ("wrote <path>").
89
+ */
90
+ export function buildExportContent(records: WorkRecord[], options: ExportContentOptions): { name: string; content: string; rowCount: number } {
91
+ const { format, all } = options;
92
+ const today = localDay(new Date().toISOString());
93
+ const tasks = buildTasks(records).filter((task) => all || localDay(task.startedAt) === today);
94
+ const rows = exportRows(tasks);
95
+ const content = format === "json" ? toJson(rows) : toCsv(rows);
96
+ const name = `tasks-${all ? "all" : today}.${format}`;
97
+ return { name, content, rowCount: rows.length };
98
+ }