@kirkchinese/harness-forge-core 0.4.0 → 0.5.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 (56) hide show
  1. package/lib/assess.js +24 -4
  2. package/lib/contracts.d.ts +1 -1
  3. package/lib/dialects/claude-code/index.js +38 -41
  4. package/lib/dialects/claude-code/sessions/discover.js +31 -17
  5. package/lib/dialects/claude-code/sessions/parse.js +89 -83
  6. package/lib/dialects/claude-code/sessions/title.d.ts +23 -0
  7. package/lib/dialects/claude-code/sessions/title.js +74 -0
  8. package/lib/dialects/claude-code/statusline.d.ts +12 -0
  9. package/lib/dialects/claude-code/statusline.js +74 -0
  10. package/lib/dialects/claude-code/user-assets.d.ts +37 -6
  11. package/lib/dialects/claude-code/user-assets.js +155 -34
  12. package/lib/dialects/codex/index.js +8 -1
  13. package/lib/dialects/codex/mcp-server.d.ts +17 -0
  14. package/lib/dialects/codex/mcp-server.js +116 -0
  15. package/lib/dialects/codex/plugins.d.ts +16 -0
  16. package/lib/dialects/codex/plugins.js +120 -0
  17. package/lib/dialects/codex/user-assets.d.ts +10 -6
  18. package/lib/dialects/codex/user-assets.js +26 -42
  19. package/lib/dialects/opencode/index.js +43 -8
  20. package/lib/dialects/opencode/inventory.d.ts +100 -0
  21. package/lib/dialects/opencode/inventory.js +318 -0
  22. package/lib/dialects/opencode/plugin-id.d.ts +21 -0
  23. package/lib/dialects/opencode/plugin-id.js +296 -0
  24. package/lib/dialects/opencode/scan.d.ts +22 -0
  25. package/lib/dialects/opencode/scan.js +119 -121
  26. package/lib/dialects/types.d.ts +60 -6
  27. package/lib/discover.d.ts +32 -7
  28. package/lib/discover.js +58 -17
  29. package/lib/fingerprint.js +7 -0
  30. package/lib/harness-installs.d.ts +42 -0
  31. package/lib/harness-installs.js +59 -0
  32. package/lib/index.d.ts +6 -0
  33. package/lib/index.js +5 -0
  34. package/lib/instructions.d.ts +28 -2
  35. package/lib/instructions.js +202 -30
  36. package/lib/license.js +12 -11
  37. package/lib/manifest.d.ts +6 -0
  38. package/lib/manifest.js +41 -12
  39. package/lib/marketplace.d.ts +15 -1
  40. package/lib/marketplace.js +55 -38
  41. package/lib/paths.d.ts +65 -0
  42. package/lib/paths.js +152 -2
  43. package/lib/plan.js +3 -1
  44. package/lib/port-brief.d.ts +28 -5
  45. package/lib/port-brief.js +52 -10
  46. package/lib/remote.d.ts +121 -0
  47. package/lib/remote.js +352 -0
  48. package/lib/sessions/index.d.ts +1 -0
  49. package/lib/sessions/index.js +1 -0
  50. package/lib/sessions/lines.d.ts +57 -0
  51. package/lib/sessions/lines.js +122 -0
  52. package/lib/text.d.ts +9 -0
  53. package/lib/text.js +19 -0
  54. package/lib/trust.js +19 -6
  55. package/lib/types.d.ts +48 -1
  56. package/package.json +1 -1
package/lib/assess.js CHANGED
@@ -7,6 +7,14 @@
7
7
  */
8
8
  import { EXECUTED_HOOK_HANDLERS, OBSERVED_ONLY_HOOK_EVENTS, SERVED_HOOK_EVENTS } from './hook-events.js';
9
9
  import { countComponents } from './types.js';
10
+ /**
11
+ * Parts of a harness's own configuration DSH runs as they are: Codex's
12
+ * global instructions (added to the main system prompt) and its `notify`
13
+ * program (run after each completed turn).
14
+ */
15
+ function mappedOther(component) {
16
+ return component.originalKind === 'codex-notify' || (component.originalKind === 'codex-instructions' && component.path !== undefined);
17
+ }
10
18
  /** Context cost heuristic used until a real schema/token probe runs. */
11
19
  export function estimateContextCost(plugin) {
12
20
  let skillChars = 0;
@@ -15,7 +23,7 @@ export function estimateContextCost(plugin) {
15
23
  if (component.kind === 'skill') {
16
24
  skillChars += component.frontmatter.name.length + component.frontmatter.description.length + 8;
17
25
  }
18
- if (component.kind === 'mcp')
26
+ if (component.kind === 'mcp' && component.notStarted === undefined)
19
27
  mcpServers += 1;
20
28
  }
21
29
  const residentTokens = Math.ceil(skillChars / 4) + mcpServers * 40;
@@ -30,7 +38,18 @@ export function estimateContextCost(plugin) {
30
38
  export function collectGaps(plugin) {
31
39
  const gaps = [];
32
40
  for (const component of plugin.components) {
33
- if (component.kind === 'mcp' && component.transport === 'unknown') {
41
+ if (component.kind === 'mcp' && component.notStarted?.reason === 'unsupported') {
42
+ gaps.push({
43
+ id: `${component.id}:unsupported`,
44
+ componentId: component.id,
45
+ // What it needs lies outside DSH (a ChatGPT sign-in): an adapter written for DSH cannot supply it.
46
+ kind: 'external-requirement',
47
+ summary: `MCP server is not supported in DSH: it ${component.notStarted.detail}`,
48
+ detail: 'DSH does not start it; the plugin\'s other parts still work.',
49
+ suggestedAction: 'skip',
50
+ });
51
+ }
52
+ if (component.kind === 'mcp' && component.transport === 'unknown' && component.notStarted === undefined) {
34
53
  gaps.push({
35
54
  id: `${component.id}:transport`,
36
55
  componentId: component.id,
@@ -75,7 +94,7 @@ export function collectGaps(plugin) {
75
94
  });
76
95
  }
77
96
  }
78
- if (component.kind === 'other') {
97
+ if (component.kind === 'other' && !mappedOther(component)) {
79
98
  gaps.push({
80
99
  id: `${component.id}:unsupported`,
81
100
  componentId: component.id,
@@ -131,7 +150,8 @@ export function collectGaps(plugin) {
131
150
  }
132
151
  /** The capability ceiling the plugin declares. */
133
152
  export function targetLevels(plugin) {
134
- const counts = countComponents(plugin.components);
153
+ // A server its own configuration switches off is not something the plugin asks for.
154
+ const counts = countComponents(plugin.components.filter(component => component.kind !== 'mcp' || component.notStarted?.reason !== 'disabled'));
135
155
  const assets = counts.command + counts.agent > 0
136
156
  ? 'L1b'
137
157
  : counts.skill + counts.mcp > 0 ? 'L1a' : 'L0';
@@ -79,7 +79,7 @@ export interface Receipt {
79
79
  readonly achieved: CompatibilityVector['achieved'];
80
80
  }
81
81
  /** Stable, user-actionable error codes. */
82
- export type HarnessErrorCode = 'manifest-invalid' | 'manifest-not-found' | 'path-escape' | 'component-failed' | 'unsupported-transport' | 'unsupported-handler' | 'fingerprint-mismatch' | 'plan-not-found' | 'receipt-not-found' | 'already-installed' | 'not-installed' | 'host-capability-missing' | 'runtime-failed' | 'marketplace-failed' | 'plugins-missing' | 'entry-not-found' | 'unsupported-source' | 'license-unknown' | 'internal';
82
+ export type HarnessErrorCode = 'manifest-invalid' | 'manifest-not-found' | 'path-escape' | 'component-failed' | 'unsupported-transport' | 'unsupported-handler' | 'fingerprint-mismatch' | 'plan-not-found' | 'receipt-not-found' | 'already-installed' | 'not-installed' | 'host-capability-missing' | 'runtime-failed' | 'marketplace-failed' | 'fetch-failed' | 'plugins-missing' | 'entry-not-found' | 'unsupported-source' | 'license-unknown' | 'internal';
83
83
  /** Serializable error facts for receipts and routes. */
84
84
  export interface HarnessErrorInfo {
85
85
  readonly code: HarnessErrorCode;
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * The Claude Code dialect: `.claude-plugin/plugin.json` plugins (or the bare
3
3
  * plugin layout), the user's `~/.claude`, project `.claude/` directories, the
4
- * plugins and marketplaces Claude Code records, and its transcripts.
4
+ * plugins Claude Code has installed and the marketplaces it added, and its
5
+ * transcripts.
5
6
  * @module @kirkchinese/harness-forge-core
6
7
  */
7
8
  import { join, resolve } from 'node:path';
8
- import { scanPlugin } from '../../manifest.js';
9
- import { isDirectory, isFile, readJsonObject } from '../../paths.js';
10
- import { installedClaudePlugins, scanClaudeProjectAssets, scanClaudeUserAssets } from './user-assets.js';
9
+ import { cachePath } from '../codex/plugins.js';
10
+ import { hasLayoutDirectory, scanPlugin } from '../../manifest.js';
11
+ import { isFile, readJsonObject } from '../../paths.js';
12
+ import { installedClaudePlugins, isGlobalClaudeInstall, scanClaudeProjectAssets, scanClaudeUserAssets } from './user-assets.js';
11
13
  import { claudeCodeAdapter } from './sessions/adapter.js';
12
14
  export const claudeCodeDialect = {
13
15
  id: 'claude-code',
@@ -17,7 +19,7 @@ export const claudeCodeDialect = {
17
19
  {
18
20
  tier: 'layout',
19
21
  pluginRoot: false,
20
- test: directory => ['skills', 'commands', 'agents', 'hooks'].some(name => isDirectory(join(directory, name))) || isFile(join(directory, '.mcp.json')),
22
+ test: directory => hasLayoutDirectory(directory, ['skills', 'commands', 'agents', 'hooks']) || isFile(join(directory, '.mcp.json')),
21
23
  },
22
24
  ],
23
25
  scan: (root, options) => scanPlugin(root, { source: 'claude-code', ...options }).plugin,
@@ -29,50 +31,45 @@ export const claudeCodeDialect = {
29
31
  emptyMessage: 'holds no Claude Code skills, agents, commands, settings or MCP servers',
30
32
  },
31
33
  harnessPlugins: {
32
- root: home => join(home, '.claude', 'plugins'),
33
- list: home => claudeHarnessPlugins(home),
34
+ roots: home => [join(home, '.claude', 'plugins')],
35
+ // A project- or local-scope install only loads in its project's sessions, so it is not one of the person's
36
+ // plugins everywhere: discovery and "Migrate all" leave it out (see docs/user/compatibility.md).
37
+ list: (home) => {
38
+ const installed = installedClaudePlugins(home);
39
+ return {
40
+ entries: installed.plugins.filter(isGlobalClaudeInstall).map(plugin => ({ root: plugin.root, key: plugin.key, enabled: plugin.enabled, marketplace: plugin.marketplace })),
41
+ unresolved: installed.unresolved.filter(isGlobalClaudeInstall).map(({ key, message }) => ({ key, message })),
42
+ unread: installed.unread,
43
+ };
44
+ },
45
+ marketplaces: home => claudeMarketplaces(home),
46
+ identify: (home, root, name) => claudeInstallKey(home, root, name),
34
47
  },
35
48
  projectAssets: (cwd, home) => scanClaudeProjectAssets(cwd, home),
36
49
  sessions: claudeCodeAdapter,
37
50
  };
38
- /**
39
- * Claude Code's plugin directory read the way Claude Code reads it: the
40
- * installed plugins of `installed_plugins.json` (one version each) and the
41
- * plugins its added marketplaces offer, instead of every cached version.
42
- */
43
- function claudeHarnessPlugins(home) {
44
- const out = [];
45
- const installed = installedClaudePlugins(home);
46
- const installedKeys = new Set(installed.map(plugin => plugin.key));
47
- for (const plugin of installed)
48
- out.push({ root: plugin.root, origin: 'installed', enabled: plugin.enabled, marketplace: plugin.marketplace });
49
- for (const offer of claudeMarketplaceOffers(home)) {
50
- if (installedKeys.has(`${offer.name}@${offer.marketplace}`))
51
- continue;
52
- out.push({ root: offer.root, origin: 'marketplace', marketplace: offer.marketplace });
53
- }
54
- return out;
55
- }
56
- /** Plugins listed by the marketplaces Claude Code has added, with a local copy. */
57
- function claudeMarketplaceOffers(home) {
51
+ /** The marketplaces Claude Code has added (`known_marketplaces.json`) whose local copy lists plugins. */
52
+ function claudeMarketplaces(home) {
58
53
  const known = readJsonObject(join(home, '.claude', 'plugins', 'known_marketplaces.json')) ?? {};
59
54
  const out = [];
60
- for (const [marketplace, entry] of Object.entries(known)) {
55
+ for (const [name, entry] of Object.entries(known)) {
61
56
  const location = typeof entry === 'object' && entry !== null ? entry.installLocation : undefined;
62
- if (typeof location !== 'string' || !isDirectory(location))
57
+ if (typeof location !== 'string' || !isFile(join(location, '.claude-plugin', 'marketplace.json')))
63
58
  continue;
64
- const manifest = readJsonObject(join(location, '.claude-plugin', 'marketplace.json'));
65
- const listed = Array.isArray(manifest?.['plugins']) ? manifest['plugins'] : [];
66
- for (const item of listed) {
67
- if (typeof item !== 'object' || item === null)
68
- continue;
69
- const { name, source } = item;
70
- if (typeof name !== 'string' || typeof source !== 'string')
71
- continue;
72
- const root = resolve(location, source);
73
- if (isDirectory(root))
74
- out.push({ name, marketplace, root });
75
- }
59
+ out.push({ name, root: resolve(location) });
76
60
  }
77
61
  return out;
78
62
  }
63
+ /**
64
+ * The `<name>@<marketplace>` a folder of Claude Code's own layout stands for: a version in its install cache
65
+ * (`plugins/cache/<marketplace>/<name>/<version>`), or a plugin inside a marketplace's local copy
66
+ * (`plugins/marketplaces/<marketplace>/…`, what Harness Forge 0.4.0 also migrated as an offer).
67
+ */
68
+ function claudeInstallKey(home, root, name) {
69
+ const plugins = join(home, '.claude', 'plugins');
70
+ const cached = cachePath(join(plugins, 'cache'), root);
71
+ if (cached?.length === 3)
72
+ return `${cached[1]}@${cached[0]}`;
73
+ const offered = cachePath(join(plugins, 'marketplaces'), root);
74
+ return offered !== undefined && offered.length >= 2 ? `${name}@${offered[0]}` : undefined;
75
+ }
@@ -1,8 +1,11 @@
1
1
  /** Main and auxiliary transcript discovery for the Claude Code projects layout. */
2
2
  import { open, readdir, stat } from 'node:fs/promises';
3
3
  import { basename, extname, join } from 'node:path';
4
+ import { ClaudeTitle } from './title.js';
4
5
  import { parseTimestamp } from '../../../sessions/time.js';
5
6
  const PROBE_BYTES = 256 * 1024;
7
+ /** A `/rename` or a generated title is appended as the session goes on, so the end of a long file is read for it too. */
8
+ const TAIL_BYTES = 64 * 1024;
6
9
  async function probeHead(filePath, auxiliary) {
7
10
  const handle = await open(filePath, 'r');
8
11
  try {
@@ -11,29 +14,41 @@ async function probeHead(filePath, auxiliary) {
11
14
  const buffer = Buffer.alloc(length);
12
15
  const { bytesRead } = await handle.read(buffer, 0, length, 0);
13
16
  const head = buffer.toString('utf8', 0, bytesRead);
14
- return parseProbe(head, basename(filePath).replace(/\.jsonl$/i, ''), auxiliary);
17
+ let tail = '';
18
+ if (size > length) {
19
+ const tailLength = Math.min(TAIL_BYTES, size - length);
20
+ const tailBuffer = Buffer.alloc(tailLength);
21
+ const read = await handle.read(tailBuffer, 0, tailLength, size - tailLength);
22
+ // The first line read from the middle of the file is partial.
23
+ tail = tailBuffer.toString('utf8', 0, read.bytesRead).replace(/^[^\n]*\n/u, '');
24
+ }
25
+ return parseProbe(head, tail, basename(filePath).replace(/\.jsonl$/i, ''), auxiliary);
15
26
  }
16
27
  finally {
17
28
  await handle.close();
18
29
  }
19
30
  }
20
- function parseProbe(head, fileStem, auxiliary) {
21
- const lines = head.split('\n');
22
- let sessionId;
23
- let agentId;
24
- let cwd;
25
- let title;
26
- let createdAt;
27
- for (const raw of lines) {
31
+ function records(text) {
32
+ const out = [];
33
+ for (const raw of text.split('\n')) {
28
34
  if (raw.length === 0)
29
35
  continue;
30
- let record;
31
36
  try {
32
- record = JSON.parse(raw);
37
+ out.push(JSON.parse(raw));
33
38
  }
34
39
  catch {
35
- continue;
40
+ // A line cut at the end of the head, or a malformed one.
36
41
  }
42
+ }
43
+ return out;
44
+ }
45
+ function parseProbe(head, tail, fileStem, auxiliary) {
46
+ let sessionId;
47
+ let agentId;
48
+ let cwd;
49
+ let createdAt;
50
+ const titles = new ClaudeTitle();
51
+ for (const record of records(head)) {
37
52
  if (sessionId === undefined && typeof record.sessionId === 'string' && record.sessionId.length > 0)
38
53
  sessionId = record.sessionId;
39
54
  if (agentId === undefined && typeof record.agentId === 'string' && record.agentId.length > 0)
@@ -42,12 +57,11 @@ function parseProbe(head, fileStem, auxiliary) {
42
57
  cwd = record.cwd;
43
58
  if (createdAt === undefined && record.timestamp !== undefined)
44
59
  createdAt = parseTimestamp(record.timestamp, createdAt);
45
- if (title === undefined && record.type === 'ai-title' && typeof record.aiTitle === 'string' && record.aiTitle.trim().length > 0) {
46
- title = record.aiTitle.trim();
47
- }
48
- if (cwd !== undefined && createdAt !== undefined && title !== undefined)
49
- break;
60
+ titles.observe(record);
50
61
  }
62
+ for (const record of records(tail))
63
+ titles.observe(record);
64
+ const title = titles.title;
51
65
  return {
52
66
  sourceId: auxiliary ? (agentId ?? fileStem) : (sessionId ?? fileStem),
53
67
  ...(cwd !== undefined ? { cwd } : {}),
@@ -1,8 +1,9 @@
1
1
  /** Claude Code JSONL -> normalized session model. */
2
- import { readFile } from 'node:fs/promises';
3
2
  import { basename } from 'node:path';
4
3
  import { isAuxiliaryTranscriptPath } from './discover.js';
5
4
  import { parseTimestamp } from '../../../sessions/time.js';
5
+ import { assertFileImportable, fileLines } from '../../../sessions/lines.js';
6
+ import { ClaudeTitle } from './title.js';
6
7
  function withTimestamp(timestamp) {
7
8
  return timestamp !== undefined ? { timestamp } : {};
8
9
  }
@@ -23,10 +24,10 @@ function imageMediaType(value) {
23
24
  function mapImageBlock(raw) {
24
25
  const source = raw.source;
25
26
  const mediaType = imageMediaType(source?.media_type);
26
- const base64 = typeof source?.data === 'string' ? source.data : undefined;
27
- if (mediaType === undefined || base64 === undefined)
27
+ // The data is not kept: the synthesizer renders every image as a placeholder, so holding it only costs memory.
28
+ if (mediaType === undefined || typeof source?.data !== 'string')
28
29
  return undefined;
29
- return { type: 'image', mediaType, base64 };
30
+ return { type: 'image', mediaType };
30
31
  }
31
32
  function extractUserPrompt(content) {
32
33
  if (typeof content === 'string')
@@ -144,31 +145,37 @@ function mapToolResultBlocks(content, result) {
144
145
  */
145
146
  export async function readClaudeSession(ref, options = {}) {
146
147
  options.signal?.throwIfAborted();
147
- const text = await readFile(ref.ref, 'utf8');
148
- const lines = text.split('\n');
149
- const rawLines = [];
148
+ // Decided before a byte is read; the transcript is then streamed, never held (see the two passes below).
149
+ await assertFileImportable(ref.ref);
150
+ // Pass 1: one line at a time, keep only what choosing the main chain and the session's facts need.
151
+ const index = [];
150
152
  const malformed = [];
153
+ const oversized = [];
151
154
  let records = 0;
152
- for (let index = 0; index < lines.length; index++) {
153
- const raw = lines[index];
154
- if (raw === undefined || raw.trim() === '')
155
+ let parsed = 0;
156
+ let sessionId;
157
+ let cwd;
158
+ let createdAt;
159
+ let model;
160
+ const titles = new ClaudeTitle();
161
+ for await (const raw of fileLines(ref.ref, options.signal !== undefined ? { signal: options.signal } : {})) {
162
+ if (raw.oversized) {
163
+ records += 1;
164
+ oversized.push(raw.number);
165
+ continue;
166
+ }
167
+ if (raw.text.trim() === '')
155
168
  continue;
156
169
  records += 1;
170
+ let rec;
157
171
  try {
158
- rawLines.push({ line: index + 1, record: asRecord(JSON.parse(raw)) });
172
+ rec = asRecord(JSON.parse(raw.text));
159
173
  }
160
174
  catch {
161
- malformed.push(index + 1);
175
+ malformed.push(raw.number);
176
+ continue;
162
177
  }
163
- }
164
- options.signal?.throwIfAborted();
165
- let sessionId;
166
- let cwd;
167
- let createdAt;
168
- let model;
169
- let explicitTitle;
170
- for (const entry of rawLines) {
171
- const rec = entry.record;
178
+ parsed += 1;
172
179
  if (sessionId === undefined && typeof rec.sessionId === 'string' && rec.sessionId.length > 0)
173
180
  sessionId = rec.sessionId;
174
181
  if (cwd === undefined && typeof rec.cwd === 'string' && rec.cwd.length > 0)
@@ -178,37 +185,58 @@ export async function readClaudeSession(ref, options = {}) {
178
185
  const recModel = typeof rec.message?.model === 'string' ? rec.message.model : typeof rec.model === 'string' ? rec.model : undefined;
179
186
  if (model === undefined && recModel !== undefined)
180
187
  model = recModel;
181
- if (rec.type === 'ai-title' && typeof rec.aiTitle === 'string' && rec.aiTitle.trim().length > 0) {
182
- explicitTitle = rec.aiTitle.trim();
183
- }
184
- if (rec.type === 'summary') {
185
- const candidate = typeof rec.summary === 'string' && rec.summary.trim().length > 0
186
- ? rec.summary
187
- : typeof rec.title === 'string' && rec.title.trim().length > 0
188
- ? rec.title
189
- : undefined;
190
- if (candidate !== undefined)
191
- explicitTitle = candidate;
188
+ titles.observe(rec);
189
+ if (typeof rec.uuid === 'string' && rec.uuid.length > 0) {
190
+ index.push({
191
+ line: raw.number,
192
+ uuid: rec.uuid,
193
+ parent: typeof rec.parentUuid === 'string' ? rec.parentUuid : undefined,
194
+ chained: rec.type === 'user' || rec.type === 'assistant',
195
+ sidechain: rec.isSidechain === true,
196
+ });
192
197
  }
193
198
  }
199
+ options.signal?.throwIfAborted();
194
200
  const fileStem = basename(ref.ref).replace(/\.jsonl$/i, '');
195
201
  const auxiliary = isAuxiliaryTranscriptPath(ref.ref);
196
202
  const sourceId = auxiliary ? (ref.sourceId ?? sessionId ?? fileStem) : (sessionId ?? ref.sourceId ?? fileStem);
197
203
  const skipReason = isAuxiliaryTranscript(ref.ref, fileStem, sessionId, auxiliary && options.allowAuxiliary === true);
204
+ const unreadable = [...malformed, ...oversized].sort((a, b) => a - b);
205
+ const unreadableReasons = [
206
+ ...malformed.slice(0, 5).map((line) => `malformed line ${line}`),
207
+ ...oversized.slice(0, 5).map((line) => `line ${line} is too long to read and was skipped`),
208
+ ];
198
209
  if (skipReason !== undefined) {
199
210
  return {
200
211
  session: emptySession(ref, sourceId, createdAt, cwd),
201
- stats: emptyStats(rawLines.length, skipReason, malformed),
212
+ stats: emptyStats(parsed, skipReason, unreadable, unreadableReasons),
202
213
  };
203
214
  }
204
215
  const nodes = new Map();
205
- for (const entry of rawLines) {
206
- const uuid = entry.record.uuid;
207
- if (typeof uuid === 'string' && uuid.length > 0)
208
- nodes.set(uuid, entry);
216
+ for (const entry of index)
217
+ nodes.set(entry.uuid, entry);
218
+ const chain = selectMainChain(index, nodes);
219
+ // Pass 2: only the lines on the chain are read again, whole.
220
+ const wanted = new Set([...chain.values()].map((entry) => entry.line));
221
+ let last = 0;
222
+ for (const line of wanted)
223
+ if (line > last)
224
+ last = line;
225
+ const byLine = [];
226
+ if (wanted.size > 0) {
227
+ for await (const raw of fileLines(ref.ref, options.signal !== undefined ? { signal: options.signal } : {})) {
228
+ if (raw.number > last)
229
+ break;
230
+ if (!wanted.has(raw.number) || raw.oversized)
231
+ continue;
232
+ try {
233
+ byLine.push({ line: raw.number, record: asRecord(JSON.parse(raw.text)) });
234
+ }
235
+ catch {
236
+ // The file changed under the first pass; the line is not there to read.
237
+ }
238
+ }
209
239
  }
210
- const selected = selectMainChain(rawLines, nodes);
211
- const byLine = [...selected.values()].sort((a, b) => a.line - b.line);
212
240
  const turns = [];
213
241
  const reasons = [];
214
242
  const callTargets = new Map();
@@ -308,7 +336,7 @@ export async function readClaudeSession(ref, options = {}) {
308
336
  toolResults: step.toolResults,
309
337
  })),
310
338
  }));
311
- const title = explicitTitle ?? (normalizedTurns[0] !== undefined ? firstTitle(normalizedTurns[0].prompt) : undefined);
339
+ const title = titles.title;
312
340
  const session = {
313
341
  id,
314
342
  source: { tool: 'claude-code', path: ref.ref, sessionId: sourceId },
@@ -324,13 +352,13 @@ export async function readClaudeSession(ref, options = {}) {
324
352
  const attachedResults = normalizedTurns.reduce((sum, turn) => sum + turn.steps.reduce((inner, step) => inner + step.toolResults.length, 0), 0);
325
353
  const stats = {
326
354
  records,
327
- skipped: Math.max(0, rawLines.length - selected.size),
328
- malformed: malformed.length,
355
+ skipped: Math.max(0, parsed - chain.size),
356
+ malformed: unreadable.length,
329
357
  droppedToolResults,
330
358
  synthesizedToolResults: Math.max(0, toolCalls - attachedResults),
331
359
  droppedUserRecords,
332
- auxiliaryBranches: selected.size > 0 ? nodes.size - selected.size : 0,
333
- reasons: [...reasons, ...malformed.slice(0, 5).map((line) => `malformed line ${line}`)],
360
+ auxiliaryBranches: chain.size > 0 ? nodes.size - chain.size : 0,
361
+ reasons: [...reasons, ...unreadableReasons],
334
362
  };
335
363
  return { session, stats };
336
364
  }
@@ -354,47 +382,29 @@ function extractToolResults(content) {
354
382
  }
355
383
  return out;
356
384
  }
357
- function selectMainChain(rawLines, nodes) {
385
+ function selectMainChain(index, nodes) {
358
386
  const selected = new Map();
359
- let last;
360
- for (let index = rawLines.length - 1; index >= 0; index--) {
361
- const entry = rawLines[index];
362
- if (entry === undefined)
363
- continue;
364
- const rec = entry.record;
365
- if ((rec.type !== 'user' && rec.type !== 'assistant') || typeof rec.uuid !== 'string')
366
- continue;
367
- if (rec.isSidechain === true)
368
- continue;
369
- last = entry;
370
- break;
371
- }
372
- if (last === undefined) {
373
- for (let index = rawLines.length - 1; index >= 0; index--) {
374
- const entry = rawLines[index];
375
- if (entry === undefined)
376
- continue;
377
- const rec = entry.record;
378
- if ((rec.type === 'user' || rec.type === 'assistant') && typeof rec.uuid === 'string') {
379
- last = entry;
380
- break;
381
- }
387
+ const lastOf = (accept) => {
388
+ for (let at = index.length - 1; at >= 0; at--) {
389
+ const entry = index[at];
390
+ if (entry !== undefined && entry.chained && accept(entry))
391
+ return entry;
382
392
  }
383
- }
393
+ return undefined;
394
+ };
395
+ const last = lastOf((entry) => !entry.sidechain) ?? lastOf(() => true);
384
396
  if (last === undefined)
385
397
  return selected;
386
398
  const visited = new Set();
387
399
  let cursor = last;
388
400
  while (cursor !== undefined) {
389
- const uuid = cursor.record.uuid;
390
- if (typeof uuid !== 'string' || visited.has(uuid))
401
+ if (visited.has(cursor.uuid))
391
402
  break;
392
- visited.add(uuid);
393
- selected.set(uuid, cursor);
394
- const parent = cursor.record.parentUuid;
395
- if (typeof parent !== 'string' || parent.length === 0)
403
+ visited.add(cursor.uuid);
404
+ selected.set(cursor.uuid, cursor);
405
+ if (cursor.parent === undefined || cursor.parent.length === 0)
396
406
  break;
397
- cursor = nodes.get(parent);
407
+ cursor = nodes.get(cursor.parent);
398
408
  }
399
409
  return selected;
400
410
  }
@@ -408,10 +418,6 @@ function isAuxiliaryTranscript(filePath, fileStem, sessionId, allowAuxiliary) {
408
418
  }
409
419
  return undefined;
410
420
  }
411
- function firstTitle(prompt) {
412
- const text = prompt.trim().replace(/\s+/g, ' ');
413
- return text.length > 0 ? text : undefined;
414
- }
415
421
  function emptySession(ref, sourceId, createdAt, cwd) {
416
422
  return {
417
423
  id: mintClaudeSessionId(sourceId, basename(ref.ref)),
@@ -421,15 +427,15 @@ function emptySession(ref, sourceId, createdAt, cwd) {
421
427
  turns: [],
422
428
  };
423
429
  }
424
- function emptyStats(records, reason, malformed) {
430
+ function emptyStats(records, reason, unreadable, unreadableReasons) {
425
431
  return {
426
432
  records,
427
433
  skipped: 1,
428
- malformed: malformed.length,
434
+ malformed: unreadable.length,
429
435
  droppedToolResults: 0,
430
436
  synthesizedToolResults: 0,
431
437
  droppedUserRecords: 0,
432
438
  auxiliaryBranches: 0,
433
- reasons: [reason, ...malformed.slice(0, 5).map((line) => `malformed line ${line}`)],
439
+ reasons: [reason, ...unreadableReasons],
434
440
  };
435
441
  }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A Claude Code session's title, chosen the way Claude Code shows it: the
3
+ * name given with `/rename` (a `custom-title` record, the last one wins), else
4
+ * the generated title (the first `ai-title` record; later ones are rewritten
5
+ * per turn), else the latest `summary` record (older transcripts), else the
6
+ * person's first real message.
7
+ */
8
+ import type { RawRecord } from './types.js';
9
+ /** Text on one line, whitespace collapsed; `undefined` when nothing is left. */
10
+ export declare function oneLine(text: string, max?: number): string | undefined;
11
+ /** Whether a user message's text is something Claude Code or the IDE put there rather than the person. */
12
+ export declare function isInjectedPrompt(text: string): boolean;
13
+ /** The text the person typed in a user record, or `undefined` for anything else (tool results, meta, wrappers). */
14
+ export declare function typedPrompt(record: RawRecord): string | undefined;
15
+ /** Collects the title carriers of one transcript, record by record, in file order. */
16
+ export declare class ClaudeTitle {
17
+ private custom;
18
+ private ai;
19
+ private summary;
20
+ private prompt;
21
+ observe(record: RawRecord): void;
22
+ get title(): string | undefined;
23
+ }
@@ -0,0 +1,74 @@
1
+ /** Longest title kept for a first message; the rest of a long paste is not a title. */
2
+ const PROMPT_TITLE_CHARS = 200;
3
+ /**
4
+ * What Claude Code writes as a user message that the person did not type:
5
+ * slash-command wrappers and their output, system reminders, IDE and
6
+ * environment blocks. Such a message is never the title.
7
+ */
8
+ const INJECTED_PREFIXES = [
9
+ '<command-name>', '<command-message>', '<command-args>', '<local-command-caveat>', '<local-command-stdout>', '<local-command-stderr>',
10
+ '<system-reminder>', '<environment_context>', '<user_instructions>', '<ide_opened_file>', '<ide_selection>', '<ide_diagnostics>',
11
+ '<bash-input>', '<bash-stdout>', '<bash-stderr>', 'Caveat: The messages below were generated by the user while running local commands',
12
+ '[Request interrupted by user',
13
+ ];
14
+ /** Text on one line, whitespace collapsed; `undefined` when nothing is left. */
15
+ export function oneLine(text, max = Number.POSITIVE_INFINITY) {
16
+ const line = text.trim().replace(/\s+/gu, ' ');
17
+ if (line.length === 0)
18
+ return undefined;
19
+ return line.length <= max ? line : `${line.slice(0, max - 1).trimEnd()}…`;
20
+ }
21
+ function nonEmpty(value) {
22
+ return typeof value === 'string' ? oneLine(value) : undefined;
23
+ }
24
+ /** Whether a user message's text is something Claude Code or the IDE put there rather than the person. */
25
+ export function isInjectedPrompt(text) {
26
+ const trimmed = text.trimStart();
27
+ return trimmed.length === 0 || INJECTED_PREFIXES.some(prefix => trimmed.startsWith(prefix));
28
+ }
29
+ /** The text the person typed in a user record, or `undefined` for anything else (tool results, meta, wrappers). */
30
+ export function typedPrompt(record) {
31
+ if (record.type !== 'user' || record.isMeta === true || record.isCompactSummary === true)
32
+ return undefined;
33
+ const content = record.message?.content;
34
+ const parts = [];
35
+ if (typeof content === 'string')
36
+ parts.push(content);
37
+ else if (Array.isArray(content)) {
38
+ for (const block of content) {
39
+ if (typeof block === 'string')
40
+ parts.push(block);
41
+ else if (typeof block === 'object' && block !== null && block.type === 'text' && typeof block.text === 'string') {
42
+ parts.push(block.text);
43
+ }
44
+ }
45
+ }
46
+ // A message's own blocks can mix an IDE note with what was typed: the first block that is not injected is the prompt.
47
+ for (const part of parts)
48
+ if (!isInjectedPrompt(part))
49
+ return part;
50
+ return undefined;
51
+ }
52
+ /** Collects the title carriers of one transcript, record by record, in file order. */
53
+ export class ClaudeTitle {
54
+ custom;
55
+ ai;
56
+ summary;
57
+ prompt;
58
+ observe(record) {
59
+ if (record.type === 'custom-title')
60
+ this.custom = nonEmpty(record.customTitle) ?? this.custom;
61
+ else if (record.type === 'ai-title')
62
+ this.ai ??= nonEmpty(record.aiTitle);
63
+ else if (record.type === 'summary')
64
+ this.summary = nonEmpty(record.summary) ?? nonEmpty(record.title) ?? this.summary;
65
+ else if (this.prompt === undefined) {
66
+ const typed = typedPrompt(record);
67
+ if (typed !== undefined)
68
+ this.prompt = oneLine(typed, PROMPT_TITLE_CHARS);
69
+ }
70
+ }
71
+ get title() {
72
+ return this.custom ?? this.ai ?? this.summary ?? this.prompt;
73
+ }
74
+ }
@@ -0,0 +1,12 @@
1
+ import type { ForeignPlugin, UiComponent } from '../../types.js';
2
+ /** A settings entry that configures a Claude Code plugin's status line. */
3
+ export interface ClaudeStatusLineProvider {
4
+ readonly plugin: ForeignPlugin;
5
+ readonly component: UiComponent;
6
+ }
7
+ /** Locate the owner among the plugins Forge actually discovered, not arbitrary cache entries. */
8
+ export declare function claudeStatusLineProvider(command: string, plugins: readonly ForeignPlugin[], home: string): ClaudeStatusLineProvider | undefined;
9
+ export declare function claudeSettingsStatusLine(plugin: ForeignPlugin): {
10
+ readonly component: UiComponent;
11
+ readonly command: string;
12
+ } | undefined;