@zergai/ztc 0.23.1-dev.202611152321 → 0.24.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +299 -13
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-computer-darwin-arm64 +0 -0
  6. package/bin/ztc-llm-darwin-arm64 +0 -0
  7. package/bin/ztc-tts-darwin-arm64 +0 -0
  8. package/bin/ztc-tui-darwin-arm64 +0 -0
  9. package/bin/zterm-darwin-arm64 +2 -2
  10. package/dist/agent/agent.js +57 -14
  11. package/dist/agent/backends/http_error.d.ts +2 -0
  12. package/dist/agent/backends/http_error.js +2 -0
  13. package/dist/agent/backends/router_gate.d.ts +3 -2
  14. package/dist/agent/backends/router_gate.js +5 -4
  15. package/dist/agent/backends/router_keys.d.ts +14 -0
  16. package/dist/agent/backends/router_keys.js +19 -0
  17. package/dist/agent/backends/router_refusal.d.ts +5 -3
  18. package/dist/agent/backends/router_refusal.js +28 -6
  19. package/dist/agent/backends/types.d.ts +1 -1
  20. package/dist/agent/backends/zrouter_stream.js +10 -6
  21. package/dist/agent/commands/agent_cli.d.ts +11 -1
  22. package/dist/agent/commands/agent_cli.js +295 -38
  23. package/dist/agent/commands/diff.js +4 -1
  24. package/dist/agent/commands/help.js +4 -1
  25. package/dist/agent/commands/plan.js +3 -1
  26. package/dist/agent/commands/session_redaction.d.ts +16 -0
  27. package/dist/agent/commands/session_redaction.js +77 -0
  28. package/dist/agent/commands/settings.js +144 -0
  29. package/dist/agent/commands/types.d.ts +5 -0
  30. package/dist/agent/commands/usage_spec.d.ts +4 -0
  31. package/dist/agent/commands/usage_spec.js +10 -4
  32. package/dist/agent/runtime/policy.d.ts +25 -0
  33. package/dist/agent/runtime/policy.js +154 -26
  34. package/dist/agent/runtime/source_verification.js +6 -2
  35. package/dist/agent/runtime/tool_runtime.js +81 -3
  36. package/dist/agent/tools/apply_patch.js +678 -131
  37. package/dist/agent/tools/bus_message.d.ts +26 -1
  38. package/dist/agent/tools/bus_message.js +126 -10
  39. package/dist/agent/tools/file.d.ts +16 -1
  40. package/dist/agent/tools/file.js +43 -5
  41. package/dist/agent/tools/index.d.ts +1 -1
  42. package/dist/agent/tools/index.js +1 -1
  43. package/dist/agent/tools/pane.js +5 -0
  44. package/dist/agent/tools/search.js +5 -1
  45. package/dist/agent/tools/supervision.js +16 -2
  46. package/dist/agent/tools/types.d.ts +22 -0
  47. package/dist/app/mirror_startup.d.ts +7 -5
  48. package/dist/app/mirror_startup.js +7 -5
  49. package/dist/app/navigator_mirrors.d.ts +20 -0
  50. package/dist/app/navigator_mirrors.js +36 -0
  51. package/dist/app/workspace_layout_controller.d.ts +11 -2
  52. package/dist/app/workspace_layout_controller.js +13 -2
  53. package/dist/batch/worktree.js +9 -1
  54. package/dist/cli_ratatui.d.ts +264 -12
  55. package/dist/cli_ratatui.js +1198 -103
  56. package/dist/config/types.d.ts +29 -0
  57. package/dist/desktop/daily/source_baseline.js +3 -1
  58. package/dist/diagnostics/session_export.d.ts +1 -0
  59. package/dist/diagnostics/session_export.js +229 -26
  60. package/dist/emulation/tool_adapters.js +42 -5
  61. package/dist/headless.js +24 -5
  62. package/dist/instance_registry.d.ts +7 -0
  63. package/dist/mcp/workspace_server.d.ts +12 -1
  64. package/dist/mcp/workspace_server.js +75 -8
  65. package/dist/panes/agent_cli.d.ts +60 -3
  66. package/dist/panes/agent_cli.js +169 -16
  67. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  68. package/dist/panes/agent_pane_sessions.js +111 -0
  69. package/dist/panes/agent_panes.d.ts +77 -3
  70. package/dist/panes/agent_panes.js +199 -10
  71. package/dist/panes/agent_profiles.d.ts +5 -0
  72. package/dist/panes/agent_profiles.js +7 -0
  73. package/dist/panes/agent_resume.d.ts +134 -0
  74. package/dist/panes/agent_resume.js +155 -0
  75. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  76. package/dist/panes/agent_sessions/claude_head.js +122 -0
  77. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  78. package/dist/panes/agent_sessions/claude_store.js +223 -0
  79. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  80. package/dist/panes/agent_sessions/codex_head.js +161 -0
  81. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  82. package/dist/panes/agent_sessions/codex_store.js +187 -0
  83. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  84. package/dist/panes/agent_sessions/controller.js +110 -0
  85. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  86. package/dist/panes/agent_sessions/cut_json.js +109 -0
  87. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  88. package/dist/panes/agent_sessions/limits.js +48 -0
  89. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  90. package/dist/panes/agent_sessions/scan.js +86 -0
  91. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  92. package/dist/panes/agent_sessions/store_fs.js +128 -0
  93. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  94. package/dist/panes/agent_sessions/stores.js +89 -0
  95. package/dist/panes/agent_sessions/title.d.ts +9 -0
  96. package/dist/panes/agent_sessions/title.js +51 -0
  97. package/dist/panes/agent_sessions/types.d.ts +48 -0
  98. package/dist/panes/agent_sessions/types.js +2 -0
  99. package/dist/panes/reply_arbitrator.d.ts +39 -0
  100. package/dist/panes/reply_arbitrator.js +185 -0
  101. package/dist/panes/reply_modes.d.ts +291 -0
  102. package/dist/panes/reply_modes.js +598 -0
  103. package/dist/runtime_info.js +11 -2
  104. package/dist/session.js +4 -2
  105. package/dist/simulation/living/context.d.ts +8 -8
  106. package/dist/simulation/living/types.d.ts +5 -5
  107. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  108. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  109. package/dist/ui/ratatui/ipc_path.js +23 -3
  110. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  111. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  112. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  113. package/dist/ui/ratatui/pane_relay.js +86 -19
  114. package/dist/ui/ratatui/process.js +3 -0
  115. package/dist/ui/ratatui/protocol.d.ts +50 -1
  116. package/dist/ui/ratatui/protocol.js +56 -0
  117. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  118. package/dist/ui/ratatui/relay_policy.js +94 -0
  119. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  120. package/dist/ui/ratatui/screen_privacy.js +24 -0
  121. package/dist/ui/scrollback.js +8 -0
  122. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  123. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  124. package/dist/ui/widgets/log_view.d.ts +5 -1
  125. package/dist/ui/widgets/log_view.js +40 -4
  126. package/dist/utils/atomic_write.js +9 -11
  127. package/dist/utils/canonical_path.d.ts +19 -0
  128. package/dist/utils/canonical_path.js +44 -0
  129. package/dist/utils/compaction.d.ts +2 -1
  130. package/dist/utils/compaction.js +3 -1
  131. package/dist/utils/git_directory_names.d.ts +51 -0
  132. package/dist/utils/git_directory_names.js +429 -0
  133. package/dist/utils/temporary_write_root.d.ts +6 -1
  134. package/dist/utils/temporary_write_root.js +32 -2
  135. package/dist/utils/tool_result_message.d.ts +4 -1
  136. package/dist/utils/tool_result_message.js +6 -2
  137. package/dist/web/bus_hold.d.ts +70 -0
  138. package/dist/web/bus_hold.js +118 -0
  139. package/dist/web/mirror_client.d.ts +7 -3
  140. package/dist/web/mirror_client.js +61 -23
  141. package/dist/web/mirror_route_gate.d.ts +40 -0
  142. package/dist/web/mirror_route_gate.js +71 -0
  143. package/dist/web/mirror_stream.d.ts +147 -22
  144. package/dist/web/mirror_stream.js +350 -83
  145. package/dist/web/pane_credentials.d.ts +32 -1
  146. package/dist/web/pane_credentials.js +62 -2
  147. package/dist/workspace_collision.js +11 -2
  148. package/dist/zlm-embed.mjs +940 -273
  149. package/package.json +39 -7
@@ -35,7 +35,8 @@ export async function writeFileAtomic(path, data, options = {}) {
35
35
  const { signal } = options;
36
36
  signal?.throwIfAborted();
37
37
  const tmp = tmpPath(path);
38
- const written = writeFileAsync(tmp, data);
38
+ // O_EXCL: never write through a file or symlink that is already at the temporary path.
39
+ const written = writeFileAsync(tmp, data, { flag: 'wx' });
39
40
  const modePromise = existingMode(path);
40
41
  try {
41
42
  if (signal) {
@@ -59,18 +60,15 @@ export async function writeFileAtomic(path, data, options = {}) {
59
60
  await renameAsync(tmp, path);
60
61
  }
61
62
  catch (err) {
62
- // Join late completion for cleanup without making cancellation wait on it.
63
- void written.then(async () => { try {
64
- await unlinkAsync(tmp);
65
- }
66
- catch { /* already removed */ } }, async () => { try {
67
- await unlinkAsync(tmp);
68
- }
69
- catch { /* no temporary file */ } });
70
- try {
63
+ const removeTemporary = async () => { try {
71
64
  await unlinkAsync(tmp);
72
65
  }
73
- catch { /* ignore */ }
66
+ catch { /* no temporary file */ } };
67
+ // Join late completion for cleanup without making cancellation wait on it.
68
+ // A temporary path that already existed (EEXIST) holds someone else's file.
69
+ void written.then(removeTemporary, (error) => error?.code === 'EEXIST' ? undefined : removeTemporary());
70
+ if (err.code !== 'EEXIST')
71
+ await removeTemporary();
74
72
  throw err;
75
73
  }
76
74
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * An absolute path with every existing component resolved, and any tail that does not exist yet appended as written.
3
+ * The native realpath also spells each existing component the way the filesystem stores it, so on APFS or NTFS
4
+ * `SECRETS` and a decomposed `café` compare as the `secrets` and composed `café` they are.
5
+ */
6
+ export declare function canonicalPath(absolute: string): string;
7
+ /**
8
+ * Whether `text` is well-formed Unicode: it holds no lone UTF-16 surrogate. Text that is not names or says something
9
+ * other than its string spells once Node writes it: two paths that differ only in their lone surrogates are one file
10
+ * on disk, and git reads a patch holding one with U+FFFD there.
11
+ */
12
+ export declare function isWellFormedText(text: string): boolean;
13
+ /**
14
+ * One spelling for every name that can mean the same file: each lone surrogate as the U+FFFD Node writes for it,
15
+ * Unicode NFC, and case folded where names ignore case. Lower case alone keeps apart letters a volume that ignores
16
+ * case treats as one (ſ and s, ς and σ); upper case first joins them. Folding more than the volume does only makes a
17
+ * denial match more names.
18
+ */
19
+ export declare function sameFileKey(path: string): string;
@@ -0,0 +1,44 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { basename, dirname, resolve } from 'node:path';
3
+ /**
4
+ * An absolute path with every existing component resolved, and any tail that does not exist yet appended as written.
5
+ * The native realpath also spells each existing component the way the filesystem stores it, so on APFS or NTFS
6
+ * `SECRETS` and a decomposed `café` compare as the `secrets` and composed `café` they are.
7
+ */
8
+ export function canonicalPath(absolute) {
9
+ try {
10
+ return realpathSync.native(absolute);
11
+ }
12
+ catch (error) {
13
+ const code = error.code;
14
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
15
+ throw error;
16
+ const parent = dirname(absolute);
17
+ if (parent === absolute)
18
+ return absolute;
19
+ return resolve(canonicalPath(parent), basename(absolute));
20
+ }
21
+ }
22
+ /** Volumes on these platforms ignore case by default (APFS, NTFS). */
23
+ const CASE_INSENSITIVE_BY_DEFAULT = process.platform === 'darwin' || process.platform === 'win32';
24
+ /** A lone UTF-16 surrogate. Node encodes each one as U+FFFD on its way to the filesystem or into a file. */
25
+ const LONE_SURROGATE = /\p{Cs}/u;
26
+ const LONE_SURROGATES = /\p{Cs}/gu;
27
+ /**
28
+ * Whether `text` is well-formed Unicode: it holds no lone UTF-16 surrogate. Text that is not names or says something
29
+ * other than its string spells once Node writes it: two paths that differ only in their lone surrogates are one file
30
+ * on disk, and git reads a patch holding one with U+FFFD there.
31
+ */
32
+ export function isWellFormedText(text) {
33
+ return !LONE_SURROGATE.test(text);
34
+ }
35
+ /**
36
+ * One spelling for every name that can mean the same file: each lone surrogate as the U+FFFD Node writes for it,
37
+ * Unicode NFC, and case folded where names ignore case. Lower case alone keeps apart letters a volume that ignores
38
+ * case treats as one (ſ and s, ς and σ); upper case first joins them. Folding more than the volume does only makes a
39
+ * denial match more names.
40
+ */
41
+ export function sameFileKey(path) {
42
+ const composed = path.replace(LONE_SURROGATES, '\uFFFD').normalize('NFC');
43
+ return CASE_INSENSITIVE_BY_DEFAULT ? composed.toUpperCase().toLowerCase().normalize('NFC') : composed;
44
+ }
@@ -62,7 +62,8 @@ export declare function localSummarizer(messages: Message[]): string;
62
62
  export declare function condenseConversation(messages: Message[]): string;
63
63
  /**
64
64
  * Render messages for recap generation with tool activity intact.
65
- * Filters out older recap breadcrumbs so the recap model only sees the real turn.
65
+ * Filters out older recap breadcrumbs so the recap model only sees the real turn, and lines shown only in this
66
+ * terminal (metadata.localOnly: /mirror's link, a resumed session's folder and id), which never reach a model.
66
67
  */
67
68
  export declare function condenseRecapConversation(messages: Message[]): string;
68
69
  /**
@@ -292,11 +292,13 @@ function condenseToolMessage(message) {
292
292
  }
293
293
  /**
294
294
  * Render messages for recap generation with tool activity intact.
295
- * Filters out older recap breadcrumbs so the recap model only sees the real turn.
295
+ * Filters out older recap breadcrumbs so the recap model only sees the real turn, and lines shown only in this
296
+ * terminal (metadata.localOnly: /mirror's link, a resumed session's folder and id), which never reach a model.
296
297
  */
297
298
  export function condenseRecapConversation(messages) {
298
299
  return messages
299
300
  .filter((message) => !(message.role === 'system' && Boolean(message.metadata?.recap)))
301
+ .filter((message) => !(message.role === 'system' && message.metadata?.localOnly === true))
300
302
  .filter((message) => !isPrivateReasoning(message))
301
303
  .filter((message) => message.role === 'user'
302
304
  || message.role === 'assistant'
@@ -0,0 +1,51 @@
1
+ /** Whether one path component names git's own directory. */
2
+ export declare function isGitDirectoryName(name: string): boolean;
3
+ /** The first component of `path` that names git's own directory, or null. */
4
+ export declare function gitDirectoryComponent(path: string): string | null;
5
+ /**
6
+ * The git directory that holds `target` (an absolute path) when it is not named .git, or null. That is any existing
7
+ * ancestor of `target` that git itself would take for a git directory (is_git_directory: a HEAD that names a ref or
8
+ * an object, and objects/ and refs/ in its common directory), however it is reached: a bare repository, a separate
9
+ * git directory or a worktree's directory beside the working directory or above it. It is also the git directory a
10
+ * work tree around `target` or one of `from` names through a .git file or link, and the common directory that one
11
+ * names, even when it does not exist yet, since git uses whatever is made there. `git init --separate-git-dir`,
12
+ * `git worktree add` and the bare-repository workflow keep git's directory beside the work tree under any name, with
13
+ * a .git file (`gitdir: <path>`, relative to the directory holding it) pointing there, and a linked worktree's
14
+ * directory names the repository's common directory, which holds its config and hooks, in a `commondir` file
15
+ * (relative to it). Each of `from` and `target`'s parent is walked up to the filesystem root. Paths are compared
16
+ * canonically, with the case and Unicode folding a denied path gets.
17
+ *
18
+ * A worktree added inside its own bare repository (`git worktree add main` run in repo.git) holds work-tree files,
19
+ * not git's. A .git file that names its own work tree or a directory above it (`gitdir: .`) makes git refuse to run
20
+ * until that directory is a git directory, so there only the entries that would make it one (HEAD, commondir,
21
+ * objects, refs) are git's. Synchronous, for the policy; a .git entry git ignores or dies on counts for nothing.
22
+ */
23
+ export declare function linkedGitDirectoryHolding(target: string, from: readonly string[]): string | null;
24
+ /**
25
+ * The directory a confined write set would turn into one git's is_git_directory accepts, or null. A confined write
26
+ * never reaches a path named .git (gitDirectoryComponent refuses that) and never writes into a directory git already
27
+ * takes for its own (linkedGitDirectoryHolding refuses that); this closes the last route, a plain directory the set
28
+ * completes into a git directory from nothing, in one call or across several.
29
+ *
30
+ * `target` is one path the call writes, deletes or moves (absolute); `writeSet` is every such path of the whole
31
+ * call (absolute, `target` among them). git's is_git_directory accepts a directory A with a HEAD that names a ref or
32
+ * an object and, in its common directory, objects/ and refs/ it can search; a commondir file stands in for both. So
33
+ * for each ancestor-or-self P of `target` whose final component folds (as GIT_DIRECTORY_MAKERS does) to HEAD,
34
+ * commondir, objects or refs, let A = dirname(P): A is refused when, once the set is written, it holds a HEAD and
35
+ * either a commondir or both objects and refs. A HEAD the set writes counts whatever its bytes (an edit may make an
36
+ * invalid one valid); a HEAD only on disk must pass validHead. A commondir, objects or refs counts when the set
37
+ * writes it (or, being a directory, an ancestor of a path the set writes) or it is on disk (lstat, so a dangling
38
+ * link counts, and a path the set is about to delete still counts — deleting a commondir beside objects/ and refs/
39
+ * completes the directory). Names fold by case and Unicode as the rest of this module does, so planted/head is
40
+ * planted/HEAD on APFS, and p\uD800 is p\uDC00 (Node writes both as p\uFFFD).
41
+ *
42
+ * Checking `target`'s own components covers every git directory a confined agent can build: each write that
43
+ * completes is_git_directory touches one of the four names directly under A, and the disk carries the rest from
44
+ * earlier calls. It does not cover pieces already on disk that the agent could not have made, since writing either
45
+ * beside the other is refused: a HEAD and a commondir naming a directory C that lacks objects/ and refs/, which a
46
+ * write into C completes, and a HEAD beside dangling objects and refs links, which a write at their targets completes.
47
+ *
48
+ * The set is indexed once per array (see writeSetIndex), so admitting each of a call's N paths costs the depth of
49
+ * that path, not N. Synchronous, for the policy.
50
+ */
51
+ export declare function gitDirectoryPlantedByWriteSet(target: string, writeSet: readonly string[]): string | null;
@@ -0,0 +1,429 @@
1
+ import { accessSync, closeSync, constants, fstatSync, lstatSync, openSync, readlinkSync, readSync, realpathSync, statSync } from 'fs';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
3
+ import { canonicalPath, sameFileKey } from './canonical_path.js';
4
+ /**
5
+ * Names for git's own directory, `.git`, in every spelling git's verify_path refuses (read-cache.c): any case; with
6
+ * the Unicode code points HFS+ ignores when it compares names (core.protectHFS); and with NTFS's trailing dots or
7
+ * spaces, an alternate data stream after a colon, or as its 8.3 short name GIT~1 (core.protectNTFS). A write under
8
+ * such a name can change what git does when it next runs there: a filter or core.fsmonitor in .git/config is a
9
+ * command git runs.
10
+ */
11
+ // The code points git's next_hfs_char skips, as HFS+ does.
12
+ const HFS_IGNORED = /[‌-‏‪-‮-]/g;
13
+ const GIT_DIRECTORY_NAME = /^(?:\.git|git~1)[. ]*(?::.*)?$/s;
14
+ /** Whether one path component names git's own directory. */
15
+ export function isGitDirectoryName(name) {
16
+ return GIT_DIRECTORY_NAME.test(name.replace(HFS_IGNORED, '').toLowerCase());
17
+ }
18
+ /** The first component of `path` that names git's own directory, or null. */
19
+ export function gitDirectoryComponent(path) {
20
+ for (const component of path.split(sep === '\\' ? /[\\/]/ : '/')) {
21
+ if (isGitDirectoryName(component))
22
+ return component;
23
+ }
24
+ return null;
25
+ }
26
+ /** git reads a .git file only up to this size (read_gitfile_gently); larger, it refuses to run there. */
27
+ const MAX_POINTER_BYTES = 1024 * 1024;
28
+ /** validate_headref reads this much of HEAD. */
29
+ const MAX_HEAD_BYTES = 255;
30
+ /** A bound on one upward walk; a real path ends at the filesystem root long before it. */
31
+ const MAX_WALK_LEVELS = 4096;
32
+ /** Directories git reads inside its own directory: a work tree there would be read as git's. */
33
+ const GIT_DIRECTORY_ENTRIES = new Set(['hooks', 'info', 'logs', 'modules', 'objects', 'refs', 'worktrees'].map(sameFileKey));
34
+ /** What makes a directory a git directory (is_git_directory), or names the directory that completes it. */
35
+ const GIT_DIRECTORY_MAKERS = new Set(['HEAD', 'commondir', 'objects', 'refs'].map(sameFileKey));
36
+ /** A pointer file git cannot read: git dies on it. */
37
+ const UNREADABLE = Symbol('unreadable');
38
+ /**
39
+ * The git directory that holds `target` (an absolute path) when it is not named .git, or null. That is any existing
40
+ * ancestor of `target` that git itself would take for a git directory (is_git_directory: a HEAD that names a ref or
41
+ * an object, and objects/ and refs/ in its common directory), however it is reached: a bare repository, a separate
42
+ * git directory or a worktree's directory beside the working directory or above it. It is also the git directory a
43
+ * work tree around `target` or one of `from` names through a .git file or link, and the common directory that one
44
+ * names, even when it does not exist yet, since git uses whatever is made there. `git init --separate-git-dir`,
45
+ * `git worktree add` and the bare-repository workflow keep git's directory beside the work tree under any name, with
46
+ * a .git file (`gitdir: <path>`, relative to the directory holding it) pointing there, and a linked worktree's
47
+ * directory names the repository's common directory, which holds its config and hooks, in a `commondir` file
48
+ * (relative to it). Each of `from` and `target`'s parent is walked up to the filesystem root. Paths are compared
49
+ * canonically, with the case and Unicode folding a denied path gets.
50
+ *
51
+ * A worktree added inside its own bare repository (`git worktree add main` run in repo.git) holds work-tree files,
52
+ * not git's. A .git file that names its own work tree or a directory above it (`gitdir: .`) makes git refuse to run
53
+ * until that directory is a git directory, so there only the entries that would make it one (HEAD, commondir,
54
+ * objects, refs) are git's. Synchronous, for the policy; a .git entry git ignores or dies on counts for nothing.
55
+ */
56
+ export function linkedGitDirectoryHolding(target, from) {
57
+ const canonicalTarget = canonicalPath(resolve(target));
58
+ const key = sameFileKey(canonicalTarget);
59
+ const repositories = linkedRepositories([...from, dirname(canonicalTarget)]);
60
+ for (const { workTree, directories } of repositories) {
61
+ for (const directory of directories) {
62
+ const root = sameFileKey(directory);
63
+ if (!isWithin(key, root, true))
64
+ continue;
65
+ if (isWithin(sameFileKey(workTree), root, true) && !isGitDirectory(directory)) {
66
+ if (GIT_DIRECTORY_MAKERS.has(relative(root, key).split(sep)[0]))
67
+ return directory;
68
+ continue;
69
+ }
70
+ if (!inOwnWorkTree(key, directory, repositories))
71
+ return directory;
72
+ }
73
+ }
74
+ for (const directory of ancestorGitDirectories(dirname(canonicalTarget))) {
75
+ if (isWithin(key, sameFileKey(directory), true) && !inOwnWorkTree(key, directory, repositories))
76
+ return directory;
77
+ }
78
+ return null;
79
+ }
80
+ /**
81
+ * The directory a confined write set would turn into one git's is_git_directory accepts, or null. A confined write
82
+ * never reaches a path named .git (gitDirectoryComponent refuses that) and never writes into a directory git already
83
+ * takes for its own (linkedGitDirectoryHolding refuses that); this closes the last route, a plain directory the set
84
+ * completes into a git directory from nothing, in one call or across several.
85
+ *
86
+ * `target` is one path the call writes, deletes or moves (absolute); `writeSet` is every such path of the whole
87
+ * call (absolute, `target` among them). git's is_git_directory accepts a directory A with a HEAD that names a ref or
88
+ * an object and, in its common directory, objects/ and refs/ it can search; a commondir file stands in for both. So
89
+ * for each ancestor-or-self P of `target` whose final component folds (as GIT_DIRECTORY_MAKERS does) to HEAD,
90
+ * commondir, objects or refs, let A = dirname(P): A is refused when, once the set is written, it holds a HEAD and
91
+ * either a commondir or both objects and refs. A HEAD the set writes counts whatever its bytes (an edit may make an
92
+ * invalid one valid); a HEAD only on disk must pass validHead. A commondir, objects or refs counts when the set
93
+ * writes it (or, being a directory, an ancestor of a path the set writes) or it is on disk (lstat, so a dangling
94
+ * link counts, and a path the set is about to delete still counts — deleting a commondir beside objects/ and refs/
95
+ * completes the directory). Names fold by case and Unicode as the rest of this module does, so planted/head is
96
+ * planted/HEAD on APFS, and p\uD800 is p\uDC00 (Node writes both as p\uFFFD).
97
+ *
98
+ * Checking `target`'s own components covers every git directory a confined agent can build: each write that
99
+ * completes is_git_directory touches one of the four names directly under A, and the disk carries the rest from
100
+ * earlier calls. It does not cover pieces already on disk that the agent could not have made, since writing either
101
+ * beside the other is refused: a HEAD and a commondir naming a directory C that lacks objects/ and refs/, which a
102
+ * write into C completes, and a HEAD beside dangling objects and refs links, which a write at their targets completes.
103
+ *
104
+ * The set is indexed once per array (see writeSetIndex), so admitting each of a call's N paths costs the depth of
105
+ * that path, not N. Synchronous, for the policy.
106
+ */
107
+ export function gitDirectoryPlantedByWriteSet(target, writeSet) {
108
+ const index = writeSetIndex(writeSet);
109
+ let path = canonicalPath(resolve(target));
110
+ for (let level = 0; level < MAX_WALK_LEVELS; level++) {
111
+ if (GIT_DIRECTORY_MAKERS.has(sameFileKey(basename(path)))) {
112
+ const directory = dirname(path);
113
+ if (completesGitDirectory(directory, index))
114
+ return directory;
115
+ }
116
+ const parent = dirname(path);
117
+ if (parent === path)
118
+ break;
119
+ path = parent;
120
+ }
121
+ return null;
122
+ }
123
+ /**
124
+ * One index per write-set array, so a call's N paths are canonicalized once, not once for each of them. A caller
125
+ * builds a fresh array for each admission pass (the runtime's refuseWrites, apply_patch's in-lock admission), so a
126
+ * later pass reads the disk again; an index lives only as long as its array.
127
+ */
128
+ const WRITE_SET_INDEXES = new WeakMap();
129
+ function writeSetIndex(writeSet) {
130
+ const known = WRITE_SET_INDEXES.get(writeSet);
131
+ if (known !== undefined)
132
+ return known;
133
+ const written = new Set();
134
+ const holding = new Set();
135
+ for (const path of writeSet) {
136
+ let key = sameFileKey(canonicalPath(resolve(path)));
137
+ written.add(key);
138
+ // A directory already held was walked up from before.
139
+ for (let level = 0; level < MAX_WALK_LEVELS && !holding.has(key); level++) {
140
+ holding.add(key);
141
+ const parent = dirname(key);
142
+ if (parent === key)
143
+ break;
144
+ key = parent;
145
+ }
146
+ }
147
+ const index = { written, holding };
148
+ WRITE_SET_INDEXES.set(writeSet, index);
149
+ return index;
150
+ }
151
+ /** Whether the write set writes `path` itself. */
152
+ function writeSetWrites(index, path) {
153
+ return index.written.has(sameFileKey(canonicalPath(resolve(path))));
154
+ }
155
+ /** Whether the write set writes `directory` itself or any path inside it. */
156
+ function writeSetWritesWithin(index, directory) {
157
+ return index.holding.has(sameFileKey(canonicalPath(resolve(directory))));
158
+ }
159
+ /** A path that exists on disk now, by lstat (a dangling link and any non-regular entry count). */
160
+ function existsOnDisk(path) {
161
+ try {
162
+ lstatSync(path);
163
+ return true;
164
+ }
165
+ catch {
166
+ return false;
167
+ }
168
+ }
169
+ /** Whether directory A holds a maker named `name` once the set is written: in the set, or on disk. */
170
+ function makerPresent(directory, name, index, asDirectory) {
171
+ const path = join(directory, name);
172
+ if (asDirectory ? writeSetWritesWithin(index, path) : writeSetWrites(index, path))
173
+ return true;
174
+ return existsOnDisk(path);
175
+ }
176
+ /** Whether, once the set is written, `directory` is a directory git's is_git_directory accepts. */
177
+ function completesGitDirectory(directory, index) {
178
+ const head = join(directory, 'HEAD');
179
+ // A HEAD the set writes counts whatever its bytes; one only on disk must be a valid HEAD.
180
+ const hasHead = writeSetWrites(index, head) || validHead(head);
181
+ if (!hasHead)
182
+ return false;
183
+ if (makerPresent(directory, 'commondir', index, false))
184
+ return true;
185
+ return makerPresent(directory, 'objects', index, true) && makerPresent(directory, 'refs', index, true);
186
+ }
187
+ /**
188
+ * Whether `key` lies in the work tree of a worktree that git keeps inside `directory`, its own git directory: a file
189
+ * there is the work tree's, unless the worktree sits where git reads its own hooks, info, logs, modules, objects,
190
+ * refs or worktrees.
191
+ */
192
+ function inOwnWorkTree(key, directory, repositories) {
193
+ const root = sameFileKey(directory);
194
+ return repositories.some(({ workTree, directories: used }) => {
195
+ const tree = sameFileKey(workTree);
196
+ return used.includes(directory) && isWithin(key, tree, false) && isWithin(tree, root, false)
197
+ && !GIT_DIRECTORY_ENTRIES.has(relative(root, tree).split(sep)[0]);
198
+ });
199
+ }
200
+ /** Each existing directory from `start` up to the filesystem root that git takes for a git directory. */
201
+ function ancestorGitDirectories(start) {
202
+ const found = [];
203
+ let directory = start;
204
+ for (let level = 0; level < MAX_WALK_LEVELS; level++) {
205
+ if (isGitDirectory(directory))
206
+ found.push(directory);
207
+ const parent = dirname(directory);
208
+ if (parent === directory)
209
+ break;
210
+ directory = parent;
211
+ }
212
+ return found;
213
+ }
214
+ /**
215
+ * setup.c's is_git_directory: a HEAD that is a link into refs/, or a file naming a ref (`ref: refs/...`) or an
216
+ * object id; and objects/ and refs/ git can search in the common directory. A commondir file that cannot be read
217
+ * makes git die rather than say no, so a directory with a valid HEAD and one counts.
218
+ */
219
+ function isGitDirectory(directory) {
220
+ if (!validHead(join(directory, 'HEAD')))
221
+ return false;
222
+ const common = commonDirectory(directory);
223
+ if (common === UNREADABLE)
224
+ return true;
225
+ const base = common ?? directory;
226
+ return searchable(join(base, 'objects')) && searchable(join(base, 'refs'));
227
+ }
228
+ /** refs.c's validate_headref. */
229
+ function validHead(path) {
230
+ let info;
231
+ try {
232
+ info = lstatSync(path);
233
+ }
234
+ catch {
235
+ return false;
236
+ }
237
+ if (info.isSymbolicLink()) {
238
+ try {
239
+ return readlinkSync(path).startsWith('refs/');
240
+ }
241
+ catch {
242
+ return false;
243
+ }
244
+ }
245
+ const read = readPointerFile(path, MAX_HEAD_BYTES, true);
246
+ if (typeof read !== 'string')
247
+ return false;
248
+ const text = untilNul(read);
249
+ return /^ref:[ \t\n\r]*refs\//.test(text) || /^[0-9a-fA-F]{40}/.test(text);
250
+ }
251
+ /** access(X_OK), as is_git_directory checks objects/ and refs/. */
252
+ function searchable(path) {
253
+ try {
254
+ accessSync(path, constants.X_OK);
255
+ return true;
256
+ }
257
+ catch {
258
+ return false;
259
+ }
260
+ }
261
+ /** Whether `path` lies inside `root` (or is it, when `orSame`); both spelled alike. */
262
+ function isWithin(path, root, orSame) {
263
+ return (orSame && path === root) || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
264
+ }
265
+ /** The work trees that hold a .git file, link or directory among `directories` and their ancestors. */
266
+ function linkedRepositories(directories) {
267
+ const found = [];
268
+ const visited = new Set();
269
+ for (const start of directories) {
270
+ let directory = canonicalPath(resolve(start));
271
+ // A directory already visited was walked up from before.
272
+ for (let level = 0; level < MAX_WALK_LEVELS && !visited.has(directory); level++) {
273
+ visited.add(directory);
274
+ const gitDirectory = dotGitDirectory(directory);
275
+ if (gitDirectory !== null) {
276
+ const common = commonDirectory(gitDirectory);
277
+ found.push({ workTree: directory, directories: typeof common === 'string' ? [gitDirectory, common] : [gitDirectory] });
278
+ }
279
+ const parent = dirname(directory);
280
+ if (parent === directory)
281
+ break;
282
+ directory = parent;
283
+ }
284
+ }
285
+ return found;
286
+ }
287
+ /**
288
+ * The git directory `directory`'s .git names, canonical, or null when git finds no repository there: no .git, a
289
+ * .git it cannot stat (a link loop) or a .git directory it cannot search, which git passes over, or a .git file it
290
+ * cannot open, read or use, on which git dies. The agent cannot change any of these, since a confined write never
291
+ * reaches a path named .git.
292
+ */
293
+ function dotGitDirectory(directory) {
294
+ const dotGit = join(directory, '.git');
295
+ let info;
296
+ try {
297
+ info = lstatSync(dotGit);
298
+ }
299
+ catch {
300
+ return null;
301
+ }
302
+ // A .git directory is matched by name; its commondir, if any, still counts.
303
+ if (info.isDirectory())
304
+ return searchable(dotGit) ? reachablePath(dotGit) : null;
305
+ if (info.isFile())
306
+ return gitFileDirectory(dotGit, directory);
307
+ if (!info.isSymbolicLink())
308
+ return null;
309
+ // git follows a .git link: to a directory it uses as the git directory, to a file it reads as a .git file. A link
310
+ // that leads nowhere yet names the directory git will use once it is made.
311
+ let resolved;
312
+ try {
313
+ resolved = realpathSync.native(dotGit);
314
+ }
315
+ catch (error) {
316
+ if (!isMissing(error))
317
+ return null;
318
+ let link;
319
+ try {
320
+ link = readlinkSync(dotGit);
321
+ }
322
+ catch {
323
+ return null;
324
+ }
325
+ return reachablePath(isAbsolute(link) ? link : `${directory}${sep}${link}`);
326
+ }
327
+ let target;
328
+ try {
329
+ target = lstatSync(resolved);
330
+ }
331
+ catch {
332
+ return null;
333
+ }
334
+ if (target.isFile())
335
+ return gitFileDirectory(resolved, directory);
336
+ return target.isDirectory() && searchable(resolved) ? resolved : null;
337
+ }
338
+ /**
339
+ * The directory a .git file names on its `gitdir: ` line, relative to `directory`, as read_gitfile_gently reads it:
340
+ * up to 1 MiB, its trailing newlines dropped, and ending at its first NUL byte. Null when git would not use it.
341
+ */
342
+ function gitFileDirectory(file, directory) {
343
+ const text = readPointerFile(file, MAX_POINTER_BYTES);
344
+ if (typeof text !== 'string' || !text.startsWith('gitdir: '))
345
+ return null;
346
+ const named = untilNul(text.replace(/[\r\n]+$/, '')).slice('gitdir: '.length);
347
+ if (named === '')
348
+ return null;
349
+ return reachablePath(isAbsolute(named) ? named : `${directory}${sep}${named}`);
350
+ }
351
+ /**
352
+ * The common directory a git directory's `commondir` file names, relative to it, as get_common_dir reads it: null
353
+ * when there is no such file, UNREADABLE when git would die reading it (it cannot be opened or read, or is empty).
354
+ */
355
+ function commonDirectory(gitDirectory) {
356
+ const path = join(gitDirectory, 'commondir');
357
+ // git's file_exists: a commondir it cannot stat is none.
358
+ try {
359
+ statSync(path);
360
+ }
361
+ catch {
362
+ return null;
363
+ }
364
+ const text = readPointerFile(path, MAX_POINTER_BYTES);
365
+ if (text === null)
366
+ return null;
367
+ if (text === UNREADABLE)
368
+ return UNREADABLE;
369
+ const named = untilNul(text.replace(/[\r\n]+$/, ''));
370
+ if (named === '')
371
+ return UNREADABLE;
372
+ return reachablePath(isAbsolute(named) ? named : `${gitDirectory}${sep}${named}`) ?? UNREADABLE;
373
+ }
374
+ /** Text as git's C strings see it: up to its first NUL byte. */
375
+ function untilNul(text) {
376
+ const nul = text.indexOf('\0');
377
+ return nul < 0 ? text : text.slice(0, nul);
378
+ }
379
+ /** `path` canonical, or null when no process can reach it: a link loop, a name too long, or a directory it may not search. */
380
+ function reachablePath(path) {
381
+ try {
382
+ return canonicalPath(path);
383
+ }
384
+ catch {
385
+ return null;
386
+ }
387
+ }
388
+ /**
389
+ * A regular file's text: null when it is missing or not a regular file (git reads neither), UNREADABLE when it cannot
390
+ * be opened or read or is larger than `limit`. `truncate` reads the first `limit` bytes of a larger file instead, as
391
+ * git reads HEAD. It is opened without blocking, so a FIFO cannot hang the policy.
392
+ */
393
+ function readPointerFile(path, limit, truncate = false) {
394
+ let fd;
395
+ try {
396
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
397
+ }
398
+ catch (error) {
399
+ if (isMissing(error) || error.code === 'EISDIR')
400
+ return null;
401
+ return UNREADABLE;
402
+ }
403
+ try {
404
+ const info = fstatSync(fd);
405
+ if (!info.isFile())
406
+ return null;
407
+ if (info.size > limit && !truncate)
408
+ return UNREADABLE;
409
+ const buffer = Buffer.alloc(Math.min(info.size, limit));
410
+ let length = 0;
411
+ while (length < buffer.length) {
412
+ const read = readSync(fd, buffer, length, buffer.length - length, length);
413
+ if (read === 0)
414
+ break;
415
+ length += read;
416
+ }
417
+ return buffer.subarray(0, length).toString('utf8');
418
+ }
419
+ catch {
420
+ return UNREADABLE;
421
+ }
422
+ finally {
423
+ closeSync(fd);
424
+ }
425
+ }
426
+ function isMissing(error) {
427
+ const code = error.code;
428
+ return code === 'ENOENT' || code === 'ENOTDIR';
429
+ }
@@ -1,4 +1,9 @@
1
1
  export declare function isPathWithinRoot(path: string, root: string): boolean;
2
2
  export declare function prepareTemporaryWriteRoot(cwd: string, root: string): Promise<string>;
3
- export declare function assertTemporaryWritePathAllowed(target: string, root: string, action: string): Promise<void>;
3
+ export declare function assertTemporaryWritePathAllowed(target: string, root: string, action: string,
4
+ /** The working directory a relative path was resolved from: a work tree there may name its git directory. */
5
+ cwd?: string,
6
+ /** Every path the whole call writes, deletes or moves (absolute, `target` among them); `target` alone when a
7
+ * caller writes one file. A set that completes a git directory across its paths is refused as one. */
8
+ writeSet?: readonly string[]): Promise<void>;
4
9
  export declare function assertTemporaryRootSafe(root: string, action: string): Promise<string>;