{"version":3,"file":"server.mjs","names":["isInside","hasCode","hasCode","rootSession","channelFileEdits","apiRoute","hookToolExecutionEnd","hookToolExecutionStart","hookToolResult"],"sources":["../../src/constants/editPresence.ts","../../src/services/editPathNames/index.ts","../../src/services/fileEditPaths/index.ts","../../src/services/gitStatus/index.ts","../../src/constants/snapshots.ts","../../src/services/fileChanges/index.ts","../../src/services/lineDiff/index.ts","../../src/services/fileEditsViews/index.ts","../../src/services/nodeWorkingFiles/index.ts","../../src/services/sessionStateSweep/index.ts","../../src/services/snapshotStore/index.ts","../../src/services/timelineStore/index.ts","../../src/services/manifestComparison/index.ts","../../src/services/treeManifest/index.ts","../../src/types/webFiles.ts","../../src/services/filesChannel/index.ts","../../src/services/poIgnore/index.ts","../../src/services/sessionFileRows/index.ts","../../src/services/webFilesChannel/index.ts","../../src/services/fileEditStorage/index.ts","../../src/services/editPresence/index.ts","../../src/services/bashTargets/index.ts","../../src/services/editTracker/index.ts","../../src/types/apiRoutes.ts","../../src/types/fileEditsApi.ts","../../src/services/fileEditsApi/index.ts","../../src/services/fileEditSession/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/(backend)/channel/fileEdits.server.ts","../../src/extensions/workspaces/sessions/(backend)/api/file-edits/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/tool-result.server.ts","../../generated/server.ts"],"sourcesContent":["export const PRESENCE_NOTE_TITLE = '[Po: other active agents edited files in this result]';\nexport const PRESENCE_NOTE_GUIDANCE =\n  'Preserve unrelated edits. If coordination would help, you can use intercom to send to the session id, or ask the subagent by name if it is on your team. Contact is optional; this notice does not block editing.';\n","import { createHash } from 'node:crypto';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/po-core/childProcess';\nimport { piAgentDirectory } from '@agimon-ai/po-core/piSettings';\n\n/** The directory this package owns, under whichever root holds agent state. */\nconst STATE_DIRECTORY = 'po-file-edit';\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\n/** A stable short name for a path or session key, so state files are found from those two alone. */\nexport function pathHash(value: string): string {\n  return createHash('sha256').update(value).digest('hex').slice(0, 16);\n}\n\n/** A subagent child writes to its parent's timeline, so the two stay one session to every reader. */\nexport function sessionKeyFor(sessionId: string, environment: Environment): string {\n  if (environment[SUBAGENT_CHILD_ENV]) {\n    const parent = environment[SUBAGENT_PARENT_SESSION_ENV];\n    if (parent) return parent;\n  }\n  return sessionId;\n}\n\n/** Where every session's state lives: beside the other Po packages' agent state, never in the working tree. */\nexport function stateDirectoryFor(environment: Environment): string {\n  return path.join(piAgentDirectory(environment, environment.HOME), STATE_DIRECTORY);\n}\n\n/** Snapshots sit beside their timeline and take its name, so the two are found and cleared together. */\nexport function snapshotsPathOf(timelinePath: string): string {\n  return `${timelinePath.replace(/\\.jsonl$/u, '')}.blobs`;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { IFileEditPaths } from '../../types/fileEditPaths';\nimport { pathHash, sessionKeyFor, snapshotsPathOf, stateDirectoryFor } from '../editPathNames';\n\nexport class FileEditPaths implements IFileEditPaths {\n  constructor(private readonly environment: Readonly<Record<string, string | undefined>> = process.env) {}\n\n  sessionKey(sessionId: string, env: Readonly<Record<string, string | undefined>> = this.environment): string {\n    return sessionKeyFor(sessionId, env);\n  }\n\n  /**\n   * Where every session's state lives: the Pi agent directory, the same root\n   * every other Po package writes to, and never inside the working tree.\n   *\n   * An earlier layout put this in the repository's git common directory. That\n   * is git's own storage: nothing in git's lifecycle prunes a directory we add\n   * to it, a linked worktree writes into the main checkout rather than its own,\n   * a submodule writes inside `.git/modules`, and `PI_CODING_AGENT_DIR` was\n   * ignored outright. The snapshots are verbatim copies of files the session\n   * touched, so where they land is a question about handling content, not a\n   * question about convenience.\n   */\n  stateDirectory(): string {\n    return stateDirectoryFor(this.environment);\n  }\n\n  /**\n   * One session's timeline, named from its working directory and its session so\n   * the hub and the session API can find it from another process knowing only\n   * those two things.\n   */\n  async timelinePath(cwd: string, sessionKey: string): Promise<string> {\n    const directory = this.stateDirectory();\n    await fs.mkdir(directory, { recursive: true });\n    return path.join(directory, `${pathHash(await fs.realpath(cwd))}-${pathHash(sessionKey)}.jsonl`);\n  }\n\n  /**\n   * Where this session's content snapshots live: beside its timeline and named\n   * after it, so the two are found together and cleared together.\n   */\n  async snapshotsPath(cwd: string, sessionKey: string): Promise<string> {\n    return snapshotsPathOf(await this.timelinePath(cwd, sessionKey));\n  }\n}\n","import { execFile } from 'node:child_process';\nimport path from 'node:path';\nimport { promisify } from 'node:util';\n\nimport type { GitStatusPort } from '../../types/gitStatus';\n\n/**\n * Answers the unchanged question with git, in two batched calls per chunk.\n *\n * One technology per adapter. This is where git enters the scan path; the\n * tracker that depends on the capability keeps importing the port.\n *\n * `ls-files` names which of the given paths git tracks at all, and `status`\n * names which of those moved. Everything else, an ignored build artefact, a\n * temporary file, a tree with no repository, falls out of both answers and is\n * therefore never reported as unchanged: the caller must keep recording it,\n * because git has nothing to say about a file it never saw.\n */\n\n/** Paths per git invocation, so a large scan cannot overflow the argument list. */\nconst CHUNK = 200;\nconst MAX_BUFFER = 4 * 1024 * 1024;\n\nconst run = promisify(execFile);\n\nfunction chunked<T>(values: readonly T[], size: number): T[][] {\n  const groups: T[][] = [];\n  for (let index = 0; index < values.length; index += size) groups.push(values.slice(index, index + size));\n  return groups;\n}\n\nfunction splitRecords(output: string): string[] {\n  return output.split('\\0').filter((entry) => entry !== '');\n}\n\n/**\n * The paths named by `status --porcelain -z`, whose records carry a two-letter\n * code and a space. A rename adds a bare second record; keeping it is harmless,\n * because every path in this set is one the caller records anyway.\n */\nfunction statusPaths(output: string): string[] {\n  return splitRecords(output).map((record) => (record.length > 3 && record[2] === ' ' ? record.slice(3) : record));\n}\n\nfunction isInside(root: string, filePath: string): boolean {\n  const relative = path.relative(root, filePath);\n  return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);\n}\n\nexport class NodeGitStatusAdapter implements GitStatusPort {\n  /** Repository roots already found, so a call per bash command costs one git process, not two. */\n  private readonly roots = new Map<string, string>();\n\n  async dirty(cwd: string): Promise<readonly string[] | undefined> {\n    const root = await this.topLevel(cwd);\n    if (root === undefined) return undefined;\n    // `-- .` keeps git's own walk inside cwd; porcelain paths stay relative to the root.\n    const output = await this.git(cwd, ['status', '--porcelain', '-z', '--untracked-files=all', '--', '.']);\n    return output === undefined ? undefined : statusPaths(output).map((entry) => path.resolve(root, entry));\n  }\n  async unchanged(cwd: string, filePaths: readonly string[]): Promise<ReadonlySet<string>> {\n    const clean = new Set<string>();\n    if (filePaths.length === 0) return clean;\n    const root = await this.topLevel(cwd);\n    if (root === undefined) return clean;\n\n    for (const group of chunked(\n      filePaths.filter((filePath) => isInside(root, filePath)),\n      CHUNK,\n    )) {\n      const relative = group.map((filePath) => path.relative(root, filePath));\n      const tracked = await this.git(root, ['ls-files', '-z', '--', ...relative]);\n      if (tracked === undefined) continue;\n      const dirty = await this.git(root, ['status', '--porcelain', '-z', '--untracked-files=no', '--', ...relative]);\n      if (dirty === undefined) continue;\n      const moved = new Set(statusPaths(dirty));\n      for (const entry of splitRecords(tracked)) {\n        if (!moved.has(entry)) clean.add(path.resolve(root, entry));\n      }\n    }\n    return clean;\n  }\n\n  /** The repository root, or undefined when this tree is not one. */\n  private async topLevel(cwd: string): Promise<string | undefined> {\n    const known = this.roots.get(cwd);\n    if (known !== undefined) return known;\n    const output = await this.git(cwd, ['rev-parse', '--show-toplevel']);\n    const root = output?.trim();\n    if (root === undefined || root === '') return undefined;\n    this.roots.set(cwd, path.resolve(root));\n    return path.resolve(root);\n  }\n\n  /** Git's stdout, or undefined when the call failed for any reason at all. */\n  private async git(cwd: string, args: readonly string[]): Promise<string | undefined> {\n    try {\n      const { stdout } = await run('git', [...args], { cwd, encoding: 'utf8', maxBuffer: MAX_BUFFER });\n      return stdout;\n    } catch {\n      return undefined;\n    }\n  }\n}\n","/** Past this, a file is listed as changed without content rather than snapshotted. */\nexport const MAX_SNAPSHOT_BYTES = 1024 * 1024;\n\n/** How much of a file is read before deciding it is binary. */\nexport const BINARY_SAMPLE_BYTES = 8192;\n","import type { FileEditEntry, FileEditVersion, LegacyTimelineEvent, TimelineEvent } from '../../types/domain';\n\n/**\n * Fold a session's recorded changes into the per-file rows and version\n * histories the surfaces show.\n *\n * The timeline is append-only, one line per change, so every reader folds it\n * the same way and the folding belongs somewhere both the store and its tests\n * can reach without a filesystem. Version 1 lines are still read: a session\n * already running when the package updates keeps appending to the file it\n * opened, and dropping its earlier lines would blank a list mid-session.\n */\n\n/** Either shape the timeline file can hold. */\nexport type AnyTimelineEvent = TimelineEvent | LegacyTimelineEvent;\n\nconst TOOLS = new Set(['edit', 'write', 'bash', 'user']);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction optionalString(value: unknown): string | undefined {\n  return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\nfunction optionalCount(value: unknown): number | undefined {\n  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;\n}\n\n/** Narrows one parsed line, or answers null so a malformed line can be skipped. */\nexport function parseTimelineEvent(value: unknown): AnyTimelineEvent | null {\n  if (!isRecord(value)) return null;\n  const { version, path: filePath, tool, at } = value;\n  if (typeof filePath !== 'string' || filePath === '') return null;\n  if (typeof at !== 'number' || !Number.isFinite(at)) return null;\n  if (typeof tool !== 'string' || !TOOLS.has(tool)) return null;\n\n  if (version === 1) {\n    if (tool === 'user') return null; // The version 1 vocabulary had no manual saves.\n    return { version: 1, path: filePath, tool: tool as LegacyTimelineEvent['tool'], at };\n  }\n  if (version !== 2) return null;\n  const origin = value.origin === 'scan' ? 'scan' : 'tool';\n  return {\n    version: 2,\n    path: filePath,\n    tool: tool as TimelineEvent['tool'],\n    at,\n    origin,\n    ...(optionalString(value.before) === undefined ? {} : { before: value.before as string }),\n    ...(optionalString(value.after) === undefined ? {} : { after: value.after as string }),\n    ...(optionalCount(value.additions) === undefined ? {} : { additions: value.additions as number }),\n    ...(optionalCount(value.removals) === undefined ? {} : { removals: value.removals as number }),\n    ...(value.verified === true ? { verified: true } : {}),\n    ...(value.created === true ? { created: true } : {}),\n  };\n}\n\n/** Every recorded line of the timeline, malformed ones dropped, in file order. */\nexport function parseTimeline(content: string, onMalformed?: (line: string) => void): AnyTimelineEvent[] {\n  const events: AnyTimelineEvent[] = [];\n  for (const line of content.split('\\n')) {\n    if (line === '') continue;\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(line);\n    } catch {\n      onMalformed?.(line);\n      continue;\n    }\n    const event = parseTimelineEvent(parsed);\n    if (event === null) onMalformed?.(line);\n    else events.push(event);\n  }\n  return events;\n}\n\n/**\n * Whether a recorded change is evidence that the file's content actually moved.\n *\n * A tool change names its file and reads both sides, so it always is. A scan\n * change is a tree comparison of size and modification time, which a checkout,\n * an install, or a command that merely touched a file moves as readily as an\n * edit does; only a scan the tracker confirmed carries `verified`. Version 1\n * lines predate the distinction entirely, so a bash one cannot be trusted.\n */\nexport function isConfirmedChange(event: AnyTimelineEvent): boolean {\n  if (event.version !== 2) return event.tool !== 'bash';\n  return event.origin !== 'scan' || event.verified === true;\n}\n\n/** The recorded changes worth listing, which is every change but an unconfirmed touch. */\nexport function confirmedChanges(events: readonly AnyTimelineEvent[]): AnyTimelineEvent[] {\n  return events.filter(isConfirmedChange);\n}\n/** One row per file, newest change first, which is the order both docks list in. */\nexport function foldEntries(events: readonly AnyTimelineEvent[]): FileEditEntry[] {\n  const folded = new Map<string, FileEditEntry>();\n  for (const event of events) {\n    const current = folded.get(event.path);\n    folded.set(event.path, {\n      path: event.path,\n      tool: event.at >= (current?.at ?? 0) ? event.tool : (current?.tool ?? event.tool),\n      at: Math.max(event.at, current?.at ?? 0),\n      count: (current?.count ?? 0) + 1,\n    });\n  }\n  return [...folded.values()].sort((left, right) => right.at - left.at);\n}\n\n/** One file's history, oldest first, numbered so a reader can name a version. */\nexport function foldVersions(events: readonly AnyTimelineEvent[], filePath: string): FileEditVersion[] {\n  return events\n    .filter((event) => event.path === filePath)\n    .sort((left, right) => left.at - right.at)\n    .map((event, offset) => {\n      const version: FileEditVersion = {\n        index: offset + 1,\n        tool: event.tool,\n        at: event.at,\n        origin: event.version === 2 ? event.origin : 'scan',\n      };\n      if (event.version !== 2) return version;\n      return {\n        ...version,\n        ...(event.before === undefined ? {} : { before: event.before }),\n        ...(event.after === undefined ? {} : { after: event.after }),\n        ...(event.additions === undefined ? {} : { additions: event.additions }),\n        ...(event.removals === undefined ? {} : { removals: event.removals }),\n        ...(event.verified === true ? { verified: true } : {}),\n        ...(event.created === true ? { created: true } : {}),\n      };\n    });\n}\n\n/**\n * Whether a file can be diffed at all: some version has to give the diff a\n * starting point. A captured baseline is one. So is a version that created the\n * file, whose starting point is nothing at all.\n *\n * A file only ever seen after the fact, which is every file a bash script\n * wrote, still cannot be.\n */\nexport function isDiffable(versions: readonly FileEditVersion[]): boolean {\n  return versions.some((version) => version.before !== undefined || version.created === true);\n}\n\n/** The oldest captured baseline for a file, which is what the whole-session diff starts from. */\nexport function baselineOf(versions: readonly FileEditVersion[]): string | undefined {\n  return versions.find((version) => version.before !== undefined)?.before;\n}\n","import type { FileEditsDiffHunk, FileEditsDiffRow } from '../../types/fileEditsApi';\n\n/**\n * The line difference between two versions of a file, as bounded hunks.\n *\n * This is deliberately the package's own rather than Pi's `generateDiffString`:\n * that helper reaches the session process through an optional peer dependency,\n * and these routes run in a host that imports only the built entry, so its\n * presence is an assumption rather than a fact. A line diff is small enough to\n * own outright, and owning it means the wire carries structured rows instead of\n * a formatted string the browser has to parse back apart.\n *\n * Bounded twice over. Common prefix and suffix are trimmed first, which is what\n * makes a one-line change in a large file cheap. What remains is matched with a\n * longest-common-subsequence table, and only while that table stays under\n * MAX_MATRIX_CELLS: past it the changed region is reported as one replacement\n * rather than growing a matrix that would outweigh the file.\n */\n\n/** Lines of unchanged context kept either side of a change. */\nconst CONTEXT_LINES = 3;\n\n/** The largest LCS table worth building; past it the changed region is one replacement. */\nconst MAX_MATRIX_CELLS = 1_000_000;\n\nexport interface LineDiffResult {\n  hunks: FileEditsDiffHunk[];\n  additions: number;\n  removals: number;\n  /** True when the changed region was too large to match line by line. */\n  approximate: boolean;\n}\n\n/** One step of the match, before it is grouped into hunks. */\ninterface DiffStep {\n  marker: '+' | '-' | ' ';\n  content: string;\n  /** Line number in whichever side owns the step, 1-based. */\n  line: number;\n}\n\nfunction splitLines(text: string): string[] {\n  const normalized = text.replaceAll('\\r\\n', '\\n').replaceAll('\\r', '\\n');\n  return normalized === '' ? [] : normalized.split('\\n');\n}\n\n/** How many leading lines the two sides share. */\nfunction commonPrefix(before: readonly string[], after: readonly string[]): number {\n  const limit = Math.min(before.length, after.length);\n  let count = 0;\n  while (count < limit && before[count] === after[count]) count += 1;\n  return count;\n}\n\n/** How many trailing lines the two sides share, never overlapping the prefix. */\nfunction commonSuffix(before: readonly string[], after: readonly string[], prefix: number): number {\n  const limit = Math.min(before.length, after.length) - prefix;\n  let count = 0;\n  while (count < limit && before[before.length - 1 - count] === after[after.length - 1 - count]) count += 1;\n  return count;\n}\n\n/**\n * The classic LCS length table. Only ever called once the caller has checked\n * the region against MAX_MATRIX_CELLS, so the allocation is bounded.\n */\nfunction lcsTable(before: readonly string[], after: readonly string[]): Uint32Array {\n  const rows = before.length + 1;\n  const columns = after.length + 1;\n  const table = new Uint32Array(rows * columns);\n  for (let row = before.length - 1; row >= 0; row -= 1) {\n    for (let column = after.length - 1; column >= 0; column -= 1) {\n      const index = row * columns + column;\n      table[index] =\n        before[row] === after[column]\n          ? (table[index + columns + 1] ?? 0) + 1\n          : Math.max(table[index + columns] ?? 0, table[index + 1] ?? 0);\n    }\n  }\n  return table;\n}\n\n/** Walks the table to turn it back into an ordered run of keeps, removals and additions. */\nfunction backtrack(\n  before: readonly string[],\n  after: readonly string[],\n  beforeStart: number,\n  afterStart: number,\n): DiffStep[] {\n  const table = lcsTable(before, after);\n  const columns = after.length + 1;\n  const steps: DiffStep[] = [];\n  let row = 0;\n  let column = 0;\n  while (row < before.length && column < after.length) {\n    if (before[row] === after[column]) {\n      steps.push({ marker: ' ', content: after[column] ?? '', line: afterStart + column });\n      row += 1;\n      column += 1;\n      continue;\n    }\n    if ((table[(row + 1) * columns + column] ?? 0) >= (table[row * columns + column + 1] ?? 0)) {\n      steps.push({ marker: '-', content: before[row] ?? '', line: beforeStart + row });\n      row += 1;\n      continue;\n    }\n    steps.push({ marker: '+', content: after[column] ?? '', line: afterStart + column });\n    column += 1;\n  }\n  while (row < before.length) {\n    steps.push({ marker: '-', content: before[row] ?? '', line: beforeStart + row });\n    row += 1;\n  }\n  while (column < after.length) {\n    steps.push({ marker: '+', content: after[column] ?? '', line: afterStart + column });\n    column += 1;\n  }\n  return steps;\n}\n\n/** The whole changed region as one replacement, for a region too large to match. */\nfunction wholesale(\n  before: readonly string[],\n  after: readonly string[],\n  beforeStart: number,\n  afterStart: number,\n): DiffStep[] {\n  return [\n    ...before.map((content, offset) => ({ marker: '-' as const, content, line: beforeStart + offset })),\n    ...after.map((content, offset) => ({ marker: '+' as const, content, line: afterStart + offset })),\n  ];\n}\n\n/** Groups the steps into hunks, keeping CONTEXT_LINES of unchanged text either side of a change. */\nfunction toHunks(steps: readonly DiffStep[]): FileEditsDiffHunk[] {\n  const keep: boolean[] = Array.from({ length: steps.length }, () => false);\n  for (const [index, step] of steps.entries()) {\n    if (step.marker === ' ') continue;\n    const from = Math.max(0, index - CONTEXT_LINES);\n    const to = Math.min(steps.length - 1, index + CONTEXT_LINES);\n    for (let cursor = from; cursor <= to; cursor += 1) keep[cursor] = true;\n  }\n\n  const hunks: FileEditsDiffHunk[] = [];\n  let rows: FileEditsDiffRow[] = [];\n  for (const [index, step] of steps.entries()) {\n    if (!keep[index]) {\n      if (rows.length > 0) {\n        hunks.push({ start: rows[0]?.line ?? 1, rows });\n        rows = [];\n      }\n      continue;\n    }\n    rows.push({ marker: step.marker, line: step.line, content: step.content });\n  }\n  if (rows.length > 0) hunks.push({ start: rows[0]?.line ?? 1, rows });\n  return hunks;\n}\n\n/**\n * The difference between a file that did not exist and the one that now does.\n *\n * Kept separate from a two-sided diff because an empty baseline is the one case\n * where the trailing newline matters. `splitLines` reads \"a\\n\" as a line and\n * then an empty one, which is invisible in a normal diff because both sides\n * carry it and it cancels, but against nothing it would report a file of three\n * lines as four. A creation is counted on the lines the file actually holds.\n */\nexport function lineDiffFromEmpty(after: string): LineDiffResult {\n  return lineDiff('', after.endsWith('\\n') ? after.slice(0, -1) : after);\n}\n\n/**\n * The difference between two versions of a file.\n *\n * Line numbers are the new file's for context and additions, and the old\n * file's for removals, which is the pairing a reader expects: the number\n * beside a line is where that line actually lives.\n */\nexport function lineDiff(before: string, after: string): LineDiffResult {\n  const beforeLines = splitLines(before);\n  const afterLines = splitLines(after);\n  const prefix = commonPrefix(beforeLines, afterLines);\n  const suffix = commonSuffix(beforeLines, afterLines, prefix);\n  const beforeMiddle = beforeLines.slice(prefix, beforeLines.length - suffix);\n  const afterMiddle = afterLines.slice(prefix, afterLines.length - suffix);\n\n  const approximate = beforeMiddle.length * afterMiddle.length > MAX_MATRIX_CELLS;\n  const middle = approximate\n    ? wholesale(beforeMiddle, afterMiddle, prefix + 1, prefix + 1)\n    : backtrack(beforeMiddle, afterMiddle, prefix + 1, prefix + 1);\n\n  const head: DiffStep[] = beforeLines\n    .slice(0, prefix)\n    .map((content, offset) => ({ marker: ' ' as const, content, line: offset + 1 }));\n  const tail: DiffStep[] = afterLines\n    .slice(afterLines.length - suffix)\n    .map((content, offset) => ({ marker: ' ' as const, content, line: afterLines.length - suffix + offset + 1 }));\n\n  const steps = [...head, ...middle, ...tail];\n  return {\n    hunks: toHunks(steps),\n    additions: steps.filter((step) => step.marker === '+').length,\n    removals: steps.filter((step) => step.marker === '-').length,\n    approximate,\n  };\n}\n","import { createHash } from 'node:crypto';\nimport path from 'node:path';\n\nimport { BINARY_SAMPLE_BYTES } from '../../constants/snapshots';\nimport type { FileEditVersion } from '../../types/domain';\nimport type { FileEditsCumulativeView, FileEditsVersionView, FileEditsWorkingView } from '../../types/fileEditsApi';\nimport type { SnapshotStorePort } from '../../types/snapshotStore';\nimport { baselineOf } from '../fileChanges';\nimport { lineDiff, lineDiffFromEmpty } from '../lineDiff';\n\n/** Past this, the working view reports the file rather than carrying it. */\nexport const MAX_WORKING_BYTES = 1024 * 1024;\n\nconst NO_BASELINE_NOTE = 'changed by a command, so no baseline was captured; showing the file as it stands';\n/**\n * A change the tool layer named but never captured content for. That is what\n * every record written before this package learned to snapshot looks like, and\n * calling those \"changed by a command\" would be wrong: the tool is right there\n * in the record.\n */\nconst NO_SNAPSHOT_NOTE = 'recorded before this session began capturing content, so there is no diff for it';\nconst NO_AFTER_NOTE = 'the new content could not be captured: the file is binary or past the size cap';\nconst NO_BEFORE_NOTE = 'the previous content could not be captured: it was binary or past the size cap';\nconst APPROXIMATE_NOTE = 'the changed region was too large to match line by line';\n\n/** Like Node's utf8 read, a byte-order mark stays in the text. */\nconst decoder = new TextDecoder('utf-8', { fatal: false, ignoreBOM: true });\n\nexport function hashOf(content: string): string {\n  return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\nexport function isInside(root: string, candidate: string): boolean {\n  return candidate === root || candidate.startsWith(`${root}${path.sep}`);\n}\n\n/** A file the source view cannot show, with the reason it says instead. */\nexport function unavailable(reason: string): FileEditsWorkingView {\n  return { content: '', hash: '', unavailable: true, reason };\n}\n\n/** The source view of a file's bytes: refused when oversized or binary, otherwise its text and hash. */\nexport function workingViewOf(raw: Uint8Array): FileEditsWorkingView {\n  if (raw.byteLength > MAX_WORKING_BYTES) return unavailable(`the file is larger than ${MAX_WORKING_BYTES} bytes`);\n  if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) return unavailable('the file is binary');\n  const content = decoder.decode(raw);\n  return { content, hash: hashOf(content), unavailable: false };\n}\n\n/**\n * One recorded change as the page renders it. A change with both sides captured\n * carries its own diff; one without says why, rather than showing nothing.\n *\n * A file this session created counts as captured on both sides. Its baseline is\n * empty rather than missing, so the whole file reads as arriving at once, which\n * is exactly what happened.\n */\nexport async function toVersionView(\n  version: FileEditVersion,\n  snapshots: SnapshotStorePort,\n): Promise<FileEditsVersionView> {\n  const view: FileEditsVersionView = {\n    index: version.index,\n    tool: version.tool,\n    at: version.at,\n    origin: version.origin,\n    additions: version.additions ?? 0,\n    removals: version.removals ?? 0,\n  };\n  const createdHere = version.before === undefined && version.created === true;\n  if (version.after === undefined || (version.before === undefined && !createdHere)) {\n    // A scan found the path only after it changed, so no baseline exists. A\n    // tool named the path but content was not stored: either it did not fit, or\n    // the record predates content capture, which the tool tells apart.\n    if (version.origin === 'tool') {\n      return { ...view, note: version.after === undefined ? NO_AFTER_NOTE : NO_BEFORE_NOTE };\n    }\n    return { ...view, note: version.tool === 'bash' ? NO_BASELINE_NOTE : NO_SNAPSHOT_NOTE };\n  }\n  const after = await snapshots.read(version.after);\n  if (after === undefined) {\n    return { ...view, note: 'the content behind this change is no longer held' };\n  }\n  if (version.before === undefined) {\n    const fresh = lineDiffFromEmpty(after);\n    return {\n      ...view,\n      additions: fresh.additions,\n      removals: fresh.removals,\n      hunks: fresh.hunks,\n      ...(fresh.approximate ? { note: APPROXIMATE_NOTE } : {}),\n    };\n  }\n  const before = await snapshots.read(version.before);\n  if (before === undefined) {\n    return { ...view, note: 'the content behind this change is no longer held' };\n  }\n  const diff = lineDiff(before, after);\n  return {\n    ...view,\n    additions: diff.additions,\n    removals: diff.removals,\n    hunks: diff.hunks,\n    ...(diff.approximate ? { note: APPROXIMATE_NOTE } : {}),\n  };\n}\n\n/** Everything the session did to the file: its oldest baseline against what is on disk now. */\nexport async function toCumulativeView(\n  versions: readonly FileEditVersion[],\n  working: FileEditsWorkingView,\n  snapshots: SnapshotStorePort,\n): Promise<FileEditsCumulativeView> {\n  // A file this session created starts from nothing, and nothing is a baseline\n  // the snapshot store never has to hold.\n  const createdHere = versions[0]?.created === true;\n  const baseline = baselineOf(versions);\n  if (!createdHere && baseline === undefined) {\n    return {\n      additions: 0,\n      removals: 0,\n      note: versions[0]?.origin === 'tool' ? NO_BEFORE_NOTE : NO_BASELINE_NOTE,\n    };\n  }\n  if (working.unavailable) {\n    return { additions: 0, removals: 0, note: working.reason ?? 'the file cannot be read' };\n  }\n  if (createdHere || baseline === undefined) {\n    const fresh = lineDiffFromEmpty(working.content);\n    return {\n      additions: fresh.additions,\n      removals: fresh.removals,\n      hunks: fresh.hunks,\n      ...(fresh.approximate ? { note: APPROXIMATE_NOTE } : {}),\n    };\n  }\n  const before = await snapshots.read(baseline);\n  if (before === undefined) {\n    return { additions: 0, removals: 0, note: 'the content this session started from is no longer held' };\n  }\n  const diff = lineDiff(before, working.content);\n  return {\n    additions: diff.additions,\n    removals: diff.removals,\n    hunks: diff.hunks,\n    ...(diff.approximate ? { note: APPROXIMATE_NOTE } : {}),\n  };\n}\n","import fs, { type FileHandle } from 'node:fs/promises';\n\nimport { fileMutationRunner, openGuardedFile } from '@agimon-ai/po-core/platform';\n\nimport type { FileEditsWorkingView } from '../../types/fileEditsApi';\nimport type { RemoveOutcome, SaveOutcome, SaveRequest, WorkingFilesPort } from '../../types/workingFiles';\nimport { hashOf, isInside, MAX_WORKING_BYTES, unavailable, workingViewOf } from '../fileEditsViews';\n\n/**\n * The routes' file operations over Node's real files.\n *\n * One technology per adapter. This is where node enters the API: a link or a\n * rename can swap what a path names between two checks, so every read and write\n * pins the file it checked by its open descriptor instead of by its name.\n */\n\nfunction hasCode(error: unknown, code: string): boolean {\n  return error instanceof Error && 'code' in error && error.code === code;\n}\n\nfunction describe(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * The same containment check after symlinks are followed. A path that does not\n * exist yet resolves to nothing, and there is nothing to hand out, so it\n * passes and the read below reports it missing.\n */\nasync function isRealPathInside(root: string, candidate: string): Promise<boolean> {\n  let realRoot: string;\n  let real: string;\n  try {\n    realRoot = await fs.realpath(root);\n    real = await fs.realpath(candidate);\n  } catch (error) {\n    return hasCode(error, 'ENOENT');\n  }\n  return isInside(realRoot, real);\n}\n\n/** Reads the file as the source view will show it, or says why it cannot. */\nasync function readWorking(filePath: string, opened?: FileHandle, allowedRoot?: string): Promise<FileEditsWorkingView> {\n  let handle = opened;\n  let raw: Buffer;\n  try {\n    handle ??= await openGuardedFile(filePath, { root: allowedRoot });\n    const stats = await handle.stat();\n    if (!stats.isFile()) return unavailable('the file is not a regular file');\n    const named = await fs.lstat(filePath);\n    if (\n      !named.isFile() ||\n      stats.dev !== named.dev ||\n      stats.ino !== named.ino ||\n      (allowedRoot !== undefined && !(await isRealPathInside(allowedRoot, filePath)))\n    ) {\n      return unavailable('the file path changed or leaves its readable directory');\n    }\n    // The extra byte detects growth after stat without an unbounded readFile allocation.\n    raw = Buffer.alloc(MAX_WORKING_BYTES + 1);\n    if (stats.size <= MAX_WORKING_BYTES) {\n      let offset = 0;\n      while (offset < raw.length) {\n        const { bytesRead } = await handle.read(raw, offset, raw.length - offset, offset);\n        if (bytesRead === 0) break;\n        offset += bytesRead;\n      }\n      raw = raw.subarray(0, offset);\n    }\n  } catch {\n    return unavailable('the file no longer exists or cannot be safely read');\n  } finally {\n    if (opened === undefined) await handle?.close();\n  }\n  return workingViewOf(raw);\n}\n\nasync function isInsideRoot(root: string, filePath: string): Promise<boolean> {\n  return isInside(root, filePath) && (await isRealPathInside(root, filePath));\n}\n\nexport class NodeWorkingFiles implements WorkingFilesPort {\n  readWorking(filePath: string, allowedRoot?: string): Promise<FileEditsWorkingView> {\n    return readWorking(filePath, undefined, allowedRoot);\n  }\n\n  isRealPathInside(root: string, candidate: string): Promise<boolean> {\n    return isRealPathInside(root, candidate);\n  }\n\n  async save({ filePath, root, content, expectedHash }: SaveRequest): Promise<SaveOutcome> {\n    const canonical = await fs.realpath(filePath);\n    return fileMutationRunner.forKey(canonical)(async (): Promise<SaveOutcome> => {\n      const handle = await openGuardedFile(filePath, { write: true, root });\n      try {\n        if ((await fs.realpath(filePath)) !== canonical) return { status: 'moved' };\n        const current = await readWorking(filePath, handle, root);\n        if (current.unavailable) return { status: 'unreadable', reason: current.reason ?? 'The file cannot be read.' };\n        if (current.hash !== expectedHash) return { status: 'stale', hash: current.hash };\n        const opened = await handle.stat();\n        const named = await fs.lstat(filePath);\n        if (\n          !opened.isFile() ||\n          opened.nlink !== 1 ||\n          !named.isFile() ||\n          named.nlink !== 1 ||\n          opened.dev !== named.dev ||\n          opened.ino !== named.ino ||\n          (await fs.realpath(filePath)) !== canonical ||\n          !(await isInsideRoot(root, filePath))\n        ) {\n          return { status: 'moved' };\n        }\n        // Keep the descriptor used for the comparison. Never reopen the checked path for writing.\n        await handle.writeFile(content, 'utf8');\n        await handle.truncate(Buffer.byteLength(content, 'utf8'));\n        return { status: 'saved', hash: hashOf(content) };\n      } finally {\n        await handle.close();\n      }\n    });\n  }\n\n  async remove(filePath: string, root: string): Promise<RemoveOutcome> {\n    try {\n      const canonical = await fs.realpath(filePath).catch((error: unknown) => {\n        // A dangling link still needs unlinking. There is no target save to coordinate with.\n        if (hasCode(error, 'ENOENT')) return filePath;\n        throw error;\n      });\n      return await fileMutationRunner.forKey(canonical)(async (): Promise<RemoveOutcome> => {\n        if (!(await isInsideRoot(root, filePath))) return { status: 'outside' };\n        await fs.unlink(filePath);\n        return { status: 'removed' };\n      });\n    } catch (error) {\n      // Already gone is the outcome the caller wanted, so it is not a failure.\n      if (hasCode(error, 'ENOENT')) return { status: 'removed' };\n      return { status: 'failed', reason: describe(error) };\n    }\n  }\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\n/**\n * Remove the state sessions left behind when they never got to clean up.\n *\n * A session clears its own timeline and snapshots on shutdown, which covers the\n * ordinary case and nothing else: a killed process, a crash, or a machine that\n * lost power leaves both behind, and nothing ever looked at the directory\n * again. One week of that filled a real checkout with hundreds of megabytes.\n *\n * Age is the only signal used, because it is the only one that is true from\n * another process. A running session appends as it works, so its timeline is\n * recent; a dead one stops moving at the moment it died.\n */\n\n/**\n * How long state may sit untouched before a later session removes it.\n *\n * Generous on purpose. The cost of waiting is disk, and the cost of being wrong\n * is deleting a live session's history, so this is set far beyond any plausible\n * gap between two appends rather than close to it.\n */\nexport const STATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;\n\nconst TIMELINE_SUFFIX = '.jsonl';\nconst SNAPSHOTS_SUFFIX = '.blobs';\n\nexport interface SweepSessionStateOptions {\n  directory: string;\n  /** The caller's own timeline, which is never a candidate however it looks. */\n  keep?: string;\n  /** Remove the directory itself once nothing is left in it. */\n  removeDirectory?: boolean;\n  now?: number;\n  maxAgeMs?: number;\n}\n\nasync function remove(target: string): Promise<void> {\n  await fs.rm(target, { recursive: true, force: true });\n}\n\n/** The most recent time anything under this session's state moved. */\nasync function lastTouched(paths: readonly string[]): Promise<number | undefined> {\n  let newest: number | undefined;\n  for (const target of paths) {\n    try {\n      const stat = await fs.stat(target);\n      if (newest === undefined || stat.mtimeMs > newest) newest = stat.mtimeMs;\n    } catch {\n      // Not there is not a reason to keep the rest.\n    }\n  }\n  return newest;\n}\n\n/** How many sessions' worth of state was removed. */\nexport async function sweepSessionState(options: SweepSessionStateOptions): Promise<number> {\n  const { directory, keep, removeDirectory = false, now = Date.now(), maxAgeMs = STATE_MAX_AGE_MS } = options;\n  let entries: string[];\n  try {\n    entries = await fs.readdir(directory);\n  } catch {\n    return 0;\n  }\n  const floor = now - maxAgeMs;\n  const timelines = new Set(entries.filter((entry) => entry.endsWith(TIMELINE_SUFFIX)));\n  let removed = 0;\n\n  for (const entry of timelines) {\n    const timelinePath = path.join(directory, entry);\n    if (keep !== undefined && timelinePath === keep) continue;\n    const snapshotsPath = `${timelinePath.slice(0, -TIMELINE_SUFFIX.length)}${SNAPSHOTS_SUFFIX}`;\n    const lockPath = `${timelinePath}.lock`;\n    const touched = await lastTouched([timelinePath, snapshotsPath, lockPath]);\n    if (touched === undefined || touched >= floor) continue;\n    // Content first. A crash between the two leaves a timeline whose snapshots\n    // are gone, which reads as a session whose diffs expired. The other order\n    // leaves a blob tree nothing will ever name again, which is the shape of\n    // the leak this exists to clear.\n    await remove(snapshotsPath);\n    await remove(timelinePath);\n    await remove(lockPath);\n    removed += 1;\n  }\n\n  // A blob tree whose timeline is already gone is exactly what a half-finished\n  // cleanup leaves, and nothing else will ever look for it.\n  for (const entry of entries) {\n    if (!entry.endsWith(SNAPSHOTS_SUFFIX)) continue;\n    if (timelines.has(`${entry.slice(0, -SNAPSHOTS_SUFFIX.length)}${TIMELINE_SUFFIX}`)) continue;\n    const orphan = path.join(directory, entry);\n    const touched = await lastTouched([orphan]);\n    if (touched === undefined || touched >= floor) continue;\n    await remove(orphan);\n  }\n\n  if (removeDirectory) {\n    try {\n      await fs.rmdir(directory);\n    } catch {\n      // Still holding something, so it is not this sweep's to remove.\n    }\n  }\n  return removed;\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { BINARY_SAMPLE_BYTES, MAX_SNAPSHOT_BYTES } from '../../constants/snapshots';\nimport type { SnapshotStorePort } from '../../types/snapshotStore';\n\nexport { MAX_SNAPSHOT_BYTES } from '../../constants/snapshots';\n\n/**\n * Store and read the file content this session's diffs are built from.\n *\n * One technology per adapter. This is where node enters the package; the\n * services that depend on the capability keep importing the port.\n *\n * Snapshots are content-addressed, so a file written twice with the same bytes\n * occupies one blob and the second capture is a hash and an exists check. The\n * whole directory goes when the session's timeline does, which is what keeps\n * this from growing without bound across a machine's lifetime.\n */\n\nconst MISSING_CODES = new Set(['ENOENT', 'ENOTDIR', 'EISDIR', 'ENAMETOOLONG']);\n\nfunction hasCode(error: unknown, codes: ReadonlySet<string>): boolean {\n  return error instanceof Error && 'code' in error && typeof error.code === 'string' && codes.has(error.code);\n}\n\nexport class NodeSnapshotStoreAdapter implements SnapshotStorePort {\n  private directory: string | undefined;\n\n  initialize(directory: string): void {\n    this.directory = directory;\n  }\n\n  async capture(filePath: string): Promise<string | undefined> {\n    let raw: Buffer;\n    try {\n      if ((await fs.stat(filePath)).size > MAX_SNAPSHOT_BYTES) return undefined;\n      raw = await fs.readFile(filePath);\n    } catch (error) {\n      if (hasCode(error, MISSING_CODES)) return undefined;\n      throw error;\n    }\n    if (raw.byteLength > MAX_SNAPSHOT_BYTES) return undefined;\n    if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) return undefined;\n    return this.put(raw.toString('utf8'));\n  }\n\n  async put(content: string): Promise<string> {\n    const hash = createHash('sha256').update(content, 'utf8').digest('hex');\n    const blobPath = path.join(this.requireDirectory(), hash);\n    // An existing blob already holds exactly this content, by construction, so\n    // rewriting it would only cost a write.\n    try {\n      await fs.access(blobPath);\n      return hash;\n    } catch (error) {\n      if (!hasCode(error, MISSING_CODES)) throw error;\n    }\n    await fs.mkdir(this.requireDirectory(), { recursive: true });\n    await fs.writeFile(blobPath, content, 'utf8');\n    return hash;\n  }\n\n  async read(hash: string): Promise<string | undefined> {\n    if (!/^[0-9a-f]{64}$/u.test(hash)) return undefined;\n    try {\n      return await fs.readFile(path.join(this.requireDirectory(), hash), 'utf8');\n    } catch (error) {\n      if (hasCode(error, MISSING_CODES)) return undefined;\n      throw error;\n    }\n  }\n\n  async clear(): Promise<void> {\n    if (this.directory === undefined) return;\n    await fs.rm(this.directory, { recursive: true, force: true });\n  }\n\n  private requireDirectory(): string {\n    if (this.directory === undefined) throw new Error('Snapshot store is not initialized');\n    return this.directory;\n  }\n}\n","import fs, { type FileHandle } from 'node:fs/promises';\n\nimport type { FileEditEntry, FileEditVersion, TimelineEvent } from '../../types/domain';\nimport type { ITimelineStore } from '../../types/timelineStore';\nimport { type AnyTimelineEvent, confirmedChanges, foldEntries, foldVersions, parseTimeline } from '../fileChanges';\n\nconst LOCK_RETRY_MS = 25;\nconst LOCK_RETRIES = 400;\n/**\n * How long a lock file may sit untouched before a waiter treats it as abandoned.\n *\n * An append writes one line, so a holder that has been there for half a minute\n * is a process that died without unlinking. Without this, that one file would\n * block every later append to the same timeline permanently.\n */\nconst LOCK_STALE_MS = 30_000;\n\nfunction hasCode(error: unknown, code: string): boolean {\n  return error instanceof Error && 'code' in error && error.code === code;\n}\n\nexport class TimelineStore implements ITimelineStore {\n  private filePath: string | undefined;\n\n  initialize(filePath: string): void {\n    this.filePath = filePath;\n  }\n\n  async append(event: TimelineEvent): Promise<void> {\n    await this.withLock(async () => fs.appendFile(this.requirePath(), `${JSON.stringify(event)}\\n`, 'utf8'));\n  }\n\n  async list(): Promise<FileEditEntry[]> {\n    // Listing shows what was edited, so a path a command only touched is left out.\n    return foldEntries(confirmedChanges(await this.events()));\n  }\n\n  async versions(filePath: string): Promise<FileEditVersion[]> {\n    // Same bar as the listing above: a file's history must not reintroduce the\n    // touches the list already left out.\n    return foldVersions(confirmedChanges(await this.events()), filePath);\n  }\n\n  async clear(): Promise<void> {\n    try {\n      await fs.unlink(this.requirePath());\n    } catch (error) {\n      if (!hasCode(error, 'ENOENT')) throw error;\n    }\n  }\n\n  /** Every recorded change, or none at all when the session has not written yet. */\n  private async events(): Promise<AnyTimelineEvent[]> {\n    let content: string;\n    try {\n      content = await fs.readFile(this.requirePath(), 'utf8');\n    } catch (error) {\n      if (hasCode(error, 'ENOENT')) return [];\n      throw error;\n    }\n    return parseTimeline(content, (line) =>\n      console.warn(`Ignoring malformed file edit timeline line: ${line.slice(0, 200)}`),\n    );\n  }\n\n  private requirePath(): string {\n    if (!this.filePath) throw new Error('Timeline store is not initialized');\n    return this.filePath;\n  }\n\n  private async withLock<T>(operation: () => Promise<T>): Promise<T> {\n    const lockPath = `${this.requirePath()}.lock`;\n    const lock = await this.acquire(lockPath);\n    try {\n      return await operation();\n    } finally {\n      await lock.close();\n      await this.release(lockPath);\n    }\n  }\n\n  /** Waits for the lock file, breaking one an earlier process left behind. */\n  private async acquire(lockPath: string): Promise<FileHandle> {\n    for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) {\n      try {\n        return await fs.open(lockPath, 'wx');\n      } catch (error) {\n        if (!hasCode(error, 'EEXIST')) throw error;\n        if (await this.breakStale(lockPath)) continue;\n        await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));\n      }\n    }\n    throw new Error(`Timed out acquiring timeline lock ${lockPath}`);\n  }\n\n  /** Whether the lock is now free to take, having removed it when its holder is gone. */\n  private async breakStale(lockPath: string): Promise<boolean> {\n    try {\n      const stats = await fs.stat(lockPath);\n      if (Date.now() - stats.mtimeMs < LOCK_STALE_MS) return false;\n      await fs.unlink(lockPath);\n      return true;\n    } catch (error) {\n      // Already gone, or another waiter broke it first: either way, try again.\n      if (hasCode(error, 'ENOENT')) return true;\n      throw error;\n    }\n  }\n\n  private async release(lockPath: string): Promise<void> {\n    try {\n      await fs.unlink(lockPath);\n    } catch (error) {\n      if (!hasCode(error, 'ENOENT')) console.warn(`Could not remove timeline lock: ${String(error)}`);\n    }\n  }\n}\n","import type { TreeManifest } from '../../types/treeManifest';\n\n/**\n * Directories a working tree fills with output nobody wants listed as an edit.\n *\n * Two kinds live here. Most are the build and dependency trees every checkout\n * grows. The rest are where tooling, including this agent's own, writes while a\n * session runs: a telemetry log under `logs`, a test run's artifacts under\n * `test-results` and `playwright-report`, scratch space under `tmp`, and agent\n * state under `.pi`. A changed path under any of them is dropped by construction\n * rather than judged file by file, because recording it reports the session\n * watching itself.\n */\nexport const IGNORED_DIRECTORIES: ReadonlySet<string> = new Set([\n  '.git',\n  '.hg',\n  '.svn',\n  '.cache',\n  '.gradle',\n  '.next',\n  '.nuxt',\n  '.nx',\n  '.pi',\n  '.pnpm-store',\n  '.turbo',\n  '.venv',\n  '__pycache__',\n  'build',\n  'coverage',\n  'dist',\n  'logs',\n  'node_modules',\n  'out',\n  'playwright-report',\n  'target',\n  'test-results',\n  'tmp',\n  'vendor',\n  'venv',\n]);\n\n/**\n * How a file is summarised. Size and modification time are one stat away;\n * hashing every candidate would turn each comparison into a read of each file.\n */\nexport function fingerprintOf(size: number, modifiedMs: number): string {\n  return `${size}:${modifiedMs}`;\n}\n\n/** The size half of a fingerprint, which only the adapter that wrote it can read. */\nfunction sizeOf(fingerprint: string): string {\n  const separator = fingerprint.indexOf(':');\n  return separator === -1 ? fingerprint : fingerprint.slice(0, separator);\n}\n\n/** Every path added, removed, or modified between two manifests, sorted. */\nexport function changedBetween(before: TreeManifest, after: TreeManifest): string[] {\n  const moved = new Set<string>();\n  for (const [filePath, fingerprint] of after.entries) {\n    if (before.entries.get(filePath) !== fingerprint) moved.add(filePath);\n  }\n  for (const filePath of before.entries.keys()) {\n    if (!after.entries.has(filePath)) moved.add(filePath);\n  }\n  return [...moved].sort();\n}\n\n/** Whether two fingerprints disagree about size; false when either side is absent. */\nexport function sizesDiffer(before: string | undefined, after: string | undefined): boolean {\n  if (before === undefined || after === undefined) return false;\n  return sizeOf(before) !== sizeOf(after);\n}\n","import fs from 'node:fs/promises';\n\nimport type { TreeManifest, TreeManifestPort } from '../../types/treeManifest';\nimport { changedBetween, fingerprintOf, sizesDiffer } from '../manifestComparison';\n\n/**\n * Fingerprints single files with node's fs.\n *\n * One technology per adapter. This is where node enters the package; the\n * services that depend on the capability keep importing the port.\n */\nexport class NodeTreeManifestAdapter implements TreeManifestPort {\n  async fingerprint(filePath: string): Promise<string | undefined> {\n    try {\n      const stat = await fs.stat(filePath);\n      return stat.isFile() ? fingerprintOf(stat.size, stat.mtimeMs) : undefined;\n    } catch {\n      return undefined;\n    }\n  }\n\n  async modifiedAt(filePath: string): Promise<number | undefined> {\n    try {\n      const stat = await fs.stat(filePath);\n      return stat.isFile() ? stat.mtimeMs : undefined;\n    } catch {\n      return undefined;\n    }\n  }\n\n  changed(before: TreeManifest, after: TreeManifest): string[] {\n    return changedBetween(before, after);\n  }\n\n  sizeChanged(before: string | undefined, after: string | undefined): boolean {\n    return sizesDiffer(before, after);\n  }\n}\n","import type { FileEditTool } from './domain';\n\n/**\n * View types shared by this package's hub channel and its web plugin. Wire\n * JSON only, no node types, so the cockpit bundle can carry them; the\n * cockpit receives them as 'file_edits' channel payloads.\n *\n * The channel carries the list alone. One file's diffs and content are large\n * and only wanted once a reader opens the file, so those come from the session\n * API instead (see fileEditsApi.ts).\n */\n\n/** One file this session changed, as the activity dock lists it. */\nexport interface FilesItemView {\n  /** Absolute path, and the identity every API route takes back. */\n  path: string;\n  /** Path relative to the session's working directory, which is what a row shows. */\n  relPath: string;\n  /** The tool behind the most recent change. */\n  tool: FileEditTool;\n  /** When that change happened, epoch milliseconds. */\n  at: number;\n  /** How many changes this session recorded for the file. */\n  count: number;\n  /**\n   * Whether any change captured a baseline, so a diff can be shown at all. A\n   * file found by comparing the tree around a bash call has no \"before\", so it\n   * is listed and readable but never diffed.\n   */\n  diffable: boolean;\n}\n\n/** The frame type the hub publishes and the web plugin claims; declared in the poWeb block too. */\nexport const filesChannelType = 'file_edits';\n\n/** Footer status key whose presence shows the activity group; the extension publishes it. */\nexport const filesStatusKey = 'po-file-edit-files';\n","import type { PoHubChannel, PoHubChannelSource } from '@agimon-ai/po-core/hubChannel';\n\nimport type { FileEditStorage } from '../../types/fileEditStorage';\nimport { filesChannelType, type FilesItemView } from '../../types/webFiles';\n\n/** The two things the channel asks the host for. */\nexport type FilesChannelStorage = Pick<FileEditStorage, 'paths' | 'sessionFiles'>;\n\n/**\n * The changed-files channel consumes snapshots emitted by the owning session's\n * server plugin. Durable timeline reads seed a channel that starts after session\n * startup.\n */\n\nfunction filesPayload(value: unknown): value is { items: FilesItemView[] } {\n  return typeof value === 'object' && value !== null && Array.isArray((value as { items?: unknown }).items);\n}\n\n/**\n * The files data channel: one direct-event subscription per managed session,\n * published as { items } payloads under the 'file_edits' frame type.\n */\nexport function createFilesChannel(storage: FilesChannelStorage): PoHubChannel {\n  return {\n    frameType: filesChannelType,\n    start(host) {\n      const latest = new Map<string, FilesItemView[]>();\n      const subscriptions = new Map<string, () => void>();\n      const channelSource: PoHubChannelSource = {\n        payloadFor(scope) {\n          const items = latest.get(scope.sessionId);\n          return items === undefined ? undefined : { items };\n        },\n        sessionAdded(scope) {\n          subscriptions.get(scope.sessionId)?.();\n          const paths = storage.paths(scope.environment);\n          let current = true;\n          let receivedDirect = false;\n          const unsubscribe = host.directEvents.subscribe(\n            filesChannelType,\n            scope.sessionId,\n            (payload) => {\n              if (!filesPayload(payload)) return;\n              receivedDirect = true;\n              latest.set(scope.sessionId, payload.items);\n              host.publish(scope.sessionId, payload);\n            },\n            { replayLatest: true },\n          );\n          subscriptions.set(scope.sessionId, () => {\n            current = false;\n            unsubscribe();\n          });\n          void (async () => {\n            let items: FilesItemView[] = [];\n            try {\n              const timelinePath = await paths.timelinePath(scope.cwd, paths.sessionKey(scope.sessionId));\n              items = await storage.sessionFiles(timelinePath, scope.cwd);\n            } catch {\n              // The session has no readable state path yet.\n            }\n            if (!current || receivedDirect) return;\n            latest.set(scope.sessionId, items);\n            host.publish(scope.sessionId, { items });\n          })().catch((error: unknown) => host.onNotice(`File-edit channel seed failed: ${String(error)}`));\n        },\n        sessionRemoved(sessionId) {\n          subscriptions.get(sessionId)?.();\n          subscriptions.delete(sessionId);\n          latest.delete(sessionId);\n        },\n        close() {\n          for (const unsubscribe of subscriptions.values()) unsubscribe();\n          subscriptions.clear();\n          latest.clear();\n        },\n      };\n      return channelSource;\n    },\n  };\n}\n","import ignore from 'ignore';\n\nimport type { FilesItemView } from '../../types/webFiles';\n\nfunction matchablePath(relPath: string): string | undefined {\n  const normalized = relPath.replace(/\\\\/gu, '/');\n  if (\n    normalized.length === 0 ||\n    normalized.includes('\\0') ||\n    normalized === '..' ||\n    normalized.startsWith('../') ||\n    normalized.startsWith('/') ||\n    /^[A-Za-z]:\\//u.test(normalized)\n  ) {\n    return undefined;\n  }\n  return normalized;\n}\n\n/**\n * Builds the project's ignore test, or nothing when there are no rules.\n *\n * Shared because the same rules are needed twice: once when deciding what to\n * record, and once when deciding what to list. A caller that built its own\n * matcher would let the two drift apart.\n *\n * The test answers false for anything it cannot safely match, so a path that\n * escapes the project stays visible rather than being hidden by accident.\n */\nexport function createPoIgnoreMatcher(content: string): ((relPath: string) => boolean) | undefined {\n  try {\n    if (content.trim().length === 0) return undefined;\n    const matcher = ignore().add(content);\n    return (relPath: string): boolean => {\n      const candidate = matchablePath(relPath);\n      return candidate !== undefined && matcher.ignores(candidate);\n    };\n  } catch {\n    return undefined;\n  }\n}\n\n/** Applies project-local gitignore rules while keeping unsafe candidates visible. */\nexport function filterPoIgnoredFiles(items: FilesItemView[], content: string): FilesItemView[] {\n  const ignored = createPoIgnoreMatcher(content);\n  if (ignored === undefined) return items;\n  return items.filter((item) => !ignored(item.relPath));\n}\n","import path from 'node:path';\n\nimport type { FilesItemView } from '../../types/webFiles';\nimport { confirmedChanges, foldEntries, foldVersions, isDiffable, parseTimeline } from '../fileChanges';\nimport { filterPoIgnoredFiles } from '../poIgnore';\n\nexport interface SessionFileRowsInput {\n  /** The timeline file's text. */\n  readonly content: string;\n  readonly cwd: string;\n  /** Whether the file is still there to be opened. */\n  readonly exists: (filePath: string) => Promise<boolean>;\n  /** The project's `.poignore` text. Throws when it cannot be read, which leaves every row in. */\n  readonly readPoIgnore: () => Promise<string>;\n}\n\n/**\n * Presents a session's timeline as the rows the dock lists.\n *\n * A file the session changed and then removed is left out, and so is a path a\n * bash call only touched: a command that moves a modification time without\n * changing a byte is not an edit, and listing it buries the ones that are. The\n * dock is a list of things to open, and a row that can only ever answer \"this\n * is gone\" is a dead end; the timeline still holds the change, so a tab already\n * open on the file keeps working and says so.\n */\nexport async function sessionFileRows({\n  content,\n  cwd,\n  exists,\n  readPoIgnore,\n}: SessionFileRowsInput): Promise<FilesItemView[]> {\n  const events = confirmedChanges(parseTimeline(content));\n  const entries = foldEntries(events);\n  const present = await Promise.all(entries.map((entry) => exists(entry.path)));\n  const items = entries\n    .filter((_entry, index) => present[index])\n    .map((entry) => ({\n      path: entry.path,\n      relPath: path.relative(cwd, entry.path) || entry.path,\n      tool: entry.tool,\n      at: entry.at,\n      count: entry.count,\n      diffable: isDiffable(foldVersions(events, entry.path)),\n    }));\n\n  try {\n    return filterPoIgnoredFiles(items, await readPoIgnore());\n  } catch {\n    return items;\n  }\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { PoHubChannel } from '@agimon-ai/po-core/hubChannel';\n\nimport type { FilesItemView } from '../../types/webFiles';\nimport { FileEditPaths } from '../fileEditPaths';\nimport { createFilesChannel as createChannel } from '../filesChannel';\nimport { sessionFileRows } from '../sessionFileRows';\n\n/** Whether the file is still there to be opened. */\nasync function stillExists(filePath: string): Promise<boolean> {\n  try {\n    return (await fs.stat(filePath)).isFile();\n  } catch {\n    return false;\n  }\n}\n\n/** Reads one session's timeline from Node's files and presents it as the rows the dock lists. */\nexport async function readSessionFiles(timelinePath: string, cwd: string): Promise<FilesItemView[]> {\n  let content: string;\n  try {\n    content = await fs.readFile(timelinePath, 'utf8');\n  } catch {\n    return [];\n  }\n  return sessionFileRows({\n    content,\n    cwd,\n    exists: stillExists,\n    readPoIgnore: () => fs.readFile(path.join(cwd, '.poignore'), 'utf8'),\n  });\n}\n\n/** The files data channel over Node's real files, for a host that gives the package no file system. */\nexport function createFilesChannel(): PoHubChannel {\n  return createChannel({\n    paths: (environment) => new FileEditPaths(environment),\n    sessionFiles: readSessionFiles,\n  });\n}\n","import fs from 'node:fs/promises';\nimport os from 'node:os';\n\nimport { readPoConfig, resolvePlanningPlansDirectory } from '@agimon-ai/po-config';\nimport { createNodePlatform } from '@agimon-ai/po-core/nodePlatform';\nimport { BACKGROUND_CONTEXT, type FileSystem } from '@agimon-ai/po-core/platform';\n\nimport type { FileEditStorage } from '../../types/fileEditStorage';\nimport type { PresenceFiles } from '../../types/presenceFiles';\nimport { FileEditPaths } from '../fileEditPaths';\nimport { NodeGitStatusAdapter } from '../gitStatus';\nimport { NodeWorkingFiles } from '../nodeWorkingFiles';\nimport { sweepSessionState } from '../sessionStateSweep';\nimport { NodeSnapshotStoreAdapter } from '../snapshotStore';\nimport { TimelineStore } from '../timelineStore';\nimport { NodeTreeManifestAdapter } from '../treeManifest';\nimport { readSessionFiles } from '../webFilesChannel';\n\n/**\n * The storage a session's file history uses on Node: the real file system,\n * read directly, with the cross-process lock a subagent child's appends need.\n *\n * The edge build replaces this module with `index.edge.ts`, which reads the\n * file system the host injects. On Node, an injected file system is used for\n * config reads when provided, falling back to `createNodePlatform().env(cwd)`.\n */\n\nconst nodePresenceFiles: PresenceFiles = {\n  isFile: async (filePath) => (await fs.stat(filePath).catch(() => undefined))?.isFile() === true,\n  realpath: (filePath) => fs.realpath(filePath).catch(() => undefined),\n  read: (filePath) => fs.readFile(filePath).catch(() => undefined),\n};\n\n/**\n * The plans directory Plan mode writes to, resolved the way Plan resolves it, so\n * a plan link in the transcript opens in the file view. A config that cannot be\n * read admits nothing extra rather than failing the preview.\n */\nasync function plansRoots(\n  files: FileSystem | undefined,\n  cwd: string,\n  environment: Readonly<Record<string, string | undefined>>,\n  homeDirectory?: string,\n): Promise<string[]> {\n  const home = homeDirectory ?? environment.HOME ?? os.homedir();\n  const fs = files ?? createNodePlatform().env(cwd);\n  try {\n    const config = await readPoConfig(fs, cwd, BACKGROUND_CONTEXT, {\n      environment,\n      homeDirectory: home,\n    });\n    return [resolvePlanningPlansDirectory(config.modes?.planning?.plansDirectory, cwd, home)];\n  } catch {\n    return [];\n  }\n}\n\nexport function createFileEditStorage(fileSystem?: FileSystem): FileEditStorage {\n  return {\n    paths: (environment) => new FileEditPaths(environment),\n    timeline: () => new TimelineStore(),\n    snapshots: () => new NodeSnapshotStoreAdapter(),\n    manifests: () => new NodeTreeManifestAdapter(),\n    git: () => new NodeGitStatusAdapter(),\n    workingFiles: () => new NodeWorkingFiles(),\n    presenceFiles: () => nodePresenceFiles,\n    sessionFiles: readSessionFiles,\n    // Resolved per request, so a config change applies without restarting the session.\n    readableRoots:\n      ({ cwd, environment, homeDirectory }) =>\n      () =>\n        plansRoots(fileSystem, cwd, environment, homeDirectory),\n    sweepAbandoned: (directory, keep) => sweepSessionState({ directory, keep }),\n    clearOnClose: true,\n  };\n}\n","import path from 'node:path';\n\nimport type { PoChildSessionHooks } from '@agimon-ai/po-core/childSession';\nimport type { PoHeadlessContent, PoHeadlessHook } from '@agimon-ai/po-core/headless';\nimport type { PoEditPresence } from '@agimon-ai/po-core/packageApi';\nimport { parseFileHeader } from '@agimon-ai/po-hashline';\nimport { computeFileTag, displayPath, resolveInputPath, resolveReadInputPath } from '@agimon-ai/po-hashline/files';\n\nimport { PRESENCE_NOTE_GUIDANCE, PRESENCE_NOTE_TITLE } from '../../constants/editPresence';\nimport type { PresenceFiles } from '../../types/presenceFiles';\nimport { createFileEditStorage } from '../fileEditStorage';\nimport type { PresenceAgent, PresenceContent, PresenceNote, PresenceToolCall } from './type';\n\nconst PATH_TOOLS = new Set(['read', 'edit', 'write']);\nconst EDIT_TOOLS = new Set(['edit', 'write']);\nconst MAX_GREP_FILES = 50;\nconst MAX_NOTE_LINES = 10;\nconst MINUTE_MS = 60_000;\nconst SHORT_ID_LENGTH = 8;\n/** Pi's built-in grep prints match rows as `relative/path:line: text`. */\nconst PI_GREP_ROW = /^(.+?):(\\d+): /u;\n\nfunction stringArg(args: unknown, key: string): string | undefined {\n  if (typeof args !== 'object' || args === null) return undefined;\n  const value = (args as Record<string, unknown>)[key];\n  return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction textOf(content: readonly PresenceContent[]): string {\n  return content\n    .map((part) => (part.type === 'text' && 'text' in part && typeof part.text === 'string' ? part.text : ''))\n    .join('\\n');\n}\n\nasync function grepFiles(call: PresenceToolCall<PresenceContent>, files: PresenceFiles): Promise<string[]> {\n  const lines = textOf(call.content).split('\\n');\n  // po-grep groups rows under `@file <path relative to cwd>#<tag>` headers.\n  const headers = lines.flatMap((line) => {\n    const header = parseFileHeader(line);\n    return header === undefined ? [] : [resolveInputPath(header.path, call.cwd)];\n  });\n  if (headers.length > 0) return [...new Set(headers)].slice(0, MAX_GREP_FILES);\n  // ponytail: Pi grep rows are parsed with a lazy `path:line: ` match, so a path containing `:<digits>: `\n  // is misread. Upgrade path: ask Pi for structured match details.\n  const rows = lines.flatMap((line) => {\n    const match = PI_GREP_ROW.exec(line)?.[1];\n    return match === undefined ? [] : [match];\n  });\n  if (rows.length === 0) return [];\n  const searchPath = resolveInputPath(stringArg(call.args, 'path') ?? '.', call.cwd);\n  // A single-file search prints only the basename, so the searched path is the file.\n  if (await files.isFile(searchPath)) return [searchPath];\n  return [...new Set(rows.map((row) => path.resolve(searchPath, row)))].slice(0, MAX_GREP_FILES);\n}\n\nasync function touchedFiles(call: PresenceToolCall<PresenceContent>, files: PresenceFiles): Promise<string[]> {\n  if (PATH_TOOLS.has(call.toolName)) {\n    const input = stringArg(call.args, 'path');\n    return input === undefined ? [] : [await resolveReadInputPath(input, call.cwd)];\n  }\n  return call.toolName === 'grep' ? grepFiles(call, files) : [];\n}\n\nfunction ago(elapsed: number): string {\n  const minutes = Math.floor(elapsed / MINUTE_MS);\n  return minutes < 1 ? 'under 1m ago' : `${minutes}m ago`;\n}\n\nfunction renderNote(lines: readonly string[]): string {\n  const shown = lines.slice(0, MAX_NOTE_LINES);\n  const more = lines.length - shown.length;\n  return [PRESENCE_NOTE_TITLE, ...shown, ...(more > 0 ? [`- and ${more} more`] : []), PRESENCE_NOTE_GUIDANCE].join(\n    '\\n',\n  );\n}\n\n/**\n * Notes live editors of the files a tool call touched, then records the caller's own successful edit.\n * Returns the content with one note appended, or undefined when there is nothing to add, so callers\n * never rewrite a result needlessly.\n */\nexport async function observePresence<TContent extends PresenceContent>(\n  presence: PoEditPresence,\n  agent: PresenceAgent,\n  call: PresenceToolCall<TContent>,\n  now: number = Date.now(),\n  files: PresenceFiles = createFileEditStorage().presenceFiles(),\n): Promise<(TContent | PresenceNote)[] | undefined> {\n  const recording = EDIT_TOOLS.has(call.toolName) && !call.isError;\n  const lines: string[] = [];\n  for (const file of await touchedFiles(call, files)) {\n    const real = await files.realpath(file);\n    if (real === undefined) continue;\n    const others = presence.touch(real, agent);\n    let bytes: Uint8Array | undefined;\n    if (others.length > 0) {\n      bytes = await files.read(real);\n      const current = bytes === undefined ? undefined : computeFileTag(bytes);\n      const shown = displayPath(file, call.cwd);\n      for (const entry of others) {\n        const state = entry.tag === current ? 'unchanged' : 'changed';\n        lines.push(`- ${shown}: ${entry.agent.label()}, ${ago(now - entry.at)}, file ${state} since their edit.`);\n      }\n    }\n    if (recording) {\n      bytes ??= await files.read(real);\n      if (bytes !== undefined) presence.record(real, { agent, tag: computeFileTag(bytes), at: now });\n    }\n  }\n  if (lines.length === 0) return undefined;\n  return [...call.content, { type: 'text', text: renderNote(lines) }];\n}\n\nexport interface SessionPresenceOptions {\n  /** The hub's workspace-scoped Cordis service. */\n  readonly presence: PoEditPresence;\n  readonly sessionId: string;\n  readonly cwd: string;\n  readonly workflowStep: boolean;\n  readonly isLive: () => boolean;\n  /** Team names for child runs. Undefined without a team layer. */\n  readonly labelFor: (runId: string) => string | undefined;\n  readonly onError?: (error: unknown) => void;\n  /** The host's files; defaults to the ones this build runs on. */\n  readonly files?: PresenceFiles;\n}\n\nexport interface SessionPresence {\n  readonly toolResult: PoHeadlessHook<'tool_result'>;\n  readonly childHooks: PoChildSessionHooks;\n  dispose(): void;\n}\n\n/** Edit presence for one hub session and the in-process children it spawns. */\nexport function createSessionPresence(options: SessionPresenceOptions): SessionPresence {\n  const { sessionId, presence } = options;\n  const sessionAgent: PresenceAgent = {\n    key: `session:${sessionId}`,\n    label: () => `session ${sessionId}${options.workflowStep ? ' (workflow step)' : ''}`,\n    contact: sessionId,\n    isLive: options.isLive,\n  };\n  // Presence is advisory: a failure must never change the tool result it observes.\n  const safely = async <T>(work: () => Promise<T | undefined>): Promise<T | undefined> => {\n    try {\n      return await work();\n    } catch (error) {\n      options.onError?.(error);\n      return undefined;\n    }\n  };\n  const toolResult: PoHeadlessHook<'tool_result'> = {\n    event: 'tool_result',\n    async handle(event, execution) {\n      const toolName = event.toolName;\n      if (execution.sessionId !== sessionId || typeof toolName !== 'string' || !Array.isArray(event.content)) return;\n      const content = event.content as PoHeadlessContent[];\n      const next = await safely(() =>\n        observePresence(\n          presence,\n          sessionAgent,\n          {\n            toolName,\n            args: event.args,\n            content,\n            isError: event.isError === true,\n            cwd: execution.cwd,\n          },\n          undefined,\n          options.files,\n        ),\n      );\n      return next === undefined ? undefined : { content: next };\n    },\n  };\n  const childHooks: PoChildSessionHooks = {\n    bind(scope) {\n      const { runId, parentSessionId, agent } = scope.request;\n      const child: PresenceAgent = {\n        key: `run:${runId}`,\n        label: () =>\n          `${options.labelFor(runId) ?? `${agent} (run ${runId.slice(0, SHORT_ID_LENGTH)})`} (subagent of session ${parentSessionId})`,\n        contact: parentSessionId,\n        isLive: () => !scope.signal.aborted,\n      };\n      return {\n        beforeTool: () => undefined,\n        async afterTool(event) {\n          const next = await safely(() =>\n            observePresence(\n              presence,\n              child,\n              {\n                toolName: event.toolName,\n                args: event.args,\n                content: event.content,\n                isError: event.isError,\n                cwd: scope.request.cwd || options.cwd,\n              },\n              undefined,\n              options.files,\n            ),\n          );\n          return next === undefined ? undefined : { content: next };\n        },\n        dispose: async () => presence.forget(child.key),\n      };\n    },\n  };\n  return { toolResult, childHooks, dispose: () => presence.forget(sessionAgent.key) };\n}\n","import path from 'node:path';\n\n/**\n * The files a bash command names as its own outputs, read from the command text.\n *\n * Knowingly partial: a script the command runs can write files its text never\n * names, and the git comparison catches those instead. What this does find is\n * read before the command runs, so it gets a real baseline and a real diff.\n *\n * ponytail: a hand-rolled tokenizer, not a shell. Heredoc bodies, functions and\n * nested quoting are read as plain words; a wrong guess costs one file read,\n * because an unchanged file is never recorded. Upgrade to a real parser only if\n * a missed target is reported.\n */\n\ninterface Token {\n  op: boolean;\n  value: string;\n}\n\nconst SEPARATOR = ';';\n/** `>&2` and `2>&1` duplicate a descriptor and name no file. */\nconst DUPLICATE = '>&';\n/** Words a shell would expand: what they name is unknowable from the text. */\nconst EXPANDS = /[$`*?{}()<>]/u;\nconst WRITE_ARGUMENTS = new Set(['tee', 'touch', 'rm', 'truncate']);\nconst WRITE_DESTINATION = new Set(['cp', 'mv', 'install']);\n\nfunction tokens(command: string): Token[] {\n  const out: Token[] = [];\n  let word = '';\n  let started = false;\n  let quote: string | undefined;\n  const flush = () => {\n    if (started) out.push({ op: false, value: word });\n    word = '';\n    started = false;\n  };\n  for (let index = 0; index < command.length; index += 1) {\n    const character = command[index]!;\n    const next = command[index + 1];\n    if (quote !== undefined) {\n      if (character === quote) quote = undefined;\n      else if (character === '\\\\' && quote === '\"' && next !== undefined) word += command[++index];\n      else word += character;\n    } else if (character === \"'\" || character === '\"') {\n      quote = character;\n      started = true;\n    } else if (character === '\\\\' && next !== undefined) {\n      word += command[++index];\n      started = true;\n    } else if (character === '&' && next === '>') {\n      flush();\n      word = '&';\n      started = true;\n    } else if (character === '>') {\n      // A bare descriptor right before it belongs to the operator: 2>, &>.\n      const prefix = started && /^(?:\\d|&)$/u.test(word) ? word : '';\n      if (prefix) {\n        word = '';\n        started = false;\n      } else flush();\n      let operator = `${prefix}>`;\n      if (command[index + 1] === '>') operator += command[++index];\n      if (command[index + 1] === '&') {\n        while (/[&\\d-]/u.test(command[index + 1] ?? '')) index += 1;\n        operator = DUPLICATE;\n      }\n      out.push({ op: true, value: operator });\n    } else if (character === ';' || character === '|' || character === '&' || character === '\\n') {\n      flush();\n      if ((character === '&' || character === '|') && (next === character || next === '&')) index += 1;\n      out.push({ op: true, value: SEPARATOR });\n    } else if (/\\s/u.test(character)) flush();\n    else {\n      word += character;\n      started = true;\n    }\n  }\n  flush();\n  return out;\n}\n\n/** The targets one simple command writes through its arguments. */\nfunction argumentTargets(words: readonly string[]): string[] {\n  const start = words.findIndex((word) => !/^\\w+=/u.test(word));\n  if (start === -1) return [];\n  const program = path.basename(words[start]!);\n  const rest = words.slice(start + 1);\n  const operands = rest.filter((word) => word !== '' && !word.startsWith('-'));\n  if (WRITE_ARGUMENTS.has(program)) return operands;\n  if (WRITE_DESTINATION.has(program)) return operands.length >= 2 ? [operands.at(-1)!] : [];\n  if (program === 'sed' && rest.some((word) => word.startsWith('-i') || word === '--in-place')) {\n    // The script is the first operand, unless -e or -f gave it as an option's value.\n    if (!rest.some((word) => word === '-e' || word === '-f')) return operands.slice(1);\n    return rest.filter(\n      (word, index) => word !== '' && !word.startsWith('-') && rest[index - 1] !== '-e' && rest[index - 1] !== '-f',\n    );\n  }\n  if (program === 'git' && (operands[0] === 'checkout' || operands[0] === 'restore')) {\n    const separator = rest.indexOf('--');\n    if (separator !== -1) return rest.slice(separator + 1);\n    return operands[0] === 'restore' ? operands.slice(1) : [];\n  }\n  return [];\n}\n\n/** Absolute paths of the files `command`, run in `cwd`, names as outputs. */\nexport function bashTargets(command: string, cwd: string): string[] {\n  const named = new Set<string>();\n  const add = (word: string) => {\n    if (word === '' || word.startsWith('-') || word.startsWith('~') || EXPANDS.test(word)) return;\n    if (word.startsWith('/dev/')) return;\n    named.add(path.resolve(cwd, word));\n  };\n  let words: string[] = [];\n  const list = tokens(command);\n  for (let index = 0; index < list.length; index += 1) {\n    const token = list[index]!;\n    if (!token.op) words.push(token.value);\n    else if (token.value === SEPARATOR) {\n      argumentTargets(words).forEach(add);\n      words = [];\n    } else if (token.value !== DUPLICATE && list[index + 1]?.op === false) add(list[++index]!.value);\n  }\n  argumentTargets(words).forEach(add);\n  return [...named];\n}\n","import path from 'node:path';\n\nimport type { FileEditTool, TimelineEvent } from '../../types/domain';\nimport type { IEditTracker } from '../../types/editTracker';\nimport type { GitStatusPort } from '../../types/gitStatus';\nimport type { SnapshotStorePort } from '../../types/snapshotStore';\nimport type { ITimelineStore } from '../../types/timelineStore';\nimport type { TreeManifest, TreeManifestPort } from '../../types/treeManifest';\nimport { bashTargets } from '../bashTargets';\nimport { lineDiff, lineDiffFromEmpty } from '../lineDiff';\nimport { IGNORED_DIRECTORIES } from '../manifestComparison';\n\nconst EDIT_TOOL = 'edit';\nconst WRITE_TOOL = 'write';\nconst BASH_TOOL = 'bash';\n/** Code mode scripts can write files like a shell can, so they get the same git comparison. */\nconst EXEC_TOOL = 'exec';\n\n/**\n * Records what the session changed, and captures enough of it to be diffed.\n *\n * Three mechanisms, because none is enough alone, and none walks the tree.\n * `edit` and `write` name their file in the call arguments, so the content is\n * read before the tool runs and both sides of the change are known exactly. A\n * `bash` command that names its outputs (`> f`, `tee f`, `sed -i f`, `rm f`)\n * gets the same treatment from its text. Whatever a command writes without\n * naming it, through a script or a build, is found by asking git which files\n * are dirty either side of the call; outside a repository it goes unseen.\n *\n * A git-found path is recorded without a baseline, because it was only\n * identified after it had already changed. That is a real limit and the wire\n * carries it as `origin: 'scan'` rather than pretending a diff exists.\n *\n * A manifest compares size and modification time, so it answers whether a file\n * differs, never when it moved. A path a previous session left dirty, or one a\n * checkout or an install rewrote, differs exactly like a path the command just\n * wrote. So a candidate is called verified only when something actually proves\n * its bytes moved: it appeared, it vanished, its recorded size differs, or its\n * content hash differs from one this session already took. Absence of proof is\n * not proof, so a candidate that shows none of those is still recorded, because\n * the timeline is the evidence, but it goes out unverified and every surface\n * leaves it out.\n *\n * ponytail: a tracked file a script deletes without naming it is not seen, since\n * the manifest only fingerprints files that exist. Carry a deletion marker in\n * the manifest if those deletions need to show.\n */\ninterface PendingEdit {\n  tool: FileEditTool;\n  filePath: string;\n  before: string | undefined;\n  /**\n   * Whether the file was there when the call began. A missing `before` cannot\n   * say on its own: content is left uncaptured both for a file that does not\n   * exist and for one too large or too binary to store.\n   */\n  existed: boolean;\n}\n\nfunction objectValue(value: unknown, key: string): string | undefined {\n  if (!value || typeof value !== 'object') return undefined;\n  const found = (value as Record<string, unknown>)[key];\n  return typeof found === 'string' ? found : undefined;\n}\n\nexport interface EditTrackerOptions {\n  /** Injectable so a test can pin the recorded timestamps. */\n  now?: () => number;\n  /**\n   * Decides whether a first-seen scan candidate actually changed. Optional:\n   * without it the tracker keeps recording every candidate it cannot disprove.\n   */\n  git?: GitStatusPort;\n  /**\n   * Told when a deferred comparison fails. Required: the chain carries on\n   * regardless, so this is the only place the failure becomes visible. It must\n   * not throw, or every later call waits on a rejected chain.\n   */\n  onScanFailed: (error: unknown) => void;\n}\n\n/**\n * How far before a call started a write may claim to have happened and still be\n * attributed to it. A working tree can sit on a filesystem that stores whole\n * seconds, which floors a write made just after the call began to a stamp just\n * before it, and the cost of being generous here is one second of the staleness\n * this check exists to remove.\n */\nconst MODIFIED_TOLERANCE_MS = 1000;\n\nexport class EditTracker implements IEditTracker {\n  private readonly pending = new Map<string, PendingEdit>();\n  /** The files each in-flight bash call named in its text, read before it ran. */\n  private readonly named = new Map<string, PendingEdit[]>();\n  /** Start time per in-flight bash call, so its end knows what it may claim. */\n  private readonly bracketed = new Map<string, number>();\n  /**\n   * The watched files as this tracker last saw them. A bash call compares\n   * against it and then replaces it, so a change made between calls is still\n   * noticed on the next one.\n   */\n  private manifest: TreeManifest | undefined;\n  /**\n   * This package's own storage, which must never be reported. The timeline and\n   * its snapshots can land inside the tree being watched, and recording them\n   * would make every change cause another one.\n   */\n  private excluded: readonly string[] = [];\n  /**\n   * The project's own ignore rules. A path the project disowns is not worth a\n   * git call, a read, or a stored copy of its content, so it is dropped before\n   * it costs any of them.\n   */\n  private isIgnored: ((filePath: string) => boolean) | undefined;\n  /**\n   * The last content hash this session saw per path, from either mechanism.\n   * A candidate whose hash has not moved was touched, not edited.\n   */\n  private readonly contents = new Map<string, string>();\n  private readonly now: () => number;\n  private readonly git: GitStatusPort | undefined;\n  private readonly onScanFailed: (error: unknown) => void;\n  /**\n   * The scan deferred by the last bash call. Every bracket joins this chain, so\n   * at most one comparison runs at a time and each one sees the baseline the\n   * previous one left behind.\n   */\n  private scanning: Promise<void> = Promise.resolve();\n\n  constructor(\n    private readonly timeline: ITimelineStore,\n    private readonly snapshots: SnapshotStorePort,\n    private readonly manifests: TreeManifestPort,\n    options: EditTrackerOptions,\n  ) {\n    this.now = options.now ?? Date.now;\n    this.git = options.git;\n    this.onScanFailed = options.onScanFailed;\n  }\n\n  /**\n   * Forgets the previous session's tree so a new one does not inherit its\n   * baseline, and takes the paths this session's own bookkeeping occupies.\n   */\n  reset(options: { exclude?: readonly string[]; isIgnored?: (filePath: string) => boolean } = {}): void {\n    this.pending.clear();\n    this.named.clear();\n    this.bracketed.clear();\n    this.contents.clear();\n    this.manifest = undefined;\n    this.scanning = Promise.resolve();\n    this.excluded = options.exclude ?? [];\n    this.isIgnored = options.isIgnored;\n  }\n\n  /**\n   * Awaits a scan still running in the background. A caller that is about to\n   * clear the timeline needs this, or the scan appends after the clear.\n   */\n  async flush(): Promise<void> {\n    await this.scanning;\n  }\n  async start(id: string, tool: string, args: unknown, cwd: string): Promise<boolean> {\n    // A deferred scan still owns the baseline manifest, so it settles before\n    // this bracket reads or replaces it.\n    await this.scanning;\n    if (tool === EDIT_TOOL || tool === WRITE_TOOL) {\n      const supplied = objectValue(args, 'path');\n      if (!supplied) return false;\n      this.pending.set(id, await this.prepare(tool, path.resolve(cwd, supplied)));\n      return true;\n    }\n    if (tool !== BASH_TOOL && tool !== EXEC_TOOL) return false;\n    // Read before the baseline, which is the one thing here that can take long\n    // enough to matter: a write that races it belongs to this call.\n    this.bracketed.set(id, this.now());\n    const command = tool === BASH_TOOL ? objectValue(args, 'command') : undefined;\n    if (command !== undefined) {\n      const targets = bashTargets(command, cwd).filter((filePath) => this.watched(cwd, filePath));\n      this.named.set(id, await Promise.all(targets.map((filePath) => this.prepare(BASH_TOOL, filePath))));\n    }\n    // The first bash call of a session has nothing to compare against, so it\n    // pays for the baseline; every later call reuses the previous end.\n    this.manifest ??= await this.takeManifest(cwd);\n    return true;\n  }\n\n  /**\n   * Reads a named file before the call that may change it. The fingerprint is\n   * the only thing that tells a file being created from one whose content could\n   * not be captured, because a capture answers undefined for either.\n   */\n  private async prepare(tool: FileEditTool, filePath: string): Promise<PendingEdit> {\n    const [before, fingerprint] = await Promise.all([\n      this.snapshots.capture(filePath),\n      this.manifests.fingerprint(filePath),\n    ]);\n    return { tool, filePath, before, existed: fingerprint !== undefined };\n  }\n\n  async end(id: string, isError: boolean, cwd: string): Promise<void> {\n    const pending = this.pending.get(id);\n    this.pending.delete(id);\n    const startedAt = this.bracketed.get(id);\n    this.bracketed.delete(id);\n    const named = this.named.get(id) ?? [];\n    this.named.delete(id);\n    if (pending) {\n      // A failed edit or write never landed, and its arguments named the file,\n      // so there is nothing left to look for.\n      if (!isError) await this.recordTool(pending);\n      return;\n    }\n    // A failed command may still have written before it failed. Skipping the\n    // comparison would leave the baseline stale and hand those writes to\n    // whichever call closes next.\n    if (startedAt === undefined) return;\n    // Pi awaits this hook before it hands the tool result back to the model.\n    // Deferring the work onto the chain moves its cost into the model's own\n    // thinking time instead of the user's wait; start() joins the same chain,\n    // so ordering still holds.\n    this.scanning = this.scanning.then(async () => {\n      try {\n        for (const target of named) {\n          // An existing file read before the call diffs exactly, and a file that\n          // did not exist and does now was created. One that existed but could\n          // not be read has no baseline to prove a guessed target moved, so it is\n          // left to the git comparison and its checks.\n          const recordable = target.existed\n            ? target.before !== undefined\n            : (await this.manifests.fingerprint(target.filePath)) !== undefined;\n          if (recordable) await this.recordTool(target);\n        }\n        await this.recordScan(cwd, startedAt);\n      } catch (error) {\n        // One failed scan must not poison the chain for every later call, so it\n        // is reported rather than rethrown.\n        this.onScanFailed(error);\n      }\n    });\n  }\n\n  /** A file named before the call, by `edit`, `write` or a bash command's text, read on both sides of it. */\n  private async recordTool(pending: PendingEdit): Promise<void> {\n    const after = await this.snapshots.capture(pending.filePath);\n    const created = !pending.existed;\n    const counts = await this.countChanges(pending.before, after, created);\n    if (after !== undefined) this.contents.set(pending.filePath, after);\n    await this.append({\n      version: 2,\n      path: pending.filePath,\n      tool: pending.tool,\n      at: this.now(),\n      origin: 'tool',\n      ...(pending.before === undefined ? {} : { before: pending.before }),\n      ...(after === undefined ? {} : { after }),\n      ...(created ? { created: true } : {}),\n      ...counts,\n    });\n    // The tool already accounted for this path, so the next bash comparison\n    // must not report it a second time under its own name.\n    await this.remember(pending.filePath);\n  }\n\n  /**\n   * Whether a path is worth watching: inside the session's tree, outside this\n   * package's own storage and the directories builds and tooling fill, and not\n   * disowned by the project.\n   */\n  private watched(cwd: string, filePath: string): boolean {\n    const relative = path.relative(cwd, filePath);\n    if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) return false;\n    if (this.excluded.some((entry) => filePath === entry || filePath.startsWith(`${entry}${path.sep}`))) return false;\n    if (relative.split(path.sep).some((segment) => IGNORED_DIRECTORIES.has(segment))) return false;\n    return this.isIgnored === undefined || !this.isIgnored(filePath);\n  }\n\n  /**\n   * Fingerprints what git calls dirty under `cwd`, plus the paths already being\n   * followed, so a file reverted to clean still shows as moved. Outside a\n   * repository it holds only what it carries.\n   */\n  private async takeManifest(cwd: string, carried: Iterable<string> = []): Promise<TreeManifest> {\n    const paths = new Set(carried);\n    for (const filePath of (await this.git?.dirty(cwd)) ?? []) if (this.watched(cwd, filePath)) paths.add(filePath);\n    const entries = new Map<string, string>();\n    for (const filePath of paths) {\n      const fingerprint = await this.manifests.fingerprint(filePath);\n      if (fingerprint !== undefined) entries.set(filePath, fingerprint);\n    }\n    return { entries };\n  }\n\n  /** Whatever a bash call actually edited, however the command wrote it. */\n  private async recordScan(cwd: string, startedAt: number): Promise<void> {\n    const before = this.manifest;\n    if (before === undefined) return;\n    const after = await this.takeManifest(cwd, before.entries.keys());\n    this.manifest = after;\n    const disowned = this.isIgnored;\n    const named = this.manifests\n      .changed(before, after)\n      .filter((filePath) => disowned === undefined || !disowned(filePath));\n    const candidates = await this.writtenDuring(named, startedAt);\n    if (candidates.length === 0) return;\n    const unchanged = await this.unchangedInGit(cwd, candidates);\n    for (const filePath of candidates) {\n      const known = this.contents.get(filePath);\n      // Asked before the file is read: a path git vouches for is worth neither\n      // the read nor the stored copy that reading it leaves behind.\n      if (known === undefined && unchanged.has(filePath)) continue;\n      const beforePrint = before.entries.get(filePath);\n      const afterPrint = after.entries.get(filePath);\n      // A path that is gone has nothing to read, and reading it back would only\n      // confirm that.\n      const captured = afterPrint === undefined ? undefined : await this.snapshots.capture(filePath);\n      if (captured !== undefined) this.contents.set(filePath, captured);\n      // The bytes are the ones this session already recorded: the call moved the\n      // modification time and nothing else.\n      if (captured !== undefined && captured === known) continue;\n      const proven =\n        beforePrint === undefined ||\n        afterPrint === undefined ||\n        this.manifests.sizeChanged(beforePrint, afterPrint) ||\n        (known !== undefined && captured !== undefined && captured !== known);\n      await this.append({\n        version: 2,\n        path: filePath,\n        tool: BASH_TOOL,\n        at: this.now(),\n        origin: 'scan',\n        ...(proven ? { verified: true } : {}),\n        ...(captured === undefined ? {} : { after: captured }),\n      });\n    }\n  }\n\n  /**\n   * Narrows candidates to the ones that could have been written by the call\n   * being closed.\n   *\n   * This is what keeps a working tree that was already dirty out of the list. A\n   * file whose bytes were last written before the call began was differed by\n   * something else, whatever moved its fingerprint. A file that is no longer\n   * there has no time to read and a delete is a change the call may well have\n   * made, so it stays a candidate.\n   */\n  private async writtenDuring(candidates: readonly string[], startedAt: number): Promise<string[]> {\n    const floor = startedAt - MODIFIED_TOLERANCE_MS;\n    const written: string[] = [];\n    for (const filePath of candidates) {\n      const modifiedAt = await this.manifests.modifiedAt(filePath);\n      if (modifiedAt === undefined || modifiedAt >= floor) written.push(filePath);\n    }\n    return written;\n  }\n\n  /** Which candidates git tracks and reports as untouched; empty when it cannot say. */\n  private async unchangedInGit(cwd: string, candidates: readonly string[]): Promise<ReadonlySet<string>> {\n    const unseen = candidates.filter((filePath) => !this.contents.has(filePath));\n    if (this.git === undefined || unseen.length === 0) return new Set();\n    return this.git.unchanged(cwd, unseen);\n  }\n\n  /** How many lines moved, when there is enough captured content to say. */\n  private async countChanges(\n    before: string | undefined,\n    after: string | undefined,\n    created: boolean,\n  ): Promise<{ additions?: number; removals?: number }> {\n    if (after === undefined) return {};\n    if (before === undefined) {\n      // A file that did not exist has an empty baseline, so every line it now\n      // holds is an addition. A file that existed but went uncaptured has no\n      // baseline to count against at all.\n      if (!created) return {};\n      const createdText = await this.snapshots.read(after);\n      if (createdText === undefined) return {};\n      const fresh = lineDiffFromEmpty(createdText);\n      return { additions: fresh.additions, removals: fresh.removals };\n    }\n    if (before === after) return { additions: 0, removals: 0 };\n    const [beforeText, afterText] = await Promise.all([this.snapshots.read(before), this.snapshots.read(after)]);\n    if (beforeText === undefined || afterText === undefined) return {};\n    const diff = lineDiff(beforeText, afterText);\n    return { additions: diff.additions, removals: diff.removals };\n  }\n\n  /** Records the change unless it turned out to be no change at all. */\n  private async append(event: TimelineEvent): Promise<void> {\n    if (event.before !== undefined && event.before === event.after) return;\n    await this.timeline.append(event);\n  }\n\n  /**\n   * Folds a path the tool layer just handled into the tracked manifest, so the\n   * next bash comparison sees it as already accounted for.\n   *\n   * The fingerprint has to be the one a comparison would read, not a stand-in, or the\n   * next comparison reports the file again under bash and every tool edit is\n   * recorded twice.\n   */\n  private async remember(filePath: string): Promise<void> {\n    if (this.manifest === undefined) return;\n    const entries = new Map(this.manifest.entries);\n    const fingerprint = await this.manifests.fingerprint(filePath);\n    if (fingerprint === undefined) entries.delete(filePath);\n    else entries.set(filePath, fingerprint);\n    this.manifest = { entries };\n  }\n}\n\n/** The tools this tracker knows how to attribute a change to. */\nexport const TRACKED_TOOLS: readonly FileEditTool[] = [EDIT_TOOL, WRITE_TOOL, BASH_TOOL];\n","import type { ApiResponseOf, ApiRoutes } from '@agimon-ai/po-core/web';\n\nimport type { FileEditsDetailView, FileEditsPreviewView, FileEditsSaveView } from './fileEditsApi';\n\n/**\n * This package's routes, as data.\n *\n * No scope and no base path. The build reads both off\n * `src/extensions/workspaces/sessions/(backend)/api/file-edits/`, so the mount\n * is stated once, by the folder that creates it. They used to be written here,\n * in the contract and again inside every URL the page built, and the copies\n * were free to disagree.\n *\n * This is the one file the routes, the Hono app and the browser all read, so a\n * path cannot move on one side alone.\n */\nexport const routes = {\n  detail: {\n    method: 'GET',\n    path: '/detail',\n    query: ['path'],\n    response: undefined as unknown as ApiResponseOf<FileEditsDetailView>,\n  },\n  preview: {\n    method: 'GET',\n    path: '/preview',\n    query: ['path'],\n    response: undefined as unknown as ApiResponseOf<FileEditsPreviewView>,\n  },\n  save: {\n    method: 'PUT',\n    path: '/content',\n    response: undefined as unknown as ApiResponseOf<FileEditsSaveView>,\n  },\n  /** The same path as `save`; the method is the whole of the difference. */\n  remove: {\n    method: 'DELETE',\n    path: '/content',\n    query: ['path'],\n  },\n  /**\n   * The host's own bytes route, not this package's.\n   *\n   * `host: true` hangs it off the session root rather than under `/plugins`,\n   * which is how the cockpit already serves it. Declaring it here is the first\n   * time anything records that this package's previews depend on it.\n   */\n  file: {\n    method: 'GET',\n    path: '/file',\n    raw: true,\n    query: ['path'],\n    host: true,\n  },\n} as const satisfies ApiRoutes;\n","import type { FileEditOrigin, FileEditTool } from './domain';\n\n/**\n * The wire vocabulary this package's API shares with whatever calls it.\n *\n * It lives under src/types because that is the one server root a browser\n * bundle may read: the cockpit plugin builds its URLs from these and the\n * routes answer them, so neither half can drift from the other.\n *\n * Routes live in `./apiRoutes`, which the contract, the Hono app and the\n * generated client all read. This file holds the shapes that travel over them.\n *\n * Opening a changed file wants its whole history at once, so `detail` answers\n * in one round trip rather than making the page stitch three reads together;\n * `content` takes the manual save back; `preview` reads a file the session\n * never changed, which has no history to answer with.\n */\n\n/** Where a host mounts this package's API; the segment after /api/plugins/. */\nexport const API_BASE_PATH = 'file-edits';\n\n/** Query parameter naming the file a request is about. */\nexport const PATH_QUERY_PARAM = 'path';\n\n/**\n * One line of a diff. The number is the new file's for context and additions\n * and the old file's for removals, so it always says where the line lives.\n */\nexport interface FileEditsDiffRow {\n  marker: '+' | '-' | ' ';\n  line: number;\n  content: string;\n}\n\n/**\n * A run of changed lines with its surrounding context. Hunks are sent apart\n * rather than joined by an elision marker, so the page draws the gap between\n * them instead of parsing one out of a string.\n */\nexport interface FileEditsDiffHunk {\n  /** The line number the hunk opens at. */\n  start: number;\n  rows: FileEditsDiffRow[];\n}\n\n/**\n * One change in a file's history, each rendered on its own so a file edited\n * four times shows four distinct diffs rather than one merged blur.\n */\nexport interface FileEditsVersionView {\n  /** Position in the file's history, oldest first, starting at 1. */\n  index: number;\n  tool: FileEditTool;\n  at: number;\n  origin: FileEditOrigin;\n  additions: number;\n  removals: number;\n  /** The changed lines of this one change; absent when no baseline was captured. */\n  hunks?: FileEditsDiffHunk[];\n  /** Why there is no diff, shown in its place. */\n  note?: string;\n}\n\n/** Everything this session did to the file: its first baseline against what is on disk now. */\nexport interface FileEditsCumulativeView {\n  additions: number;\n  removals: number;\n  hunks?: FileEditsDiffHunk[];\n  note?: string;\n}\n\n/** The file as it stands on disk right now, which is what the source view edits. */\nexport interface FileEditsWorkingView {\n  content: string;\n  /** sha256 of the content; the token a save hands back to prove it is not stale. */\n  hash: string;\n  /** True when the file is binary, missing, or past the size cap, so `content` is empty. */\n  unavailable: boolean;\n  reason?: string;\n}\n\n/** What the detail route answers with. */\nexport interface FileEditsDetailView {\n  path: string;\n  relPath: string;\n  versions: FileEditsVersionView[];\n  cumulative: FileEditsCumulativeView;\n  working: FileEditsWorkingView;\n}\n\n/**\n * What the preview route answers with: the file as it stands, and nothing\n * about how it got there. A file this session never touched has no history and\n * no baseline, so there is no diff to send and no save to take back.\n */\nexport interface FileEditsPreviewView {\n  path: string;\n  relPath: string;\n  working: FileEditsWorkingView;\n}\n\n/** What the save route takes. */\nexport interface FileEditsSaveRequest {\n  path: string;\n  /** The hash the reader loaded; a mismatch means the file moved underneath them. */\n  expectedHash: string;\n  content: string;\n}\n\n/** What the save route answers with. */\nexport interface FileEditsSaveView {\n  hash: string;\n}\n\n/** What a route reports when it refuses; the page shows `error` verbatim. */\nexport interface FileEditsErrorView {\n  error: string;\n  /** On a stale save, the hash the file actually has now. */\n  hash?: string;\n}\n","import path from 'node:path';\n\nimport type { PoApi, PoApiContext, PoApiHandler } from '@agimon-ai/po-core/packageApi';\nimport { Hono } from 'hono';\n\nimport { routes } from '../../types/apiRoutes';\nimport type { FileEditVersion } from '../../types/domain';\nimport type { IFileEditPaths } from '../../types/fileEditPaths';\nimport {\n  API_BASE_PATH,\n  type FileEditsDetailView,\n  type FileEditsPreviewView,\n  type FileEditsSaveView,\n  PATH_QUERY_PARAM,\n} from '../../types/fileEditsApi';\nimport type { FileEditStorage, ReadableRoots } from '../../types/fileEditStorage';\nimport type { SnapshotStorePort } from '../../types/snapshotStore';\nimport type { ITimelineStore } from '../../types/timelineStore';\nimport type { WorkingFilesPort } from '../../types/workingFiles';\nimport { createFileEditStorage } from '../fileEditStorage';\nimport { isInside, MAX_WORKING_BYTES, toCumulativeView, toVersionView } from '../fileEditsViews';\n\nexport { MAX_WORKING_BYTES } from '../fileEditsViews';\n\n/**\n * This package's HTTP surface: one file's history, and the manual save.\n *\n * Routes are relative to the mount its host gives it, so nothing here repeats\n * where it was mounted. The host is one session's own server, which is what\n * makes the session id and working directory available without the page\n * supplying either: a page names a file, never a session's private paths.\n *\n * The detail route answers everything a reader needs to open a changed file,\n * because splitting it would make the page stitch three responses together for\n * one click. The save route is the only mutation, and it refuses unless the\n * reader proves they were looking at the content that is still on disk. The\n * preview route is the read-only way in to a file the session never changed,\n * bounded by the working directory instead of by the timeline.\n *\n * What a request may do is decided here and is the same on every host. The\n * host's files come in through the storage the API is given.\n */\n\nexport interface FileEditsApiOptions {\n  /** The session these routes answer for; absent when the host is the hub. */\n  sessionId?: string;\n  /** The session's working directory, which relative paths are shown against. */\n  cwd?: string;\n  /**\n   * Po-owned folders outside the working directory that the preview route may\n   * also read, such as the plans directory. Resolved per request, so a config\n   * change applies without restarting the session.\n   */\n  readableRoots?: ReadableRoots;\n  timeline?: ITimelineStore;\n  snapshots?: SnapshotStorePort;\n  paths?: IFileEditPaths;\n  /** The host's files; defaults to the ones this build runs on. */\n  storage?: FileEditStorage;\n  files?: WorkingFilesPort;\n}\n\nexport function createFileEditsApi(options: FileEditsApiOptions = {}): Hono {\n  const storage = options.storage ?? createFileEditStorage();\n  const timeline = options.timeline ?? storage.timeline();\n  const snapshots = options.snapshots ?? storage.snapshots();\n  const paths = options.paths ?? storage.paths();\n  const files = options.files ?? storage.workingFiles();\n  const cwd = options.cwd ?? '';\n  const app = new Hono();\n\n  // The routes and the extension run in different processes, so this half\n  // opens the same two locations from the same inputs rather than sharing an\n  // instance with the half that writes them.\n  //\n  // Only what this function built gets pointed at them. A store handed in\n  // through the options arrives already configured, and repointing it would\n  // make the option a lie: the caller would be injecting a store the routes\n  // then read somewhere else entirely.\n  if (options.sessionId !== undefined && cwd !== '') {\n    const sessionKey = paths.sessionKey(options.sessionId);\n    let initializing: Promise<void> | undefined;\n    app.use(async (_context, next) => {\n      initializing ??= (async () => {\n        if (options.timeline === undefined) timeline.initialize(await paths.timelinePath(cwd, sessionKey));\n        if (options.snapshots === undefined) snapshots.initialize(await paths.snapshotsPath(cwd, sessionKey));\n      })();\n      await initializing;\n      await next();\n    });\n  }\n\n  /**\n   * The file a request names, rejected unless this session actually recorded a\n   * change to it. That check is the authorization: these routes read and write\n   * whatever path they are handed, so the timeline is what bounds them to files\n   * the session already touched.\n   */\n  const recordedVersions = async (filePath: string | undefined): Promise<FileEditVersion[] | undefined> => {\n    if (filePath === undefined || filePath === '') return undefined;\n    const versions = await timeline.versions(path.resolve(cwd, filePath));\n    return versions.length === 0 ? undefined : versions;\n  };\n\n  const isInsideSession = async (filePath: string): Promise<boolean> => {\n    if (cwd === '') return false;\n    const root = path.resolve(cwd);\n    return isInside(root, filePath) && (await files.isRealPathInside(root, filePath));\n  };\n\n  /** The Po-owned folder holding the file, checked the same two ways as the working directory. */\n  const readableRootOf = async (filePath: string): Promise<string | undefined> => {\n    for (const root of (await options.readableRoots?.()) ?? []) {\n      const resolved = path.resolve(root);\n      if (isInside(resolved, filePath) && (await files.isRealPathInside(resolved, filePath))) return resolved;\n    }\n    return undefined;\n  };\n  app.get(routes.detail.path, async (context) => {\n    const requested = context.req.query(PATH_QUERY_PARAM);\n    const versions = await recordedVersions(requested);\n    if (versions === undefined || requested === undefined) {\n      return context.json({ error: 'This session recorded no changes to that file.' }, 404);\n    }\n    const filePath = path.resolve(cwd, requested);\n    // A directly recorded outside file remains viewable. An inside path is not a grant to an outside symlink target.\n    const allowedRoot = cwd !== '' && isInside(path.resolve(cwd), filePath) ? path.resolve(cwd) : undefined;\n    const working = await files.readWorking(filePath, allowedRoot);\n    const body: FileEditsDetailView = {\n      path: filePath,\n      relPath: cwd === '' ? filePath : path.relative(cwd, filePath),\n      versions: await Promise.all(versions.map((version) => toVersionView(version, snapshots))),\n      cumulative: await toCumulativeView(versions, working, snapshots),\n      working,\n    };\n    return context.json(body);\n  });\n\n  /**\n   * The file a request names, read only, for a file the timeline knows nothing\n   * about: a path the agent read but never changed is still a path the reader\n   * clicked, and refusing it would leave the link dead.\n   *\n   * The working directory is the boundary here, since the timeline is not.\n   * Containment is checked lexically and again on the real path, so a symlink\n   * inside the tree cannot hand out something beyond it, and a host that gave\n   * these routes no working directory has no boundary to enforce and so serves\n   * nothing.\n   */\n  app.get(routes.preview.path, async (context) => {\n    const requested = context.req.query(PATH_QUERY_PARAM);\n    if (requested === undefined || requested === '' || requested.includes('\\0')) {\n      return context.json({ error: 'A preview names a path.' }, 400);\n    }\n    if (cwd === '') return context.json({ error: 'This session has no working directory to read from.' }, 403);\n    const root = path.resolve(cwd);\n    const filePath = path.resolve(root, requested);\n    const inSession = await isInsideSession(filePath);\n    const allowedRoot = inSession ? root : await readableRootOf(filePath);\n    if (allowedRoot === undefined) {\n      return context.json({ error: 'The path leaves the session directory.' }, 403);\n    }\n    const body: FileEditsPreviewView = {\n      path: filePath,\n      // A file in a Po-owned folder has no useful path relative to the project.\n      relPath: inSession ? path.relative(root, filePath) : filePath,\n      working: await files.readWorking(filePath, allowedRoot),\n    };\n    return context.json(body);\n  });\n\n  app.put(routes.save.path, async (context) => {\n    let request: unknown;\n    try {\n      request = await context.req.json();\n    } catch {\n      return context.json({ error: 'The save body is not JSON.' }, 400);\n    }\n    if (\n      typeof request !== 'object' ||\n      request === null ||\n      Array.isArray(request) ||\n      !('path' in request) ||\n      typeof request.path !== 'string' ||\n      !('content' in request) ||\n      typeof request.content !== 'string' ||\n      !('expectedHash' in request) ||\n      typeof request.expectedHash !== 'string'\n    ) {\n      return context.json({ error: 'A save names a path, the content to write and the hash it was read at.' }, 400);\n    }\n    const { path: requested, content, expectedHash } = request;\n    if ((await recordedVersions(requested)) === undefined) {\n      return context.json({ error: 'This session recorded no changes to that file.' }, 404);\n    }\n    const filePath = path.resolve(cwd, requested);\n    if (!(await isInsideSession(filePath))) {\n      return context.json({ error: 'Files outside the session directory are read-only.' }, 403);\n    }\n    if (new TextEncoder().encode(content).byteLength > MAX_WORKING_BYTES) {\n      return context.json({ error: `The file is larger than ${MAX_WORKING_BYTES} bytes.` }, 413);\n    }\n    try {\n      const outcome = await files.save({ filePath, root: path.resolve(cwd), content, expectedHash });\n      switch (outcome.status) {\n        case 'saved': {\n          const body: FileEditsSaveView = { hash: outcome.hash };\n          return context.json(body);\n        }\n        case 'stale':\n          return context.json({ error: 'The file changed since it was opened.', hash: outcome.hash }, 409);\n        case 'unreadable':\n          return context.json({ error: outcome.reason }, 409);\n        case 'moved':\n          return context.json({ error: 'The file changed before it could be written.' }, 409);\n      }\n    } catch {\n      return context.json({ error: 'The file cannot be safely written.' }, 409);\n    }\n  });\n\n  app.delete(routes.remove.path, async (context) => {\n    const requested = context.req.query(PATH_QUERY_PARAM);\n    if ((await recordedVersions(requested)) === undefined || requested === undefined) {\n      return context.json({ error: 'This session recorded no changes to that file.' }, 404);\n    }\n    const filePath = path.resolve(cwd, requested);\n    if (!(await isInsideSession(filePath))) {\n      return context.json({ error: 'Files outside the session directory are read-only.' }, 403);\n    }\n    const outcome = await files.remove(filePath, path.resolve(cwd));\n    switch (outcome.status) {\n      case 'outside':\n        return context.json({ error: 'Files outside the session directory are read-only.' }, 403);\n      case 'failed':\n        return context.json({ error: `The file could not be deleted: ${outcome.reason}` }, 409);\n      case 'removed':\n        return context.body(null, 204);\n    }\n  });\n\n  return app;\n}\n\n/** The named export a host mounts, built over the storage it runs on. */\nexport function createFileEditsPoApi(storage: FileEditStorage): PoApi {\n  return {\n    basePath: API_BASE_PATH,\n    start(context: PoApiContext): PoApiHandler {\n      const environment = context.environment ?? {};\n      const cwd = context.cwd;\n      const app = createFileEditsApi({\n        storage,\n        paths: storage.paths({ ...environment, HOME: context.homeDirectory ?? environment.HOME }),\n        ...(context.sessionId === undefined ? {} : { sessionId: context.sessionId }),\n        ...(cwd === undefined\n          ? {}\n          : {\n              cwd,\n              readableRoots: storage.readableRoots({\n                cwd,\n                environment,\n                ...(context.homeDirectory === undefined ? {} : { homeDirectory: context.homeDirectory }),\n              }),\n            }),\n      });\n      return {\n        fetch: (request) => app.fetch(request),\n        // Nothing outlives a request here: every route reads, answers and closes.\n        close: () => undefined,\n      };\n    },\n  };\n}\n\n/** The API over the files this build runs on, for a host that gives the package no file system. */\nexport const api: PoApi = {\n  basePath: API_BASE_PATH,\n  start: (context) => createFileEditsPoApi(createFileEditStorage()).start(context),\n};\n","import path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV } from '@agimon-ai/po-core/childProcess';\nimport { runCleanups } from '@agimon-ai/po-core/extensionFile';\nimport {\n  type PoHeadlessExecutionContext,\n  type PoHeadlessActivity,\n  type PoHeadlessHook,\n} from '@agimon-ai/po-core/headless';\nimport { BACKGROUND_CONTEXT, readTextIfExists, type FileSystem } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext, PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { createPoTelemetry } from '@agimon-ai/po-core/telemetry';\n\nimport { EditTracker } from '../../services/editTracker';\nimport { createPoIgnoreMatcher } from '../../services/poIgnore';\nimport type { FileEditStorage } from '../../types/fileEditStorage';\nimport { filesChannelType, filesStatusKey } from '../../types/webFiles';\nimport { createFileEditsPoApi } from '../fileEditsApi';\nimport { createFileEditStorage } from '../fileEditStorage';\n\nconst PO_IGNORE_FILE = '.poignore';\n\nasync function readPoIgnore(cwd: string, fs: FileSystem): Promise<((filePath: string) => boolean) | undefined> {\n  try {\n    const content = await readTextIfExists(fs, path.join(cwd, PO_IGNORE_FILE), BACKGROUND_CONTEXT);\n    if (content === undefined) return undefined;\n    const matcher = createPoIgnoreMatcher(content);\n    return matcher === undefined ? undefined : (filePath: string) => matcher(path.relative(cwd, filePath));\n  } catch {\n    return undefined;\n  }\n}\n\n/** Export only fixed categories from structured tool details, never displayed output. */\nfunction failureAttributes(result: unknown): Record<string, string | number> {\n  if (!result || typeof result !== 'object' || !('details' in result)) return {};\n  const details = result.details;\n  if (!details || typeof details !== 'object') return {};\n  const failure = 'failure' in details ? details.failure : undefined;\n  const kind = failure && typeof failure === 'object' && 'kind' in failure ? failure.kind : undefined;\n  return {\n    ...(typeof kind === 'string' &&\n    ['timeout', 'exit_code', 'not_found', 'permission', 'validation', 'aborted', 'unknown'].includes(kind)\n      ? { 'failure.kind': kind }\n      : {}),\n    ...('exit_code' in details && typeof details.exit_code === 'number' && Number.isFinite(details.exit_code)\n      ? { exit_code: details.exit_code }\n      : {}),\n  };\n}\n\nfunction stringValue(value: Readonly<Record<string, unknown>>, key: string): string | undefined {\n  const candidate = value[key];\n  return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined;\n}\n\nexport function createFileEditSession(\n  { agent, host }: PoServerPluginContext,\n  fs: FileSystem,\n  storage: FileEditStorage = createFileEditStorage(fs),\n): PoServerSessionPlugin {\n  const fileEditsApi = createFileEditsPoApi(storage);\n  if (!agent) return { api: [fileEditsApi] };\n  // Storage selection and deletion must share host ownership, never activity environment.\n  const environment = Object.freeze({ ...host.context.environment });\n  const paths = storage.paths(environment);\n  const timeline = storage.timeline();\n  const snapshots = storage.snapshots();\n  const telemetry = createPoTelemetry({\n    serviceName: 'po-file-edit',\n    packageName: '@agimon-ai/po-file-edit',\n    env: environment,\n    enableLogs: true,\n    enableTraces: true,\n  });\n  const editTracker = new EditTracker(timeline, snapshots, storage.manifests(), {\n    git: storage.git(),\n    // Telemetry sanitizes the error and never rejects, so the chain stays intact.\n    onScanFailed: (error) => void track(() => telemetry.recordWarning('po_file_edit.scan_failed', error)),\n  });\n  if (host.context.directEvents === undefined)\n    throw new Error('File-edit server plugin requires the session direct event bus.');\n  const directEvents = host.context.directEvents;\n  const toolStartedAt = new Map<string, number>();\n  const pending = new Set<Promise<unknown>>();\n  let closed = false;\n  let disposal: Promise<void> | undefined;\n  let stopping: Promise<void> | undefined;\n  let starting: Promise<() => Promise<void>> | undefined;\n  let initialized = false;\n  // Admit work before disposal starts, then drain it before clearing its stores.\n  const track = <T>(work: () => Promise<T>): Promise<T> => {\n    const task = work();\n    pending.add(task);\n    void task.finally(() => pending.delete(task)).catch(() => {});\n    return task;\n  };\n  let active:\n    | {\n        readonly context: PoHeadlessExecutionContext;\n        readonly timelinePath: string;\n        readonly snapshotsPath: string;\n      }\n    | undefined;\n  let lastRuntime: NonNullable<typeof active> | undefined;\n  /**\n   * The channel carries the rows; the status decides whether the group exists.\n   *\n   * A cockpit drives this server plugin and never the Pi runtime, so without the status\n   * the dock had the file list on the wire and no frame to draw it in. The empty\n   * string is deliberate: the group declares `hideWhenEmpty`, so a session that\n   * has edited nothing publishes a key with no content and stays hidden.\n   */\n  const publish = async (runtime: NonNullable<typeof active>): Promise<void> => {\n    const items = await storage.sessionFiles(runtime.timelinePath, runtime.context.cwd);\n    if (active !== runtime || closed || stopping) return;\n    directEvents.publish(filesChannelType, runtime.context.sessionId, { items });\n    runtime.context.client.setStatus(\n      filesStatusKey,\n      items.length === 0 ? '' : `${items.length} ${items.length === 1 ? 'file' : 'files'}`,\n    );\n  };\n  const stopActivity = (): Promise<void> => {\n    if (stopping) return stopping;\n    const runtime = active;\n    active = undefined;\n    stopping = (async () => {\n      while (pending.size > 0) await Promise.allSettled(pending);\n      const startedRuntime = active;\n      active = undefined;\n      await editTracker.flush();\n      editTracker.reset();\n      toolStartedAt.clear();\n      (runtime ?? startedRuntime)?.context.client.setStatus(filesStatusKey, undefined);\n    })();\n    return stopping;\n  };\n  const dispose = (): Promise<void> => {\n    if (disposal) return disposal;\n    closed = true;\n    disposal = runCleanups(\n      [\n        stopActivity,\n        // Where a released session is rebuilt from its history, closing is not its end, so the history stays.\n        async () => {\n          if (storage.clearOnClose && lastRuntime && !environment[SUBAGENT_CHILD_ENV]) await timeline.clear();\n        },\n        async () => {\n          if (storage.clearOnClose && lastRuntime && !environment[SUBAGENT_CHILD_ENV]) await snapshots.clear();\n        },\n        async () => {\n          if (lastRuntime) await telemetry.recordEvent('po_file_edit.timeline_finished', { outcome: 'closed' });\n        },\n        () => telemetry.shutdown(),\n      ],\n      'File-edit session cleanup failed.',\n    );\n    return disposal;\n  };\n  const activity: PoHeadlessActivity = {\n    name: 'file-edits',\n    start: async (executionContext) => {\n      if (closed) throw new Error('File-edit session is closed.');\n      if (starting) return starting;\n      if (active) return stopActivity;\n      if (stopping) await stopping;\n      if (closed) throw new Error('File-edit session is closed.');\n      if (starting) return starting;\n      stopping = undefined;\n      starting = track(async () => {\n        const sessionKey = paths.sessionKey(executionContext.sessionId);\n        const timelinePath = await paths.timelinePath(executionContext.cwd, sessionKey);\n        const snapshotsPath = await paths.snapshotsPath(executionContext.cwd, sessionKey);\n        timeline.initialize(timelinePath);\n        snapshots.initialize(snapshotsPath);\n        const isIgnored = await readPoIgnore(executionContext.cwd, fs);\n        editTracker.reset({\n          exclude: [timelinePath, `${timelinePath}.lock`, snapshotsPath],\n          ...(isIgnored === undefined ? {} : { isIgnored }),\n        });\n        const runtime = { context: executionContext, timelinePath, snapshotsPath };\n        active = runtime;\n        lastRuntime = runtime;\n        await publish(runtime);\n        void track(async () => {\n          try {\n            await storage.sweepAbandoned?.(paths.stateDirectory(), timelinePath);\n          } catch (error) {\n            // Abandoned state must never prevent session startup, so it is reported, not rethrown.\n            await telemetry.recordWarning('po_file_edit.sweep_failed', error);\n          }\n        });\n        if (!initialized) {\n          initialized = true;\n          await track(() => telemetry.recordEvent('po_file_edit.timeline_started', { outcome: 'initialized' }));\n        }\n        return () => (active === runtime ? stopActivity() : Promise.resolve());\n      });\n      try {\n        return await starting;\n      } finally {\n        starting = undefined;\n      }\n    },\n  };\n  const startHook: PoHeadlessHook = {\n    event: 'tool_execution_start',\n    handle: (event, executionContext) => {\n      if (closed || stopping) return;\n      const runtime = active;\n      const toolCallId = stringValue(event, 'toolCallId');\n      const toolName = stringValue(event, 'toolName');\n      if (runtime === undefined || runtime.context.sessionId !== executionContext.sessionId || !toolCallId || !toolName)\n        return;\n      return track(async () => {\n        const hookStartedAt = Date.now();\n        const admitted = await editTracker.start(toolCallId, toolName, event.args, executionContext.cwd);\n        if (!admitted || active !== runtime) return;\n        toolStartedAt.set(toolCallId, hookStartedAt);\n        await telemetry.recordEvent('po_file_edit.edit_started', {\n          'tool.name': toolName,\n          hook_ms: Date.now() - hookStartedAt,\n        });\n      });\n    },\n  };\n  const endHook: PoHeadlessHook = {\n    event: 'tool_execution_end',\n    handle: (event, executionContext) => {\n      if (closed || stopping) return;\n      const runtime = active;\n      const toolCallId = stringValue(event, 'toolCallId');\n      const toolName = stringValue(event, 'toolName');\n      if (runtime === undefined || runtime.context.sessionId !== executionContext.sessionId || !toolCallId || !toolName)\n        return;\n      return track(async () => {\n        const startedAt = toolStartedAt.get(toolCallId);\n        if (startedAt === undefined) return;\n        toolStartedAt.delete(toolCallId);\n        const hookStartedAt = Date.now();\n        const isError = event.isError === true;\n        await editTracker.end(toolCallId, isError, executionContext.cwd);\n        if (active !== runtime) return;\n        await publish(runtime);\n        await telemetry.recordEvent('po_file_edit.edit_finished', {\n          'tool.name': toolName,\n          'tool.result.error': isError,\n          ...failureAttributes(event.result),\n          ...(startedAt === undefined ? {} : { duration_ms: Date.now() - startedAt }),\n          hook_ms: Date.now() - hookStartedAt,\n          outcome: isError ? 'failed' : 'completed',\n        });\n      });\n    },\n  };\n  return { api: [fileEditsApi], activities: [activity], hooks: [startHook, endHook], onDispose: dispose };\n}\n","import { PO_CHILD_SESSION_HOOK_REGISTRY_SERVICE, readPoChildSessionLabels } from '@agimon-ai/po-core/childSession';\nimport { runCleanups } from '@agimon-ai/po-core/extensionFile';\nimport { WORKFLOW_STEP_SESSION_PROVENANCE } from '@agimon-ai/po-core/hubChannel';\nimport { PO_EDIT_PRESENCE_SERVICE, type PoEditPresence } from '@agimon-ai/po-core/packageApi';\nimport type { FileSystem } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext, PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createSessionPresence, type SessionPresence } from '../../../../../services/editPresence';\nimport { createFileEditSession } from '../../../../../services/fileEditSession';\nimport { createFileEditStorage } from '../../../../../services/fileEditStorage';\nimport type { PresenceFiles } from '../../../../../types/presenceFiles';\n\nexport interface FileEditServerScope extends PoServerSessionPlugin {\n  readonly presence?: SessionPresence;\n}\n\nfunction createPresence(\n  { agent, host, context }: PoServerPluginContext,\n  presence: PoEditPresence,\n  files: PresenceFiles,\n) {\n  if (!agent || !presence) return undefined;\n  const execution = agent.context;\n  return createSessionPresence({\n    presence,\n    sessionId: execution.sessionId,\n    cwd: execution.cwd,\n    files,\n    workflowStep: execution.sessionContext?.provenance === WORKFLOW_STEP_SESSION_PROVENANCE,\n    isLive: () => host.context.sessionService?.isLive(execution.sessionId) ?? true,\n    labelFor: (runId) => readPoChildSessionLabels(context)?.labelFor(runId),\n    onError: (error) =>\n      host.context.onNotice(`Edit presence failed: ${error instanceof Error ? error.message : String(error)}`),\n  });\n}\n\nexport const createFileEditServerRoot = (context: PoServerPluginContext, fs: FileSystem) => {\n  const storage = createFileEditStorage(fs);\n  const runtime = createFileEditSession(context, fs, storage);\n  let presence: SessionPresence | undefined;\n  let disposePresence = () => {};\n  let closed = false;\n  let disposal: Promise<void> | undefined;\n  const value: FileEditServerScope = {\n    ...runtime,\n    get presence() {\n      return presence;\n    },\n  };\n  return {\n    value,\n    activities: runtime.activities,\n    services: [\n      (cordis: PoServerPluginContext['context']) => {\n        cordis.inject([PO_EDIT_PRESENCE_SERVICE], (presenceContext) => {\n          if (closed) return;\n          const bound = createPresence(\n            context,\n            presenceContext.get(PO_EDIT_PRESENCE_SERVICE)!,\n            storage.presenceFiles(),\n          );\n          if (!bound) return;\n          presence = bound;\n          let disposed = false;\n          const cleanup = () => {\n            if (disposed) return;\n            disposed = true;\n            if (presence === bound) presence = undefined;\n            bound.dispose();\n          };\n          disposePresence = cleanup;\n          presenceContext.inject([PO_CHILD_SESSION_HOOK_REGISTRY_SERVICE], (registryContext) => {\n            const registration = registryContext\n              .get(PO_CHILD_SESSION_HOOK_REGISTRY_SERVICE)!\n              .register(bound.childHooks);\n            return () => registration.dispose();\n          });\n          return cleanup;\n        });\n      },\n    ],\n    onDispose: (pluginContext: PoServerPluginContext) => {\n      closed = true;\n      return (disposal ??= runCleanups(\n        [() => disposePresence(), () => runtime.onDispose?.(pluginContext)],\n        'File-edit root cleanup failed.',\n      ));\n    },\n  };\n};\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { requirePoFs } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createFileEditServerRoot } from './_lib/serverRoot';\n\nexport default defineRoot((context: PoServerPluginContext) =>\n  createFileEditServerRoot(context, requirePoFs(context.context)),\n);\n","import { defineChannel } from '@agimon-ai/po-core/extensionFile';\nimport type { PoHubChannel } from '@agimon-ai/po-core/hubChannel';\nimport { readPoFs } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createFileEditStorage } from '../../../services/fileEditStorage';\nimport { createFilesChannel } from '../../../services/filesChannel';\n\nexport default defineChannel(\n  function fileEditsChannel(context: PoServerPluginContext): PoHubChannel {\n    return createFilesChannel(createFileEditStorage(readPoFs(context.context)));\n  },\n  { context: true },\n);\n","import { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport { readPoFs } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createFileEditsPoApi } from '../../../../../../services/fileEditsApi';\nimport { createFileEditStorage } from '../../../../../../services/fileEditStorage';\n\n/**\n * Mounts this package's HTTP API at `file-edits`, which the folder names.\n *\n * Until this file existed the API was never mounted at all. The session root\n * returns a runtime carrying `api`, but a root's `api` is not folded into the\n * generated entry the way its services and activities are, so the registration\n * was dropped in silence and the cockpit called routes that answered 404.\n *\n * The API reads the files of the host it runs on, so it is built from the file\n * system the session was given.\n */\nexport default defineRoute((context: PoServerPluginContext) =>\n  createFileEditsPoApi(createFileEditStorage(readPoFs(context.context))),\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { FileEditServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, FileEditServerScope>) => context.root.hooks![1]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { FileEditServerScope } from '../_lib/serverRoot';\nexport default defineHook((context: WithRoot<PoServerPluginContext, FileEditServerScope>) => context.root.hooks![0]!);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { FileEditServerScope } from '../_lib/serverRoot';\n\ntype HookContext = WithRoot<PoServerPluginContext, FileEditServerScope>;\n\n// A host without a hub edit presence ledger gets a hook that leaves every result untouched.\nexport default defineHook<'tool_result', HookContext>(({ root }) => ({\n  event: 'tool_result',\n  handle: async (event, execution) => root.presence?.toolResult.handle(event, execution),\n}));\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport channelFileEdits from '../src/extensions/(backend)/channel/fileEdits.server';\nimport apiRoute from '../src/extensions/workspaces/sessions/(backend)/api/file-edits/route.server';\nimport hookToolExecutionEnd from '../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server';\nimport hookToolExecutionStart from '../src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server';\nimport hookToolResult from '../src/extensions/workspaces/sessions/(backend)/hook/tool-result.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n  typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\n/* v8 ignore next -- generated normalization branch */\nconst defined = <T>(values: readonly (T | undefined)[]): T[] =>\n  values.filter((value): value is T => value !== undefined);\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n  (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n  name: '@agimon-ai/po-file-edit',\n  providerOverrides: composeServerProviderOverrides(rootSession),\n  injects: composeRootInjects({ session: [rootSession] }),\n  host: (context) => ({\n    get channels(): PoServerSessionPlugin['channels'] { return [() => via({ frameType: 'file_edits' }, at(channelFileEdits, context))]; },\n  }),\n  workspace: (context) => ({\n    get channels(): PoServerSessionPlugin['channels'] { return defined([context.hosted('host') ? undefined : () => via({ frameType: 'file_edits' }, at(channelFileEdits, context))]); },\n  }),\n  session: async (context) => {\n    const scopeSession = await context.scopeRoot('session', rootSession, context);\n    const contextSession = { ...context, root: scopeSession.value };\n    return {\n      ...composeRootHooks(scopeSession),\n      get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, contextSession)]; },\n      get channels(): PoServerSessionPlugin['channels'] { return defined([context.hosted('host') ? undefined : () => via({ frameType: 'file_edits' }, at(channelFileEdits, context))]); },\n      get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'tool_execution_end' }, at(hookToolExecutionEnd, contextSession)), via({ event: 'tool_execution_start' }, at(hookToolExecutionStart, contextSession)), via({ event: 'tool_result' }, at(hookToolResult, contextSession))]; },\n      services: [...(scopeSession.services ?? [])],\n      get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n    };\n  },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,sBAAsB;AACnC,MAAa,yBACX;;;;ACKF,MAAM,kBAAkB;;AAKxB,SAAgB,SAAS,OAAuB;CAC9C,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;AACrE;;AAGA,SAAgB,cAAc,WAAmB,aAAkC;CACjF,IAAI,YAAY,qBAAqB;EACnC,MAAM,SAAS,YAAY;EAC3B,IAAI,QAAQ,OAAO;CACrB;CACA,OAAO;AACT;;AAGA,SAAgB,kBAAkB,aAAkC;CAClE,OAAO,KAAK,KAAK,iBAAiB,aAAa,YAAY,IAAI,GAAG,eAAe;AACnF;;AAGA,SAAgB,gBAAgB,cAA8B;CAC5D,OAAO,GAAG,aAAa,QAAQ,aAAa,EAAE,EAAE;AAClD;;;AC3BA,IAAa,gBAAb,MAAqD;CACtB;CAA7B,YAAY,cAA6E,QAAQ,KAAK;EAAzE,KAAA,cAAA;CAA0E;CAEvG,WAAW,WAAmB,MAAoD,KAAK,aAAqB;EAC1G,OAAO,cAAc,WAAW,GAAG;CACrC;;;;;;;;;;;;;CAcA,iBAAyB;EACvB,OAAO,kBAAkB,KAAK,WAAW;CAC3C;;;;;;CAOA,MAAM,aAAa,KAAa,YAAqC;EACnE,MAAM,YAAY,KAAK,eAAe;EACtC,MAAM,GAAG,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;EAC7C,OAAO,KAAK,KAAK,WAAW,GAAG,SAAS,MAAM,GAAG,SAA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