apex-code 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/client/transcript.d.ts.map +1 -1
  3. package/dist/client/transcript.js +1 -1
  4. package/dist/client/transcript.js.map +1 -1
  5. package/dist/core/agent-session-services.d.ts.map +1 -1
  6. package/dist/core/agent-session-services.js +2 -1
  7. package/dist/core/agent-session-services.js.map +1 -1
  8. package/dist/core/delegation/runtime.d.ts.map +1 -1
  9. package/dist/core/delegation/runtime.js +2 -2
  10. package/dist/core/delegation/runtime.js.map +1 -1
  11. package/dist/core/durable-state/daemon.d.ts.map +1 -1
  12. package/dist/core/durable-state/daemon.js +1 -1
  13. package/dist/core/durable-state/daemon.js.map +1 -1
  14. package/dist/core/extensions/types.d.ts +1 -1
  15. package/dist/core/extensions/types.d.ts.map +1 -1
  16. package/dist/core/extensions/types.js.map +1 -1
  17. package/dist/core/keybindings.d.ts +1 -1
  18. package/dist/core/keybindings.d.ts.map +1 -1
  19. package/dist/core/keybindings.js.map +1 -1
  20. package/dist/core/mcp/mcp-tool.d.ts.map +1 -1
  21. package/dist/core/mcp/mcp-tool.js +2 -4
  22. package/dist/core/mcp/mcp-tool.js.map +1 -1
  23. package/dist/core/mcp/oauth/authorize.d.ts.map +1 -1
  24. package/dist/core/mcp/oauth/authorize.js +7 -2
  25. package/dist/core/mcp/oauth/authorize.js.map +1 -1
  26. package/dist/core/mcp/runtime.d.ts +2 -2
  27. package/dist/core/mcp/runtime.d.ts.map +1 -1
  28. package/dist/core/mcp/runtime.js +8 -3
  29. package/dist/core/mcp/runtime.js.map +1 -1
  30. package/dist/core/permissions/store.d.ts +7 -2
  31. package/dist/core/permissions/store.d.ts.map +1 -1
  32. package/dist/core/permissions/store.js +6 -1
  33. package/dist/core/permissions/store.js.map +1 -1
  34. package/dist/core/project-resources.d.ts +12 -0
  35. package/dist/core/project-resources.d.ts.map +1 -1
  36. package/dist/core/project-resources.js +19 -0
  37. package/dist/core/project-resources.js.map +1 -1
  38. package/dist/core/provider-composer.d.ts.map +1 -1
  39. package/dist/core/provider-composer.js +10 -1
  40. package/dist/core/provider-composer.js.map +1 -1
  41. package/dist/core/resource-loader.d.ts +6 -0
  42. package/dist/core/resource-loader.d.ts.map +1 -1
  43. package/dist/core/resource-loader.js +9 -3
  44. package/dist/core/resource-loader.js.map +1 -1
  45. package/dist/core/sdk.d.ts +1 -1
  46. package/dist/core/sdk.d.ts.map +1 -1
  47. package/dist/core/sdk.js +3 -3
  48. package/dist/core/sdk.js.map +1 -1
  49. package/dist/core/settings-manager.d.ts +16 -3
  50. package/dist/core/settings-manager.d.ts.map +1 -1
  51. package/dist/core/settings-manager.js +38 -15
  52. package/dist/core/settings-manager.js.map +1 -1
  53. package/dist/core/tools/bash.d.ts +9 -0
  54. package/dist/core/tools/bash.d.ts.map +1 -1
  55. package/dist/core/tools/bash.js +29 -16
  56. package/dist/core/tools/bash.js.map +1 -1
  57. package/dist/core/tools/edit.d.ts.map +1 -1
  58. package/dist/core/tools/edit.js +3 -3
  59. package/dist/core/tools/edit.js.map +1 -1
  60. package/dist/core/tools/path-utils.d.ts +9 -0
  61. package/dist/core/tools/path-utils.d.ts.map +1 -1
  62. package/dist/core/tools/path-utils.js +235 -10
  63. package/dist/core/tools/path-utils.js.map +1 -1
  64. package/dist/core/tools/write.d.ts.map +1 -1
  65. package/dist/core/tools/write.js +3 -3
  66. package/dist/core/tools/write.js.map +1 -1
  67. package/dist/core/workspace/state.d.ts.map +1 -1
  68. package/dist/core/workspace/state.js +1 -1
  69. package/dist/core/workspace/state.js.map +1 -1
  70. package/dist/main.d.ts.map +1 -1
  71. package/dist/main.js +3 -1
  72. package/dist/main.js.map +1 -1
  73. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  74. package/dist/modes/interactive/components/diff.js +2 -2
  75. package/dist/modes/interactive/components/diff.js.map +1 -1
  76. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  77. package/dist/modes/interactive/interactive-mode.js +1 -1
  78. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  79. package/dist/tsconfig.json +3 -0
  80. package/dist/utils/clipboard-image.d.ts.map +1 -1
  81. package/dist/utils/clipboard-image.js +1 -1
  82. package/dist/utils/clipboard-image.js.map +1 -1
  83. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  84. package/dist/utils/syntax-highlight.js +22 -22
  85. package/dist/utils/syntax-highlight.js.map +1 -1
  86. package/docs/models.md +1 -1
  87. package/examples/extensions/gondolin/package-lock.json +3 -3
  88. package/examples/extensions/minimal-mode.ts +6 -6
  89. package/examples/extensions/sandbox/package-lock.json +4 -4
  90. package/examples/extensions/sandbox/package.json +1 -1
  91. package/examples/sdk/10-settings.ts +2 -2
  92. package/examples/sdk/README.md +1 -1
  93. package/npm-shrinkwrap.json +19 -34
  94. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../../../src/core/tools/path-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,UAAU,EACV,SAAS,EACT,aAAa,EACb,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,QAAQ,EACR,SAAS,GACT,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAGlE,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAEvC,MAAM,UAAU,oBAAoB,CAAC,QAAgB,EAAE,GAAW,EAAyB;IAC1F,MAAM,aAAa,GAAG,YAAY,CAAC,QAAQ,EAAE,GAAG,CAA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AAe,KAAK,QAAQ,IAAI,CAAC,MAAM,UAAU,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC;QACzE,OAAO,eAAe,CAAC;IACxB,CAAC;IAED,OAAO,QAAQ,CAAC;AAAA,CAChB","sourcesContent":["import {\n\taccessSync,\n\tcloseSync,\n\tconstants,\n\texistsSync,\n\tfstatSync,\n\tftruncateSync,\n\tmkdirSync,\n\topenSync,\n\treadSync,\n\trealpathSync,\n\tstatSync,\n\twriteSync,\n} from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, parse, sep } from \"node:path\";\nimport { normalizePath, resolvePath } from \"../../utils/paths.ts\";\nimport type { PreparedPathOperation } from \"../permissions/operations.ts\";\n\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nexport function preparePathOperation(filePath: string, cwd: string): PreparedPathOperation {\n\tconst canonicalPath = resolveToCwd(filePath, cwd);\n\tif (!isAbsolute(canonicalPath)) throw new Error(\"Canonical path must be absolute\");\n\ttry {\n\t\tconst stats = statSync(canonicalPath);\n\t\treturn {\n\t\t\tkind: \"path-existing\",\n\t\t\tpath: { kind: \"canonical-path\", value: canonicalPath },\n\t\t\tidentity: { device: stats.dev, inode: stats.ino },\n\t\t};\n\t} catch {\n\t\treturn { kind: \"path-new\", path: { kind: \"canonical-path\", value: canonicalPath } };\n\t}\n}\n\n/**\n * Read the authorized target through a no-follow final-component open, verifying\n * the descriptor identity captured at authorization before any byte is returned.\n * A replaced alias or an injected symlink never matches and the read aborts.\n */\nexport function readPreparedPath(operation: PreparedPathOperation, maxBytes?: number): Buffer {\n\tif (operation.kind !== \"path-existing\") {\n\t\tthrow new PreparedTargetChangedError(\"Authorized read target did not exist when permission was checked\");\n\t}\n\treturn withTargetDirectory(operation, { createMissingDirectories: false }, (parent, name) => {\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(parent, name, constants.O_RDONLY | constants.O_NOFOLLOW);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized read target changed before execution\", { cause: error });\n\t\t}\n\t\ttry {\n\t\t\tconst stats = fstatSync(fd);\n\t\t\tif (stats.dev !== operation.identity.device || stats.ino !== operation.identity.inode) {\n\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized read target changed before execution\");\n\t\t\t}\n\t\t\tconst length = maxBytes === undefined ? stats.size : Math.min(stats.size, maxBytes);\n\t\t\tconst buffer = Buffer.alloc(length);\n\t\t\tlet offset = 0;\n\t\t\twhile (offset < buffer.length) {\n\t\t\t\tconst read = readSync(fd, buffer, offset, buffer.length - offset, null);\n\t\t\t\tif (read === 0) break;\n\t\t\t\toffset += read;\n\t\t\t}\n\t\t\treturn offset === buffer.length ? buffer : buffer.subarray(0, offset);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t});\n}\n\n/** The authorized target changed between permission evaluation and execution. */\nexport class PreparedTargetChangedError extends Error {}\n\nconst PROC_FD = \"/proc/self/fd\";\nlet procFdAvailable: boolean | undefined;\n\n/** /proc lets an already-open directory fd act as the parent of the next open, so a swapped intermediate directory cannot be traversed. */\nfunction useProcFd(): boolean {\n\tif (procFdAvailable === undefined) {\n\t\ttry {\n\t\t\tprocFdAvailable = existsSync(`${PROC_FD}/self`);\n\t\t} catch {\n\t\t\tprocFdAvailable = false;\n\t\t}\n\t}\n\treturn procFdAvailable;\n}\n\ninterface OpenDirectory {\n\tfd: number;\n\t/** Fallback parent path for platforms without /proc/self/fd. */\n\tpath: string;\n}\n\nfunction openUnder(parent: OpenDirectory, name: string, flags: number, mode?: number): number {\n\tif (useProcFd()) return openSync(`${PROC_FD}/${parent.fd}/${name}`, flags, mode);\n\treturn openSync(join(parent.path, name), flags, mode);\n}\n\nfunction mkdirUnder(parent: OpenDirectory, name: string): void {\n\tif (useProcFd()) mkdirSync(`${PROC_FD}/${parent.fd}/${name}`);\n\telse mkdirSync(join(parent.path, name));\n}\n\nfunction openChildDirectory(parent: OpenDirectory, name: string): OpenDirectory {\n\tconst flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;\n\tconst fd = openUnder(parent, name, flags);\n\tcloseSync(parent.fd);\n\treturn { fd, path: join(parent.path, name) };\n}\n\nfunction writeAll(fd: number, content: string | Buffer): void {\n\tconst buffer = typeof content === \"string\" ? Buffer.from(content, \"utf-8\") : content;\n\tlet written = 0;\n\twhile (written < buffer.length) {\n\t\twritten += writeSync(fd, buffer, written, buffer.length - written);\n\t}\n}\n\nfunction isMissingEntryError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: unknown }).code === \"ENOENT\"\n\t);\n}\n\n/**\n * Walk every directory component of the authorized path no-follow, holding one\n * directory fd across the walk, then run the caller's final-component step against\n * that walked parent. Any intermediate that is not a real directory — a swapped\n * symlink, a removed component — aborts before the target is touched.\n */\nfunction withTargetDirectory<T>(\n\toperation: PreparedPathOperation,\n\toptions: { createMissingDirectories: boolean },\n\trun: (parent: OpenDirectory, name: string) => T,\n): T {\n\tconst root = parse(operation.path.value).root;\n\tconst components = operation.path.value\n\t\t.slice(root.length)\n\t\t.split(sep)\n\t\t.filter((component) => component.length > 0);\n\tconst name = components[components.length - 1];\n\tif (name === undefined) throw new PreparedTargetChangedError(\"Authorized path has no final component\");\n\tlet parent: OpenDirectory = { fd: openSync(root, constants.O_RDONLY | constants.O_DIRECTORY), path: root };\n\tconst closeParent = (): void => {\n\t\ttry {\n\t\t\tcloseSync(parent.fd);\n\t\t} catch {}\n\t};\n\tfor (const component of components.slice(0, -1)) {\n\t\ttry {\n\t\t\tparent = openChildDirectory(parent, component);\n\t\t} catch (error) {\n\t\t\tif (options.createMissingDirectories && isMissingEntryError(error)) {\n\t\t\t\ttry {\n\t\t\t\t\tmkdirUnder(parent, component);\n\t\t\t\t\tparent = openChildDirectory(parent, component);\n\t\t\t\t\tcontinue;\n\t\t\t\t} catch (mkdirError) {\n\t\t\t\t\tcloseParent();\n\t\t\t\t\tthrow new PreparedTargetChangedError(`Authorized write parent \"${component}\" changed before execution`, {\n\t\t\t\t\t\tcause: mkdirError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcloseParent();\n\t\t\tthrow new PreparedTargetChangedError(`Authorized path component \"${component}\" changed before execution`, {\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\t}\n\ttry {\n\t\treturn run(parent, name);\n\t} finally {\n\t\tcloseParent();\n\t}\n}\n\n/**\n * Execute an authorized write against the prepared target.\n *\n * - `path-existing`: the final component is opened `O_NOFOLLOW`, its descriptor\n * identity is compared with the identity captured at authorization, and only\n * then is the file truncated and written through that descriptor. A swapped\n * alias, an injected symlink, or a redirected parent never matches and the\n * write aborts before any byte changes.\n * - `path-new`: missing parents are created no-follow under the walked directory\n * descriptor, and the file is created `O_CREAT | O_EXCL | O_NOFOLLOW`, so a\n * replaced parent or a pre-placed symlink is never followed.\n */\nexport function writePreparedPath(operation: PreparedPathOperation, content: string | Buffer): void {\n\twithTargetDirectory(operation, { createMissingDirectories: operation.kind === \"path-new\" }, (parent, name) => {\n\t\tif (operation.kind === \"path-existing\") {\n\t\t\tlet fd: number;\n\t\t\ttry {\n\t\t\t\tfd = openUnder(parent, name, constants.O_WRONLY | constants.O_NOFOLLOW);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst stats = fstatSync(fd);\n\t\t\t\tif (stats.dev !== operation.identity.device || stats.ino !== operation.identity.inode) {\n\t\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\");\n\t\t\t\t}\n\t\t\t\tftruncateSync(fd, 0);\n\t\t\t\twriteAll(fd, content);\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(\n\t\t\t\tparent,\n\t\t\t\tname,\n\t\t\t\tconstants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n\t\t\t\t0o600,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized new-file target changed before execution\", { cause: error });\n\t\t}\n\t\ttry {\n\t\t\twriteAll(fd, content);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t});\n}\n\nfunction tryMacOSScreenshotPath(filePath: string): string {\n\treturn filePath.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);\n}\n\nfunction tryNFDVariant(filePath: string): string {\n\t// macOS stores filenames in NFD (decomposed) form, try converting user input to NFD\n\treturn filePath.normalize(\"NFD\");\n}\n\nfunction tryCurlyQuoteVariant(filePath: string): string {\n\t// macOS uses U+2019 (right single quotation mark) in screenshot names like \"Capture d'écran\"\n\t// Users typically type U+0027 (straight apostrophe)\n\treturn filePath.replace(/'/g, \"\\u2019\");\n}\n\nfunction fileExists(filePath: string): boolean {\n\ttry {\n\t\taccessSync(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport async function pathExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function expandPath(filePath: string): string {\n\treturn normalizePath(filePath, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\n/**\n * Resolve a path relative to the given cwd, handling ~ expansion and absolute\n * paths. The result is the single target used by both permission matching and\n * filesystem execution.\n */\nexport function resolveToCwd(filePath: string, cwd: string): string {\n\tconst requested = resolvePath(filePath, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n\ttry {\n\t\treturn realpathSync(requested);\n\t} catch {\n\t\ttry {\n\t\t\treturn joinCanonicalParent(requested);\n\t\t} catch {\n\t\t\treturn requested;\n\t\t}\n\t}\n}\n\nfunction joinCanonicalParent(requested: string): string {\n\treturn join(realpathSync(dirname(requested)), basename(requested));\n}\n\nexport function resolveReadPath(filePath: string, cwd: string): string {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (fileExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && fileExists(amPmVariant)) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && fileExists(nfdVariant)) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && fileExists(curlyVariant)) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n\nexport async function resolveReadPathAsync(filePath: string, cwd: string): Promise<string> {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (await pathExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && (await pathExists(amPmVariant))) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && (await pathExists(nfdVariant))) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && (await pathExists(curlyVariant))) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && (await pathExists(nfdCurlyVariant))) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n"]}
1
+ {"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../../../src/core/tools/path-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,UAAU,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,SAAS,GACT,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAGlE,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAEvC,MAAM,UAAU,oBAAoB,CAAC,QAAgB,EAAE,GAAW,EAAyB;IAC1F,MAAM,aAAa,GAAG,YAAY,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAClD,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACnF,IAAI,CAAC;QACJ,MAAM,KAAK,GAAG,QAAQ,CAAC,aAAa,CAAC,CAAC;QACtC,OAAO;YACN,IAAI,EAAE,eAAe;YACrB,IAAI,EAAE,EAAE,IAAI,EAAE,gBAAgB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U,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;IAC3C,IAAI,UAAU,KAAK,QAAQ,IAAI,CAAC,MAAM,UAAU,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;QAC/D,OAAO,UAAU,CAAC;IACnB,CAAC;IAED,kEAAkE;IAClE,MAAM,YAAY,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IACpD,IAAI,YAAY,KAAK,QAAQ,IAAI,CAAC,MAAM,UAAU,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC;QACnE,OAAO,YAAY,CAAC;IACrB,CAAC;IAED,wFAAuF;IACvF,MAAM,eAAe,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;IACzD,IAAI,eAAe,KAAK,QAAQ,IAAI,CAAC,MAAM,UAAU,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC;QACzE,OAAO,eAAe,CAAC;IACxB,CAAC;IAED,OAAO,QAAQ,CAAC;AAAA,CAChB","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport {\n\taccessSync,\n\tcloseSync,\n\tconstants,\n\texistsSync,\n\tfchmodSync,\n\tfstatSync,\n\tftruncateSync,\n\tmkdirSync,\n\topenSync,\n\treadSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, parse, sep } from \"node:path\";\nimport { normalizePath, resolvePath } from \"../../utils/paths.ts\";\nimport type { FileIdentity, PreparedPathOperation } from \"../permissions/operations.ts\";\n\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nexport function preparePathOperation(filePath: string, cwd: string): PreparedPathOperation {\n\tconst canonicalPath = resolveToCwd(filePath, cwd);\n\tif (!isAbsolute(canonicalPath)) throw new Error(\"Canonical path must be absolute\");\n\ttry {\n\t\tconst stats = statSync(canonicalPath);\n\t\treturn {\n\t\t\tkind: \"path-existing\",\n\t\t\tpath: { kind: \"canonical-path\", value: canonicalPath },\n\t\t\tidentity: { device: stats.dev, inode: stats.ino },\n\t\t};\n\t} catch {\n\t\treturn { kind: \"path-new\", path: { kind: \"canonical-path\", value: canonicalPath } };\n\t}\n}\n\n/**\n * Verify a descriptor's identity against the one captured at authorization.\n *\n * A zero inode is not an identity. POSIX reserves inode 0 for \"no file\", and Node reports 0\n * on Windows when the file index is unavailable for the handle. Comparing two of them\n * succeeds trivially, which would turn this check -- the only thing standing between an\n * authorized target and one swapped underneath it -- into a no-op at exactly the moment the\n * platform could not say what we are holding. An unverifiable target is not an authorized\n * one, so refuse rather than proceed.\n *\n * The mismatched case keeps its own wording: \"changed\" and \"could not be verified\" are\n * different facts, and an operator reading the refusal should be able to tell them apart.\n */\nfunction verifyPreparedIdentity(subject: \"read\" | \"write\", stats: Stats, identity: FileIdentity): void {\n\tif (stats.ino === 0 || identity.inode === 0) {\n\t\tthrow new PreparedTargetChangedError(`Authorized ${subject} target identity could not be verified`);\n\t}\n\tif (stats.dev !== identity.device || stats.ino !== identity.inode) {\n\t\tthrow new PreparedTargetChangedError(`Authorized ${subject} target changed before execution`);\n\t}\n}\n\n/**\n * Read the authorized target through a no-follow final-component open, verifying\n * the descriptor identity captured at authorization before any byte is returned.\n * A replaced alias or an injected symlink never matches and the read aborts.\n */\nexport function readPreparedPath(operation: PreparedPathOperation, maxBytes?: number): Buffer {\n\tif (operation.kind !== \"path-existing\") {\n\t\tthrow new PreparedTargetChangedError(\"Authorized read target did not exist when permission was checked\");\n\t}\n\treturn withTargetDirectory(operation, { createMissingDirectories: false }, (parent, name) => {\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(parent, name, constants.O_RDONLY | constants.O_NOFOLLOW);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized read target changed before execution\", { cause: error });\n\t\t}\n\t\ttry {\n\t\t\tconst stats = fstatSync(fd);\n\t\t\tverifyPreparedIdentity(\"read\", stats, operation.identity);\n\t\t\tconst length = maxBytes === undefined ? stats.size : Math.min(stats.size, maxBytes);\n\t\t\tconst buffer = Buffer.alloc(length);\n\t\t\tlet offset = 0;\n\t\t\twhile (offset < buffer.length) {\n\t\t\t\tconst read = readSync(fd, buffer, offset, buffer.length - offset, null);\n\t\t\t\tif (read === 0) break;\n\t\t\t\toffset += read;\n\t\t\t}\n\t\t\treturn offset === buffer.length ? buffer : buffer.subarray(0, offset);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t});\n}\n\n/** The authorized target changed between permission evaluation and execution. */\nexport class PreparedTargetChangedError extends Error {}\n\nconst PROC_FD = \"/proc/self/fd\";\nlet procFdAvailable: boolean | undefined;\n\n/** /proc lets an already-open directory fd act as the parent of the next open, so a swapped intermediate directory cannot be traversed. */\nfunction useProcFd(): boolean {\n\tif (procFdAvailable === undefined) {\n\t\ttry {\n\t\t\tprocFdAvailable = existsSync(`${PROC_FD}/self`);\n\t\t} catch {\n\t\t\tprocFdAvailable = false;\n\t\t}\n\t}\n\treturn procFdAvailable;\n}\n\ninterface OpenDirectory {\n\tfd: number;\n\t/** Fallback parent path for platforms without /proc/self/fd. */\n\tpath: string;\n}\n\nfunction openUnder(parent: OpenDirectory, name: string, flags: number, mode?: number): number {\n\tif (useProcFd()) return openSync(`${PROC_FD}/${parent.fd}/${name}`, flags, mode);\n\treturn openSync(join(parent.path, name), flags, mode);\n}\n\nfunction renameUnder(parent: OpenDirectory, from: string, to: string): void {\n\tif (useProcFd()) renameSync(`${PROC_FD}/${parent.fd}/${from}`, `${PROC_FD}/${parent.fd}/${to}`);\n\telse renameSync(join(parent.path, from), join(parent.path, to));\n}\n\nfunction unlinkUnder(parent: OpenDirectory, name: string): void {\n\ttry {\n\t\tif (useProcFd()) unlinkSync(`${PROC_FD}/${parent.fd}/${name}`);\n\t\telse unlinkSync(join(parent.path, name));\n\t} catch {}\n}\n\n/**\n * The name of the sibling a publish stages into.\n *\n * It carries enough of the destination to be recognizable if a crash ever strands one, and\n * a pid and a random suffix so two publishes in one directory cannot collide. The base is\n * truncated to fit: a destination already at the filesystem's per-component limit would\n * otherwise produce a staging name past it, and fail a write that truncate-in-place handled.\n * 255 is the limit on every filesystem this runs on that has one at all.\n */\nfunction stagingName(name: string): string {\n\tconst suffix = `.apex-${process.pid}-${randomUUID().slice(0, 8)}`;\n\tconst budget = 255 - suffix.length - 1;\n\treturn `.${name.slice(0, Math.max(1, budget))}${suffix}`;\n}\n\n/**\n * Write `content` to a sibling of `name` and rename it over `name`.\n *\n * The rename is the publish. Until it runs, `name` still refers to the old inode with all\n * of its old bytes, so a crash, a full disk, or a kill mid-write destroys nothing. The\n * caller has already proved that `name` refers to the authorized target; this only decides\n * how the bytes arrive.\n *\n * `mode` is the destination's, captured from the descriptor the identity check used, so a\n * publish does not quietly reset a file's permissions to the temp file's. Ownership is not\n * carried: a rename installs a file this process created, so a target owned by someone else\n * and merely writable by us changes owner. That is inherent to publishing by rename and is\n * the same trade the session store already makes.\n *\n * One guarantee narrows, and it is worth stating plainly rather than leaving for a reader to\n * derive. ADR 0029's identity check still runs and still aborts on a mismatch, but it now\n * proves the name referred to the authorized file at the moment of the check rather than at\n * the moment of the write. Writing through the checked descriptor could not be redirected by\n * a later swap; a rename can be, because it resolves the name again. The window is between\n * the identity check and the rename, both anchored to the same validated parent descriptor,\n * and exploiting it needs a local attacker placing a file at that exact name in a directory\n * the call was already authorized to write. That is traded for crash safety, which is not a\n * race: it is what every interrupted write did.\n *\n * Windows refuses a rename onto a destination another handle holds open, and an ordinary read\n * handle is enough to trigger it. An earlier version of this comment called that an acceptable\n * trade. Three-OS CI disproved it: the case is an editor, a watcher, or a language server with\n * the file open, which is the common case rather than an exotic one, and failing the write\n * there is not a trade a user opted into. It falls back to `writeInPlace` instead, so Windows\n * gets atomic publish whenever it can and a working write when it cannot.\n */\nfunction publishByRename(parent: OpenDirectory, name: string, content: string | Buffer, mode: number): boolean {\n\tconst temporary = stagingName(name);\n\tlet fd: number;\n\ttry {\n\t\tfd = openUnder(\n\t\t\tparent,\n\t\t\ttemporary,\n\t\t\tconstants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n\t\t\tmode,\n\t\t);\n\t} catch (error) {\n\t\tthrow new PreparedTargetChangedError(\"Authorized write could not stage its replacement\", { cause: error });\n\t}\n\ttry {\n\t\twriteAll(fd, content);\n\t\t// The create mode passes through umask; the destination's mode does not.\n\t\tfchmodSync(fd, mode);\n\t\tcloseSync(fd);\n\t} catch (error) {\n\t\ttry {\n\t\t\tcloseSync(fd);\n\t\t} catch {}\n\t\tunlinkUnder(parent, temporary);\n\t\tthrow error;\n\t}\n\ttry {\n\t\trenameUnder(parent, temporary, name);\n\t\treturn true;\n\t} catch (error) {\n\t\tunlinkUnder(parent, temporary);\n\t\tif (isWindowsSharingViolation(error)) return false;\n\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t}\n}\n\n/**\n * Windows refuses to rename onto a destination another handle holds open, and an ordinary\n * read handle is enough. An editor, a watcher, or a language server with the file open is\n * the common case, not an exotic one, so a rename that cannot land there has to fall back\n * rather than fail the write.\n *\n * Three OS CI found this. The Linux and macOS jobs pass, because POSIX renames over an open\n * file happily.\n */\nfunction isWindowsSharingViolation(error: unknown): boolean {\n\tif (process.platform !== \"win32\") return false;\n\tconst code = (error as { code?: unknown } | null)?.code;\n\treturn code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n}\n\n/**\n * The pre-rename publish, kept for the one case that cannot use a rename.\n *\n * This is the truncate-then-write window the rename exists to close, so it runs only when\n * Windows has refused the rename. Crash safety is lost for that write; the alternative is\n * refusing to write a file something else has open, which is worse and is not a trade a\n * user opted into. The identity check is re-run against a freshly opened descriptor, so the\n * weaker durability does not come with a weaker target guarantee.\n */\nfunction writeInPlace(parent: OpenDirectory, name: string, content: string | Buffer, identity?: FileIdentity): void {\n\tlet fd: number;\n\ttry {\n\t\tfd = openUnder(parent, name, constants.O_WRONLY | constants.O_NOFOLLOW);\n\t} catch (error) {\n\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t}\n\ttry {\n\t\tif (identity) {\n\t\t\tverifyPreparedIdentity(\"write\", fstatSync(fd), identity);\n\t\t}\n\t\tftruncateSync(fd, 0);\n\t\twriteAll(fd, content);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n}\n\nfunction mkdirUnder(parent: OpenDirectory, name: string): void {\n\tif (useProcFd()) mkdirSync(`${PROC_FD}/${parent.fd}/${name}`);\n\telse mkdirSync(join(parent.path, name));\n}\n\nfunction openChildDirectory(parent: OpenDirectory, name: string): OpenDirectory {\n\tconst flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;\n\tconst fd = openUnder(parent, name, flags);\n\tcloseSync(parent.fd);\n\treturn { fd, path: join(parent.path, name) };\n}\n\nfunction writeAll(fd: number, content: string | Buffer): void {\n\tconst buffer = typeof content === \"string\" ? Buffer.from(content, \"utf-8\") : content;\n\tlet written = 0;\n\twhile (written < buffer.length) {\n\t\twritten += writeSync(fd, buffer, written, buffer.length - written);\n\t}\n}\n\nfunction isMissingEntryError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: unknown }).code === \"ENOENT\"\n\t);\n}\n\n/**\n * Walk every directory component of the authorized path no-follow, holding one\n * directory fd across the walk, then run the caller's final-component step against\n * that walked parent. Any intermediate that is not a real directory — a swapped\n * symlink, a removed component — aborts before the target is touched.\n */\nfunction withTargetDirectory<T>(\n\toperation: PreparedPathOperation,\n\toptions: { createMissingDirectories: boolean },\n\trun: (parent: OpenDirectory, name: string) => T,\n): T {\n\tconst root = parse(operation.path.value).root;\n\tconst components = operation.path.value\n\t\t.slice(root.length)\n\t\t.split(sep)\n\t\t.filter((component) => component.length > 0);\n\tconst name = components[components.length - 1];\n\tif (name === undefined) throw new PreparedTargetChangedError(\"Authorized path has no final component\");\n\tlet parent: OpenDirectory = { fd: openSync(root, constants.O_RDONLY | constants.O_DIRECTORY), path: root };\n\tconst closeParent = (): void => {\n\t\ttry {\n\t\t\tcloseSync(parent.fd);\n\t\t} catch {}\n\t};\n\tfor (const component of components.slice(0, -1)) {\n\t\ttry {\n\t\t\tparent = openChildDirectory(parent, component);\n\t\t} catch (error) {\n\t\t\tif (options.createMissingDirectories && isMissingEntryError(error)) {\n\t\t\t\ttry {\n\t\t\t\t\tmkdirUnder(parent, component);\n\t\t\t\t\tparent = openChildDirectory(parent, component);\n\t\t\t\t\tcontinue;\n\t\t\t\t} catch (mkdirError) {\n\t\t\t\t\tcloseParent();\n\t\t\t\t\tthrow new PreparedTargetChangedError(`Authorized write parent \"${component}\" changed before execution`, {\n\t\t\t\t\t\tcause: mkdirError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcloseParent();\n\t\t\tthrow new PreparedTargetChangedError(`Authorized path component \"${component}\" changed before execution`, {\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\t}\n\ttry {\n\t\treturn run(parent, name);\n\t} finally {\n\t\tcloseParent();\n\t}\n}\n\n/**\n * Execute an authorized write against the prepared target.\n *\n * - `path-existing`: the final component is opened `O_NOFOLLOW`, its descriptor\n * identity is compared with the identity captured at authorization, and only\n * then is the file truncated and written through that descriptor. A swapped\n * alias, an injected symlink, or a redirected parent never matches and the\n * write aborts before any byte changes.\n * - `path-new`: missing parents are created no-follow under the walked directory\n * descriptor, and the file is created `O_CREAT | O_EXCL | O_NOFOLLOW`, so a\n * replaced parent or a pre-placed symlink is never followed.\n */\nexport function writePreparedPath(operation: PreparedPathOperation, content: string | Buffer): void {\n\twithTargetDirectory(operation, { createMissingDirectories: operation.kind === \"path-new\" }, (parent, name) => {\n\t\tif (operation.kind === \"path-existing\") {\n\t\t\tlet fd: number;\n\t\t\ttry {\n\t\t\t\tfd = openUnder(parent, name, constants.O_WRONLY | constants.O_NOFOLLOW);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t\t\t}\n\t\t\tlet mode: number;\n\t\t\ttry {\n\t\t\t\tconst stats = fstatSync(fd);\n\t\t\t\tverifyPreparedIdentity(\"write\", stats, operation.identity);\n\t\t\t\tmode = stats.mode & 0o7777;\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\tif (!publishByRename(parent, name, content, mode)) {\n\t\t\t\twriteInPlace(parent, name, content, operation.identity);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t// The exclusive create is what proves the name was still absent, which is the whole\n\t\t// authorization for a new-file write. It reserves the name; the rename below then\n\t\t// replaces that empty placeholder, so the name never holds a half-written file.\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(\n\t\t\t\tparent,\n\t\t\t\tname,\n\t\t\t\tconstants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n\t\t\t\t0o600,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized new-file target changed before execution\", { cause: error });\n\t\t}\n\t\tcloseSync(fd);\n\t\ttry {\n\t\t\t// The reservation this just created is ours, so there is no prior identity to\n\t\t\t// re-check if Windows refuses the rename onto it.\n\t\t\tif (!publishByRename(parent, name, content, 0o600)) {\n\t\t\t\twriteInPlace(parent, name, content);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tunlinkUnder(parent, name);\n\t\t\tthrow error;\n\t\t}\n\t});\n}\n\n/**\n * Atomic publish for an ungated write, where no prepared operation exists to pin the target.\n *\n * `writePreparedPath` is the gated path and the one that matters; this is its counterpart for\n * a tool invoked outside the permission gate, so that neither route can leave a half-written\n * file. It makes no containment claim: with no authorization there is no authorized target to\n * hold the write to, and the no-follow walk would have nothing to check against.\n */\nexport function writePathAtomically(filePath: string, content: string | Buffer): void {\n\tconst temporary = join(dirname(filePath), stagingName(basename(filePath)));\n\t// Only an existing destination has a mode worth carrying. For a new file there is\n\t// nothing to capture, and chmod'ing to the 0o666 open default would force past the\n\t// caller's umask and publish a world-writable file, which `writeFile` never did.\n\tlet destinationMode: number | undefined;\n\ttry {\n\t\tdestinationMode = statSync(filePath).mode & 0o7777;\n\t} catch {}\n\tconst fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, destinationMode ?? 0o666);\n\ttry {\n\t\twriteAll(fd, content);\n\t\tif (destinationMode !== undefined) fchmodSync(fd, destinationMode);\n\t\tcloseSync(fd);\n\t} catch (error) {\n\t\ttry {\n\t\t\tcloseSync(fd);\n\t\t} catch {}\n\t\ttry {\n\t\t\tunlinkSync(temporary);\n\t\t} catch {}\n\t\tthrow error;\n\t}\n\ttry {\n\t\trenameSync(temporary, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tunlinkSync(temporary);\n\t\t} catch {}\n\t\t// Same Windows sharing case as the gated path, and the same answer: a file something\n\t\t// else has open is still a file the caller asked to write.\n\t\tif (!isWindowsSharingViolation(error)) throw error;\n\t\tconst fd = openSync(filePath, constants.O_WRONLY | constants.O_CREAT, destinationMode ?? 0o666);\n\t\ttry {\n\t\t\tftruncateSync(fd, 0);\n\t\t\twriteAll(fd, content);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t}\n}\n\nfunction tryMacOSScreenshotPath(filePath: string): string {\n\treturn filePath.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);\n}\n\nfunction tryNFDVariant(filePath: string): string {\n\t// macOS stores filenames in NFD (decomposed) form, try converting user input to NFD\n\treturn filePath.normalize(\"NFD\");\n}\n\nfunction tryCurlyQuoteVariant(filePath: string): string {\n\t// macOS uses U+2019 (right single quotation mark) in screenshot names like \"Capture d'écran\"\n\t// Users typically type U+0027 (straight apostrophe)\n\treturn filePath.replace(/'/g, \"\\u2019\");\n}\n\nfunction fileExists(filePath: string): boolean {\n\ttry {\n\t\taccessSync(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport async function pathExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function expandPath(filePath: string): string {\n\treturn normalizePath(filePath, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\n/**\n * Resolve a path relative to the given cwd, handling ~ expansion and absolute\n * paths. The result is the single target used by both permission matching and\n * filesystem execution.\n */\nexport function resolveToCwd(filePath: string, cwd: string): string {\n\tconst requested = resolvePath(filePath, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n\ttry {\n\t\treturn realpathSync(requested);\n\t} catch {\n\t\ttry {\n\t\t\treturn joinCanonicalParent(requested);\n\t\t} catch {\n\t\t\treturn requested;\n\t\t}\n\t}\n}\n\nfunction joinCanonicalParent(requested: string): string {\n\treturn join(realpathSync(dirname(requested)), basename(requested));\n}\n\nexport function resolveReadPath(filePath: string, cwd: string): string {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (fileExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && fileExists(amPmVariant)) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && fileExists(nfdVariant)) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && fileExists(curlyVariant)) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n\nexport async function resolveReadPathAsync(filePath: string, cwd: string): Promise<string> {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (await pathExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && (await pathExists(amPmVariant))) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && (await pathExists(nfdVariant))) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && (await pathExists(curlyVariant))) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && (await pathExists(nfdCurlyVariant))) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAK5C,OAAO,EAA4B,KAAK,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAEpG,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,eAAe,CAAC;AACxE,OAAO,KAAK,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQlF,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,eAAO,MAAM,iCAAiC;;;CAGpC,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD,MAAM,WAAW,gBAAgB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,wFAAwF;IACxF,WAAW,CAAC,EAAE,kBAAkB,CAAC;CACjC;AAMD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC/B,8BAA8B;IAC9B,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,mCAAmC;IACnC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC;;;;OAIG;IACH,aAAa,CAAC,EAAE,CAAC,SAAS,EAAE,qBAAqB,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAC5E;AAQD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B;;;;;OAKG;IACH,qBAAqB,CAAC,EAAE,qBAAqB,CAAC;CAC9C;AAwLD,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gBAAgB,GACxB,kBAAkB,CAAC,OAAO,WAAW,EAAE,gBAAgB,CAAC,CA6H1D;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,SAAS,CAAC,OAAO,WAAW,CAAC,CAEtG","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentTool } from \"apex-code-agent-core\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { getPreparedPathOperation, type PreparedPathOperation } from \"../permissions/operations.ts\";\nimport type { PermissionPreview } from \"../permissions/responder.ts\";\nimport type { ApexToolDefinition, EvidenceRecord } from \"./contract.ts\";\nimport type { DiagnosticsOperations, DiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { diagnosticEvidenceForPath, formatDiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { createPathPermissionSpec } from \"./path-permission.ts\";\nimport { readPreparedPath, resolveToCwd, writePreparedPath } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport const writeToolSystemPromptContribution = {\n\tsnippet: \"Create or overwrite files\",\n\tguidelines: [\"Use write only for new files or complete rewrites.\"],\n} as const;\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\nexport interface WriteToolDetails {\n\tbyteCount: number;\n\tcontentHash: string;\n\t/** Present only when `WriteToolOptions.diagnosticsOperations` is configured (LSP.4). */\n\tdiagnostics?: DiagnosticsOutcome;\n}\n\nfunction sha256(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n\t/**\n\t * Execute a gate-prepared write no-follow against the authorized target.\n\t * Required for gated calls: when a prepared operation exists, pathname writes\n\t * are never used, so an unset implementation fails closed.\n\t */\n\twritePrepared?: (operation: PreparedPathOperation, content: string) => void;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n\twritePrepared: (operation, content) => writePreparedPath(operation, content),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n\t/**\n\t * Optional post-mutation diagnostics (LSP.4). Absent by default -- byte-identical\n\t * existing behavior. When present, called inside `withFileMutationQueue` after the\n\t * write succeeds and before the queue releases, matching `TestOperations`/\n\t * `GrepOperations`' injection pattern (`test.ts:28`, `grep.ts:58`).\n\t */\n\tdiagnosticsOperations?: DiagnosticsOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nconst WRITE_PREVIEW_MAX_BYTES = 512 * 1024;\n\n/** A trailing newline terminates the last line rather than starting an empty one. */\nconst countLines = (text: string): number => {\n\tif (text === \"\") return 0;\n\tconst body = text.endsWith(\"\\n\") ? text.slice(0, -1) : text;\n\treturn body.split(\"\\n\").length;\n};\n\nconst lineCount = (text: string): string => {\n\tconst n = countLines(text);\n\treturn `${n} ${n === 1 ? \"line\" : \"lines\"}`;\n};\n\n/**\n * Describe a whole-file replacement without drawing the whole file.\n *\n * A diff of a write is the file twice over, which is not what a person needs in\n * order to decide. Sizes on both sides answer the question that matters, which is\n * whether this replaces something substantial. Read through the prepared\n * operation, so a swapped target fails here as it fails the write (ADR 0029).\n */\nfunction previewWrite(params: { path: string; content: string }): PermissionPreview {\n\tconst incoming = `${lineCount(params.content)}, ${Buffer.byteLength(params.content)} bytes`;\n\tconst prepared = getPreparedPathOperation(params);\n\tif (!prepared) return { kind: \"unavailable\", reason: \"No authorized target was prepared for this call\" };\n\tif (prepared.kind === \"path-new\") {\n\t\treturn { kind: \"summary\", lines: [`Create ${params.path} with ${incoming}`] };\n\t}\n\n\tconst buffer = readPreparedPath(prepared, WRITE_PREVIEW_MAX_BYTES + 1);\n\tif (buffer.byteLength > WRITE_PREVIEW_MAX_BYTES) {\n\t\treturn {\n\t\t\tkind: \"summary\",\n\t\t\tlines: [`Replace ${params.path}, over ${WRITE_PREVIEW_MAX_BYTES / 1024}KB, with ${incoming}`],\n\t\t};\n\t}\n\tconst existing = buffer.includes(0)\n\t\t? `${buffer.byteLength} bytes of binary`\n\t\t: `${lineCount(buffer.toString(\"utf-8\"))}, ${buffer.byteLength} bytes`;\n\treturn { kind: \"summary\", lines: [`Replace ${params.path}`, `${existing} becomes ${incoming}`] };\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ApexToolDefinition<typeof writeSchema, WriteToolDetails> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\tconst diagnosticsOperations = options?.diagnosticsOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: writeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...writeToolSystemPromptContribution.guidelines],\n\t\tparameters: writeSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"fs.write\"]),\n\t\t\tpermission: createPathPermissionSpec({\n\t\t\t\tcwd,\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tverb: \"Write\",\n\t\t\t\tgetPath: (params) => params.path,\n\t\t\t\tpreviewCall: (params) => previewWrite(params as { path: string; content: string }),\n\t\t\t}),\n\t\t\tcontext: { resultRecoverable: true, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set(diagnosticsOperations ? [\"diff\", \"diagnostic\"] : [\"diff\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst details = result.details;\n\t\t\t\t\tconst records: EvidenceRecord[] = details\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"diff\",\n\t\t\t\t\t\t\t\t\tpath: params.path,\n\t\t\t\t\t\t\t\t\tbyteCount: details.byteCount,\n\t\t\t\t\t\t\t\t\tcontentHash: details.contentHash,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [{ kind: \"diff\", path: params.path }];\n\t\t\t\t\tif (details?.diagnostics) records.push(diagnosticEvidenceForPath(params.path, details.diagnostics));\n\t\t\t\t\treturn records;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(_toolCallId, input: { path: string; content: string }, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst { path, content } = input;\n\t\t\tconst prepared = getPreparedPathOperation(input);\n\t\t\tconst absolutePath = prepared?.path.value ?? resolveToCwd(path, cwd);\n\t\t\tif (prepared && !ops.writePrepared) {\n\t\t\t\tthrow new Error(\"No safe prepared write operation is available for this gated write\");\n\t\t\t}\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\tif (prepared) {\n\t\t\t\t\t// Gated path: no-follow execution against the exact authorized target.\n\t\t\t\t\tops.writePrepared!(prepared, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t} else {\n\t\t\t\t\t// Create parent directories if needed.\n\t\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\t\tthrowIfAborted();\n\n\t\t\t\t\t// Write the file contents.\n\t\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t}\n\n\t\t\t\tconst successText = `Successfully wrote ${content.length} bytes to ${path}`;\n\n\t\t\t\tif (diagnosticsOperations) {\n\t\t\t\t\tconst diagnostics = await diagnosticsOperations.afterMutation(absolutePath, signal);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `${successText}\\n\\n${formatDiagnosticsOutcome(diagnostics)}` }],\n\t\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content), diagnostics },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: successText }],\n\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content) },\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.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,OAAO,WAAW,EAAE,gBAAgB,CAAC,CA6H1D;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,SAAS,CAAC,OAAO,WAAW,CAAC,CAEtG","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentTool } from \"apex-code-agent-core\";\nimport { mkdir as fsMkdir } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { getPreparedPathOperation, type PreparedPathOperation } from \"../permissions/operations.ts\";\nimport type { PermissionPreview } from \"../permissions/responder.ts\";\nimport type { ApexToolDefinition, EvidenceRecord } from \"./contract.ts\";\nimport type { DiagnosticsOperations, DiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { diagnosticEvidenceForPath, formatDiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { createPathPermissionSpec } from \"./path-permission.ts\";\nimport { readPreparedPath, resolveToCwd, writePathAtomically, writePreparedPath } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport const writeToolSystemPromptContribution = {\n\tsnippet: \"Create or overwrite files\",\n\tguidelines: [\"Use write only for new files or complete rewrites.\"],\n} as const;\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\nexport interface WriteToolDetails {\n\tbyteCount: number;\n\tcontentHash: string;\n\t/** Present only when `WriteToolOptions.diagnosticsOperations` is configured (LSP.4). */\n\tdiagnostics?: DiagnosticsOutcome;\n}\n\nfunction sha256(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n\t/**\n\t * Execute a gate-prepared write no-follow against the authorized target.\n\t * Required for gated calls: when a prepared operation exists, pathname writes\n\t * are never used, so an unset implementation fails closed.\n\t */\n\twritePrepared?: (operation: PreparedPathOperation, content: string) => void;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: async (path, content) => writePathAtomically(path, content),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n\twritePrepared: (operation, content) => writePreparedPath(operation, content),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n\t/**\n\t * Optional post-mutation diagnostics (LSP.4). Absent by default -- byte-identical\n\t * existing behavior. When present, called inside `withFileMutationQueue` after the\n\t * write succeeds and before the queue releases, matching `TestOperations`/\n\t * `GrepOperations`' injection pattern (`test.ts:28`, `grep.ts:58`).\n\t */\n\tdiagnosticsOperations?: DiagnosticsOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nconst WRITE_PREVIEW_MAX_BYTES = 512 * 1024;\n\n/** A trailing newline terminates the last line rather than starting an empty one. */\nconst countLines = (text: string): number => {\n\tif (text === \"\") return 0;\n\tconst body = text.endsWith(\"\\n\") ? text.slice(0, -1) : text;\n\treturn body.split(\"\\n\").length;\n};\n\nconst lineCount = (text: string): string => {\n\tconst n = countLines(text);\n\treturn `${n} ${n === 1 ? \"line\" : \"lines\"}`;\n};\n\n/**\n * Describe a whole-file replacement without drawing the whole file.\n *\n * A diff of a write is the file twice over, which is not what a person needs in\n * order to decide. Sizes on both sides answer the question that matters, which is\n * whether this replaces something substantial. Read through the prepared\n * operation, so a swapped target fails here as it fails the write (ADR 0029).\n */\nfunction previewWrite(params: { path: string; content: string }): PermissionPreview {\n\tconst incoming = `${lineCount(params.content)}, ${Buffer.byteLength(params.content)} bytes`;\n\tconst prepared = getPreparedPathOperation(params);\n\tif (!prepared) return { kind: \"unavailable\", reason: \"No authorized target was prepared for this call\" };\n\tif (prepared.kind === \"path-new\") {\n\t\treturn { kind: \"summary\", lines: [`Create ${params.path} with ${incoming}`] };\n\t}\n\n\tconst buffer = readPreparedPath(prepared, WRITE_PREVIEW_MAX_BYTES + 1);\n\tif (buffer.byteLength > WRITE_PREVIEW_MAX_BYTES) {\n\t\treturn {\n\t\t\tkind: \"summary\",\n\t\t\tlines: [`Replace ${params.path}, over ${WRITE_PREVIEW_MAX_BYTES / 1024}KB, with ${incoming}`],\n\t\t};\n\t}\n\tconst existing = buffer.includes(0)\n\t\t? `${buffer.byteLength} bytes of binary`\n\t\t: `${lineCount(buffer.toString(\"utf-8\"))}, ${buffer.byteLength} bytes`;\n\treturn { kind: \"summary\", lines: [`Replace ${params.path}`, `${existing} becomes ${incoming}`] };\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ApexToolDefinition<typeof writeSchema, WriteToolDetails> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\tconst diagnosticsOperations = options?.diagnosticsOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: writeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...writeToolSystemPromptContribution.guidelines],\n\t\tparameters: writeSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"fs.write\"]),\n\t\t\tpermission: createPathPermissionSpec({\n\t\t\t\tcwd,\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tverb: \"Write\",\n\t\t\t\tgetPath: (params) => params.path,\n\t\t\t\tpreviewCall: (params) => previewWrite(params as { path: string; content: string }),\n\t\t\t}),\n\t\t\tcontext: { resultRecoverable: true, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set(diagnosticsOperations ? [\"diff\", \"diagnostic\"] : [\"diff\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst details = result.details;\n\t\t\t\t\tconst records: EvidenceRecord[] = details\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"diff\",\n\t\t\t\t\t\t\t\t\tpath: params.path,\n\t\t\t\t\t\t\t\t\tbyteCount: details.byteCount,\n\t\t\t\t\t\t\t\t\tcontentHash: details.contentHash,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [{ kind: \"diff\", path: params.path }];\n\t\t\t\t\tif (details?.diagnostics) records.push(diagnosticEvidenceForPath(params.path, details.diagnostics));\n\t\t\t\t\treturn records;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(_toolCallId, input: { path: string; content: string }, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst { path, content } = input;\n\t\t\tconst prepared = getPreparedPathOperation(input);\n\t\t\tconst absolutePath = prepared?.path.value ?? resolveToCwd(path, cwd);\n\t\t\tif (prepared && !ops.writePrepared) {\n\t\t\t\tthrow new Error(\"No safe prepared write operation is available for this gated write\");\n\t\t\t}\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\tif (prepared) {\n\t\t\t\t\t// Gated path: no-follow execution against the exact authorized target.\n\t\t\t\t\tops.writePrepared!(prepared, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t} else {\n\t\t\t\t\t// Create parent directories if needed.\n\t\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\t\tthrowIfAborted();\n\n\t\t\t\t\t// Write the file contents.\n\t\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t}\n\n\t\t\t\tconst successText = `Successfully wrote ${content.length} bytes to ${path}`;\n\n\t\t\t\tif (diagnosticsOperations) {\n\t\t\t\t\tconst diagnostics = await diagnosticsOperations.afterMutation(absolutePath, signal);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `${successText}\\n\\n${formatDiagnosticsOutcome(diagnostics)}` }],\n\t\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content), diagnostics },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: successText }],\n\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content) },\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Container, Text } from "@earendil-works/pi-tui";
3
- import { mkdir as fsMkdir, writeFile as fsWriteFile } from "fs/promises";
3
+ import { mkdir as fsMkdir } from "fs/promises";
4
4
  import { dirname } from "path";
5
5
  import { Type } from "typebox";
6
6
  import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
@@ -10,7 +10,7 @@ import { getPreparedPathOperation } from "../permissions/operations.js";
10
10
  import { diagnosticEvidenceForPath, formatDiagnosticsOutcome } from "./diagnostics.js";
11
11
  import { withFileMutationQueue } from "./file-mutation-queue.js";
12
12
  import { createPathPermissionSpec } from "./path-permission.js";
13
- import { readPreparedPath, resolveToCwd, writePreparedPath } from "./path-utils.js";
13
+ import { readPreparedPath, resolveToCwd, writePathAtomically, writePreparedPath } from "./path-utils.js";
14
14
  import { normalizeDisplayText, renderToolPath, replaceTabs, str } from "./render-utils.js";
15
15
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
16
16
  const writeSchema = Type.Object({
@@ -25,7 +25,7 @@ function sha256(value) {
25
25
  return createHash("sha256").update(value).digest("hex");
26
26
  }
27
27
  const defaultWriteOperations = {
28
- writeFile: (path, content) => fsWriteFile(path, content, "utf-8"),
28
+ writeFile: async (path, content) => writePathAtomically(path, content),
29
29
  mkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => { }),
30
30
  writePrepared: (operation, content) => writePreparedPath(operation, content),
31
31
  };
@@ -1 +1 @@
1
- {"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/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C,OAAO,CAAC,MAAM,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,OAA0B,EAAiC;IACvG,OAAO,kBAAkB,CAAC,yBAAyB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACnE","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentTool } from \"apex-code-agent-core\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { getPreparedPathOperation, type PreparedPathOperation } from \"../permissions/operations.ts\";\nimport type { PermissionPreview } from \"../permissions/responder.ts\";\nimport type { ApexToolDefinition, EvidenceRecord } from \"./contract.ts\";\nimport type { DiagnosticsOperations, DiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { diagnosticEvidenceForPath, formatDiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { createPathPermissionSpec } from \"./path-permission.ts\";\nimport { readPreparedPath, resolveToCwd, writePreparedPath } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport const writeToolSystemPromptContribution = {\n\tsnippet: \"Create or overwrite files\",\n\tguidelines: [\"Use write only for new files or complete rewrites.\"],\n} as const;\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\nexport interface WriteToolDetails {\n\tbyteCount: number;\n\tcontentHash: string;\n\t/** Present only when `WriteToolOptions.diagnosticsOperations` is configured (LSP.4). */\n\tdiagnostics?: DiagnosticsOutcome;\n}\n\nfunction sha256(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n\t/**\n\t * Execute a gate-prepared write no-follow against the authorized target.\n\t * Required for gated calls: when a prepared operation exists, pathname writes\n\t * are never used, so an unset implementation fails closed.\n\t */\n\twritePrepared?: (operation: PreparedPathOperation, content: string) => void;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n\twritePrepared: (operation, content) => writePreparedPath(operation, content),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n\t/**\n\t * Optional post-mutation diagnostics (LSP.4). Absent by default -- byte-identical\n\t * existing behavior. When present, called inside `withFileMutationQueue` after the\n\t * write succeeds and before the queue releases, matching `TestOperations`/\n\t * `GrepOperations`' injection pattern (`test.ts:28`, `grep.ts:58`).\n\t */\n\tdiagnosticsOperations?: DiagnosticsOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nconst WRITE_PREVIEW_MAX_BYTES = 512 * 1024;\n\n/** A trailing newline terminates the last line rather than starting an empty one. */\nconst countLines = (text: string): number => {\n\tif (text === \"\") return 0;\n\tconst body = text.endsWith(\"\\n\") ? text.slice(0, -1) : text;\n\treturn body.split(\"\\n\").length;\n};\n\nconst lineCount = (text: string): string => {\n\tconst n = countLines(text);\n\treturn `${n} ${n === 1 ? \"line\" : \"lines\"}`;\n};\n\n/**\n * Describe a whole-file replacement without drawing the whole file.\n *\n * A diff of a write is the file twice over, which is not what a person needs in\n * order to decide. Sizes on both sides answer the question that matters, which is\n * whether this replaces something substantial. Read through the prepared\n * operation, so a swapped target fails here as it fails the write (ADR 0029).\n */\nfunction previewWrite(params: { path: string; content: string }): PermissionPreview {\n\tconst incoming = `${lineCount(params.content)}, ${Buffer.byteLength(params.content)} bytes`;\n\tconst prepared = getPreparedPathOperation(params);\n\tif (!prepared) return { kind: \"unavailable\", reason: \"No authorized target was prepared for this call\" };\n\tif (prepared.kind === \"path-new\") {\n\t\treturn { kind: \"summary\", lines: [`Create ${params.path} with ${incoming}`] };\n\t}\n\n\tconst buffer = readPreparedPath(prepared, WRITE_PREVIEW_MAX_BYTES + 1);\n\tif (buffer.byteLength > WRITE_PREVIEW_MAX_BYTES) {\n\t\treturn {\n\t\t\tkind: \"summary\",\n\t\t\tlines: [`Replace ${params.path}, over ${WRITE_PREVIEW_MAX_BYTES / 1024}KB, with ${incoming}`],\n\t\t};\n\t}\n\tconst existing = buffer.includes(0)\n\t\t? `${buffer.byteLength} bytes of binary`\n\t\t: `${lineCount(buffer.toString(\"utf-8\"))}, ${buffer.byteLength} bytes`;\n\treturn { kind: \"summary\", lines: [`Replace ${params.path}`, `${existing} becomes ${incoming}`] };\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ApexToolDefinition<typeof writeSchema, WriteToolDetails> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\tconst diagnosticsOperations = options?.diagnosticsOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: writeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...writeToolSystemPromptContribution.guidelines],\n\t\tparameters: writeSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"fs.write\"]),\n\t\t\tpermission: createPathPermissionSpec({\n\t\t\t\tcwd,\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tverb: \"Write\",\n\t\t\t\tgetPath: (params) => params.path,\n\t\t\t\tpreviewCall: (params) => previewWrite(params as { path: string; content: string }),\n\t\t\t}),\n\t\t\tcontext: { resultRecoverable: true, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set(diagnosticsOperations ? [\"diff\", \"diagnostic\"] : [\"diff\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst details = result.details;\n\t\t\t\t\tconst records: EvidenceRecord[] = details\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"diff\",\n\t\t\t\t\t\t\t\t\tpath: params.path,\n\t\t\t\t\t\t\t\t\tbyteCount: details.byteCount,\n\t\t\t\t\t\t\t\t\tcontentHash: details.contentHash,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [{ kind: \"diff\", path: params.path }];\n\t\t\t\t\tif (details?.diagnostics) records.push(diagnosticEvidenceForPath(params.path, details.diagnostics));\n\t\t\t\t\treturn records;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(_toolCallId, input: { path: string; content: string }, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst { path, content } = input;\n\t\t\tconst prepared = getPreparedPathOperation(input);\n\t\t\tconst absolutePath = prepared?.path.value ?? resolveToCwd(path, cwd);\n\t\t\tif (prepared && !ops.writePrepared) {\n\t\t\t\tthrow new Error(\"No safe prepared write operation is available for this gated write\");\n\t\t\t}\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\tif (prepared) {\n\t\t\t\t\t// Gated path: no-follow execution against the exact authorized target.\n\t\t\t\t\tops.writePrepared!(prepared, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t} else {\n\t\t\t\t\t// Create parent directories if needed.\n\t\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\t\tthrowIfAborted();\n\n\t\t\t\t\t// Write the file contents.\n\t\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t}\n\n\t\t\t\tconst successText = `Successfully wrote ${content.length} bytes to ${path}`;\n\n\t\t\t\tif (diagnosticsOperations) {\n\t\t\t\t\tconst diagnostics = await diagnosticsOperations.afterMutation(absolutePath, signal);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `${successText}\\n\\n${formatDiagnosticsOutcome(diagnostics)}` }],\n\t\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content), diagnostics },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: successText }],\n\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content) },\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,KAAK,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAc,MAAM,wCAAwC,CAAC;AACxG,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EAAE,wBAAwB,EAA8B,MAAM,8BAA8B,CAAC;AAIpG,OAAO,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AACvF,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACzG,OAAO,EAAE,oBAAoB,EAAE,cAAc,EA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,GAAG,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;YACjF,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,MAAM,SAAS,GAAI,OAAO,CAAC,aAAuC,IAAI,IAAI,SAAS,EAAE,CAAC;gBACtF,SAAS,CAAC,KAAK,EAAE,CAAC;gBAClB,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,OAA0B,EAAiC;IACvG,OAAO,kBAAkB,CAAC,yBAAyB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACnE","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentTool } from \"apex-code-agent-core\";\nimport { mkdir as fsMkdir } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { getPreparedPathOperation, type PreparedPathOperation } from \"../permissions/operations.ts\";\nimport type { PermissionPreview } from \"../permissions/responder.ts\";\nimport type { ApexToolDefinition, EvidenceRecord } from \"./contract.ts\";\nimport type { DiagnosticsOperations, DiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { diagnosticEvidenceForPath, formatDiagnosticsOutcome } from \"./diagnostics.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { createPathPermissionSpec } from \"./path-permission.ts\";\nimport { readPreparedPath, resolveToCwd, writePathAtomically, writePreparedPath } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport const writeToolSystemPromptContribution = {\n\tsnippet: \"Create or overwrite files\",\n\tguidelines: [\"Use write only for new files or complete rewrites.\"],\n} as const;\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\nexport interface WriteToolDetails {\n\tbyteCount: number;\n\tcontentHash: string;\n\t/** Present only when `WriteToolOptions.diagnosticsOperations` is configured (LSP.4). */\n\tdiagnostics?: DiagnosticsOutcome;\n}\n\nfunction sha256(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n\t/**\n\t * Execute a gate-prepared write no-follow against the authorized target.\n\t * Required for gated calls: when a prepared operation exists, pathname writes\n\t * are never used, so an unset implementation fails closed.\n\t */\n\twritePrepared?: (operation: PreparedPathOperation, content: string) => void;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: async (path, content) => writePathAtomically(path, content),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n\twritePrepared: (operation, content) => writePreparedPath(operation, content),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n\t/**\n\t * Optional post-mutation diagnostics (LSP.4). Absent by default -- byte-identical\n\t * existing behavior. When present, called inside `withFileMutationQueue` after the\n\t * write succeeds and before the queue releases, matching `TestOperations`/\n\t * `GrepOperations`' injection pattern (`test.ts:28`, `grep.ts:58`).\n\t */\n\tdiagnosticsOperations?: DiagnosticsOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nconst WRITE_PREVIEW_MAX_BYTES = 512 * 1024;\n\n/** A trailing newline terminates the last line rather than starting an empty one. */\nconst countLines = (text: string): number => {\n\tif (text === \"\") return 0;\n\tconst body = text.endsWith(\"\\n\") ? text.slice(0, -1) : text;\n\treturn body.split(\"\\n\").length;\n};\n\nconst lineCount = (text: string): string => {\n\tconst n = countLines(text);\n\treturn `${n} ${n === 1 ? \"line\" : \"lines\"}`;\n};\n\n/**\n * Describe a whole-file replacement without drawing the whole file.\n *\n * A diff of a write is the file twice over, which is not what a person needs in\n * order to decide. Sizes on both sides answer the question that matters, which is\n * whether this replaces something substantial. Read through the prepared\n * operation, so a swapped target fails here as it fails the write (ADR 0029).\n */\nfunction previewWrite(params: { path: string; content: string }): PermissionPreview {\n\tconst incoming = `${lineCount(params.content)}, ${Buffer.byteLength(params.content)} bytes`;\n\tconst prepared = getPreparedPathOperation(params);\n\tif (!prepared) return { kind: \"unavailable\", reason: \"No authorized target was prepared for this call\" };\n\tif (prepared.kind === \"path-new\") {\n\t\treturn { kind: \"summary\", lines: [`Create ${params.path} with ${incoming}`] };\n\t}\n\n\tconst buffer = readPreparedPath(prepared, WRITE_PREVIEW_MAX_BYTES + 1);\n\tif (buffer.byteLength > WRITE_PREVIEW_MAX_BYTES) {\n\t\treturn {\n\t\t\tkind: \"summary\",\n\t\t\tlines: [`Replace ${params.path}, over ${WRITE_PREVIEW_MAX_BYTES / 1024}KB, with ${incoming}`],\n\t\t};\n\t}\n\tconst existing = buffer.includes(0)\n\t\t? `${buffer.byteLength} bytes of binary`\n\t\t: `${lineCount(buffer.toString(\"utf-8\"))}, ${buffer.byteLength} bytes`;\n\treturn { kind: \"summary\", lines: [`Replace ${params.path}`, `${existing} becomes ${incoming}`] };\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ApexToolDefinition<typeof writeSchema, WriteToolDetails> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\tconst diagnosticsOperations = options?.diagnosticsOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: writeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...writeToolSystemPromptContribution.guidelines],\n\t\tparameters: writeSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"fs.write\"]),\n\t\t\tpermission: createPathPermissionSpec({\n\t\t\t\tcwd,\n\t\t\t\tdefaultBehavior: \"ask\",\n\t\t\t\tverb: \"Write\",\n\t\t\t\tgetPath: (params) => params.path,\n\t\t\t\tpreviewCall: (params) => previewWrite(params as { path: string; content: string }),\n\t\t\t}),\n\t\t\tcontext: { resultRecoverable: true, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set(diagnosticsOperations ? [\"diff\", \"diagnostic\"] : [\"diff\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst details = result.details;\n\t\t\t\t\tconst records: EvidenceRecord[] = details\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"diff\",\n\t\t\t\t\t\t\t\t\tpath: params.path,\n\t\t\t\t\t\t\t\t\tbyteCount: details.byteCount,\n\t\t\t\t\t\t\t\t\tcontentHash: details.contentHash,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [{ kind: \"diff\", path: params.path }];\n\t\t\t\t\tif (details?.diagnostics) records.push(diagnosticEvidenceForPath(params.path, details.diagnostics));\n\t\t\t\t\treturn records;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(_toolCallId, input: { path: string; content: string }, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst { path, content } = input;\n\t\t\tconst prepared = getPreparedPathOperation(input);\n\t\t\tconst absolutePath = prepared?.path.value ?? resolveToCwd(path, cwd);\n\t\t\tif (prepared && !ops.writePrepared) {\n\t\t\t\tthrow new Error(\"No safe prepared write operation is available for this gated write\");\n\t\t\t}\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\tif (prepared) {\n\t\t\t\t\t// Gated path: no-follow execution against the exact authorized target.\n\t\t\t\t\tops.writePrepared!(prepared, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t} else {\n\t\t\t\t\t// Create parent directories if needed.\n\t\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\t\tthrowIfAborted();\n\n\t\t\t\t\t// Write the file contents.\n\t\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t}\n\n\t\t\t\tconst successText = `Successfully wrote ${content.length} bytes to ${path}`;\n\n\t\t\t\tif (diagnosticsOperations) {\n\t\t\t\t\tconst diagnostics = await diagnosticsOperations.afterMutation(absolutePath, signal);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `${successText}\\n\\n${formatDiagnosticsOutcome(diagnostics)}` }],\n\t\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content), diagnostics },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: successText }],\n\t\t\t\t\tdetails: { byteCount: Buffer.byteLength(content), contentHash: sha256(content) },\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../../src/core/workspace/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAe,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvF;;;;;;;GAOG;AAEH,eAAO,MAAM,uBAAuB,+BAA+B,CAAC;AACpE,eAAO,MAAM,sBAAsB,8BAA8B,CAAC;AAElE,qCAAqC;AACrC,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAE1C,oEAAoE;AACpE,MAAM,WAAW,sBAAsB;IACtC,2CAA2C;IAC3C,OAAO,EAAE,OAAO,CAAC;IACjB,4CAA4C;IAC5C,MAAM,EAAE,OAAO,CAAC;IAChB,sCAAsC;IACtC,QAAQ,EAAE,OAAO,CAAC;IAClB,qCAA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E7G;AAED,oFAAoF;AACpF,wBAAgB,qCAAqC,CACpD,OAAO,EAAE,cAAc,EACvB,YAAY,EAAE,MAAM,GAClB;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,oBAAoB,CAAA;CAAE,GAAG,SAAS,CAO/D;AAED,6EAA6E;AAC7E,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,cAAc,GACrB;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,oBAAoB,CAAA;CAAE,GAAG,SAAS,CAQ/D;AAED;;;;GAIG;AACH,wBAAgB,yCAAyC,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAW1F;AAED,wEAAwE;AACxE,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,GAAG,wBAAwB,EAAE,CASnH","sourcesContent":["import type { CustomEntry, SessionEntry, SessionManager } from \"../session-manager.ts\";\n\n/**\n * Workspace state records attached to compaction boundaries.\n *\n * These records reuse the existing additive `custom` session entry type with\n * reserved `customType` discriminants (see the harness-correctness spec, WS.1):\n * they never enter LLM context, readers ignore unknown discriminants, and\n * extension-owned `CompactionEntry.details` stays untouched.\n */\n\nexport const CUSTOM_TYPE_OBSERVATION = \"apex.workspace.observation\";\nexport const CUSTOM_TYPE_COMPARISON = \"apex.workspace.comparison\";\n\n/** Current record format version. */\nexport const WORKSPACE_RECORD_VERSION = 1;\n\n/** Which parts of the workspace an observation actually covered. */\nexport interface WorkspaceStateCoverage {\n\t/** Tracked modifications were observed. */\n\ttracked: boolean;\n\t/** Staged (index) changes were observed. */\n\tstaged: boolean;\n\t/** Unstaged changes were observed. */\n\tunstaged: boolean;\n\t/** Untracked files were observed. */\n\tuntracked: boolean;\n\t/** Ignored files were observed. */\n\tignored: boolean;\n\t/** Per-path content hashes were captured. */\n\thashes: boolean;\n\t/** Patch bytes were captured (on disk or inline-limited). */\n\tpatch: boolean;\n}\n\n/** The commit a working tree was observed against, when a backend has one. */\nexport interface WorkspaceBase {\n\theadCommit?: string;\n\tbranch?: string;\n\t/** Digest over the index baseline, when the backend has one. */\n\tindexDigest?: string;\n\t/** Digest over the worktree baseline as observed, when complete. */\n\tworktreeDigest?: string;\n}\n\n/** What kind of change a path carried at capture time. */\nexport type WorkspacePathKind = \"added\" | \"modified\" | \"deleted\" | \"renamed\" | \"untracked\";\n\n/** One path observed in the workspace at a compaction boundary. */\nexport interface WorkspaceStatePath {\n\tpath: string;\n\tkind: WorkspacePathKind;\n\tstaged?: boolean;\n\tunstaged?: boolean;\n\t/** Path is ignored by the backend's ignore rules. */\n\tignored?: boolean;\n\t/** Content hash at capture time (`sha256:<hex>`), when hashes were covered. */\n\tcontentHash?: string;\n\t/** Previous path for renames. */\n\tpreviousPath?: string;\n}\n\n/** Reference to a patch artifact owned by the session artifact store. */\nexport interface WorkspaceArtifactRef {\n\tartifactId: string;\n\t/** Store-relative path inside the session's `.artifacts` directory. */\n\tfile: string;\n\t/** `sha256:<hex>` of the artifact bytes. */\n\tsha256: string;\n\tbytes: number;\n}\n\n/** Immutable snapshot of workspace state taken at a compaction boundary. */\nexport interface WorkspaceStateRecord {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\t/** Stable id, independent of entry ids; comparisons reference it. */\n\tobservationId: string;\n\t/**\n\t * `observed` — the adapter observed the fields named by `coverage`;\n\t * `incomplete` — a configured limit prevented complete capture;\n\t * `unsupported` — no adapter can observe this workspace; `failed` — an\n\t * adapter attempted capture and could not complete it.\n\t */\n\tstatus: \"observed\" | \"incomplete\" | \"unsupported\" | \"failed\";\n\t/** Backend that produced the record. */\n\tbackend: \"git\" | \"filesystem\" | \"none\";\n\t/** Absolute workspace root the record describes. */\n\tworkspaceRoot: string;\n\tcapturedAt: string;\n\tcoverage: WorkspaceStateCoverage;\n\t/** The commit the tree was observed against, when applicable. */\n\tbase?: WorkspaceBase;\n\tpaths: WorkspaceStatePath[];\n\t/** Present when patch capture was enabled and the artifact was stored. */\n\tpatchArtifactRef?: WorkspaceArtifactRef;\n\t/** Patch byte length when patch data was captured. */\n\tpatchBytes?: number;\n\t/** False when the patch was truncated by the capture limit. */\n\tpatchComplete?: boolean;\n\t/** Non-fatal capture notes (truncations, skipped backends, and so on). */\n\twarnings: string[];\n}\n\n/** Result of comparing fresh workspace state against a stored observation. */\nexport interface WorkspaceStateComparison {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\tcomparedAt: string;\n\t/** The observation this comparison was made against. */\n\tcomparedToObservationId: string;\n\t/** `same` — no relevant change; `drifted` — state moved;\n\t * `unavailable` — the workspace could not be observed; `inconclusive` —\n\t * no reliable comparison could be established. */\n\tresult: \"same\" | \"drifted\" | \"unavailable\" | \"inconclusive\";\n\tchangedPaths?: string[];\n\twarnings: string[];\n}\n\n/** Append an observation record as a child of the just-appended compaction entry. */\nexport function appendWorkspaceObservation(session: SessionManager, record: WorkspaceStateRecord): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_OBSERVATION, record);\n}\n\n/** Append a comparison record to the current path. */\nexport function appendWorkspaceComparison(session: SessionManager, comparison: WorkspaceStateComparison): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_COMPARISON, comparison);\n}\n\n/** Read an observation record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceObservation(entry: SessionEntry | undefined): WorkspaceStateRecord | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_OBSERVATION);\n}\n\n/** Read a comparison record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceComparison(entry: SessionEntry | undefined): WorkspaceStateComparison | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_COMPARISON);\n}\n\n/** Find the observation record attached as a direct child of a compaction entry. */\nexport function findWorkspaceObservationForCompaction(\n\tsession: SessionManager,\n\tcompactionId: string,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\" || entry.parentId !== compactionId) continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) return { entryId: entry.id, record };\n\t}\n\treturn undefined;\n}\n\n/** Find the most recent observation record in session path order, if any. */\nexport function findLatestWorkspaceObservation(\n\tsession: SessionManager,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tlet found: { entryId: string; record: WorkspaceStateRecord } | undefined;\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\") continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) found = { entryId: entry.id, record };\n\t}\n\treturn found;\n}\n\n/**\n * WS.5: does the session's most recent workspace observation postdate its\n * most recent comparison? True on resume onto a session whose latest\n * observation has not been compared yet.\n */\nexport function hasWorkspaceObservationAwaitingComparison(session: SessionManager): boolean {\n\tlet lastObservation = -1;\n\tlet lastComparison = -1;\n\tconst entries = session.getEntries();\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"custom\") continue;\n\t\tif (readWorkspaceObservation(entry)) lastObservation = i;\n\t\telse if (readWorkspaceComparison(entry)) lastComparison = i;\n\t}\n\treturn lastObservation > lastComparison;\n}\n\n/** List comparisons recorded against one observation, in path order. */\nexport function listWorkspaceComparisons(session: SessionManager, observationId: string): WorkspaceStateComparison[] {\n\tconst comparisons: WorkspaceStateComparison[] = [];\n\tfor (const entry of session.getEntries()) {\n\t\tconst comparison = readWorkspaceComparison(entry);\n\t\tif (comparison && comparison.comparedToObservationId === observationId) {\n\t\t\tcomparisons.push(comparison);\n\t\t}\n\t}\n\treturn comparisons;\n}\n\n/** Lenient read: only well-shaped records of the exact discriminant and version. */\nfunction readTypedRecord<T extends { version: number }>(\n\tentry: SessionEntry | undefined,\n\tcustomType: string,\n): T | undefined {\n\tif (!entry || entry.type !== \"custom\") return undefined;\n\tconst custom = entry as CustomEntry;\n\tif (custom.customType !== customType) return undefined;\n\tconst data = custom.data as T | undefined;\n\tif (!data || typeof data !== \"object\" || data.version !== WORKSPACE_RECORD_VERSION) {\n\t\treturn undefined;\n\t}\n\treturn data;\n}\n"]}
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../../src/core/workspace/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAe,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvF;;;;;;;GAOG;AAEH,eAAO,MAAM,uBAAuB,+BAA+B,CAAC;AACpE,eAAO,MAAM,sBAAsB,8BAA8B,CAAC;AAElE,qCAAqC;AACrC,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAE1C,oEAAoE;AACpE,MAAM,WAAW,sBAAsB;IACtC,2CAA2C;IAC3C,OAAO,EAAE,OAAO,CAAC;IACjB,4CAA4C;IAC5C,MAAM,EAAE,OAAO,CAAC;IAChB,sCAAsC;IACtC,QAAQ,EAAE,OAAO,CAAC;IAClB,qCAAqC;IACrC,SAAS,EAAE,OAAO,CAAC;IACnB,mCAAmC;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,6CAA6C;IAC7C,MAAM,EAAE,OAAO,CAAC;IAChB,6DAA6D;IAC7D,KAAK,EAAE,OAAO,CAAC;CACf;AAED,8EAA8E;AAC9E,MAAM,WAAW,aAAa;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gEAAgE;IAChE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,0DAA0D;AAC1D,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,CAAC;AAE3F,mEAAmE;AACnE,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,iBAAiB,CAAC;IACxB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qDAAqD;IACrD,OAAO,CAAC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,GAAG,cAAc,CAAC;IAC5D,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,qFAAqF;AACrF,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,oBAAoB,GAAG,MAAM,CAExG;AAED,sDAAsD;AACtD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,wBAAwB,GAAG,MAAM,CAE/G;AAED,sFAAsF;AACtF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,YAAY,GAAG,SAAS,GAAG,oBAAoB,GAAG,SAAS,CAE1G;AAED,oFAAoF;AACpF,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,YAAY,GAAG,SAAS,GAAG,wBAAwB,GAAG,SAAS,CAE7G;AAED,oFAAoF;AACpF,wBAAgB,qCAAqC,CACpD,OAAO,EAAE,cAAc,EACvB,YAAY,EAAE,MAAM,GAClB;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,oBAAoB,CAAA;CAAE,GAAG,SAAS,CAO/D;AAED,6EAA6E;AAC7E,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,cAAc,GACrB;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,oBAAoB,CAAA;CAAE,GAAG,SAAS,CAQ/D;AAED;;;;GAIG;AACH,wBAAgB,yCAAyC,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAW1F;AAED,wEAAwE;AACxE,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,GAAG,wBAAwB,EAAE,CASnH","sourcesContent":["import type { CustomEntry, SessionEntry, SessionManager } from \"../session-manager.ts\";\n\n/**\n * Workspace state records attached to compaction boundaries.\n *\n * These records reuse the existing additive `custom` session entry type with\n * reserved `customType` discriminants (see the harness-correctness spec, WS.1):\n * they never enter LLM context, readers ignore unknown discriminants, and\n * extension-owned `CompactionEntry.details` stays untouched.\n */\n\nexport const CUSTOM_TYPE_OBSERVATION = \"apex.workspace.observation\";\nexport const CUSTOM_TYPE_COMPARISON = \"apex.workspace.comparison\";\n\n/** Current record format version. */\nexport const WORKSPACE_RECORD_VERSION = 1;\n\n/** Which parts of the workspace an observation actually covered. */\nexport interface WorkspaceStateCoverage {\n\t/** Tracked modifications were observed. */\n\ttracked: boolean;\n\t/** Staged (index) changes were observed. */\n\tstaged: boolean;\n\t/** Unstaged changes were observed. */\n\tunstaged: boolean;\n\t/** Untracked files were observed. */\n\tuntracked: boolean;\n\t/** Ignored files were observed. */\n\tignored: boolean;\n\t/** Per-path content hashes were captured. */\n\thashes: boolean;\n\t/** Patch bytes were captured (on disk or inline-limited). */\n\tpatch: boolean;\n}\n\n/** The commit a working tree was observed against, when a backend has one. */\nexport interface WorkspaceBase {\n\theadCommit?: string;\n\tbranch?: string;\n\t/** Digest over the index baseline, when the backend has one. */\n\tindexDigest?: string;\n\t/** Digest over the worktree baseline as observed, when complete. */\n\tworktreeDigest?: string;\n}\n\n/** What kind of change a path carried at capture time. */\nexport type WorkspacePathKind = \"added\" | \"modified\" | \"deleted\" | \"renamed\" | \"untracked\";\n\n/** One path observed in the workspace at a compaction boundary. */\nexport interface WorkspaceStatePath {\n\tpath: string;\n\tkind: WorkspacePathKind;\n\tstaged?: boolean;\n\tunstaged?: boolean;\n\t/** Path is ignored by the backend's ignore rules. */\n\tignored?: boolean;\n\t/** Content hash at capture time (`sha256:<hex>`), when hashes were covered. */\n\tcontentHash?: string;\n\t/** Previous path for renames. */\n\tpreviousPath?: string;\n}\n\n/** Reference to a patch artifact owned by the session artifact store. */\nexport interface WorkspaceArtifactRef {\n\tartifactId: string;\n\t/** Store-relative path inside the session's `.artifacts` directory. */\n\tfile: string;\n\t/** `sha256:<hex>` of the artifact bytes. */\n\tsha256: string;\n\tbytes: number;\n}\n\n/** Immutable snapshot of workspace state taken at a compaction boundary. */\nexport interface WorkspaceStateRecord {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\t/** Stable id, independent of entry ids; comparisons reference it. */\n\tobservationId: string;\n\t/**\n\t * `observed` — the adapter observed the fields named by `coverage`;\n\t * `incomplete` — a configured limit prevented complete capture;\n\t * `unsupported` — no adapter can observe this workspace; `failed` — an\n\t * adapter attempted capture and could not complete it.\n\t */\n\tstatus: \"observed\" | \"incomplete\" | \"unsupported\" | \"failed\";\n\t/** Backend that produced the record. */\n\tbackend: \"git\" | \"filesystem\" | \"none\";\n\t/** Absolute workspace root the record describes. */\n\tworkspaceRoot: string;\n\tcapturedAt: string;\n\tcoverage: WorkspaceStateCoverage;\n\t/** The commit the tree was observed against, when applicable. */\n\tbase?: WorkspaceBase;\n\tpaths: WorkspaceStatePath[];\n\t/** Present when patch capture was enabled and the artifact was stored. */\n\tpatchArtifactRef?: WorkspaceArtifactRef;\n\t/** Patch byte length when patch data was captured. */\n\tpatchBytes?: number;\n\t/** False when the patch was truncated by the capture limit. */\n\tpatchComplete?: boolean;\n\t/** Non-fatal capture notes (truncations, skipped backends, and so on). */\n\twarnings: string[];\n}\n\n/** Result of comparing fresh workspace state against a stored observation. */\nexport interface WorkspaceStateComparison {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\tcomparedAt: string;\n\t/** The observation this comparison was made against. */\n\tcomparedToObservationId: string;\n\t/** `same` — no relevant change; `drifted` — state moved;\n\t * `unavailable` — the workspace could not be observed; `inconclusive` —\n\t * no reliable comparison could be established. */\n\tresult: \"same\" | \"drifted\" | \"unavailable\" | \"inconclusive\";\n\tchangedPaths?: string[];\n\twarnings: string[];\n}\n\n/** Append an observation record as a child of the just-appended compaction entry. */\nexport function appendWorkspaceObservation(session: SessionManager, record: WorkspaceStateRecord): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_OBSERVATION, record);\n}\n\n/** Append a comparison record to the current path. */\nexport function appendWorkspaceComparison(session: SessionManager, comparison: WorkspaceStateComparison): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_COMPARISON, comparison);\n}\n\n/** Read an observation record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceObservation(entry: SessionEntry | undefined): WorkspaceStateRecord | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_OBSERVATION);\n}\n\n/** Read a comparison record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceComparison(entry: SessionEntry | undefined): WorkspaceStateComparison | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_COMPARISON);\n}\n\n/** Find the observation record attached as a direct child of a compaction entry. */\nexport function findWorkspaceObservationForCompaction(\n\tsession: SessionManager,\n\tcompactionId: string,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\" || entry.parentId !== compactionId) continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) return { entryId: entry.id, record };\n\t}\n\treturn undefined;\n}\n\n/** Find the most recent observation record in session path order, if any. */\nexport function findLatestWorkspaceObservation(\n\tsession: SessionManager,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tlet found: { entryId: string; record: WorkspaceStateRecord } | undefined;\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\") continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) found = { entryId: entry.id, record };\n\t}\n\treturn found;\n}\n\n/**\n * WS.5: does the session's most recent workspace observation postdate its\n * most recent comparison? True on resume onto a session whose latest\n * observation has not been compared yet.\n */\nexport function hasWorkspaceObservationAwaitingComparison(session: SessionManager): boolean {\n\tlet lastObservation = -1;\n\tlet lastComparison = -1;\n\tconst entries = session.getEntries();\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"custom\") continue;\n\t\tif (readWorkspaceObservation(entry)) lastObservation = i;\n\t\telse if (readWorkspaceComparison(entry)) lastComparison = i;\n\t}\n\treturn lastObservation > lastComparison;\n}\n\n/** List comparisons recorded against one observation, in path order. */\nexport function listWorkspaceComparisons(session: SessionManager, observationId: string): WorkspaceStateComparison[] {\n\tconst comparisons: WorkspaceStateComparison[] = [];\n\tfor (const entry of session.getEntries()) {\n\t\tconst comparison = readWorkspaceComparison(entry);\n\t\tif (comparison && comparison.comparedToObservationId === observationId) {\n\t\t\tcomparisons.push(comparison);\n\t\t}\n\t}\n\treturn comparisons;\n}\n\n/** Lenient read: only well-shaped records of the exact discriminant and version. */\nfunction readTypedRecord<T extends { version: number }>(\n\tentry: SessionEntry | undefined,\n\tcustomType: string,\n): T | undefined {\n\tif (entry?.type !== \"custom\") return undefined;\n\tconst custom = entry as CustomEntry;\n\tif (custom.customType !== customType) return undefined;\n\tconst data = custom.data as T | undefined;\n\tif (!data || typeof data !== \"object\" || data.version !== WORKSPACE_RECORD_VERSION) {\n\t\treturn undefined;\n\t}\n\treturn data;\n}\n"]}
@@ -82,7 +82,7 @@ export function listWorkspaceComparisons(session, observationId) {
82
82
  }
83
83
  /** Lenient read: only well-shaped records of the exact discriminant and version. */
84
84
  function readTypedRecord(entry, customType) {
85
- if (!entry || entry.type !== "custom")
85
+ if (entry?.type !== "custom")
86
86
  return undefined;
87
87
  const custom = entry;
88
88
  if (custom.customType !== customType)
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["../../../src/core/workspace/state.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AACpE,MAAM,CAAC,MAAM,sBAAsB,GAAG,2BAA2B,CAAC;AAElE,qCAAqC;AACrC,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,CAAC;AAsG1C,qFAAqF;AACrF,MAAM,UAAU,0BAA0B,CAAC,OAAuB,EAAE,MAA4B,EAAU;IACzG,OAAO,OAAO,CAAC,iBAAiB,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;AAAA,CAClE;AAED,sDAAsD;AACtD,MAAM,UA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,UAAU;QAAE,OAAO,SAAS,CAAC;IACvD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAqB,CAAC;IAC1C,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,OAAO,KAAK,wBAAwB,EAAE,CAAC;QACpF,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import type { CustomEntry, SessionEntry, SessionManager } from \"../session-manager.ts\";\n\n/**\n * Workspace state records attached to compaction boundaries.\n *\n * These records reuse the existing additive `custom` session entry type with\n * reserved `customType` discriminants (see the harness-correctness spec, WS.1):\n * they never enter LLM context, readers ignore unknown discriminants, and\n * extension-owned `CompactionEntry.details` stays untouched.\n */\n\nexport const CUSTOM_TYPE_OBSERVATION = \"apex.workspace.observation\";\nexport const CUSTOM_TYPE_COMPARISON = \"apex.workspace.comparison\";\n\n/** Current record format version. */\nexport const WORKSPACE_RECORD_VERSION = 1;\n\n/** Which parts of the workspace an observation actually covered. */\nexport interface WorkspaceStateCoverage {\n\t/** Tracked modifications were observed. */\n\ttracked: boolean;\n\t/** Staged (index) changes were observed. */\n\tstaged: boolean;\n\t/** Unstaged changes were observed. */\n\tunstaged: boolean;\n\t/** Untracked files were observed. */\n\tuntracked: boolean;\n\t/** Ignored files were observed. */\n\tignored: boolean;\n\t/** Per-path content hashes were captured. */\n\thashes: boolean;\n\t/** Patch bytes were captured (on disk or inline-limited). */\n\tpatch: boolean;\n}\n\n/** The commit a working tree was observed against, when a backend has one. */\nexport interface WorkspaceBase {\n\theadCommit?: string;\n\tbranch?: string;\n\t/** Digest over the index baseline, when the backend has one. */\n\tindexDigest?: string;\n\t/** Digest over the worktree baseline as observed, when complete. */\n\tworktreeDigest?: string;\n}\n\n/** What kind of change a path carried at capture time. */\nexport type WorkspacePathKind = \"added\" | \"modified\" | \"deleted\" | \"renamed\" | \"untracked\";\n\n/** One path observed in the workspace at a compaction boundary. */\nexport interface WorkspaceStatePath {\n\tpath: string;\n\tkind: WorkspacePathKind;\n\tstaged?: boolean;\n\tunstaged?: boolean;\n\t/** Path is ignored by the backend's ignore rules. */\n\tignored?: boolean;\n\t/** Content hash at capture time (`sha256:<hex>`), when hashes were covered. */\n\tcontentHash?: string;\n\t/** Previous path for renames. */\n\tpreviousPath?: string;\n}\n\n/** Reference to a patch artifact owned by the session artifact store. */\nexport interface WorkspaceArtifactRef {\n\tartifactId: string;\n\t/** Store-relative path inside the session's `.artifacts` directory. */\n\tfile: string;\n\t/** `sha256:<hex>` of the artifact bytes. */\n\tsha256: string;\n\tbytes: number;\n}\n\n/** Immutable snapshot of workspace state taken at a compaction boundary. */\nexport interface WorkspaceStateRecord {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\t/** Stable id, independent of entry ids; comparisons reference it. */\n\tobservationId: string;\n\t/**\n\t * `observed` — the adapter observed the fields named by `coverage`;\n\t * `incomplete` — a configured limit prevented complete capture;\n\t * `unsupported` — no adapter can observe this workspace; `failed` — an\n\t * adapter attempted capture and could not complete it.\n\t */\n\tstatus: \"observed\" | \"incomplete\" | \"unsupported\" | \"failed\";\n\t/** Backend that produced the record. */\n\tbackend: \"git\" | \"filesystem\" | \"none\";\n\t/** Absolute workspace root the record describes. */\n\tworkspaceRoot: string;\n\tcapturedAt: string;\n\tcoverage: WorkspaceStateCoverage;\n\t/** The commit the tree was observed against, when applicable. */\n\tbase?: WorkspaceBase;\n\tpaths: WorkspaceStatePath[];\n\t/** Present when patch capture was enabled and the artifact was stored. */\n\tpatchArtifactRef?: WorkspaceArtifactRef;\n\t/** Patch byte length when patch data was captured. */\n\tpatchBytes?: number;\n\t/** False when the patch was truncated by the capture limit. */\n\tpatchComplete?: boolean;\n\t/** Non-fatal capture notes (truncations, skipped backends, and so on). */\n\twarnings: string[];\n}\n\n/** Result of comparing fresh workspace state against a stored observation. */\nexport interface WorkspaceStateComparison {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\tcomparedAt: string;\n\t/** The observation this comparison was made against. */\n\tcomparedToObservationId: string;\n\t/** `same` — no relevant change; `drifted` — state moved;\n\t * `unavailable` — the workspace could not be observed; `inconclusive` —\n\t * no reliable comparison could be established. */\n\tresult: \"same\" | \"drifted\" | \"unavailable\" | \"inconclusive\";\n\tchangedPaths?: string[];\n\twarnings: string[];\n}\n\n/** Append an observation record as a child of the just-appended compaction entry. */\nexport function appendWorkspaceObservation(session: SessionManager, record: WorkspaceStateRecord): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_OBSERVATION, record);\n}\n\n/** Append a comparison record to the current path. */\nexport function appendWorkspaceComparison(session: SessionManager, comparison: WorkspaceStateComparison): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_COMPARISON, comparison);\n}\n\n/** Read an observation record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceObservation(entry: SessionEntry | undefined): WorkspaceStateRecord | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_OBSERVATION);\n}\n\n/** Read a comparison record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceComparison(entry: SessionEntry | undefined): WorkspaceStateComparison | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_COMPARISON);\n}\n\n/** Find the observation record attached as a direct child of a compaction entry. */\nexport function findWorkspaceObservationForCompaction(\n\tsession: SessionManager,\n\tcompactionId: string,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\" || entry.parentId !== compactionId) continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) return { entryId: entry.id, record };\n\t}\n\treturn undefined;\n}\n\n/** Find the most recent observation record in session path order, if any. */\nexport function findLatestWorkspaceObservation(\n\tsession: SessionManager,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tlet found: { entryId: string; record: WorkspaceStateRecord } | undefined;\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\") continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) found = { entryId: entry.id, record };\n\t}\n\treturn found;\n}\n\n/**\n * WS.5: does the session's most recent workspace observation postdate its\n * most recent comparison? True on resume onto a session whose latest\n * observation has not been compared yet.\n */\nexport function hasWorkspaceObservationAwaitingComparison(session: SessionManager): boolean {\n\tlet lastObservation = -1;\n\tlet lastComparison = -1;\n\tconst entries = session.getEntries();\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"custom\") continue;\n\t\tif (readWorkspaceObservation(entry)) lastObservation = i;\n\t\telse if (readWorkspaceComparison(entry)) lastComparison = i;\n\t}\n\treturn lastObservation > lastComparison;\n}\n\n/** List comparisons recorded against one observation, in path order. */\nexport function listWorkspaceComparisons(session: SessionManager, observationId: string): WorkspaceStateComparison[] {\n\tconst comparisons: WorkspaceStateComparison[] = [];\n\tfor (const entry of session.getEntries()) {\n\t\tconst comparison = readWorkspaceComparison(entry);\n\t\tif (comparison && comparison.comparedToObservationId === observationId) {\n\t\t\tcomparisons.push(comparison);\n\t\t}\n\t}\n\treturn comparisons;\n}\n\n/** Lenient read: only well-shaped records of the exact discriminant and version. */\nfunction readTypedRecord<T extends { version: number }>(\n\tentry: SessionEntry | undefined,\n\tcustomType: string,\n): T | undefined {\n\tif (!entry || entry.type !== \"custom\") return undefined;\n\tconst custom = entry as CustomEntry;\n\tif (custom.customType !== customType) return undefined;\n\tconst data = custom.data as T | undefined;\n\tif (!data || typeof data !== \"object\" || data.version !== WORKSPACE_RECORD_VERSION) {\n\t\treturn undefined;\n\t}\n\treturn data;\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../../../src/core/workspace/state.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AACpE,MAAM,CAAC,MAAM,sBAAsB,GAAG,2BAA2B,CAAC;AAElE,qCAAqC;AACrC,MAAM,CAAC,MAAM,wB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F;AACpF,SAAS,eAAe,CACvB,KAA+B,EAC/B,UAAkB,EACF;IAChB,IAAI,KAAK,EAAE,IAAI,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAC/C,MAAM,MAAM,GAAG,KAAoB,CAAC;IACpC,IAAI,MAAM,CAAC,UAAU,KAAK,UAAU;QAAE,OAAO,SAAS,CAAC;IACvD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAqB,CAAC;IAC1C,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,OAAO,KAAK,wBAAwB,EAAE,CAAC;QACpF,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import type { CustomEntry, SessionEntry, SessionManager } from \"../session-manager.ts\";\n\n/**\n * Workspace state records attached to compaction boundaries.\n *\n * These records reuse the existing additive `custom` session entry type with\n * reserved `customType` discriminants (see the harness-correctness spec, WS.1):\n * they never enter LLM context, readers ignore unknown discriminants, and\n * extension-owned `CompactionEntry.details` stays untouched.\n */\n\nexport const CUSTOM_TYPE_OBSERVATION = \"apex.workspace.observation\";\nexport const CUSTOM_TYPE_COMPARISON = \"apex.workspace.comparison\";\n\n/** Current record format version. */\nexport const WORKSPACE_RECORD_VERSION = 1;\n\n/** Which parts of the workspace an observation actually covered. */\nexport interface WorkspaceStateCoverage {\n\t/** Tracked modifications were observed. */\n\ttracked: boolean;\n\t/** Staged (index) changes were observed. */\n\tstaged: boolean;\n\t/** Unstaged changes were observed. */\n\tunstaged: boolean;\n\t/** Untracked files were observed. */\n\tuntracked: boolean;\n\t/** Ignored files were observed. */\n\tignored: boolean;\n\t/** Per-path content hashes were captured. */\n\thashes: boolean;\n\t/** Patch bytes were captured (on disk or inline-limited). */\n\tpatch: boolean;\n}\n\n/** The commit a working tree was observed against, when a backend has one. */\nexport interface WorkspaceBase {\n\theadCommit?: string;\n\tbranch?: string;\n\t/** Digest over the index baseline, when the backend has one. */\n\tindexDigest?: string;\n\t/** Digest over the worktree baseline as observed, when complete. */\n\tworktreeDigest?: string;\n}\n\n/** What kind of change a path carried at capture time. */\nexport type WorkspacePathKind = \"added\" | \"modified\" | \"deleted\" | \"renamed\" | \"untracked\";\n\n/** One path observed in the workspace at a compaction boundary. */\nexport interface WorkspaceStatePath {\n\tpath: string;\n\tkind: WorkspacePathKind;\n\tstaged?: boolean;\n\tunstaged?: boolean;\n\t/** Path is ignored by the backend's ignore rules. */\n\tignored?: boolean;\n\t/** Content hash at capture time (`sha256:<hex>`), when hashes were covered. */\n\tcontentHash?: string;\n\t/** Previous path for renames. */\n\tpreviousPath?: string;\n}\n\n/** Reference to a patch artifact owned by the session artifact store. */\nexport interface WorkspaceArtifactRef {\n\tartifactId: string;\n\t/** Store-relative path inside the session's `.artifacts` directory. */\n\tfile: string;\n\t/** `sha256:<hex>` of the artifact bytes. */\n\tsha256: string;\n\tbytes: number;\n}\n\n/** Immutable snapshot of workspace state taken at a compaction boundary. */\nexport interface WorkspaceStateRecord {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\t/** Stable id, independent of entry ids; comparisons reference it. */\n\tobservationId: string;\n\t/**\n\t * `observed` — the adapter observed the fields named by `coverage`;\n\t * `incomplete` — a configured limit prevented complete capture;\n\t * `unsupported` — no adapter can observe this workspace; `failed` — an\n\t * adapter attempted capture and could not complete it.\n\t */\n\tstatus: \"observed\" | \"incomplete\" | \"unsupported\" | \"failed\";\n\t/** Backend that produced the record. */\n\tbackend: \"git\" | \"filesystem\" | \"none\";\n\t/** Absolute workspace root the record describes. */\n\tworkspaceRoot: string;\n\tcapturedAt: string;\n\tcoverage: WorkspaceStateCoverage;\n\t/** The commit the tree was observed against, when applicable. */\n\tbase?: WorkspaceBase;\n\tpaths: WorkspaceStatePath[];\n\t/** Present when patch capture was enabled and the artifact was stored. */\n\tpatchArtifactRef?: WorkspaceArtifactRef;\n\t/** Patch byte length when patch data was captured. */\n\tpatchBytes?: number;\n\t/** False when the patch was truncated by the capture limit. */\n\tpatchComplete?: boolean;\n\t/** Non-fatal capture notes (truncations, skipped backends, and so on). */\n\twarnings: string[];\n}\n\n/** Result of comparing fresh workspace state against a stored observation. */\nexport interface WorkspaceStateComparison {\n\tversion: typeof WORKSPACE_RECORD_VERSION;\n\tcomparedAt: string;\n\t/** The observation this comparison was made against. */\n\tcomparedToObservationId: string;\n\t/** `same` — no relevant change; `drifted` — state moved;\n\t * `unavailable` — the workspace could not be observed; `inconclusive` —\n\t * no reliable comparison could be established. */\n\tresult: \"same\" | \"drifted\" | \"unavailable\" | \"inconclusive\";\n\tchangedPaths?: string[];\n\twarnings: string[];\n}\n\n/** Append an observation record as a child of the just-appended compaction entry. */\nexport function appendWorkspaceObservation(session: SessionManager, record: WorkspaceStateRecord): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_OBSERVATION, record);\n}\n\n/** Append a comparison record to the current path. */\nexport function appendWorkspaceComparison(session: SessionManager, comparison: WorkspaceStateComparison): string {\n\treturn session.appendCustomEntry(CUSTOM_TYPE_COMPARISON, comparison);\n}\n\n/** Read an observation record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceObservation(entry: SessionEntry | undefined): WorkspaceStateRecord | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_OBSERVATION);\n}\n\n/** Read a comparison record from a custom entry, or undefined for anything else. */\nexport function readWorkspaceComparison(entry: SessionEntry | undefined): WorkspaceStateComparison | undefined {\n\treturn readTypedRecord(entry, CUSTOM_TYPE_COMPARISON);\n}\n\n/** Find the observation record attached as a direct child of a compaction entry. */\nexport function findWorkspaceObservationForCompaction(\n\tsession: SessionManager,\n\tcompactionId: string,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\" || entry.parentId !== compactionId) continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) return { entryId: entry.id, record };\n\t}\n\treturn undefined;\n}\n\n/** Find the most recent observation record in session path order, if any. */\nexport function findLatestWorkspaceObservation(\n\tsession: SessionManager,\n): { entryId: string; record: WorkspaceStateRecord } | undefined {\n\tlet found: { entryId: string; record: WorkspaceStateRecord } | undefined;\n\tfor (const entry of session.getEntries()) {\n\t\tif (entry.type !== \"custom\") continue;\n\t\tconst record = readWorkspaceObservation(entry);\n\t\tif (record) found = { entryId: entry.id, record };\n\t}\n\treturn found;\n}\n\n/**\n * WS.5: does the session's most recent workspace observation postdate its\n * most recent comparison? True on resume onto a session whose latest\n * observation has not been compared yet.\n */\nexport function hasWorkspaceObservationAwaitingComparison(session: SessionManager): boolean {\n\tlet lastObservation = -1;\n\tlet lastComparison = -1;\n\tconst entries = session.getEntries();\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"custom\") continue;\n\t\tif (readWorkspaceObservation(entry)) lastObservation = i;\n\t\telse if (readWorkspaceComparison(entry)) lastComparison = i;\n\t}\n\treturn lastObservation > lastComparison;\n}\n\n/** List comparisons recorded against one observation, in path order. */\nexport function listWorkspaceComparisons(session: SessionManager, observationId: string): WorkspaceStateComparison[] {\n\tconst comparisons: WorkspaceStateComparison[] = [];\n\tfor (const entry of session.getEntries()) {\n\t\tconst comparison = readWorkspaceComparison(entry);\n\t\tif (comparison && comparison.comparedToObservationId === observationId) {\n\t\t\tcomparisons.push(comparison);\n\t\t}\n\t}\n\treturn comparisons;\n}\n\n/** Lenient read: only well-shaped records of the exact discriminant and version. */\nfunction readTypedRecord<T extends { version: number }>(\n\tentry: SessionEntry | undefined,\n\tcustomType: string,\n): T | undefined {\n\tif (entry?.type !== \"custom\") return undefined;\n\tconst custom = entry as CustomEntry;\n\tif (custom.customType !== customType) return undefined;\n\tconst data = custom.data as T | undefined;\n\tif (!data || typeof data !== \"object\" || data.version !== WORKSPACE_RECORD_VERSION) {\n\t\treturn undefined;\n\t}\n\treturn data;\n}\n"]}