@letsrebase/verify 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/.claude/commands/rebase-verify.md +118 -0
  2. package/LICENSE +21 -0
  3. package/PRIVACY.md +113 -0
  4. package/README.md +210 -2
  5. package/SECURITY.md +33 -0
  6. package/bin/rebase-verify.mjs +700 -0
  7. package/package.json +38 -4
  8. package/share/practices.json +224 -0
  9. package/share/tech-labels.json +57 -0
  10. package/share/tech-lexicon.json +62 -0
  11. package/src/adapters/claude-code.mjs +225 -0
  12. package/src/adapters/codex.mjs +476 -0
  13. package/src/adapters/cursor.mjs +584 -0
  14. package/src/adapters/kimi.mjs +594 -0
  15. package/src/adapters/omp.mjs +59 -0
  16. package/src/adapters/opencode.mjs +439 -0
  17. package/src/adapters/pi.mjs +414 -0
  18. package/src/adapters/tool-vocab.mjs +15 -0
  19. package/src/agent-run.mjs +10 -0
  20. package/src/agentic-literacy.mjs +211 -0
  21. package/src/agents/acp.mjs +364 -0
  22. package/src/agents/json-answer.mjs +72 -0
  23. package/src/agents/registry.mjs +370 -0
  24. package/src/agents/run.mjs +131 -0
  25. package/src/ai-relationship.mjs +95 -0
  26. package/src/consistency.mjs +382 -0
  27. package/src/days.mjs +45 -0
  28. package/src/digest.mjs +501 -0
  29. package/src/distribution.mjs +54 -0
  30. package/src/enrich.mjs +118 -0
  31. package/src/fingerprint.mjs +134 -0
  32. package/src/forensics.mjs +178 -0
  33. package/src/groundedness.mjs +347 -0
  34. package/src/hub.mjs +136 -0
  35. package/src/intensity.mjs +132 -0
  36. package/src/live-status.mjs +79 -0
  37. package/src/practices-llm.mjs +90 -0
  38. package/src/practices-rules.mjs +295 -0
  39. package/src/practices-sample.mjs +111 -0
  40. package/src/practices.mjs +279 -0
  41. package/src/profile-llm.mjs +249 -0
  42. package/src/profile.mjs +497 -0
  43. package/src/redact.mjs +97 -0
  44. package/src/sources.mjs +91 -0
  45. package/src/submit.mjs +65 -0
  46. package/src/system-text.mjs +3 -0
  47. package/src/tech-usage.mjs +88 -0
  48. package/src/trajectory.mjs +264 -0
  49. package/src/wizard.mjs +411 -0
@@ -0,0 +1,594 @@
1
+ // kimi (kimi-code) adapter: reads kimi-code CLI's per-session wire logs
2
+ // (~/.kimi-code/sessions/wd_<slug>_<12hex>/session_<uuid>/agents/<agentId>/
3
+ // wire.jsonl, one file per AGENT within a session, plus a sibling
4
+ // state.json) and normalises them into the SAME session model
5
+ // claude-code.mjs, opencode.mjs, codex.mjs and pi.mjs produce, so every
6
+ // downstream lens (digest, agentic-literacy, forensics, fingerprint,
7
+ // intensity, distribution) keeps working unchanged.
8
+ //
9
+ // DISCOVERY is bespoke, not walk()-based: unlike the other adapters' flat
10
+ // "any .jsonl under root" sweep, kimi's session is a whole DIRECTORY
11
+ // (state.json + agents/*/wire.jsonl), and the parent of sessions/ now holds
12
+ // real provider config (config.toml), a device id, and possibly a
13
+ // credentials/ dir — none of which should ever be opened. Scoping root to
14
+ // sessions/ and only descending into wd_*/session_*/{state.json,agents/*/
15
+ // wire.jsonl} makes everything else structurally unreachable, not just
16
+ // policy-excluded.
17
+ //
18
+ // TURN SYNTHESIS, like codex: kimi's assistant output arrives as a flat
19
+ // event stream (context.append_loop_event, nested step.begin/content.part/
20
+ // tool.call/tool.result/step.end), not as ready-made messages. Every
21
+ // surviving `context.append_message` with role "user" flushes the
22
+ // previously open assistant turn, emits the user message, and opens a fresh
23
+ // turn; loop events accumulate into it until the next user message or EOF.
24
+ // UNLIKE codex, this happens once PER AGENT FILE (uuid = "<sessionId>-
25
+ // <agentId>-turn-<n>", parentUuid chains only within that file), because a
26
+ // session here is not one file but N agent files. All agents' synthesized
27
+ // messages are then merged into ONE session.messages array and sorted by
28
+ // record time — "the session dir IS the session", per the subagent-rollup
29
+ // design; unlike opencode there is no cross-session re-parenting to do,
30
+ // just an interleave. FRAMEWORK-INJECTED USER TURNS ARE NOW FILTERED, same
31
+ // per-block discipline codex uses for <environment_context>: kimi's own
32
+ // injected reminders (context.append_message with role "user", origin.kind
33
+ // "injection", e.g. a stale-TodoList nudge) arrive wrapped ENTIRELY in
34
+ // <system-reminder>...</system-reminder>. An earlier revision of this
35
+ // comment documented NOT filtering these — reversed here by observed harm: a
36
+ // real end-to-end test on this machine showed reminder text surfacing in
37
+ // promptSamples and inflating user-message signal counts as if a human had
38
+ // typed it. A block survives only when its trimmed text is not fully
39
+ // wrapped in the tag; a message where every block is wrapped (or which has
40
+ // none left) is skipped ENTIRELY — no emit, no turn flush, no turn reopen —
41
+ // so a reminder landing mid-turn can never split or corrupt the surrounding
42
+ // loop-event turn synthesis (see extractUserMessageText below).
43
+ // `turn.prompt` and `context.append_message` both record the user's prompt
44
+ // (the former is the raw input event, the latter the canonical message the
45
+ // context keeps); processing both would double-count user messages, so only
46
+ // append_message emits — turn.prompt is a no-op case in the switch below.
47
+ //
48
+ // USAGE KEYS are renamed, not reused: step.end's usage object uses kimi's
49
+ // own names (inputOther, output, inputCacheRead, inputCacheCreation) which
50
+ // get renamed to the shared contract (input, output, cacheRead,
51
+ // cacheCreate) and SUMMED across every step.end inside one synthesized
52
+ // turn (a turn can span several LLM steps when it makes several tool
53
+ // calls). The separate `usage.record` record type carries the same numbers
54
+ // at a coarser ("turn") granularity and is deliberately ignored — using it
55
+ // as well would double count, and a turn with no step.end at all (e.g. it
56
+ // was still streaming when the file was read) correctly yields usage: null
57
+ // rather than falling back to it.
58
+ //
59
+ // DISPLAY IS PREFERRED over raw args for tool.call: kimi ships its own
60
+ // normalised `display` view of a call (display.kind "file_io" -> path,
61
+ // "command" -> command) alongside the real `args` object, and display is
62
+ // trusted first with args as the fallback for tools kimi hasn't classified.
63
+ // CRITICAL: display for a file_io "write" call also carries a `content`
64
+ // field with the FULL file body about to be written (confirmed on a real
65
+ // session on this machine — tens of KB of raw source). Only display.path is
66
+ // ever read off that object; display.content (and args.content) must never
67
+ // be touched, exactly like Write's `content` argument is never touched by
68
+ // any other adapter.
69
+ //
70
+ // PRIVACY: state.json's `title` and `lastPrompt` fields are VERBATIM PROMPT
71
+ // TEXT (confirmed on a real session: lastPrompt was a full user instruction
72
+ // sentence). We parse state.json only to pull out `workDir`; the rest of
73
+ // the parsed object — including title/lastPrompt — is never assigned to
74
+ // anything and never leaves this function. There is no `title` field on
75
+ // the shared session model and none is added here.
76
+ //
77
+ // SCOPE CUT: no compaction, cancel, or session-title record shapes have
78
+ // been observed in wire.jsonl yet (only metadata/config.update/tools.
79
+ // set_active_tools/turn.prompt/context.append_message/llm.request/llm.
80
+ // tools_snapshot/usage.record/context.append_loop_event/permission.
81
+ // record_approval_result — see the switch below), so compactionSummaries
82
+ // is always []. Revisit when/if kimi ships a compaction convention.
83
+ //
84
+ // Live-append: wire.jsonl is append-only and can be mid-write (a live
85
+ // session was running while this adapter's tests were being written). A
86
+ // truncated trailing line degrades to "malformed", never throws, and the
87
+ // rest of the file still parses; stats.liveSessionsSeen counts each SESSION
88
+ // (not each file) where at least one agent's wire.jsonl ended mid-line —
89
+ // cheap, honestly-named disclosure that the read may be incomplete.
90
+ //
91
+ // Same structural-capture posture as every other adapter: thinking text,
92
+ // tool output, and systemPrompt/title/lastPrompt are reduced to lengths/
93
+ // booleans or dropped outright, never kept — see redact.mjs and
94
+ // claude-code.mjs/opencode.mjs/codex.mjs/pi.mjs for the shared contract
95
+ // this adapter has to honor.
96
+
97
+ import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
98
+ import { join, relative } from "node:path";
99
+ import { homedir } from "node:os";
100
+ import { createHash } from "node:crypto";
101
+ import { redactText, countRedactions } from "../redact.mjs";
102
+ import { toPosix } from "./claude-code.mjs";
103
+ import { fallbackToolName } from "./tool-vocab.mjs";
104
+
105
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
106
+ const shortHash = (s) => sha256(s).slice(0, 8);
107
+ const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
108
+
109
+ // ── Default location ────────────────────────────────────────────────────────
110
+ // kimi-code documents no env-var override for the sessions root (same
111
+ // honest posture as pi.mjs re: no override to invent). The PARENT of
112
+ // sessions/ (config.toml, device_id, credentials/, telemetry/, user-
113
+ // history/, logs/, session_index.jsonl, workspaces.json) is never resolved
114
+ // or opened here.
115
+ export function defaultKimiRoot() {
116
+ return join(homedir(), ".kimi-code", "sessions");
117
+ }
118
+
119
+ // ── Tool vocabulary: kimi → canonical (Claude Code) names ──────────────────
120
+ // kimi's own tool names are already PascalCase and mostly canonical (Read,
121
+ // Write, Edit, Bash, Glob confirmed on real sessions on this machine) — the
122
+ // one confirmed rename is FetchURL -> WebFetch. Anything else unmapped
123
+ // (including any that already happen to be canonical) falls through to
124
+ // fallbackToolName unchanged, same contract every other adapter honors.
125
+ const TOOL_MAP = {
126
+ FetchURL: "WebFetch",
127
+ };
128
+ function mapTool(name) {
129
+ if (!name) return name;
130
+ if (TOOL_MAP[name]) return TOOL_MAP[name];
131
+ return fallbackToolName(name);
132
+ }
133
+
134
+ // Directory listing helper, filtered to directories only. Used for the
135
+ // three fixed levels of kimi's discovery (wd_*, session_*, agents/*)
136
+ // instead of walk()'s flat recursive .jsonl sweep, which would happily
137
+ // wander into logs/ or any other sibling under a session dir.
138
+ function listDirNames(dir) {
139
+ if (!existsSync(dir)) return [];
140
+ return readdirSync(dir, { withFileTypes: true })
141
+ .filter((e) => e.isDirectory())
142
+ .map((e) => e.name);
143
+ }
144
+
145
+ // "session_<uuid>" -> "<uuid>". Falls back to the raw dir name if it
146
+ // somehow doesn't match (defensive; every session dir observed on this
147
+ // machine follows the convention).
148
+ const SESSION_DIR_RE = /^session_(.+)$/;
149
+ function sessionIdFromDirName(name) {
150
+ const m = SESSION_DIR_RE.exec(name);
151
+ return m ? m[1] : name;
152
+ }
153
+
154
+ // context.append_message's message.content / turn.prompt's input: an array
155
+ // of {type:"text", text} blocks — the only block shape observed.
156
+ function extractMessageText(content) {
157
+ if (!Array.isArray(content)) return "";
158
+ let text = "";
159
+ for (const b of content) {
160
+ if (b && typeof b === "object" && b.type === "text") text += (b.text || "") + "\n";
161
+ }
162
+ return text;
163
+ }
164
+
165
+ // Framework-injected content: kimi re-sends TodoList/other nudges as a
166
+ // synthetic role-"user" block wrapped ENTIRELY in <system-reminder> (checked
167
+ // per content block, mirroring codex's <environment_context>/<permissions
168
+ // instructions> filter — see extractUserMessageText below). Trimmed text
169
+ // must both start with the open tag and end with the close tag, so a real
170
+ // block that merely mentions <system-reminder> inline is never dropped.
171
+ const FRAMEWORK_TAGS = [{ open: "<system-reminder>", close: "</system-reminder>" }];
172
+ function isFrameworkWrapped(trimmed) {
173
+ return FRAMEWORK_TAGS.some((t) => trimmed.startsWith(t.open) && trimmed.endsWith(t.close));
174
+ }
175
+
176
+ // role "user" context.append_message content, filtered per block: a block
177
+ // that survives contributes to the message exactly like extractMessageText
178
+ // does; one that's framework-wrapped is dropped without contributing.
179
+ // Returns null when no block survives (all wrapped, or there were none) so
180
+ // the caller can skip the message entirely — no emit, no turn flush/reopen,
181
+ // so an all-filtered message mid-turn never disturbs the open loop-event
182
+ // turn (see the header's "turn synthesis safety" note).
183
+ function extractUserMessageText(content) {
184
+ if (!Array.isArray(content)) return null;
185
+ let text = "";
186
+ let survived = 0;
187
+ for (const b of content) {
188
+ if (!b || typeof b !== "object" || b.type !== "text") continue;
189
+ const blockText = b.text || "";
190
+ if (isFrameworkWrapped(blockText.trim())) continue;
191
+ survived++;
192
+ text += blockText + "\n";
193
+ }
194
+ return survived > 0 ? text : null;
195
+ }
196
+
197
+ // tool.call -> toolUse. display is kimi's own normalised view of the call
198
+ // and is preferred when its `kind` matches the field we want; args (the
199
+ // real, un-normalised tool arguments) is the fallback for anything display
200
+ // hasn't classified (or when display is entirely absent). q has no display
201
+ // counterpart (kimi doesn't model a "search" display kind) so it always
202
+ // comes straight from args.pattern (e.g. Glob's search pattern).
203
+ function buildToolCallToolUse(event) {
204
+ const args = event.args && typeof event.args === "object" && !Array.isArray(event.args) ? event.args : {};
205
+ const display = event.display && typeof event.display === "object" ? event.display : {};
206
+ const mapped = mapTool(event.name);
207
+
208
+ // NEVER read display.content / args.content here (see header) — only
209
+ // .path and .command are ever pulled off either object.
210
+ const rawPath = display.kind === "file_io" ? (display.path ?? args.path) : args.path;
211
+ const rawCmd = display.kind === "command" ? (display.command ?? args.command) : args.command;
212
+
213
+ const path = rawPath ? toPosix(redactText(String(rawPath))) : "";
214
+ const cmd = rawCmd ? redactText(String(rawCmd).slice(0, 240)) : "";
215
+ const q = args.pattern ? redactText(String(args.pattern).slice(0, 200)) : "";
216
+
217
+ return { id: event.toolCallId, name: mapped, path, cmd, q };
218
+ }
219
+
220
+ // tool.result -> toolResult. isError is present ONLY on failures (confirmed
221
+ // on real data: absent when successful, `true` with note:null on failure) —
222
+ // absence must mean false, never undefined. result.output/.note text is
223
+ // never stored, only its length.
224
+ function buildToolResultEntry(event) {
225
+ const result = event.result && typeof event.result === "object" ? event.result : {};
226
+ const output = typeof result.output === "string" ? result.output : "";
227
+ return { forId: event.toolCallId, isError: result.isError === true, bytes: output.length };
228
+ }
229
+
230
+ // step.end's usage -> the shared {input, output, cacheRead, cacheCreate}
231
+ // shape (RENAME only). Mutates turn.usage in place, summing across however
232
+ // many step.ends land in one synthesized turn.
233
+ function accumulateUsage(turn, usage) {
234
+ if (!usage || typeof usage !== "object") return;
235
+ turn.usage ||= { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 };
236
+ turn.usage.input += usage.inputOther || 0;
237
+ turn.usage.output += usage.output || 0;
238
+ turn.usage.cacheRead += usage.inputCacheRead || 0;
239
+ turn.usage.cacheCreate += usage.inputCacheCreation || 0;
240
+ }
241
+
242
+ // Process one agent's wire.jsonl records into a flat list of normalized
243
+ // messages, mutating the shared `session` object's models Set and firstTs/
244
+ // lastTs as it goes (every record's own `time` counts toward the session's
245
+ // span, not just the ones that become messages — state.json's updatedAt is
246
+ // STALE on a live session, so wire record times are the only trustworthy
247
+ // source). uuid/parentUuid chaining is local to this one agent file; the
248
+ // caller merges + time-sorts every agent's messages into one session.
249
+ function processAgentFile(session, sessionId, agentId, records) {
250
+ const messages = [];
251
+ let currentModel = null;
252
+ let turn = null; // open assistant-turn accumulator, or null between turns
253
+ let turnN = 0;
254
+ let prevUuid = null;
255
+ let redactionHits = 0;
256
+ let redactedChars = 0;
257
+
258
+ const stampSessionTs = (ts) => {
259
+ if (!ts) return;
260
+ if (!session.firstTs || ts < session.firstTs) session.firstTs = ts;
261
+ if (!session.lastTs || ts > session.lastTs) session.lastTs = ts;
262
+ };
263
+
264
+ const stampModel = (alias) => {
265
+ if (typeof alias !== "string" || !alias) return;
266
+ // Defensive redaction, mirroring pi.mjs's model-path privacy rule: a
267
+ // modelAlias isn't known to ever be a filesystem path on kimi, but
268
+ // there's no cost to treating it the same way pi treats modelId.
269
+ currentModel = redactText(alias);
270
+ session.models.add(currentModel);
271
+ };
272
+
273
+ const openTurn = () => {
274
+ turn = { ts: null, text: "", thinkingChars: 0, signatureChars: 0, toolUses: [], toolResults: [], usage: null };
275
+ };
276
+ const markTurnTs = (ts) => {
277
+ if (turn && !turn.ts && ts) turn.ts = ts;
278
+ };
279
+
280
+ const emit = (role, ts, text, extra = {}) => {
281
+ turnN += 1;
282
+ const uuid = `${sessionId}-${agentId}-turn-${turnN}`;
283
+ const parentUuid = prevUuid;
284
+ prevUuid = uuid;
285
+
286
+ redactionHits += countRedactions(text);
287
+ const textRedacted = redactText(text);
288
+ redactedChars += text.length - textRedacted.length;
289
+
290
+ messages.push({
291
+ role,
292
+ ts,
293
+ uuid,
294
+ parentUuid,
295
+ model: currentModel,
296
+ textRedacted,
297
+ textLen: text.length,
298
+ thinkingChars: extra.thinkingChars || 0,
299
+ signatureChars: extra.signatureChars || 0, // kimi has no signature field; always 0
300
+ toolUses: extra.toolUses || [],
301
+ toolResults: extra.toolResults || [],
302
+ usage: extra.usage || null,
303
+ });
304
+ };
305
+
306
+ const flushTurn = () => {
307
+ if (!turn) return;
308
+ const hasContent =
309
+ turn.text.trim().length > 0 ||
310
+ turn.toolUses.length > 0 ||
311
+ turn.toolResults.length > 0 ||
312
+ turn.thinkingChars > 0 ||
313
+ turn.signatureChars > 0 ||
314
+ !!turn.usage;
315
+ if (hasContent) {
316
+ emit("assistant", turn.ts, turn.text, {
317
+ thinkingChars: turn.thinkingChars,
318
+ signatureChars: turn.signatureChars,
319
+ toolUses: turn.toolUses,
320
+ toolResults: turn.toolResults,
321
+ usage: turn.usage,
322
+ });
323
+ }
324
+ turn = null;
325
+ };
326
+
327
+ for (const r of records) {
328
+ if (!r || typeof r !== "object") continue;
329
+ // Not every record type carries a `time` field (metadata's own
330
+ // timestamp field is `created_at`, confirmed on real data) — fall back
331
+ // to created_at so metadata's own record still counts toward the
332
+ // session span, per the "every record's time counts toward the span"
333
+ // rule below. iso() degrades a missing/non-finite value to null and
334
+ // stampSessionTs is a no-op on null, so this is safe to call
335
+ // unconditionally.
336
+ const ts = iso(r.time ?? r.created_at);
337
+ stampSessionTs(ts);
338
+
339
+ switch (r.type) {
340
+ case "metadata":
341
+ break; // provenance only; the file's raw bytes are already hashed into files[]
342
+ case "config.update":
343
+ stampModel(r.modelAlias);
344
+ // r.systemPrompt is framework text (confirmed 20K+ chars on a real
345
+ // session) — deliberately never read past the modelAlias check.
346
+ break;
347
+ case "tools.set_active_tools":
348
+ break; // the active tool-name list; no message-shaped content
349
+ case "turn.prompt":
350
+ break; // duplicates context.append_message's user text; see header
351
+ case "context.append_message": {
352
+ const message = r.message && typeof r.message === "object" ? r.message : {};
353
+ if (message.role === "user") {
354
+ const text = extractUserMessageText(message.content);
355
+ if (text === null) break; // fully framework-injected reminder: skip entirely, no turn side effects
356
+ flushTurn();
357
+ emit("user", ts, text);
358
+ openTurn();
359
+ } else if (message.role === "assistant") {
360
+ // Not observed on this machine (every context.append_message
361
+ // seen was role "user"); defensive fallback only, mirroring the
362
+ // user case's turn discipline exactly (flush -> emit -> reopen)
363
+ // rather than leaving the open loop-event turn untouched.
364
+ // Emitting straight into `emit()` without flushing first left the
365
+ // in-flight turn open: it kept accumulating loop-event content
366
+ // from BOTH sides of this injected message into one turn, whose
367
+ // ts is fixed at its FIRST folded record (i.e. from before the
368
+ // injection) but which is only pushed to `messages` later, after
369
+ // the injected message was already pushed. Once merged across
370
+ // agents and sorted by ts, that produces a parentUuid chain where
371
+ // the child (the late-flushed turn) has an EARLIER ts than its
372
+ // parent (this injected message) — plus content from before/after
373
+ // the injection wrongly folded into a single message. Flushing
374
+ // first closes out whatever was folded so far as its own message
375
+ // (preserving the ts-of-first-folded-record rule), then this
376
+ // injected message gets its own ts/uuid slot, then reopening a
377
+ // fresh turn lets subsequent loop events accumulate cleanly again.
378
+ flushTurn();
379
+ emit("assistant", ts, extractMessageText(message.content));
380
+ openTurn();
381
+ }
382
+ // any other role: ignore, forward-compat
383
+ break;
384
+ }
385
+ case "llm.request":
386
+ stampModel(r.modelAlias);
387
+ break; // otherwise just an LLM-call boundary marker
388
+ case "llm.tools_snapshot":
389
+ break; // a 67KB tool-schema dump; nothing message-shaped
390
+ case "usage.record":
391
+ break; // step.end is the summed source of truth; see header
392
+ case "context.append_loop_event": {
393
+ if (!turn) break; // events outside an open turn have nothing to attach to
394
+ const event = r.event && typeof r.event === "object" ? r.event : {};
395
+ switch (event.type) {
396
+ case "step.begin":
397
+ break; // step boundary marker only, no structural content
398
+ case "content.part": {
399
+ const part = event.part && typeof event.part === "object" ? event.part : {};
400
+ if (part.type === "think") {
401
+ turn.thinkingChars += (part.think || "").length; // NEVER store the text itself
402
+ markTurnTs(ts);
403
+ } else if (part.type === "text") {
404
+ turn.text += (part.text || "") + "\n";
405
+ markTurnTs(ts);
406
+ }
407
+ break;
408
+ }
409
+ case "tool.call":
410
+ turn.toolUses.push(buildToolCallToolUse(event));
411
+ markTurnTs(ts);
412
+ break;
413
+ case "tool.result":
414
+ turn.toolResults.push(buildToolResultEntry(event));
415
+ markTurnTs(ts);
416
+ break;
417
+ case "step.end":
418
+ accumulateUsage(turn, event.usage);
419
+ markTurnTs(ts);
420
+ break;
421
+ default:
422
+ break; // forward-compat: unknown loop-event type
423
+ }
424
+ break;
425
+ }
426
+ case "permission.record_approval_result":
427
+ // turnId here is a NUMBER (confirmed: 0) while loop events' turnId
428
+ // is a STRING ("0") — a genuine inconsistency in kimi's own wire
429
+ // format, not a bug in this adapter. Noted so nobody "fixes" one of
430
+ // the two string/number handlings later and breaks the other.
431
+ break;
432
+ default:
433
+ break; // unknown top-level type: ignore (versioned protocol, forward-compat)
434
+ }
435
+ }
436
+
437
+ flushTurn();
438
+ return { messages, redactionHits, redactedChars };
439
+ }
440
+
441
+ const EMPTY = (root) => ({
442
+ source: "kimi",
443
+ root: root || null,
444
+ files: [],
445
+ sessions: [],
446
+ compactionSummaries: [],
447
+ redaction: { hits: 0, charsRemoved: 0 },
448
+ stats: { malformedLines: 0, liveSessionsSeen: 0 },
449
+ });
450
+
451
+ export function readKimi(root) {
452
+ if (!root || !existsSync(root)) return EMPTY(root);
453
+
454
+ const files = [];
455
+ const sessions = [];
456
+ let redactionHits = 0;
457
+ let redactedChars = 0;
458
+ let malformedLinesTotal = 0;
459
+ let liveSessionsSeenTotal = 0;
460
+
461
+ for (const wdName of listDirNames(root).filter((n) => n.startsWith("wd_"))) {
462
+ const wdDir = join(root, wdName);
463
+ for (const sessName of listDirNames(wdDir).filter((n) => n.startsWith("session_"))) {
464
+ const sessionDir = join(wdDir, sessName);
465
+ const sessionId = sessionIdFromDirName(sessName);
466
+
467
+ const session = {
468
+ source: "kimi",
469
+ sessionId,
470
+ projectLabel: "project-unknown",
471
+ cwdRedacted: "",
472
+ cwdRaw: "", // local-only; never sent in the bundle
473
+ gitBranch: null, // kimi does not record the branch
474
+ cliVersions: [], // no per-session version signal observed to populate this from
475
+ models: new Set(),
476
+ messages: [],
477
+ chain: [], // {uuid, parentUuid, ts}
478
+ firstTs: null,
479
+ lastTs: null,
480
+ };
481
+
482
+ // state.json: the ONLY field ever read out of it is workDir. title/
483
+ // lastPrompt (verbatim prompt text — see header) and the agents map
484
+ // are parsed into `state` transiently and never assigned anywhere.
485
+ // Missing/malformed -> cwdRaw stays "" and projectLabel stays
486
+ // "project-unknown", same fallback codex.mjs uses for a missing cwd —
487
+ // no directory-name decode fallback exists for kimi (unlike pi).
488
+ const stateJsonPath = join(sessionDir, "state.json");
489
+ if (existsSync(stateJsonPath)) {
490
+ const buf = readFileSync(stateJsonPath);
491
+ let state = null;
492
+ let malformed = 0;
493
+ try {
494
+ state = JSON.parse(buf.toString("utf8"));
495
+ } catch {
496
+ malformed = 1;
497
+ }
498
+ if (state && typeof state.workDir === "string" && state.workDir) {
499
+ session.cwdRaw = state.workDir;
500
+ session.cwdRedacted = toPosix(redactText(state.workDir));
501
+ session.projectLabel = `project-${shortHash(state.workDir)}`;
502
+ }
503
+ files.push({ relPath: relative(root, stateJsonPath), sha256: sha256(buf), bytes: buf.length, lines: 1, malformed, cwdRaw: session.cwdRaw });
504
+ }
505
+
506
+ const agentsDir = join(sessionDir, "agents");
507
+ let sessionIsLive = false;
508
+
509
+ // agents/*: iterate in a fixed alphabetical order, never raw
510
+ // readdirSync() enumeration order. POSIX readdir does not guarantee
511
+ // any particular order (it can reflect inode/allocation history, not
512
+ // creation or name order, and differs by filesystem/OS) — two agents
513
+ // whose messages land on the exact same ts would previously merge in
514
+ // whatever order the OS handed back, reproducible on one machine but
515
+ // not across machines. Sorting here is also what the merge-sort
516
+ // tie-break below keys its "agentId" half off of.
517
+ for (const agentId of listDirNames(agentsDir).sort()) {
518
+ const wirePath = join(agentsDir, agentId, "wire.jsonl");
519
+ if (!existsSync(wirePath)) continue;
520
+
521
+ const buf = readFileSync(wirePath);
522
+ const relPath = relative(root, wirePath);
523
+ const rawLines = buf.toString("utf8").split("\n").filter((l) => l.trim());
524
+ const records = [];
525
+ let malformed = 0;
526
+ rawLines.forEach((line, i) => {
527
+ try {
528
+ records.push(JSON.parse(line));
529
+ } catch {
530
+ malformed++;
531
+ // Live-append rule: only the TRAILING line failing means the
532
+ // file was mid-write; an earlier malformed line is a genuine
533
+ // corruption, not liveness, so it doesn't set the flag.
534
+ if (i === rawLines.length - 1) sessionIsLive = true;
535
+ }
536
+ });
537
+ malformedLinesTotal += malformed;
538
+
539
+ const { messages, redactionHits: rh, redactedChars: rc } = processAgentFile(session, sessionId, agentId, records);
540
+ // Tag each message with the agentId it came from and its position
541
+ // within that agent's own emission order (0, 1, 2, ...), so the
542
+ // merge sort below has a deterministic tie-break for identical ts
543
+ // values across agents. Transient bookkeeping only — stripped
544
+ // again right after sorting, never part of the returned shape.
545
+ messages.forEach((m, i) => {
546
+ m._agentId = agentId;
547
+ m._agentSeq = i;
548
+ });
549
+ session.messages.push(...messages);
550
+ redactionHits += rh;
551
+ redactedChars += rc;
552
+
553
+ files.push({ relPath, sha256: sha256(buf), bytes: statSync(wirePath).size, lines: rawLines.length, malformed, cwdRaw: session.cwdRaw });
554
+ }
555
+
556
+ if (sessionIsLive) liveSessionsSeenTotal++;
557
+
558
+ // Every agent's messages were synthesized independently (their own
559
+ // local uuid/parentUuid chain); merge them into the one session by
560
+ // record time, per the subagent-rollup design (see header). Ties on
561
+ // identical ts are broken by agentId (alphabetical, matching the
562
+ // agentsDir iteration order above) then by each message's own
563
+ // position within its agent's emission order — both fixed,
564
+ // filesystem-independent keys, so identical-ts messages land in the
565
+ // same order on every machine instead of depending on push() order,
566
+ // which used to be at the mercy of POSIX readdir's unspecified
567
+ // enumeration order (see the agentsDir loop above).
568
+ session.messages.sort((a, b) => {
569
+ const byTs = (a.ts || "").localeCompare(b.ts || "");
570
+ if (byTs !== 0) return byTs;
571
+ const byAgent = a._agentId.localeCompare(b._agentId);
572
+ if (byAgent !== 0) return byAgent;
573
+ return a._agentSeq - b._agentSeq;
574
+ });
575
+ session.chain = session.messages.map((m) => ({ uuid: m.uuid, parentUuid: m.parentUuid, ts: m.ts }));
576
+ for (const m of session.messages) {
577
+ delete m._agentId;
578
+ delete m._agentSeq;
579
+ }
580
+
581
+ sessions.push({ ...session, models: [...session.models] });
582
+ }
583
+ }
584
+
585
+ return {
586
+ source: "kimi",
587
+ root,
588
+ files,
589
+ sessions,
590
+ compactionSummaries: [], // no compaction convention observed yet; see header scope cut
591
+ redaction: { hits: redactionHits, charsRemoved: redactedChars },
592
+ stats: { malformedLines: malformedLinesTotal, liveSessionsSeen: liveSessionsSeenTotal },
593
+ };
594
+ }
@@ -0,0 +1,59 @@
1
+ // oh-my-pi (omp) adapter. omp is a pi fork and writes pi's session format, so
2
+ // parsing is shared with pi.mjs (readPiFormat); this file only decides WHICH
3
+ // files are the person's sessions and names omp's tools.
4
+ //
5
+ // On-disk layout (established from file names only):
6
+ // ~/.omp/agent/sessions/<encoded cwd>/<ts>_<id>.jsonl the session
7
+ // ~/.omp/agent/sessions/<encoded cwd>/<ts>_<id>/ per-session dir:
8
+ // __advisor.reviewer.jsonl advisor transcript
9
+ // <AgentName>.jsonl subagent transcripts (also nested deeper)
10
+ // changes.jsonl, blobs/ bookkeeping and tool-output blobs
11
+ // Only the top-level <encoded cwd>/<ts>_<id>.jsonl files are read. Everything
12
+ // inside a per-session directory is a subagent, advisor or bookkeeping file:
13
+ // reading them would double-count the same work as extra sessions.
14
+
15
+ import { join, sep } from "node:path";
16
+ import { homedir } from "node:os";
17
+ import { readPiFormat } from "./pi.mjs";
18
+ import { AGENT_RUN_MARKER, isAgentRun } from "../agent-run.mjs";
19
+
20
+ export { AGENT_RUN_MARKER, isAgentRun };
21
+
22
+ export function defaultOmpRoot() {
23
+ return join(homedir(), ".omp", "agent", "sessions");
24
+ }
25
+
26
+ // Tool names observed in real omp sessions (counts by name only), mapped to
27
+ // the canonical Claude Code names. Every other name passes through unchanged:
28
+ // pi's "server_tool" fallback would turn omp's `browser_*` or
29
+ // `translate_catalog` into phantom MCP servers. omp's own mcp__server__tool
30
+ // names are already canonical; the `xd_mcp__` form is unwrapped to them.
31
+ const OMP_TOOL_MAP = {
32
+ bash: "Bash",
33
+ read: "Read",
34
+ edit: "Edit",
35
+ write: "Write",
36
+ ast_edit: "Edit",
37
+ grep: "Grep",
38
+ find: "Glob",
39
+ glob: "Glob",
40
+ task: "Task",
41
+ todo: "TodoWrite",
42
+ web_search: "WebSearch",
43
+ };
44
+ function mapOmpTool(name) {
45
+ if (typeof name !== "string") return name;
46
+ const n = name.trim();
47
+ if (n.startsWith("xd_mcp__")) return n.slice(3);
48
+ return Object.hasOwn(OMP_TOOL_MAP, n) ? OMP_TOOL_MAP[n] : n;
49
+ }
50
+
51
+ // relPath is relative to the sessions root: <encoded cwd>/<file>.
52
+ function isTopLevelSession(relPath) {
53
+ const parts = relPath.split(sep);
54
+ return parts.length === 2 && !parts[1].includes("__advisor");
55
+ }
56
+
57
+ export function readOmp(root) {
58
+ return readPiFormat(root, { source: "omp", mapTool: mapOmpTool, includeFile: isTopLevelSession });
59
+ }