Files
msd-core/src/profile-pipeline.cts
Tom Boucher df04aae5e4 enhancement(#537): migrate all hand-written bin/lib/*.cjs to TypeScript source of truth (ADR-457) (#602)
* enhancement(#537): migrate code-review-flags to TS source of truth

Collapse the hand-written get-shit-done/bin/lib/code-review-flags.cjs to a
TypeScript source of truth (src/code-review-flags.cts), compiled by tsc to a
gitignored .cjs build artifact at the same path, per ADR-457 (build-at-publish).
Second module after the semver-compare pilot (#541).

Behaviour is preserved byte-for-behaviour (characterization test added in
tests/code-review-flags.test.cjs locks the parser quirks). Adds compile-time
type checking: CodeReviewFlags interface + CodeReviewWorkflow literal union.
The require() path is unchanged, so code-review.md and the bug-3727 test keep
working. The emitted .cjs is gitignored and eslint-ignored, mirroring the pilot.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 9 leaf bin/lib modules to TS source of truth

ADR-457 build-at-publish, batch 1 (pure leaf modules, 0 sibling-deps):
001-legacy-orphan-files, context-utilization, redaction, artifacts,
command-arg-projection, clock, ui-safety-gate, review-reviewer-selection,
clusters. Each moves to src/*.cts (strict TS, typed), compiled by tsc to a
gitignored .cjs at the same require() path; behaviour preserved byte-for-
behaviour. Adds src/node-globals.d.ts (minimal ambient shim; "types":[]).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(#537): add @types/node, drop hand-rolled node-globals shim

ADR-457 migration infra: replace the temporary src/node-globals.d.ts ambient
shim with @types/node@22 + "types":["node"] in tsconfig.build.json. Unblocks
migrating the ~49 remaining bin/lib modules that use node:fs/path/os/
child_process. Build + full suite (3030 pass) + lint all green; no .cts type
changes were needed (real Node types matched the shim).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 9 more bin/lib modules to TS (batch 2)

ADR-457 build-at-publish. Clean leaves: installer-migration-report,
prompt-budget. Type-error-prone leaves (were tsconfig.lint-excluded; now
strict-typed and removed from that exclude list): secrets, phase-lifecycle,
workstream-name-policy, decisions, validate, schema-detect. Plus
runtime-name-policy. Strict type fixes narrow unknown->concrete domain types
(no any/ts-ignore); behaviour preserved. Full suite green, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate runtime-slash to TS (cross-import proof)

ADR-457. First cross-module TS->TS import: src/runtime-slash.cts imports
./runtime-name-policy.cjs and tsc resolves the sibling .cts types under strict
(no declaration files; NodeNext .cjs->.cts mapping), emitting a correct
require("./runtime-name-policy.cjs"). Confirms the recipe for coupled modules,
which must be migrated in dependency order (leaves-up). Suite green, lint clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 10 more bin/lib modules to TS (batch 3)

ADR-457 build-at-publish, Wave-1 leaves: event, workstream-inventory-builder,
plan-scan, fallow-runner, project-root, installer-migration-authoring,
update-context, 000-first-time-baseline, runtime-homes, model-catalog. Strict
typing fixed real issues (narrowing unknown, qualified fs/path calls, removed
unnecessary casts); plan-scan/project-root/workstream-inventory-builder dropped
from tsconfig.lint exclude. Behaviour preserved; suite green, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 5 large Wave-1 leaves to TS (batch 4)

ADR-457 build-at-publish: configuration, state-document, shell-command-
projection (42 dependents), security, command-aliases. shell-command-
projection keeps a namespace child_process import for mock-intercept
testability. loadConfig/migrateOnDisk emit synchronously (every caller uses
them sync; the one awaited migrateOnDisk caller tolerates a non-Promise) —
full suite (3030 pass) confirms behaviour preserved. configuration/
state-document/command-aliases dropped from tsconfig.lint exclude. Also fixes
the malformed batch-3 changeset frontmatter (type/pr) that failed lint:docs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 6 Wave-2 modules to TS (batch 5)

ADR-457 build-at-publish: config-schema, model-profiles,
002-codex-legacy-hooks-json, logger, active-workstream-store, adr-parser.
First batch importing already-migrated siblings (configuration, model-catalog,
shell-command-projection, redaction, security) via ./sibling.cjs specifiers.
Strict type narrowing (typeof guards over String(unknown)); behaviour
preserved; suite 3030 pass, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 5 large Wave-2 modules to TS (batch 6)

ADR-457 build-at-publish: graphify, install-profiles, intel,
installer-migrations, worktree-safety. installer-migrations preserves its
dynamic require() loader for numbered migration modules (scoped lint
suppressions). Strict typing (typeof guards over String(unknown)); behaviour
preserved; suite 3030 pass, lint 0 errors. Wave 2 complete.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate Wave-3 modules to TS (batch 7)

ADR-457 build-at-publish: planning-workspace, runtime-artifact-layout,
command-routing-hub, drift. Uses `import x = require()` for export= siblings;
drift's lazy require of runtime-slash hoisted to a top-level import (verified
non-circular). Behaviour preserved; suite 3030 pass, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate small Wave-4 modules to TS (batch 8)

ADR-457 build-at-publish: cjs-command-router-adapter, phase-command-router,
surface, roadmap-upgrade. Typed the hub router handler results as the HubResult
discriminated union; surface drops 4 genuinely-unused imports. Behaviour
preserved; suite 3030 pass, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate core hub (2.5k LOC, 68 dependents) to TS (batch 9)

ADR-457 build-at-publish: get-shit-done/bin/lib/core.cjs -> src/core.cts,
preserving all 63 exports via export=. All sibling deps already migrated
(shell-command-projection, model-profiles, model-catalog, worktree-safety,
planning-workspace, project-root, configuration, config-schema). Strict types,
no any/ts-ignore; config-schema lazy require hoisted (non-circular). Behaviour
preserved (independently verified: core's shard 3030 pass / 0 fail).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537): make ESLint-coverage + test-sprawl checks migration-aware

#551 test hardcoded 12 now-migrated modules as "hand-written, must be linted";
that invariant is obsoleted by the ADR-457 migration. Rewrite it to a
filesystem-driven invariant that holds at every stage: a bin/lib/*.cjs must be
eslint-ignored IFF it has a src/*.cts source (tsc-generated), else linted
(covers package-identity, which has no TS source). Also eslint-ignore
config-types.cjs (has a src counterpart) and drop the redundant
tests/clock.test.cjs (clock already covered by clock-seam + bug-474 tests),
which tripped the lint-test-file-count ratchet.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 9 Wave-5 router/inventory modules to TS (batch 10)

ADR-457 build-at-publish: phases/verify/init/agent/task/validate/roadmap/state
command routers + workstream-inventory. Router handler results typed against
core's exported shapes; behaviour preserved (caught+fixed a --verify boolean
flag regression mid-migration). Full suite green across all shards (only the 4
local gpg-env changeset-notes failures remain; CI passes them).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 7 Wave-5 modules to TS (batch 11)

ADR-457 build-at-publish: gap-checker, docs, check-command-router, frontmatter,
learnings, gsd2-import, profile-pipeline. Behaviour preserved; full suite green
across all shards (only the 4 local gpg-env failures remain). Also broadens
atomic-write-coverage.test.cjs to accept the tsc-compiled namespace-import form
while still asserting platformWriteSync is called (safety guard intact).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate config + profile-output to TS (batch 12)

ADR-457 build-at-publish: config (729 LOC), profile-output (1142 LOC). All
exports preserved; cmdMigrateConfig de-asynced (migrateOnDisk is sync, awaited
caller tolerates it). Behaviour preserved; suite green across all shards
(only the 4 local gpg-env failures). Wave 5 complete.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 5 Wave-6 modules to TS (batch 13)

ADR-457 build-at-publish: template, uat, workstream, roadmap, audit. Behaviour
preserved (dead toPosixPath import dropped from audit; inline requires hoisted).
Suite green across all shards (only the 4 local gpg-env failures).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate commands + state hubs to TS (batch 14)

ADR-457 build-at-publish: commands (1305 LOC), state (2074 LOC, 17 dependents).
All exports preserved; inner requires kept non-hoisted where load-order matters
(install.js, per-call security); acquireStateLock cast inlined to preserve the
err.code source token a structural test inspects. Behaviour preserved; suite
green across all shards (only the 4 local gpg-env failures). Wave 6 complete.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate milestone to TS (batch 15a, hand-authored)

ADR-457 build-at-publish: milestone -> src/milestone.cts. Authored directly
(subagent capacity was unavailable). Also relaxes core.output()'s 3rd param to
optional, matching its real always-optional call contract (unblocks remaining
2-arg output callers). Behaviour preserved; suite green across all shards
(only the 4 local gpg-env failures).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate phase, verify, init to TS (batch 15, final modules)

ADR-457 build-at-publish, Wave 7 (the last hubs): phase (1608 LOC), verify
(1615), init (2113). Adds src/package-identity.d.cts so verify can import the
permanently value-baked package-identity.cjs under strict TS.

Fixes two regressions the migration introduced in verify: restore
cmdValidateHealth's `return result` (callers/tests read result.warnings — it is
NOT side-effect-only), and make the bug-3384 source-pattern test tolerant of the
tsc-compiled bracket-notation form of the git_list_failed->W020 branch (behaviour
intact). Full suite green across all shards (only the 4 local gpg-env failures);
lint 0 errors. All 86 migratable bin/lib modules are now TypeScript sources.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(#537): finalize ADR-457 migration — retire tsconfig.lint.json

All hand-written bin/lib/*.cjs are now src/*.cts sources, so the checkJs
stopgap tsconfig.lint.json (unused; not wired into eslint, scripts, or CI) is
deleted per ADR-457's final step. Also gitignore the tsc-generated
config-types.cjs (was still committed) for consistency with every other
emitted artifact. package-identity.cjs stays value-baked (declared via
src/package-identity.d.cts). Suite green; #551 ESLint-coverage test green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): add prepare script so unpacked/git installs build bin/lib artifacts

ADR-457 build-at-publish: bin/lib/*.cjs are now gitignored, built by tsc. The
prepack/prepublishOnly hooks cover `npm pack`/publish, but `npm install -g
<dir>` and git installs run the `prepare` lifecycle — which was missing — so the
unpacked install shipped without the compiled .cjs and failed at startup with
"Cannot find module './lib/core.cjs'" (caught by the smoke-unpacked CI job).
Add `prepare` mirroring prepublishOnly (build:lib + build:hooks). prepare does
NOT run for registry consumers (they get the pre-built tarball), only for
source/local/pack installs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): make CI build/lockfile checks work with gitignored bin/lib artifacts

ADR-457 build-at-publish exposed two CI assumptions that bin/lib/*.cjs are
always present on disk:
- check:env's lockfile-sync ran `npm ci --dry-run`, which now triggers the
  `prepare` build (tsc) — but it runs before deps are installed, so tsc is
  absent and it misreported the lockfile as out of sync. Add --ignore-scripts
  (a lockfile check must not build).
- the lint-tests job installs with --ignore-scripts (no prepare build), but
  lint:skill-deps require()s the built install-profiles.cjs. Add an explicit
  `npm run build:lib` step after install.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): narrow prepare to build:lib only (unbreak packed-smoke pack step)

prepare running build:hooks emitted "✓ Copying ..." stdout during `npm pack`,
which the install-smoke "Pack root tarball" step captures into $GITHUB_OUTPUT —
breaking it with "Invalid format". build:lib (tsc) is silent on success and is
all the unpacked/source install needs (the smoke-unpacked assertions exercise
gsd-tools, i.e. bin/lib, and tolerate hook setup with `|| true`). Matches
prepack. build:hooks still runs on prepublishOnly for real publishes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): wire Stryker mutation gate to build-at-publish layout

The gate scored 0.00 because it mutated changed bin/lib/*.cjs that (a) were
generated artifacts and (b) included modules with no coverage in the command's
test set. Rework: mutation.yml now derives changed COVERED modules from
src/*.cts and maps them to their built bin/lib/*.cjs; Stryker mutates those
built artifacts with a no-rebuild command (mutating src/*.cts + per-mutant tsc
was ~3x over the 30-min CI budget).

NOTE: with the gate now correctly measuring the covered modules, their actual
mutation score is 42.94% (< break 50) — a pre-existing test-coverage gap
(adr-parser/prompt-budget/etc.), not introduced by this behaviour-preserving
migration. Reaching 50 needs more tests, a threshold/scope change, or a waiver —
a maintainer decision.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537): raise mutation coverage of covered modules above the 50 gate

Adds focused example-based unit tests that kill surviving mutants in the two
lowest-scoring covered modules:
- tests/prompt-budget.unit.test.cjs (112 tests): 17.9% -> 97.9%
- tests/adr-parser.unit.test.cjs (205 tests): 44.7% -> 89.4%
Both wired into stryker.config.mjs's command. Fresh full run over the 6 covered
modules now scores 82.25% (>= break 50); every covered module is >= 68%.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537,#609): parallelize mutation gate via dynamic per-module matrix

The serial Stryker run timed out at 30 min once the migration's added tests
made every mutant re-run ~300 tests. Replace it with a dynamic matrix so the
gate completes well under budget — folded into this PR (was tracked as #609)
because it's a prerequisite for this PR's mutation gate to pass.

- scripts/mutation-matrix.cjs: single source of truth (covered-module -> test
  files) computing changed covered modules from git diff -> {has_work, matrix}.
- mutation.yml: detect -> dynamic `matrix: fromJSON(...)` mutate job (one
  parallel shard per changed module, scoped via MUTATION_TEST_CMD to only that
  module's tests, 15-min/shard) -> summary job that KEEPS the legacy check name
  "Stryker mutation score (changed files only)" so branch protection is
  unchanged. Per-shard jobs report as "Stryker (<module>)".
- stryker.config.mjs: commandRunner.command reads MUTATION_TEST_CMD (falls back
  to the full command locally).

Closes #609.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537,#609): give each mutation shard ≥50% on its own tests; drop blacksmith note

Per-module sharding revealed that active-workstream-store (46.5%) and
frontmatter (7.4%) only cleared 50% in the old serial run via timeout-noise from
the bloated 300-test command; on their own tests they were below the gate. Add
focused unit tests:
- tests/active-workstream-store.unit.test.cjs (115 tests): 46.5% -> 81.9%
- tests/frontmatter.unit.test.cjs (165 tests): 7.4% -> 63.4%
Both wired into scripts/mutation-matrix.cjs (per-module test map) and
stryker.config.mjs DEFAULT_TEST_CMD. All 6 covered modules now clear break:50
with only their own tests (config-schema/context-utilization/prompt-budget/
adr-parser already did). Also removes the leftover blacksmith TODO comment —
GitHub-hosted runners only; speed comes from parallel per-module shards.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537,#609): strengthen prompt-budget tests to clear the gate on its own tests

prompt-budget scored 39.58% when mutation-tested with ONLY its own tests (the
way the per-module CI shard runs it) — an earlier ~98% reading was inflated by
accidentally running the full multi-module command. Add 96 targeted tests to
tests/prompt-budget.unit.test.cjs (exact note-template text, plan-truncation
arithmetic/percentages, drop-block strings, noteInjected/hardFailed booleans):
scoped score 39.58% -> 68.75% (>= break 50). All 6 covered modules now clear
the gate on their own tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 11:45:01 -04:00

628 lines
20 KiB
TypeScript

/**
* Profile Pipeline — session scanning, message extraction, and sampling
*
* Reads Claude Code session history (read-only) to extract user messages
* for behavioral profiling. Three commands:
* - scan-sessions: list all projects and sessions
* - extract-messages: extract user messages from a specific project
* - profile-sample: multi-project sampling with recency weighting
*
* ADR-457 build-at-publish: the hand-written bin/lib/profile-pipeline.cjs collapsed
* to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
* from the prior hand-written .cjs; only strict types are added.
*/
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import readline from 'node:readline';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import core = require('./core.cjs');
const { output, error, reapStaleTempFiles } = core;
// ─── Types ────────────────────────────────────────────────────────────────────
interface SessionEntry {
sessionId: string;
filePath: string;
size: number;
modified: Date;
}
interface IndexEntry {
sessionId?: string;
summary?: string;
messageCount?: number;
created?: string;
}
interface IndexData {
originalPath: string | null;
entries: Map<string, IndexEntry>;
}
interface ProjectInfo {
name: string;
directory: string;
sessionCount: number;
totalSize: number;
totalSizeHuman: string;
lastActive: string;
dateRange: { first: string; last: string };
sessions?: SessionDetail[];
}
interface SessionDetail {
sessionId: string;
size: number;
sizeHuman: string;
modified: string;
summary?: string;
messageCount?: number;
created?: string;
}
interface ExtractedMessage {
sessionId: string;
projectPath: string | null;
timestamp: string | null;
content: string;
}
interface SampleMessage {
sessionId: string;
projectName: string;
projectPath: string | null;
timestamp: string | null;
content: string;
}
interface JsonlRecord {
type?: string;
userType?: string;
isMeta?: boolean;
isSidechain?: boolean;
message?: {
content?: unknown;
};
cwd?: string;
timestamp?: string;
}
// ─── Session I/O Helpers ──────────────────────────────────────────────────────
function getSessionsDir(overridePath?: string | null): string | null {
const dir = overridePath || path.join(os.homedir(), '.claude', 'projects');
if (!fs.existsSync(dir)) return null;
return dir;
}
function scanProjectDir(projectDirPath: string): SessionEntry[] {
const entries = fs.readdirSync(projectDirPath);
const sessions: SessionEntry[] = [];
for (const entry of entries) {
if (!entry.endsWith('.jsonl')) continue;
const sessionId = entry.replace('.jsonl', '');
const filePath = path.join(projectDirPath, entry);
const stat = fs.statSync(filePath);
sessions.push({
sessionId,
filePath,
size: stat.size,
modified: stat.mtime,
});
}
sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
return sessions;
}
function readSessionIndex(projectDirPath: string): IndexData {
try {
const indexPath = path.join(projectDirPath, 'sessions-index.json');
const raw = fs.readFileSync(indexPath, 'utf-8');
const parsed = JSON.parse(raw) as { originalPath?: string; entries?: IndexEntry[] };
const entries = new Map<string, IndexEntry>();
for (const entry of (parsed.entries || [])) {
if (entry.sessionId) {
entries.set(entry.sessionId, entry);
}
}
return { originalPath: parsed.originalPath || null, entries };
} catch {
return { originalPath: null, entries: new Map() };
}
}
function getProjectName(projectDirName: string, indexData: IndexData, firstRecordCwd?: string | null): string {
if (indexData && indexData.originalPath) {
return path.basename(indexData.originalPath);
}
if (firstRecordCwd) {
return path.basename(firstRecordCwd);
}
return projectDirName;
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(1)} MB`;
return `${(bytes / 1073741824).toFixed(1)} GB`;
}
function formatProjectTable(projects: ProjectInfo[]): string {
let out = '';
out += 'Project'.padEnd(35) + 'Sessions'.padEnd(10) + 'Size'.padEnd(10) + 'Last Active\n';
out += '-'.repeat(75) + '\n';
for (const p of projects) {
const name = p.name.length > 33 ? p.name.substring(0, 30) + '...' : p.name;
out += name.padEnd(35) + String(p.sessionCount).padEnd(10) +
p.totalSizeHuman.padEnd(10) + p.lastActive + '\n';
}
return out;
}
function formatSessionTable(sessions: SessionDetail[]): string {
let out = '';
out += ' Session ID'.padEnd(42) + 'Size'.padEnd(10) + 'Modified\n';
out += ' ' + '-'.repeat(70) + '\n';
for (const s of sessions) {
const id = s.sessionId.length > 38 ? s.sessionId.substring(0, 35) + '...' : s.sessionId;
out += ' ' + id.padEnd(40) + formatBytes(s.size).padEnd(10) +
new Date(s.modified).toISOString().replace('T', ' ').substring(0, 19) + '\n';
}
return out;
}
// ─── Message Extraction Helpers ───────────────────────────────────────────────
function isGenuineUserMessage(record: JsonlRecord): boolean {
if (record.type !== 'user') return false;
if (record.userType !== 'external') return false;
if (record.isMeta === true) return false;
if (record.isSidechain === true) return false;
const content = record.message?.content;
if (typeof content !== 'string') return false;
if (content.length === 0) return false;
if (content.startsWith('<local-command')) return false;
if (content.startsWith('<command-')) return false;
if (content.startsWith('<task-notification')) return false;
if (content.startsWith('<local-command-stdout')) return false;
return true;
}
function truncateContent(content: string, maxLen = 2000): string {
if (content.length <= maxLen) return content;
return content.substring(0, maxLen) + '... [truncated]';
}
async function streamExtractMessages(filePath: string, filterFn: (r: JsonlRecord) => boolean, maxMessages = 300): Promise<ExtractedMessage[]> {
const rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity,
terminal: false,
});
const messages: ExtractedMessage[] = [];
const sessionId = path.basename(filePath, '.jsonl');
for await (const line of rl) {
if (messages.length >= maxMessages) break;
let record: JsonlRecord;
try {
record = JSON.parse(line) as JsonlRecord;
} catch {
continue;
}
if (!filterFn(record)) continue;
messages.push({
sessionId,
projectPath: record.cwd || null,
timestamp: record.timestamp || null,
// eslint-disable-next-line @typescript-eslint/no-base-to-string
content: truncateContent(String(record.message?.content ?? '')),
});
}
return messages;
}
// ─── Commands ─────────────────────────────────────────────────────────────────
function cmdScanSessions(overridePath: string | null | undefined, options: { json?: boolean; verbose?: boolean }, raw: boolean): void {
const sessionsDir = getSessionsDir(overridePath);
if (!sessionsDir) {
const searchedPath = overridePath || '~/.claude/projects';
error(`No Claude Code sessions found at ${searchedPath}.${overridePath ? '' : ' Is Claude Code installed?'}`);
}
process.stderr.write('Reading your session history (read-only, nothing is modified or sent anywhere)...\n');
let projectDirs: string[];
try {
projectDirs = fs.readdirSync(sessionsDir as string).filter(entry => {
const fullPath = path.join(sessionsDir as string, entry);
try {
return fs.statSync(fullPath).isDirectory();
} catch {
return false;
}
});
} catch (err) {
error(`Cannot read sessions directory: ${(err as Error).message}`);
return;
}
const projects: ProjectInfo[] = [];
for (const dirName of projectDirs) {
const projectPath = path.join(sessionsDir as string, dirName);
const sessions = scanProjectDir(projectPath);
if (sessions.length === 0) continue;
const indexData = readSessionIndex(projectPath);
const projectName = getProjectName(dirName, indexData);
if (indexData.entries.size === 0 && !options.json) {
process.stderr.write(`Index not found for ${projectName}, scanning directory...\n`);
}
const totalSize = sessions.reduce((sum, s) => sum + s.size, 0);
const lastActive = sessions[0].modified.toISOString();
const oldest = sessions[sessions.length - 1].modified.toISOString();
const newest = sessions[0].modified.toISOString();
const project: ProjectInfo = {
name: projectName,
directory: dirName,
sessionCount: sessions.length,
totalSize,
totalSizeHuman: formatBytes(totalSize),
lastActive: lastActive.replace('T', ' ').substring(0, 19),
dateRange: { first: oldest, last: newest },
};
if (options.verbose) {
project.sessions = sessions.map(s => {
const indexed = indexData.entries.get(s.sessionId);
const session: SessionDetail = {
sessionId: s.sessionId,
size: s.size,
sizeHuman: formatBytes(s.size),
modified: s.modified.toISOString(),
};
if (indexed) {
if (indexed.summary) session.summary = indexed.summary;
if (indexed.messageCount !== undefined) session.messageCount = indexed.messageCount;
if (indexed.created) session.created = indexed.created;
}
return session;
});
}
projects.push(project);
}
projects.sort((a, b) => b.dateRange.last.localeCompare(a.dateRange.last));
if (options.json || raw) {
output(projects, raw, undefined);
} else {
process.stdout.write('\n' + formatProjectTable(projects));
if (options.verbose) {
for (const p of projects) {
process.stdout.write(`\n ${p.name} (${p.sessionCount} sessions):\n`);
if (p.sessions) {
process.stdout.write(formatSessionTable(p.sessions));
}
}
}
process.stdout.write(`\nTotal: ${projects.length} projects\n`);
process.exit(0);
}
}
async function cmdExtractMessages(projectArg: string, options: { sessionId?: string; limit?: number }, raw: boolean, overridePath?: string | null): Promise<void> {
const sessionsDir = getSessionsDir(overridePath);
if (!sessionsDir) {
const searchedPath = overridePath || '~/.claude/projects';
error(`No Claude Code sessions found at ${searchedPath}.${overridePath ? '' : ' Is Claude Code installed?'}`);
}
let projectDirs: string[];
try {
projectDirs = fs.readdirSync(sessionsDir as string).filter(entry => {
const fullPath = path.join(sessionsDir as string, entry);
try {
return fs.statSync(fullPath).isDirectory();
} catch {
return false;
}
});
} catch (err) {
error(`Cannot read sessions directory: ${(err as Error).message}`);
return;
}
let matchedDir: string | null = null;
let matchedName: string | null = null;
for (const dirName of projectDirs) {
if (dirName === projectArg) {
matchedDir = dirName;
break;
}
}
if (!matchedDir) {
const lowerArg = projectArg.toLowerCase();
const matches = projectDirs.filter(d => d.toLowerCase().includes(lowerArg));
if (matches.length === 1) {
matchedDir = matches[0];
} else if (matches.length > 1) {
const exactNameMatches: { dirName: string; name: string }[] = [];
for (const dirName of matches) {
const indexData = readSessionIndex(path.join(sessionsDir as string, dirName));
const pName = getProjectName(dirName, indexData);
if (pName.toLowerCase() === lowerArg) {
exactNameMatches.push({ dirName, name: pName });
}
}
if (exactNameMatches.length === 1) {
matchedDir = exactNameMatches[0].dirName;
matchedName = exactNameMatches[0].name;
} else {
const names = matches.map(d => {
const idx = readSessionIndex(path.join(sessionsDir as string, d));
return ` - ${getProjectName(d, idx)} (${d})`;
});
error(`Multiple projects match "${projectArg}":\n${names.join('\n')}\nBe more specific.`);
}
}
}
if (!matchedDir) {
const available = projectDirs.map(d => {
const idx = readSessionIndex(path.join(sessionsDir as string, d));
return ` - ${getProjectName(d, idx)}`;
});
error(`No project matching "${projectArg}". Available projects:\n${available.join('\n')}`);
return;
}
const projectPath = path.join(sessionsDir as string, matchedDir);
const indexData = readSessionIndex(projectPath);
const projectName = matchedName || getProjectName(matchedDir, indexData);
process.stderr.write('Reading your session history (read-only, nothing is modified or sent anywhere)...\n');
let sessions = scanProjectDir(projectPath);
if (options.sessionId) {
sessions = sessions.filter(s => s.sessionId === options.sessionId);
if (sessions.length === 0) {
error(`Session "${options.sessionId}" not found in project "${projectName}".`);
}
}
if (options.limit && options.limit > 0) {
sessions = sessions.slice(0, options.limit);
}
reapStaleTempFiles('gsd-pipeline-', { dirsOnly: true });
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-pipeline-'));
const outputPath = path.join(tmpDir, 'extracted-messages.jsonl');
let sessionsProcessed = 0;
let sessionsSkipped = 0;
let messagesExtracted = 0;
let messagesTruncated = 0;
const total = sessions.length;
const batchLimit = 300;
for (let i = 0; i < sessions.length; i++) {
if (messagesExtracted >= batchLimit) break;
const session = sessions[i];
process.stderr.write(`\rProcessing session ${i + 1}/${total}...`);
try {
const remaining = batchLimit - messagesExtracted;
const msgs = await streamExtractMessages(session.filePath, isGenuineUserMessage, remaining);
for (const msg of msgs) {
fs.appendFileSync(outputPath, JSON.stringify(msg) + '\n');
messagesExtracted++;
if (msg.content.endsWith('... [truncated]')) {
messagesTruncated++;
}
}
sessionsProcessed++;
} catch (err) {
sessionsSkipped++;
process.stderr.write(`\nWarning: Skipped session ${session.sessionId}: ${(err as Error).message}\n`);
}
}
process.stderr.write('\r' + ' '.repeat(60) + '\r');
const result = {
output_file: outputPath,
project: projectName,
sessions_processed: sessionsProcessed,
sessions_skipped: sessionsSkipped,
messages_extracted: messagesExtracted,
messages_truncated: messagesTruncated,
};
if (sessionsSkipped > 0 && sessionsProcessed > 0) {
process.stdout.write(JSON.stringify(result, null, 2));
process.exit(2);
} else if (sessionsProcessed === 0 && sessionsSkipped > 0) {
process.stdout.write(JSON.stringify(result, null, 2));
process.exit(1);
} else {
output(result, raw, undefined);
}
}
async function cmdProfileSample(overridePath: string | null | undefined, options: { limit?: number; maxChars?: number; maxPerProject?: number }, raw: boolean): Promise<void> {
const sessionsDir = getSessionsDir(overridePath);
if (!sessionsDir) {
const searchedPath = overridePath || '~/.claude/projects';
error(`No Claude Code sessions found at ${searchedPath}.${overridePath ? '' : ' Is Claude Code installed?'}`);
}
process.stderr.write('Reading your session history (read-only, nothing is modified or sent anywhere)...\n');
const limit = options.limit || 150;
const maxChars = options.maxChars || 500;
let projectDirs: string[];
try {
projectDirs = fs.readdirSync(sessionsDir as string).filter(entry => {
const fullPath = path.join(sessionsDir as string, entry);
try {
return fs.statSync(fullPath).isDirectory();
} catch {
return false;
}
});
} catch (err) {
error(`Cannot read sessions directory: ${(err as Error).message}`);
return;
}
if (projectDirs.length === 0) {
error('No project directories found in sessions directory.');
}
interface ProjectMeta {
dirName: string;
projectPath: string;
sessions: SessionEntry[];
projectName: string;
lastActive: Date;
}
const projectMeta: ProjectMeta[] = [];
for (const dirName of projectDirs) {
const projectPath = path.join(sessionsDir as string, dirName);
const sessions = scanProjectDir(projectPath);
if (sessions.length === 0) continue;
const indexData = readSessionIndex(projectPath);
const projectName = getProjectName(dirName, indexData);
const lastActive = sessions[0].modified;
projectMeta.push({ dirName, projectPath, sessions, projectName, lastActive });
}
projectMeta.sort((a, b) => b.lastActive.getTime() - a.lastActive.getTime());
const projectCount = projectMeta.length;
if (projectCount === 0) {
error('No projects with sessions found.');
}
const perProjectCap = options.maxPerProject || Math.max(5, Math.floor(limit / projectCount));
const recencyThreshold = Date.now() - 30 * 24 * 60 * 60 * 1000;
const allMessages: SampleMessage[] = [];
let skippedContextDumps = 0;
const projectBreakdown: { project: string; messages: number; sessions: number }[] = [];
for (const proj of projectMeta) {
if (allMessages.length >= limit) break;
const cappedSessions = proj.sessions.slice(0, perProjectCap);
let projectMessages = 0;
let projectSessionsUsed = 0;
for (const session of cappedSessions) {
if (allMessages.length >= limit) break;
const isRecent = session.modified.getTime() >= recencyThreshold;
const perSessionMax = isRecent ? 10 : 3;
const remaining = Math.min(perSessionMax, limit - allMessages.length);
try {
const msgs = await streamExtractMessages(session.filePath, isGenuineUserMessage, remaining);
let sessionUsed = false;
for (const msg of msgs) {
if (allMessages.length >= limit) break;
const content = msg.content || '';
if (content.startsWith('This session is being continued')) {
skippedContextDumps++;
continue;
}
const lines = content.split('\n').filter(l => l.trim().length > 0);
if (lines.length > 3) {
const logPattern = /^\[?(DEBUG|INFO|WARN|ERROR|LOG)\]?/i;
const timestampPattern = /^\d{4}-\d{2}-\d{2}/;
const logLines = lines.filter(l => logPattern.test(l.trim()) || timestampPattern.test(l.trim()));
if (logLines.length / lines.length > 0.8) {
skippedContextDumps++;
continue;
}
}
const truncated = truncateContent(content, maxChars);
allMessages.push({
sessionId: msg.sessionId,
projectName: proj.projectName,
projectPath: msg.projectPath,
timestamp: msg.timestamp,
content: truncated,
});
projectMessages++;
sessionUsed = true;
}
if (sessionUsed) projectSessionsUsed++;
} catch {
continue;
}
}
if (projectMessages > 0) {
projectBreakdown.push({
project: proj.projectName,
messages: projectMessages,
sessions: projectSessionsUsed,
});
}
}
reapStaleTempFiles('gsd-profile-', { dirsOnly: true });
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-profile-'));
const outputPath = path.join(tmpDir, 'profile-sample.jsonl');
for (const msg of allMessages) {
fs.appendFileSync(outputPath, JSON.stringify(msg) + '\n');
}
const result = {
output_file: outputPath,
projects_sampled: projectBreakdown.length,
messages_sampled: allMessages.length,
per_project_cap: perProjectCap,
message_char_limit: maxChars,
skipped_context_dumps: skippedContextDumps,
project_breakdown: projectBreakdown,
};
output(result, raw, undefined);
}
export = {
cmdScanSessions,
cmdExtractMessages,
cmdProfileSample,
};