kankaku-pi 1.0.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 (153) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1438 -0
  3. package/dist/adapters/cached-catalog.d.ts +42 -0
  4. package/dist/adapters/cached-catalog.js +121 -0
  5. package/dist/adapters/export-writer.d.ts +13 -0
  6. package/dist/adapters/export-writer.js +28 -0
  7. package/dist/adapters/file-modes.d.ts +20 -0
  8. package/dist/adapters/file-modes.js +34 -0
  9. package/dist/adapters/hub-actions.d.ts +35 -0
  10. package/dist/adapters/hub-actions.js +70 -0
  11. package/dist/adapters/hub-credentials.d.ts +35 -0
  12. package/dist/adapters/hub-credentials.js +58 -0
  13. package/dist/adapters/jsonl-work-log.d.ts +20 -0
  14. package/dist/adapters/jsonl-work-log.js +62 -0
  15. package/dist/adapters/kankaku-dir.d.ts +38 -0
  16. package/dist/adapters/kankaku-dir.js +85 -0
  17. package/dist/adapters/lazy-jsonl-work-log.d.ts +17 -0
  18. package/dist/adapters/lazy-jsonl-work-log.js +31 -0
  19. package/dist/adapters/pocketbase-catalog.d.ts +16 -0
  20. package/dist/adapters/pocketbase-catalog.js +56 -0
  21. package/dist/adapters/pocketbase-client.d.ts +81 -0
  22. package/dist/adapters/pocketbase-client.js +148 -0
  23. package/dist/adapters/pocketbase-sink.d.ts +53 -0
  24. package/dist/adapters/pocketbase-sink.js +181 -0
  25. package/dist/adapters/project-config.d.ts +42 -0
  26. package/dist/adapters/project-config.js +108 -0
  27. package/dist/adapters/report-data.d.ts +12 -0
  28. package/dist/adapters/report-data.js +8 -0
  29. package/dist/adapters/report-views.d.ts +45 -0
  30. package/dist/adapters/report-views.js +73 -0
  31. package/dist/adapters/report.d.ts +112 -0
  32. package/dist/adapters/report.js +236 -0
  33. package/dist/adapters/sync-runner.d.ts +114 -0
  34. package/dist/adapters/sync-runner.js +273 -0
  35. package/dist/adapters/sync-state-store.d.ts +62 -0
  36. package/dist/adapters/sync-state-store.js +188 -0
  37. package/dist/config.d.ts +168 -0
  38. package/dist/config.js +392 -0
  39. package/dist/domain/ancestry-match.d.ts +49 -0
  40. package/dist/domain/ancestry-match.js +82 -0
  41. package/dist/domain/client-label.d.ts +28 -0
  42. package/dist/domain/client-label.js +44 -0
  43. package/dist/domain/day.d.ts +2 -0
  44. package/dist/domain/day.js +8 -0
  45. package/dist/domain/export.d.ts +38 -0
  46. package/dist/domain/export.js +68 -0
  47. package/dist/domain/hub-entry.d.ts +234 -0
  48. package/dist/domain/hub-entry.js +265 -0
  49. package/dist/domain/index.d.ts +19 -0
  50. package/dist/domain/index.js +19 -0
  51. package/dist/domain/intervals.d.ts +17 -0
  52. package/dist/domain/intervals.js +43 -0
  53. package/dist/domain/registry-health.d.ts +49 -0
  54. package/dist/domain/registry-health.js +58 -0
  55. package/dist/domain/segment-rule.d.ts +10 -0
  56. package/dist/domain/segment-rule.js +1 -0
  57. package/dist/domain/subagent-profile.d.ts +278 -0
  58. package/dist/domain/subagent-profile.js +418 -0
  59. package/dist/domain/sync-plan.d.ts +151 -0
  60. package/dist/domain/sync-plan.js +196 -0
  61. package/dist/domain/task-view.d.ts +117 -0
  62. package/dist/domain/task-view.js +428 -0
  63. package/dist/domain/work-record.d.ts +236 -0
  64. package/dist/domain/work-record.js +91 -0
  65. package/dist/domain/work-target.d.ts +101 -0
  66. package/dist/domain/work-target.js +149 -0
  67. package/dist/domain/work-tracker.d.ts +90 -0
  68. package/dist/domain/work-tracker.js +405 -0
  69. package/dist/hub/index.d.ts +25 -0
  70. package/dist/hub/index.js +25 -0
  71. package/dist/ports/catalog.d.ts +31 -0
  72. package/dist/ports/catalog.js +1 -0
  73. package/dist/ports/clock.d.ts +3 -0
  74. package/dist/ports/clock.js +1 -0
  75. package/dist/ports/index.d.ts +11 -0
  76. package/dist/ports/index.js +1 -0
  77. package/dist/ports/inflight-store.d.ts +15 -0
  78. package/dist/ports/inflight-store.js +1 -0
  79. package/dist/ports/process-registry.d.ts +72 -0
  80. package/dist/ports/process-registry.js +1 -0
  81. package/dist/ports/work-log.d.ts +14 -0
  82. package/dist/ports/work-log.js +1 -0
  83. package/dist/ports/work-sink.d.ts +39 -0
  84. package/dist/ports/work-sink.js +1 -0
  85. package/package.json +66 -0
  86. package/src/adapters/agent-info.ts +86 -0
  87. package/src/adapters/ancestry.ts +260 -0
  88. package/src/adapters/cached-catalog.ts +147 -0
  89. package/src/adapters/export-writer.ts +33 -0
  90. package/src/adapters/file-inflight-store.ts +115 -0
  91. package/src/adapters/file-modes.ts +35 -0
  92. package/src/adapters/hub-actions.ts +82 -0
  93. package/src/adapters/hub-credentials.ts +95 -0
  94. package/src/adapters/jsonl-work-log.ts +67 -0
  95. package/src/adapters/kankaku-command.ts +717 -0
  96. package/src/adapters/kankaku-dir.ts +102 -0
  97. package/src/adapters/lazy-file-inflight-store.ts +43 -0
  98. package/src/adapters/lazy-jsonl-work-log.ts +39 -0
  99. package/src/adapters/machine-process-registry.ts +256 -0
  100. package/src/adapters/panel/kankaku-panel.ts +419 -0
  101. package/src/adapters/panel/panel-items.ts +87 -0
  102. package/src/adapters/panel/panel-lines.ts +13 -0
  103. package/src/adapters/panel/panel-theme.ts +32 -0
  104. package/src/adapters/panel/screens/about.ts +69 -0
  105. package/src/adapters/panel/screens/doctor.ts +89 -0
  106. package/src/adapters/panel/screens/export.ts +123 -0
  107. package/src/adapters/panel/screens/report.ts +143 -0
  108. package/src/adapters/panel/screens/sync.ts +136 -0
  109. package/src/adapters/panel/screens/target.ts +384 -0
  110. package/src/adapters/pi-tracker.ts +753 -0
  111. package/src/adapters/pocketbase-catalog.ts +89 -0
  112. package/src/adapters/pocketbase-client.ts +197 -0
  113. package/src/adapters/pocketbase-sink.ts +236 -0
  114. package/src/adapters/process-identity-memo.ts +102 -0
  115. package/src/adapters/process-identity.ts +162 -0
  116. package/src/adapters/project-config.ts +116 -0
  117. package/src/adapters/report-data.ts +13 -0
  118. package/src/adapters/report-views.ts +98 -0
  119. package/src/adapters/report.ts +335 -0
  120. package/src/adapters/session-client.ts +116 -0
  121. package/src/adapters/session-dir.ts +28 -0
  122. package/src/adapters/session-target.ts +431 -0
  123. package/src/adapters/status-bar.ts +86 -0
  124. package/src/adapters/subagent-startup.ts +66 -0
  125. package/src/adapters/sync-runner.ts +340 -0
  126. package/src/adapters/sync-state-store.ts +227 -0
  127. package/src/adapters/target-picker.ts +127 -0
  128. package/src/config.ts +536 -0
  129. package/src/domain/ancestry-match.ts +84 -0
  130. package/src/domain/client-label.ts +56 -0
  131. package/src/domain/day.ts +8 -0
  132. package/src/domain/export.ts +107 -0
  133. package/src/domain/hub-entry.ts +433 -0
  134. package/src/domain/index.ts +19 -0
  135. package/src/domain/intervals.ts +53 -0
  136. package/src/domain/panel-model.ts +270 -0
  137. package/src/domain/registry-health.ts +87 -0
  138. package/src/domain/segment-rule.ts +10 -0
  139. package/src/domain/subagent-profile.ts +495 -0
  140. package/src/domain/sync-plan.ts +266 -0
  141. package/src/domain/task-view.ts +526 -0
  142. package/src/domain/work-record.ts +320 -0
  143. package/src/domain/work-target.ts +234 -0
  144. package/src/domain/work-tracker.ts +485 -0
  145. package/src/extension.ts +346 -0
  146. package/src/hub/index.ts +25 -0
  147. package/src/ports/catalog.ts +33 -0
  148. package/src/ports/clock.ts +3 -0
  149. package/src/ports/index.ts +11 -0
  150. package/src/ports/inflight-store.ts +16 -0
  151. package/src/ports/process-registry.ts +75 -0
  152. package/src/ports/work-log.ts +15 -0
  153. package/src/ports/work-sink.ts +35 -0
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Max allowed drift (ms) between a live process's freshly re-derived start
3
+ * identity and the one recorded in its registry entry. Absorbs
4
+ * second-granularity rounding/reading noise from the underlying OS
5
+ * start-time source (`adapters/ancestry.ts`) — not a measure of real clock
6
+ * error, since both readings of the *same* process instance stay tightly
7
+ * consistent regardless of that source's own precision (see that module's
8
+ * docs). A genuine pid-reuse produces a gap far larger than this.
9
+ */
10
+ export const START_ID_TOLERANCE_MS = 2000;
11
+ /** Whether two start identities are close enough to be the same process instance. `undefined` on either side is always "no", never a coincidental match. */
12
+ function sameProcessInstance(recorded, live) {
13
+ if (recorded === undefined || live === undefined)
14
+ return false;
15
+ return Math.abs(recorded - live) <= START_ID_TOLERANCE_MS;
16
+ }
17
+ /**
18
+ * The nearest tracked ancestor whose identity can actually be *proven*: the
19
+ * first `ancestryPids` entry (ordered nearest-parent first, see
20
+ * `adapters/ancestry.ts#walkAncestry`) that has a matching
21
+ * {@link RegistryEntry} AND whose registry-recorded `processStartId`
22
+ * agrees, within {@link START_ID_TOLERANCE_MS}, with `liveStartId(pid)` —
23
+ * a fresh re-derivation of that same pid's actual OS start time, taken
24
+ * from the same ancestry snapshot the caller already has. Matching by pid
25
+ * number alone is not safe: the OS reuses pids, so a stale entry left
26
+ * behind by a dead, never-cleaned-up process can otherwise be
27
+ * misattributed to whatever unrelated live process the kernel later hands
28
+ * that same pid to (a genuine top-level session silently misclassified as
29
+ * someone's subagent forever). A candidate whose identity cannot be
30
+ * verified — no `processStartId` on the entry (legacy/malformed), or no
31
+ * live start id available for that pid (platform without ancestor-chain
32
+ * support, or a snapshot gap) — is never matched; the walk continues past
33
+ * it exactly like an untracked hop, so a further genuine ancestor can still
34
+ * be found. Returns `undefined` when no ancestor pid is trackable at all —
35
+ * callers must treat that exactly like "no registry available" (safe
36
+ * fallback to the pre-registry behaviour), never invent a match.
37
+ */
38
+ export function findAncestorEntry(ancestryPids, entries, liveStartId) {
39
+ if (ancestryPids.length === 0 || entries.length === 0)
40
+ return undefined;
41
+ const byPid = new Map();
42
+ for (const entry of entries) {
43
+ // First entry for a given pid wins; a pid should only ever have one
44
+ // live registry file, but a torn write racing a sweep could in theory
45
+ // leave two candidates behind — deterministic tie-break, not correctness-critical.
46
+ if (!byPid.has(entry.pid))
47
+ byPid.set(entry.pid, entry);
48
+ }
49
+ for (const pid of ancestryPids) {
50
+ const entry = byPid.get(pid);
51
+ if (!entry)
52
+ continue;
53
+ if (sameProcessInstance(entry.processStartId, liveStartId(pid)))
54
+ return entry;
55
+ // Either unprovable, or this pid has genuinely been reused by a
56
+ // different process instance since the entry was written: not our
57
+ // ancestor. Keep walking — a further, verifiable ancestor may still exist.
58
+ }
59
+ return undefined;
60
+ }
61
+ /**
62
+ * Resolve the ultimate, top-level {@link OrchestratorRef} for `ancestorEntry`
63
+ * (the nearest verified ancestor {@link findAncestorEntry} returned) — F4's
64
+ * nested-subagent fix. When that ancestor is itself a `subagent`-role entry
65
+ * that already resolved its own verified `orchestratorRef` (a
66
+ * subagent-of-subagent chain: this process's parent is itself someone's
67
+ * child), that inherited ref is returned instead of one built from the
68
+ * ancestor's own identity — so a grandchild's `orchestratorRef` (and, via
69
+ * its `dir`, `extension.ts`'s F1 write-routing target) always points at
70
+ * the real top-level orchestrator, never a middle hop. Falls back to an
71
+ * ancestor's own identity when it is an orchestrator, or a subagent that
72
+ * never resolved a ref of its own (e.g. it discovered no tracked ancestor
73
+ * at its own startup) — never invents one. `undefined` in, `undefined` out.
74
+ */
75
+ export function resolveOrchestratorRef(ancestorEntry) {
76
+ if (ancestorEntry === undefined)
77
+ return undefined;
78
+ if (ancestorEntry.role === "subagent" && ancestorEntry.orchestratorRef !== undefined) {
79
+ return ancestorEntry.orchestratorRef;
80
+ }
81
+ return { pid: ancestorEntry.pid, project: ancestorEntry.project, startedAt: ancestorEntry.startedAt, dir: ancestorEntry.dir };
82
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Client (billing target) label resolution: pure, no I/O.
3
+ *
4
+ * A client name identifies who a piece of work is billed to. It can come
5
+ * from three sources, in decreasing precedence: the pi session (set with
6
+ * `/kankaku client <name>`), the `KANKAKU_CLIENT` environment variable, or
7
+ * the project's `.kankaku/config.json`.
8
+ */
9
+ export interface ClientSources {
10
+ /** Set for the current pi session via `/kankaku client <name>`. Highest precedence. */
11
+ session?: string;
12
+ /** From the `KANKAKU_CLIENT` environment variable. */
13
+ env?: string;
14
+ /** From the project's `.kankaku/config.json`. Lowest precedence. */
15
+ project?: string;
16
+ }
17
+ export type ClientSourceName = "session" | "env" | "project";
18
+ /** `true` when `value` is a non-empty, safe client name. */
19
+ export declare function isValidClient(value: string): boolean;
20
+ /**
21
+ * Resolve the effective client name from `session`, `env` and `project`
22
+ * sources, in that precedence order. Each candidate is trimmed; an empty
23
+ * string or a value that does not match the safe client-name pattern is
24
+ * treated as absent and resolution falls through to the next source.
25
+ */
26
+ export declare function resolveClient(sources: ClientSources): string | undefined;
27
+ /** Which source produced {@link resolveClient}'s result, or `undefined` when none applies. */
28
+ export declare function resolveClientSource(sources: ClientSources): ClientSourceName | undefined;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Client (billing target) label resolution: pure, no I/O.
3
+ *
4
+ * A client name identifies who a piece of work is billed to. It can come
5
+ * from three sources, in decreasing precedence: the pi session (set with
6
+ * `/kankaku client <name>`), the `KANKAKU_CLIENT` environment variable, or
7
+ * the project's `.kankaku/config.json`.
8
+ */
9
+ /** Safe client name: letters, digits, `.`, `_`, `-`, 1-64 chars. */
10
+ const CLIENT_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
11
+ /** Property names that behave specially on a plain object; never usable as a client name. */
12
+ const RESERVED_NAMES = new Set(["__proto__", "constructor", "prototype"]);
13
+ /** `true` when `value` is a non-empty, safe client name. */
14
+ export function isValidClient(value) {
15
+ return CLIENT_PATTERN.test(value) && !RESERVED_NAMES.has(value);
16
+ }
17
+ /** Trim and validate a candidate client name; `undefined` when absent or invalid. */
18
+ function normalize(value) {
19
+ if (value === undefined)
20
+ return undefined;
21
+ const trimmed = value.trim();
22
+ if (trimmed.length === 0)
23
+ return undefined;
24
+ return isValidClient(trimmed) ? trimmed : undefined;
25
+ }
26
+ /**
27
+ * Resolve the effective client name from `session`, `env` and `project`
28
+ * sources, in that precedence order. Each candidate is trimmed; an empty
29
+ * string or a value that does not match the safe client-name pattern is
30
+ * treated as absent and resolution falls through to the next source.
31
+ */
32
+ export function resolveClient(sources) {
33
+ return normalize(sources.session) ?? normalize(sources.env) ?? normalize(sources.project);
34
+ }
35
+ /** Which source produced {@link resolveClient}'s result, or `undefined` when none applies. */
36
+ export function resolveClientSource(sources) {
37
+ if (normalize(sources.session) !== undefined)
38
+ return "session";
39
+ if (normalize(sources.env) !== undefined)
40
+ return "env";
41
+ if (normalize(sources.project) !== undefined)
42
+ return "project";
43
+ return undefined;
44
+ }
@@ -0,0 +1,2 @@
1
+ /** Local (not UTC) calendar day of an ISO timestamp, as `YYYY-MM-DD`. */
2
+ export declare function localDay(iso: string): string;
@@ -0,0 +1,8 @@
1
+ /** Local (not UTC) calendar day of an ISO timestamp, as `YYYY-MM-DD`. */
2
+ export function localDay(iso) {
3
+ const date = new Date(iso);
4
+ const year = date.getFullYear();
5
+ const month = String(date.getMonth() + 1).padStart(2, "0");
6
+ const day = String(date.getDate()).padStart(2, "0");
7
+ return `${year}-${month}-${day}`;
8
+ }
@@ -0,0 +1,38 @@
1
+ import type { WorkStatus } from "./work-record.ts";
2
+ import type { TaskView } from "./task-view.ts";
3
+ /** One flat, spreadsheet-friendly row per {@link TaskView}. */
4
+ export interface ExportRow {
5
+ id: string;
6
+ /** Local calendar day (`YYYY-MM-DD`) the task started on. */
7
+ day: string;
8
+ startedAt: string;
9
+ endedAt: string;
10
+ /** Empty string when the task has no resolved client. */
11
+ client: string;
12
+ /** Empty string when the orchestrator record has no session name. */
13
+ sessionName: string;
14
+ /** Empty string when the orchestrator record has no session id. */
15
+ sessionId: string;
16
+ project: string;
17
+ status: WorkStatus;
18
+ /** First 200 chars of the task's prompt, with newlines collapsed to spaces. */
19
+ prompt: string;
20
+ wallMs: number;
21
+ waitingMs: number;
22
+ workMs: number;
23
+ cost: number;
24
+ tokensIn: number;
25
+ tokensOut: number;
26
+ cacheRead: number;
27
+ subagentCount: number;
28
+ /** JSON-encoded `TaskView.segments` map. */
29
+ segments: string;
30
+ /** Empty string when the orchestrator record has no model. */
31
+ model: string;
32
+ }
33
+ /** Build one flat {@link ExportRow} per task, in the same order as `tasks`. */
34
+ export declare function exportRows(tasks: TaskView[]): ExportRow[];
35
+ /** Render `rows` as RFC 4180 CSV: a header row, one row per record, `\n` line endings. */
36
+ export declare function toCsv(rows: ExportRow[]): string;
37
+ /** Render `rows` as pretty-printed (2-space indent) JSON. */
38
+ export declare function toJson(rows: ExportRow[]): string;
@@ -0,0 +1,68 @@
1
+ import { localDay } from "./day.js";
2
+ import { finiteOrZero } from "./work-record.js";
3
+ /** First 200 chars of `prompt`, with `\n`/`\r` collapsed to a single space. */
4
+ function truncatePrompt(prompt) {
5
+ return prompt.slice(0, 200).replace(/\r\n|\r|\n/g, " ");
6
+ }
7
+ /** Build one flat {@link ExportRow} per task, in the same order as `tasks`. */
8
+ export function exportRows(tasks) {
9
+ return tasks.map((task) => ({
10
+ id: task.id,
11
+ day: localDay(task.startedAt),
12
+ startedAt: task.startedAt,
13
+ endedAt: task.endedAt,
14
+ client: task.client ?? "",
15
+ sessionName: task.sessionName ?? "",
16
+ sessionId: task.sessionId ?? "",
17
+ project: task.project,
18
+ status: task.status,
19
+ prompt: truncatePrompt(task.prompt),
20
+ wallMs: task.wallMs,
21
+ waitingMs: task.waitingMs,
22
+ workMs: task.workMs,
23
+ cost: finiteOrZero(task.usage.cost),
24
+ tokensIn: finiteOrZero(task.usage.input),
25
+ tokensOut: finiteOrZero(task.usage.output),
26
+ cacheRead: finiteOrZero(task.usage.cacheRead),
27
+ subagentCount: task.subagents.length,
28
+ segments: JSON.stringify(task.segments),
29
+ model: task.orchestrator.model ?? "",
30
+ }));
31
+ }
32
+ /** Column order for {@link toCsv}'s header row, matching {@link ExportRow}'s field order. */
33
+ const COLUMNS = [
34
+ "id",
35
+ "day",
36
+ "startedAt",
37
+ "endedAt",
38
+ "client",
39
+ "sessionName",
40
+ "sessionId",
41
+ "project",
42
+ "status",
43
+ "prompt",
44
+ "wallMs",
45
+ "waitingMs",
46
+ "workMs",
47
+ "cost",
48
+ "tokensIn",
49
+ "tokensOut",
50
+ "cacheRead",
51
+ "subagentCount",
52
+ "segments",
53
+ "model",
54
+ ];
55
+ /** RFC 4180 field quoting: quote a field containing `,`, `"`, or a newline; double any embedded quote. */
56
+ function csvField(value) {
57
+ const text = String(value);
58
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
59
+ }
60
+ /** Render `rows` as RFC 4180 CSV: a header row, one row per record, `\n` line endings. */
61
+ export function toCsv(rows) {
62
+ const lines = [COLUMNS.join(","), ...rows.map((row) => COLUMNS.map((column) => csvField(row[column])).join(","))];
63
+ return lines.join("\n");
64
+ }
65
+ /** Render `rows` as pretty-printed (2-space indent) JSON. */
66
+ export function toJson(rows) {
67
+ return JSON.stringify(rows, null, 2);
68
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Map a {@link TaskView} (and its `WorkRecord`s) to the hub's `task_entries`
3
+ * / `work_records` payload shapes. Pure, no I/O — see `contract.md` in
4
+ * kankaku-hub for the exact field names/types this mirrors.
5
+ *
6
+ * The CRITICAL rule this file encodes: assignment (`client`/`project`/
7
+ * `task`/`legacy_client_label`) is create-only. The owner reassigns rows in
8
+ * the web; a later re-sync of the same task must never undo that, so
9
+ * `buildTaskEntryUpdatePayload` never includes those fields. See
10
+ * `buildTaskEntryCreatePayload` vs `buildTaskEntryUpdatePayload`.
11
+ */
12
+ import type { TaskView } from "./task-view.ts";
13
+ import type { WorkRecord, WorkRole, WorkStatus } from "./work-record.ts";
14
+ import type { Client, HubTask, Project } from "./work-target.ts";
15
+ export type PromptPrivacyMode = "none" | "truncated" | "full";
16
+ export interface HubEntryContext {
17
+ clients: Client[];
18
+ projects: Project[];
19
+ /** The hub's known tasks, to validate a task's linked `hubTaskId` against. See {@link resolveTaskAssignment}. */
20
+ tasks: HubTask[];
21
+ /** This machine's hostname or `KANKAKU_MACHINE`. */
22
+ machine: string;
23
+ /** `KANKAKU_SYNC_PROMPT`; see {@link applyPromptPrivacy}. */
24
+ promptMode: PromptPrivacyMode;
25
+ /** Coding agent that produced this row, lowercase slug. Always `"pi"` for this package. See kankaku-hub `docs/contract.md` "Agent and measurement quality". */
26
+ agent: string;
27
+ /** The `pi` package's own version, when it could be determined without a hot-path cost. Never guessed — omitted rather than sent wrong. */
28
+ agentVersion?: string;
29
+ /** The integration that wrote this row, lowercase slug. Always `"kankaku"` for this package. */
30
+ plugin: string;
31
+ /** This kankaku package's own version, from its `package.json`, read once. */
32
+ pluginVersion?: string;
33
+ }
34
+ export interface TaskAssignment {
35
+ /** `clients` relation id, or `""` when no usable client could be resolved. */
36
+ clientId: string;
37
+ /** `projects` relation id, or `""`. */
38
+ projectId: string;
39
+ /** `tasks` relation id, or `""` when no usable hub task could be resolved. See {@link resolveTaskAssignment}. */
40
+ hubTaskId: string;
41
+ /** Only set (non-empty) for a task routed to the unassigned client. */
42
+ legacyClientLabel: string;
43
+ /** `true` when this task was routed to the catalog's unassigned ("Sin determinar") client. */
44
+ routedToUnassigned: boolean;
45
+ }
46
+ /**
47
+ * Resolve which client/project/hub-task a task's `task_entries` row should
48
+ * link to.
49
+ *
50
+ * - A task whose `clientId` still exists in `clients` links to that client
51
+ * (regardless of its `active` flag — this is a historical fact, not a
52
+ * future selection), and to `projectId` too when it still exists and
53
+ * belongs to that client; otherwise the project relation is empty.
54
+ * - A task with no `clientId`, or whose `clientId` no longer resolves,
55
+ * routes to the catalog's unassigned client (the row with
56
+ * `unassigned: true`), carrying forward the record's free-text `client`
57
+ * label (or its `clientName` when the label itself is absent) as
58
+ * `legacyClientLabel` — the historical backfill rule (proposal §5.3).
59
+ * - `hubTaskId` is kept only when it still exists in `tasks` AND belongs to
60
+ * the resolved `projectId` (non-empty); otherwise it is `""` — including
61
+ * whenever the client fell back to unassigned, since there is then no
62
+ * resolved project for a task to belong to.
63
+ */
64
+ export declare function resolveTaskAssignment(task: TaskView, clients: Client[], projects: Project[], tasks: HubTask[]): TaskAssignment;
65
+ /**
66
+ * Privacy transform for a prompt about to leave the machine
67
+ * (`KANKAKU_SYNC_PROMPT`, default `none`): `none` omits it entirely,
68
+ * `truncated` keeps the first 120 chars plus an ellipsis marker when
69
+ * anything was cut, `full` sends it verbatim.
70
+ */
71
+ export declare function applyPromptPrivacy(prompt: string, mode: PromptPrivacyMode): string;
72
+ export type WaitingQuality = "measured" | "unavailable";
73
+ export type CostQuality = "measured" | "estimated" | "unknown";
74
+ export type SubagentLinkage = "linked" | "unlinked" | "not_applicable";
75
+ /**
76
+ * Whether waiting time (time blocked on the human) was actually observed
77
+ * for this task, as opposed to `work_ms` being an unmeasured upper bound
78
+ * equal to `wall_ms`. pi always instruments `ui_prompt_start`/`_end` and
79
+ * interactive-tool spans (`domain/work-tracker.ts`), so this is always
80
+ * `"measured"` for kankaku/pi — a constant here, not computed from a
81
+ * record, kept as its own function (rather than a literal in the payload)
82
+ * so the reasoning has one documented home.
83
+ */
84
+ export declare function computeWaitingQuality(): WaitingQuality;
85
+ /**
86
+ * Whether this task's cost figure came from a real provider-reported cost
87
+ * (`"measured"`) or not (`"unknown"`) — never `"estimated"`: kankaku has no
88
+ * token-based price-table estimator today, only a real provider figure or
89
+ * nothing. A task counts as measured when its own orchestrator record OR
90
+ * any of its joined subagent records observed one (see
91
+ * `WorkRecord.costObserved`, set by `domain/work-tracker.ts`).
92
+ */
93
+ export declare function computeCostQuality(task: TaskView): CostQuality;
94
+ /**
95
+ * Whether this task's subagent tool spans (`orchestrator.subagents`,
96
+ * `SubagentSpan[]` — the orchestrator's own tool-call bookkeeping) are
97
+ * accounted for by joined child `WorkRecord`s (`task.subagents`, from
98
+ * `domain/task-view.ts#matchChildren`). There is no explicit per-span
99
+ * correlation id today (README "Subagents" > "Limitations": upstream
100
+ * gentle-pi does not hand a child its own task id), so this is a
101
+ * task-level approximation, not a per-span one:
102
+ *
103
+ * - `not_applicable`: the orchestrator opened no subagent spans at all.
104
+ * - `linked`: at least as many child records were joined as spans were
105
+ * opened — plausibly every span is accounted for (a gentle-pi subagent
106
+ * spawns exactly one child process per span, so counts normally match
107
+ * 1:1).
108
+ * - `unlinked`: fewer joined children than spans (including zero) — at
109
+ * least one span's time is only visible inside the orchestrator's own
110
+ * tool-call span, with no corroborating child record. This also covers
111
+ * a fully in-process subagent mechanism (no separate OS process at all,
112
+ * invisible to the registry/ancestry machinery) and a genuine join miss
113
+ * alike — kankaku cannot tell those apart from here, so it reports the
114
+ * conservative, visible-gap answer rather than guessing "linked".
115
+ */
116
+ export declare function computeSubagentLinkage(task: TaskView): SubagentLinkage;
117
+ /** The `task_entries` fields present on every write. */
118
+ export interface TaskEntryPayload {
119
+ task_id: string;
120
+ client: string;
121
+ project: string;
122
+ task: string;
123
+ started_at: string;
124
+ ended_at: string;
125
+ wall_ms: number;
126
+ waiting_ms: number;
127
+ work_ms: number;
128
+ input: number;
129
+ output: number;
130
+ cache_read: number;
131
+ cache_write: number;
132
+ cost: number;
133
+ segments: Record<string, number>;
134
+ subagent_count: number;
135
+ runs: number;
136
+ turns: number;
137
+ status: WorkStatus;
138
+ session_id: string;
139
+ session_name: string;
140
+ machine: string;
141
+ model: string;
142
+ /** The model's reasoning effort; omitted when the record does not know it. */
143
+ thinking_level?: string;
144
+ prompt: string;
145
+ legacy_client_label: string;
146
+ repo_project: string;
147
+ schema: number;
148
+ /** Coding agent that MEASURED this task, lowercase slug — the orchestrator record's own {@link WorkRecordMetadata.agent} when it carries one (who measured, not who syncs), else `ctx.agent` (the syncing process's own identity) as a legacy fallback. See {@link WorkRecordMetadata.agent}. */
149
+ agent: string;
150
+ agent_version?: string;
151
+ /** Non-default session directory, see `TaskView.sessionDir`. A measurement field, not assignment: sent on both create and update. */
152
+ session_dir?: string;
153
+ /** The integration that wrote this task's records, lowercase slug — same record-wins-over-ctx rule as {@link agent}. */
154
+ plugin: string;
155
+ plugin_version?: string;
156
+ waiting_quality: WaitingQuality;
157
+ cost_quality: CostQuality;
158
+ subagent_linkage: SubagentLinkage;
159
+ }
160
+ /**
161
+ * `TaskEntryPayload` minus the assignment fields — what an update sends. See
162
+ * the module docs' CRITICAL rule.
163
+ *
164
+ * `agent`/`agent_version`/`plugin`/`plugin_version` are optional here (unlike
165
+ * on `TaskEntryPayload`, where they are always sent on create): an update for
166
+ * a task whose orchestrator record carries no who-measured identity (a
167
+ * legacy record, written before this feature existed) omits them entirely,
168
+ * so a re-sync by a DIFFERENT process never overwrites a row's original
169
+ * identity with its own. See {@link buildTaskEntryUpdatePayload}.
170
+ */
171
+ export type TaskEntryUpdatePayload = Omit<TaskEntryPayload, "client" | "project" | "task" | "legacy_client_label" | "agent" | "agent_version" | "plugin" | "plugin_version"> & {
172
+ agent?: string;
173
+ agent_version?: string;
174
+ plugin?: string;
175
+ plugin_version?: string;
176
+ };
177
+ /** Build the full `task_entries` payload for a **create** request — every field, including assignment. */
178
+ export declare function buildTaskEntryCreatePayload(task: TaskView, ctx: HubEntryContext): TaskEntryPayload;
179
+ /**
180
+ * Build the `task_entries` payload for an **update** request: measurement
181
+ * fields only — never `client`, `project`, `task` or `legacy_client_label`,
182
+ * so a re-sync can never undo a reassignment made in the web. See the
183
+ * module docs' CRITICAL rule.
184
+ *
185
+ * `agent`/`agent_version`/`plugin`/`plugin_version` are included ONLY when
186
+ * the orchestrator record itself carries a who-measured `agent` — otherwise
187
+ * they are OMITTED entirely (never sent as `ctx`'s own identity), so a
188
+ * re-sync of a legacy record by a different process never overwrites the
189
+ * row's original identity in the hub. See `domain/work-record.ts`'s
190
+ * "Measurement rules" and {@link resolveTaskIdentity}.
191
+ */
192
+ export declare function buildTaskEntryUpdatePayload(task: TaskView, ctx: HubEntryContext): TaskEntryUpdatePayload;
193
+ /** One `work_records` row — raw per-`WorkRecord` detail, always `rollup: false`. */
194
+ export interface WorkRecordPayload {
195
+ kankaku_id: string;
196
+ task_entry: string;
197
+ rollup: false;
198
+ role: WorkRole;
199
+ pid: number;
200
+ parent_pid: number;
201
+ started_at: string;
202
+ settled_at: string;
203
+ wall_ms: number;
204
+ waiting_ms: number;
205
+ work_ms: number;
206
+ runs: number;
207
+ turns: number;
208
+ status: WorkStatus;
209
+ model: string;
210
+ thinking_level?: string;
211
+ input: number;
212
+ output: number;
213
+ cache_read: number;
214
+ cache_write: number;
215
+ cost: number;
216
+ segments: Record<string, number>;
217
+ tools: Record<string, number>;
218
+ session_id: string;
219
+ prompt: string;
220
+ machine: string;
221
+ schema: number;
222
+ }
223
+ /**
224
+ * Build one `work_records` payload from a raw {@link WorkRecord}
225
+ * (orchestrator or subagent), linked to its parent `task_entries` row by
226
+ * PocketBase id. `work_records` carries no assignment fields, so there is
227
+ * no create/update distinction here — this payload is sent as-is either way.
228
+ */
229
+ export declare function buildWorkRecordPayload(record: WorkRecord, taskEntryRecordId: string, ctx: {
230
+ machine: string;
231
+ promptMode: PromptPrivacyMode;
232
+ }): WorkRecordPayload;
233
+ /** Every `WorkRecord` folded into a task: the orchestrator plus its subagents, in that order. */
234
+ export declare function taskWorkRecords(task: TaskView): WorkRecord[];