harnery 0.41.0 → 0.42.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 (212) hide show
  1. package/dist/commander.js +3 -0
  2. package/dist/commands/agents.d.ts.map +1 -1
  3. package/dist/commands/agents.js +9 -1
  4. package/dist/commands/artifacts.d.ts.map +1 -1
  5. package/dist/commands/artifacts.js +113 -12
  6. package/dist/commands/browse.d.ts +164 -0
  7. package/dist/commands/browse.d.ts.map +1 -1
  8. package/dist/commands/browse.js +263 -51
  9. package/dist/commands/claude-desktop.d.ts.map +1 -1
  10. package/dist/commands/claude-desktop.js +52 -0
  11. package/dist/commands/disk.d.ts +6 -0
  12. package/dist/commands/disk.d.ts.map +1 -0
  13. package/dist/commands/disk.js +80 -0
  14. package/dist/commands/doctor.d.ts +8 -0
  15. package/dist/commands/doctor.d.ts.map +1 -1
  16. package/dist/commands/doctor.js +48 -1
  17. package/dist/commands/files.d.ts +16 -0
  18. package/dist/commands/files.d.ts.map +1 -1
  19. package/dist/commands/files.js +54 -2
  20. package/dist/commands/init.d.ts +2 -2
  21. package/dist/commands/init.d.ts.map +1 -1
  22. package/dist/commands/init.js +43 -9
  23. package/dist/commands/rm.d.ts +4 -0
  24. package/dist/commands/rm.d.ts.map +1 -0
  25. package/dist/commands/rm.js +87 -0
  26. package/dist/commands/servers.d.ts +7 -0
  27. package/dist/commands/servers.d.ts.map +1 -0
  28. package/dist/commands/servers.js +394 -0
  29. package/dist/commands/tunnel.d.ts.map +1 -1
  30. package/dist/commands/tunnel.js +82 -2
  31. package/dist/core/adapters/profiles.d.ts +9 -0
  32. package/dist/core/adapters/profiles.d.ts.map +1 -1
  33. package/dist/core/adapters/profiles.js +22 -1
  34. package/dist/core/adapters/types.d.ts +9 -0
  35. package/dist/core/adapters/types.d.ts.map +1 -1
  36. package/dist/core/agents/cli.js +13 -6
  37. package/dist/core/agents/render/session-context.d.ts.map +1 -1
  38. package/dist/core/agents/render/session-context.js +2 -0
  39. package/dist/core/agents/state/live-coordination-view.d.ts +20 -0
  40. package/dist/core/agents/state/live-coordination-view.d.ts.map +1 -1
  41. package/dist/core/agents/state/live-coordination-view.js +60 -0
  42. package/dist/core/artifacts/delivery-card.js +9 -2
  43. package/dist/core/artifacts/index.d.ts +140 -4
  44. package/dist/core/artifacts/index.d.ts.map +1 -1
  45. package/dist/core/artifacts/index.js +522 -49
  46. package/dist/core/config.d.ts +68 -11
  47. package/dist/core/config.d.ts.map +1 -1
  48. package/dist/core/config.js +128 -3
  49. package/dist/core/diagnostics/bundle.d.ts.map +1 -1
  50. package/dist/core/diagnostics/bundle.js +2 -2
  51. package/dist/core/events/v3/producers/recorder.d.ts.map +1 -1
  52. package/dist/core/events/v3/producers/recorder.js +16 -0
  53. package/dist/core/events/v3/projection.js +9 -1
  54. package/dist/core/hooks/adapter/events.d.ts +17 -0
  55. package/dist/core/hooks/adapter/events.d.ts.map +1 -1
  56. package/dist/core/hooks/adapter/events.js +5 -0
  57. package/dist/core/hooks/adapter/runtime-telemetry.js +3 -1
  58. package/dist/core/hooks/adapter/wiring.d.ts +37 -7
  59. package/dist/core/hooks/adapter/wiring.d.ts.map +1 -1
  60. package/dist/core/hooks/adapter/wiring.js +62 -4
  61. package/dist/core/hooks/cli.js +45 -6
  62. package/dist/core/hooks/run-markers.d.ts +37 -0
  63. package/dist/core/hooks/run-markers.d.ts.map +1 -0
  64. package/dist/core/hooks/run-markers.js +109 -0
  65. package/dist/core/servers/index.d.ts +211 -0
  66. package/dist/core/servers/index.d.ts.map +1 -0
  67. package/dist/core/servers/index.js +560 -0
  68. package/dist/core/servers/net.d.ts +58 -0
  69. package/dist/core/servers/net.d.ts.map +1 -0
  70. package/dist/core/servers/net.js +270 -0
  71. package/dist/core/servers/tunnels.d.ts +14 -0
  72. package/dist/core/servers/tunnels.d.ts.map +1 -0
  73. package/dist/core/servers/tunnels.js +33 -0
  74. package/dist/core/storage/builtins.js +1 -0
  75. package/dist/core/workflow/engine.d.ts.map +1 -1
  76. package/dist/core/workflow/engine.js +30 -1
  77. package/dist/core/workflow/sandbox-projection.d.ts +13 -2
  78. package/dist/core/workflow/sandbox-projection.d.ts.map +1 -1
  79. package/dist/core/workflow/sandbox-projection.js +23 -0
  80. package/dist/core/workflow/spawn-claude.d.ts.map +1 -1
  81. package/dist/core/workflow/spawn-claude.js +6 -1
  82. package/dist/core/workflow/spawn-codex.d.ts +2 -0
  83. package/dist/core/workflow/spawn-codex.d.ts.map +1 -1
  84. package/dist/core/workflow/spawn-codex.js +20 -1
  85. package/dist/core/workflow/spawn-cursor.d.ts.map +1 -1
  86. package/dist/core/workflow/spawn-cursor.js +6 -1
  87. package/dist/core/workflow/spawn-opencode.d.ts.map +1 -1
  88. package/dist/core/workflow/spawn-opencode.js +4 -1
  89. package/dist/core/workflow/types.d.ts +47 -2
  90. package/dist/core/workflow/types.d.ts.map +1 -1
  91. package/dist/core/workflow/worker-access.d.ts +92 -0
  92. package/dist/core/workflow/worker-access.d.ts.map +1 -0
  93. package/dist/core/workflow/worker-access.js +450 -0
  94. package/dist/lib/browser/batch-steps.d.ts +18 -0
  95. package/dist/lib/browser/batch-steps.d.ts.map +1 -0
  96. package/dist/lib/browser/batch-steps.js +82 -0
  97. package/dist/lib/browser/collect/collector.d.ts +99 -0
  98. package/dist/lib/browser/collect/collector.d.ts.map +1 -0
  99. package/dist/lib/browser/collect/collector.js +202 -0
  100. package/dist/lib/browser/collect/fields.d.ts +31 -0
  101. package/dist/lib/browser/collect/fields.d.ts.map +1 -0
  102. package/dist/lib/browser/collect/fields.js +75 -0
  103. package/dist/lib/browser/collect/index.d.ts +6 -0
  104. package/dist/lib/browser/collect/index.d.ts.map +1 -0
  105. package/dist/lib/browser/collect/index.js +5 -0
  106. package/dist/lib/browser/collect/page-driver.d.ts +14 -0
  107. package/dist/lib/browser/collect/page-driver.d.ts.map +1 -0
  108. package/dist/lib/browser/collect/page-driver.js +306 -0
  109. package/dist/lib/browser/collect/presets.d.ts +52 -0
  110. package/dist/lib/browser/collect/presets.d.ts.map +1 -0
  111. package/dist/lib/browser/collect/presets.js +176 -0
  112. package/dist/lib/browser/collect/scroll-plan.d.ts +85 -0
  113. package/dist/lib/browser/collect/scroll-plan.d.ts.map +1 -0
  114. package/dist/lib/browser/collect/scroll-plan.js +118 -0
  115. package/dist/lib/browser/index.d.ts +1 -1
  116. package/dist/lib/browser/index.d.ts.map +1 -1
  117. package/dist/lib/browser/page-review-judge.d.ts +2 -0
  118. package/dist/lib/browser/page-review-judge.d.ts.map +1 -1
  119. package/dist/lib/browser/page-review-judge.js +13 -0
  120. package/dist/lib/browser/qa-run-contracts.d.ts +10 -0
  121. package/dist/lib/browser/qa-run-contracts.d.ts.map +1 -1
  122. package/dist/lib/browser/qa-run.d.ts.map +1 -1
  123. package/dist/lib/browser/qa-run.js +1 -0
  124. package/dist/lib/browser/windows-chrome.d.ts +59 -0
  125. package/dist/lib/browser/windows-chrome.d.ts.map +1 -0
  126. package/dist/lib/browser/windows-chrome.js +179 -0
  127. package/dist/lib/claude-desktop-share.d.ts +136 -0
  128. package/dist/lib/claude-desktop-share.d.ts.map +1 -0
  129. package/dist/lib/claude-desktop-share.js +394 -0
  130. package/dist/lib/disk-usage.d.ts +50 -0
  131. package/dist/lib/disk-usage.d.ts.map +1 -0
  132. package/dist/lib/disk-usage.js +303 -0
  133. package/dist/lib/docs-lint.d.ts +6 -0
  134. package/dist/lib/docs-lint.d.ts.map +1 -1
  135. package/dist/lib/docs-lint.js +8 -3
  136. package/dist/lib/guarded-remove.d.ts +34 -0
  137. package/dist/lib/guarded-remove.d.ts.map +1 -0
  138. package/dist/lib/guarded-remove.js +310 -0
  139. package/dist/lib/instructions/templates.js +8 -8
  140. package/dist/lib/tunnel/error-page.d.ts +1 -1
  141. package/dist/lib/tunnel/error-page.d.ts.map +1 -1
  142. package/dist/lib/tunnel/error-page.js +19 -8
  143. package/dist/lib/tunnel/gate.js +20 -1
  144. package/dist/lib/tunnel/path-scope.d.ts +22 -0
  145. package/dist/lib/tunnel/path-scope.d.ts.map +1 -0
  146. package/dist/lib/tunnel/path-scope.js +62 -0
  147. package/dist/lib/tunnel/state.d.ts +5 -0
  148. package/dist/lib/tunnel/state.d.ts.map +1 -1
  149. package/dist/lib/tunnel/state.js +17 -3
  150. package/package.json +6 -1
  151. package/schemas/config.schema.json +91 -0
  152. package/src/commander.ts +19 -0
  153. package/src/commands/agents.ts +14 -0
  154. package/src/commands/artifacts.ts +171 -19
  155. package/src/commands/browse.ts +400 -57
  156. package/src/commands/claude-desktop.ts +61 -0
  157. package/src/commands/disk.ts +114 -0
  158. package/src/commands/doctor.ts +52 -1
  159. package/src/commands/files.ts +93 -2
  160. package/src/commands/init.ts +55 -5
  161. package/src/commands/rm.ts +115 -0
  162. package/src/commands/servers.ts +506 -0
  163. package/src/commands/tunnel.ts +102 -2
  164. package/src/core/adapters/profiles.ts +22 -1
  165. package/src/core/adapters/types.ts +10 -0
  166. package/src/core/agents/cli.ts +14 -6
  167. package/src/core/agents/render/session-context.ts +1 -0
  168. package/src/core/agents/state/live-coordination-view.ts +73 -0
  169. package/src/core/artifacts/delivery-card.ts +10 -2
  170. package/src/core/artifacts/index.ts +697 -44
  171. package/src/core/config.ts +183 -4
  172. package/src/core/diagnostics/bundle.ts +2 -1
  173. package/src/core/events/v3/producers/recorder.ts +16 -0
  174. package/src/core/events/v3/projection.ts +11 -1
  175. package/src/core/hooks/adapter/events.ts +19 -0
  176. package/src/core/hooks/adapter/runtime-telemetry.ts +3 -1
  177. package/src/core/hooks/adapter/wiring.ts +116 -8
  178. package/src/core/hooks/cli.ts +47 -6
  179. package/src/core/hooks/run-markers.ts +132 -0
  180. package/src/core/servers/index.ts +712 -0
  181. package/src/core/servers/net.ts +283 -0
  182. package/src/core/servers/tunnels.ts +39 -0
  183. package/src/core/storage/builtins.ts +1 -0
  184. package/src/core/workflow/engine.ts +38 -1
  185. package/src/core/workflow/sandbox-projection.ts +38 -2
  186. package/src/core/workflow/spawn-claude.ts +5 -1
  187. package/src/core/workflow/spawn-codex.ts +18 -1
  188. package/src/core/workflow/spawn-cursor.ts +5 -1
  189. package/src/core/workflow/spawn-opencode.ts +4 -1
  190. package/src/core/workflow/types.ts +62 -2
  191. package/src/core/workflow/worker-access.ts +525 -0
  192. package/src/lib/browser/batch-steps.ts +79 -0
  193. package/src/lib/browser/collect/collector.ts +306 -0
  194. package/src/lib/browser/collect/fields.ts +87 -0
  195. package/src/lib/browser/collect/index.ts +47 -0
  196. package/src/lib/browser/collect/page-driver.ts +327 -0
  197. package/src/lib/browser/collect/presets.ts +237 -0
  198. package/src/lib/browser/collect/scroll-plan.ts +179 -0
  199. package/src/lib/browser/index.ts +1 -0
  200. package/src/lib/browser/page-review-judge.ts +16 -0
  201. package/src/lib/browser/qa-run-contracts.ts +11 -0
  202. package/src/lib/browser/qa-run.ts +1 -0
  203. package/src/lib/browser/windows-chrome.ts +227 -0
  204. package/src/lib/claude-desktop-share.ts +511 -0
  205. package/src/lib/disk-usage.ts +347 -0
  206. package/src/lib/docs-lint.ts +8 -3
  207. package/src/lib/guarded-remove.ts +376 -0
  208. package/src/lib/instructions/templates.ts +8 -8
  209. package/src/lib/tunnel/error-page.ts +25 -9
  210. package/src/lib/tunnel/gate.ts +22 -1
  211. package/src/lib/tunnel/path-scope.ts +73 -0
  212. package/src/lib/tunnel/state.ts +20 -3
@@ -0,0 +1,376 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { lstatSync, readdirSync, readlinkSync, realpathSync, rmSync, type Stats } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, isAbsolute, parse, relative, resolve, sep } from "node:path";
5
+
6
+ export interface RemoveOptions {
7
+ root: string;
8
+ recursive?: boolean;
9
+ yes?: boolean;
10
+ dryRun?: boolean;
11
+ /**
12
+ * Protected paths (Git metadata, credentials, Harnery state, SSH or GnuPG
13
+ * keys, a bare repository) the caller names for removal, one exact path
14
+ * each. A protected path that is not named is still refused.
15
+ */
16
+ allowProtected?: string[];
17
+ /** Directories whose own Git metadata and Harnery state may never be allowed (the live workspace). */
18
+ liveRoots?: string[];
19
+ }
20
+
21
+ export interface RemovalLink {
22
+ path: string;
23
+ /** What the link points to. It is removed as a link and never followed. */
24
+ target: string;
25
+ }
26
+
27
+ export interface RemovalReport {
28
+ schema: "harnery.removal/v1";
29
+ applied: boolean;
30
+ root: string;
31
+ targets: string[];
32
+ entries: number;
33
+ bytes: number;
34
+ /** Protected paths removed because the caller named them with allowProtected. */
35
+ protected: string[];
36
+ /** Symbolic links inside recursive targets, removed as links. */
37
+ links: RemovalLink[];
38
+ }
39
+
40
+ const protectedNames = new Set([".git", ".harnery", ".credentials", ".ssh", ".gnupg"]);
41
+ const MAX_ENTRIES = 10_000;
42
+
43
+ /** Permanent removal is deliberately limited to inspected, untracked local outputs. */
44
+ export function guardedRemove(
45
+ paths: string[],
46
+ options: RemoveOptions,
47
+ checkClaims: (targets: string[]) => void = () => {},
48
+ ): RemovalReport {
49
+ const cwd = realpathSync(process.cwd());
50
+ const root = checkedPath(options.root, new Set(), true);
51
+ const allowed = allowedProtected(options.allowProtected ?? [], root, options.liveRoots ?? []);
52
+ const rootStat = lstatSync(root);
53
+ const rootFingerprint = fingerprint(rootStat);
54
+ if (!rootStat.isDirectory()) throw new Error("--root must be a directory");
55
+ if (root === parse(root).root || root === realpathSync(homedir()))
56
+ throw new Error("--root cannot be a filesystem root or home directory");
57
+ if (paths.length === 0 || paths.length > 100) throw new Error("Supply 1-100 explicit targets");
58
+ const targets = paths.map((path) => checkedPath(path, allowed));
59
+ const snapshots = new Map<string, string>();
60
+ const removedProtected = new Set<string>();
61
+ const links: RemovalLink[] = [];
62
+ const gitDirs = new Set<string>();
63
+ let bytes = 0;
64
+ const devices = new Set<number>();
65
+
66
+ for (const target of targets) {
67
+ const home = realpathSync(homedir());
68
+ if (target === home || strictlyInside(target, home))
69
+ throw new Error(`Cannot remove the home directory or its ancestor: ${target}`);
70
+ const systemRoots =
71
+ process.platform === "win32"
72
+ ? [
73
+ process.env.SystemRoot,
74
+ process.env.ProgramFiles,
75
+ process.env["ProgramFiles(x86)"],
76
+ ].filter((value): value is string => Boolean(value))
77
+ : [
78
+ "/etc",
79
+ "/usr",
80
+ "/boot",
81
+ "/dev",
82
+ "/proc",
83
+ "/sys",
84
+ "/bin",
85
+ "/sbin",
86
+ "/lib",
87
+ "/lib64",
88
+ "/run",
89
+ ];
90
+ if (
91
+ systemRoots.some(
92
+ (system) =>
93
+ target === resolve(system) ||
94
+ strictlyInside(resolve(system), target) ||
95
+ strictlyInside(target, resolve(system)),
96
+ )
97
+ )
98
+ throw new Error(`System files are protected: ${target}`);
99
+ if (!strictlyInside(root, target))
100
+ throw new Error(`Target must be strictly inside --root: ${target}`);
101
+ if (target === cwd || strictlyInside(target, cwd))
102
+ throw new Error(`Cannot remove the working directory or its ancestor: ${target}`);
103
+ if (
104
+ targets.some((other) => other !== target && strictlyInside(other, target)) ||
105
+ targets.filter((other) => other === target).length > 1
106
+ )
107
+ throw new Error("Targets must not duplicate or contain one another");
108
+ const stat = lstatSync(target);
109
+ if (stat.dev !== rootStat.dev) throw new Error(`Target crosses a mount boundary: ${target}`);
110
+ if (stat.isDirectory() && !options.recursive)
111
+ throw new Error(`Directory removal requires --recursive: ${target}`);
112
+ const device = stat.dev;
113
+ devices.add(device);
114
+ const pending = [target];
115
+ while (pending.length) {
116
+ const path = pending.pop()!;
117
+ const info = lstatSync(path);
118
+ if (basename(path) === ARTIFACT_RECORD && insideArtifactWorkspace(path, null))
119
+ throw new Error(`An artifact's record is managed by the artifact commands: ${path}`);
120
+ if (protectedNames.has(basename(path).toLowerCase())) {
121
+ if (!allowed.has(path)) throw new Error(protectedMessage(path));
122
+ removedProtected.add(path);
123
+ }
124
+ if (info.isSymbolicLink()) {
125
+ // A link inside the tree is removed as a link; its target is never
126
+ // read, followed, or counted. (The target itself and its ancestors
127
+ // were already refused if they were links, in checkedPath.)
128
+ if (path === target) throw new Error(`Path contains a symlink: ${path}`);
129
+ if (snapshots.size >= MAX_ENTRIES)
130
+ throw new Error(
131
+ `Removal exceeds the ${MAX_ENTRIES}-entry limit; use the owning cleanup command`,
132
+ );
133
+ snapshots.set(path, fingerprint(info));
134
+ links.push({ path, target: readlinkSync(path) });
135
+ continue;
136
+ }
137
+ if (info.dev !== device || (!info.isDirectory() && !info.isFile()))
138
+ throw new Error(`Mount boundary or special file cannot be removed: ${path}`);
139
+ if (snapshots.size >= MAX_ENTRIES)
140
+ throw new Error(
141
+ `Removal exceeds the ${MAX_ENTRIES}-entry limit; use the owning cleanup command`,
142
+ );
143
+ snapshots.set(path, fingerprint(info));
144
+ if (info.isFile()) bytes += info.size;
145
+ else {
146
+ const names = readdirSync(path);
147
+ if (
148
+ names.includes("HEAD") &&
149
+ names.includes("objects") &&
150
+ names.includes("config") &&
151
+ !insideAllowed(path, allowed)
152
+ )
153
+ throw new Error(
154
+ `Repository metadata cannot be removed: ${path}. To remove it on purpose, name it with --allow-protected ${path}`,
155
+ );
156
+ if (allowed.has(path)) removedProtected.add(path);
157
+ if (isRepositoryMetadata(path)) gitDirs.add(path);
158
+ for (const name of names) pending.push(resolve(path, name));
159
+ }
160
+ }
161
+ assertUntracked(target);
162
+ }
163
+ if (devices.size > 1) throw new Error("Targets must be on one filesystem");
164
+ for (const path of allowed)
165
+ if (!removedProtected.has(path))
166
+ throw new Error(`--allow-protected names a path no target removes: ${path}`);
167
+ for (const dir of gitDirs) assertNoUnpushedHistory(dir);
168
+ checkClaims(targets);
169
+ const report: RemovalReport = {
170
+ schema: "harnery.removal/v1",
171
+ applied: false,
172
+ root,
173
+ targets,
174
+ entries: snapshots.size,
175
+ bytes,
176
+ protected: [...removedProtected].sort(),
177
+ links,
178
+ };
179
+ if (!options.yes || options.dryRun) return report;
180
+
181
+ // Recheck the entire batch before its first mutation. Filesystem changes after
182
+ // these checks remain possible; this is a guard, not a transactional filesystem.
183
+ if (
184
+ checkedPath(options.root, new Set(), true) !== root ||
185
+ fingerprint(lstatSync(root)) !== rootFingerprint
186
+ )
187
+ throw new Error("Allowed root changed during inspection");
188
+ for (const target of targets) {
189
+ checkedPath(target, allowed);
190
+ assertUntracked(target);
191
+ }
192
+ for (const dir of gitDirs) assertNoUnpushedHistory(dir);
193
+ checkClaims(targets);
194
+ for (const [path, previous] of snapshots) {
195
+ if (fingerprint(lstatSync(path)) !== previous)
196
+ throw new Error(`Target changed during inspection: ${path}`);
197
+ }
198
+ for (const target of targets)
199
+ rmSync(target, { recursive: Boolean(options.recursive), force: false });
200
+ return { ...report, applied: true };
201
+ }
202
+
203
+ /** The metadata file the artifact commands keep in each artifact workspace. */
204
+ const ARTIFACT_RECORD = ".harnery-artifact.json";
205
+
206
+ /**
207
+ * True when `path` lies strictly inside one artifact workspace,
208
+ * <dir>/.harnery/artifacts/<id>/..., under the `.harnery` component `state`
209
+ * (any `.harnery` when null). Artifact workspaces hold local outputs, so their
210
+ * contents may be removed; the workspace itself, its record file, and the rest
211
+ * of Harnery state stay protected and follow the artifact commands. `orSelf`
212
+ * accepts the workspace directory itself (used for --root, which is never removed).
213
+ */
214
+ function insideArtifactWorkspace(path: string, state: string | null, orSelf = false): boolean {
215
+ const parts = path.split(sep);
216
+ for (let i = 0; i < parts.length; i++) {
217
+ if (parts[i]!.toLowerCase() !== ".harnery") continue;
218
+ if (state !== null && parts.slice(0, i + 1).join(sep) !== state) continue;
219
+ // .harnery / artifacts / <id> / <something>
220
+ return (
221
+ parts[i + 1] === "artifacts" && Boolean(parts[i + 2]) && parts.length >= i + (orSelf ? 3 : 4)
222
+ );
223
+ }
224
+ return false;
225
+ }
226
+
227
+ function protectedMessage(path: string): string {
228
+ return `Protected state cannot be removed: ${path}. To remove it on purpose, name it with --allow-protected ${path}`;
229
+ }
230
+
231
+ function insideAllowed(path: string, allowed: ReadonlySet<string>): boolean {
232
+ for (const entry of allowed) if (path === entry || strictlyInside(entry, path)) return true;
233
+ return false;
234
+ }
235
+
236
+ /**
237
+ * Resolves the caller's --allow-protected paths. Each must be one exact
238
+ * protected path strictly inside the root, reached without symlinks, and
239
+ * never the Git metadata or Harnery state of a live workspace root.
240
+ */
241
+ function allowedProtected(paths: string[], root: string, liveRoots: string[]): Set<string> {
242
+ const allowed = new Set<string>();
243
+ const live = liveRoots.map((dir) => resolve(dir));
244
+ for (const input of paths) {
245
+ if (!input?.trim() || /[\0\r\n*?[\]$]/.test(input))
246
+ throw new Error("Use a nonempty explicit --allow-protected path without wildcards");
247
+ const path = resolve(input);
248
+ let cursor = dirname(path);
249
+ while (true) {
250
+ if (lstatSync(cursor).isSymbolicLink())
251
+ throw new Error(`--allow-protected path contains a symlink: ${cursor}`);
252
+ const parent = dirname(cursor);
253
+ if (parent === cursor) break;
254
+ cursor = parent;
255
+ }
256
+ const info = lstatSync(path);
257
+ if (info.isSymbolicLink()) throw new Error(`--allow-protected path is a symlink: ${path}`);
258
+ if (!strictlyInside(root, path))
259
+ throw new Error(`--allow-protected path must be strictly inside --root: ${path}`);
260
+ const named = protectedNames.has(basename(path).toLowerCase());
261
+ if (!named && !(info.isDirectory() && isRepositoryMetadata(path)))
262
+ throw new Error(`--allow-protected must name a protected path itself: ${path}`);
263
+ for (const dir of live) {
264
+ const own = [".git", ".harnery"].map((name) => resolve(dir, name));
265
+ if (
266
+ path === dir ||
267
+ strictlyInside(path, dir) ||
268
+ own.some((state) => path === state || strictlyInside(state, path))
269
+ )
270
+ throw new Error(`The live workspace's own state cannot be allowed: ${path}`);
271
+ }
272
+ allowed.add(realpathSync(path));
273
+ }
274
+ return allowed;
275
+ }
276
+
277
+ function isRepositoryMetadata(dir: string): boolean {
278
+ const names = readdirSync(dir);
279
+ return names.includes("HEAD") && names.includes("objects") && names.includes("config");
280
+ }
281
+
282
+ /**
283
+ * Removing a repository's metadata loses any commit that exists nowhere
284
+ * else. An allowed Git directory must have no branch or tag commit missing
285
+ * from its remotes; anything that cannot be checked is refused.
286
+ */
287
+ function assertNoUnpushedHistory(gitDir: string): void {
288
+ const result = spawnSync(
289
+ "git",
290
+ [
291
+ "--git-dir",
292
+ gitDir,
293
+ "rev-list",
294
+ "--max-count=1",
295
+ "--branches",
296
+ "--tags",
297
+ "--not",
298
+ "--remotes",
299
+ ],
300
+ {
301
+ encoding: "utf8",
302
+ timeout: 10_000,
303
+ env: { ...process.env, LC_ALL: "C", GIT_DIR: undefined, GIT_WORK_TREE: undefined },
304
+ },
305
+ );
306
+ if (result.error || result.status !== 0)
307
+ throw new Error(`Cannot confirm ${gitDir} holds no unpushed history`);
308
+ if (result.stdout.trim()) throw new Error(`Repository has commits not on any remote: ${gitDir}`);
309
+ }
310
+
311
+ function strictlyInside(parent: string, child: string): boolean {
312
+ const rel = relative(parent, child);
313
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
314
+ }
315
+
316
+ function checkedPath(
317
+ input: string,
318
+ allowed: ReadonlySet<string> = new Set(),
319
+ isRoot = false,
320
+ ): string {
321
+ if (!input?.trim() || /[\0\r\n*?[\]$]/.test(input))
322
+ throw new Error("Use a nonempty explicit path without wildcards or unresolved variables");
323
+ const path = resolve(input);
324
+ let cursor = path;
325
+ while (true) {
326
+ if (
327
+ protectedNames.has(basename(cursor).toLowerCase()) &&
328
+ !allowed.has(cursor) &&
329
+ !insideArtifactWorkspace(path, cursor, isRoot)
330
+ )
331
+ throw new Error(
332
+ cursor === path ? protectedMessage(path) : `Protected state contains this path: ${cursor}`,
333
+ );
334
+ const info = lstatSync(cursor);
335
+ if (info.isSymbolicLink()) throw new Error(`Path contains a symlink: ${cursor}`);
336
+ const parent = dirname(cursor);
337
+ if (parent === cursor) break;
338
+ cursor = parent;
339
+ }
340
+ return realpathSync(path);
341
+ }
342
+
343
+ function fingerprint(stat: Stats): string {
344
+ return [stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
345
+ }
346
+
347
+ function assertUntracked(target: string): void {
348
+ const git = (args: string[]) =>
349
+ spawnSync("git", ["-C", dirname(target), ...args], {
350
+ encoding: "utf8",
351
+ timeout: 10_000,
352
+ maxBuffer: 4 * 1024 * 1024,
353
+ env: {
354
+ ...process.env,
355
+ LC_ALL: "C",
356
+ GIT_LITERAL_PATHSPECS: "1",
357
+ GIT_DIR: undefined,
358
+ GIT_WORK_TREE: undefined,
359
+ GIT_INDEX_FILE: undefined,
360
+ },
361
+ });
362
+ const detected = git(["rev-parse", "--show-toplevel"]);
363
+ if (detected.error) throw new Error(`Cannot check Git ownership: ${detected.error.message}`);
364
+ if (detected.status !== 0) {
365
+ if (detected.status === 128 && detected.stderr.startsWith("fatal: not a git repository"))
366
+ return;
367
+ throw new Error(`Cannot check Git ownership: ${detected.stderr.trim()}`);
368
+ }
369
+ const repo = detected.stdout.trim();
370
+ const tracked = git(["ls-files", "--cached", "-z", "--full-name", "--", target]);
371
+ if (tracked.error || tracked.status !== 0) throw new Error(`Cannot inspect Git index in ${repo}`);
372
+ if (tracked.stdout.length)
373
+ throw new Error(
374
+ `Tracked files are protected; use git rm for intentional source removal: ${target}`,
375
+ );
376
+ }
@@ -89,8 +89,7 @@ export function renderInstructionsBlock(
89
89
  return `## harnery coordination
90
90
 
91
91
  This project runs [harnery](https://harnery.com) for multi-agent coordination.
92
- You share this checkout with other agents; the surfaces below keep you oriented
93
- and out of each other's way, and let you dispatch a team of your own when a job
92
+ You share this checkout with other agents; the surfaces below keep you oriented and out of each other's way, and let you dispatch a team of your own when a job
94
93
  is bigger than one session. Run \`${b} <command> --help\` for any command's full
95
94
  surface. ${deeper}
96
95
 
@@ -103,8 +102,7 @@ widely-shared files.
103
102
  **Task lifecycle.** Beside the activity peers already see, declare whether your
104
103
  objective is still open: \`${b} agents lifecycle blocked --reason "<why>"\` when
105
104
  it cannot proceed, \`${b} agents lifecycle done\` when it is complete, and
106
- \`${b} agents lifecycle active\` to reopen. \`done\` requires a current task and
107
- a passing Git finalization check (dirty or unpushed work refuses, and nothing is
105
+ \`${b} agents lifecycle active\` to reopen. \`done\` requires a current task and a passing Git finalization check (dirty or unpushed work refuses, and nothing is
108
106
  written). Ordinary \`set-task\` calls never change lifecycle, and a transition
109
107
  that re-mints the session title tells you the new name to copy. ${endPointer}
110
108
 
@@ -129,8 +127,7 @@ It reclaims an abandoned namesake (no live process) and refuses only when anothe
129
127
  live process still holds the name; never hand-edit Harnery's history, heartbeat,
130
128
  or derived identity cache.
131
129
 
132
- **Declare intent on shell commands.** Every command you run is captured to the
133
- coordination ledger (\`.harnery/ledgers/v3/\`). Lead a shell command with a
130
+ **Declare intent on shell commands.** Every command you run is captured to the coordination ledger (\`.harnery/ledgers/v3/\`). Lead a shell command with a
134
131
  \`# intent: <why>\` comment (or set the tool's description) so the recorded event
135
132
  carries a reason instead of \`(no intent)\`; the [tool-intent
136
133
  guide](https://harnery.com/guides/tool-intent/) owns the details.
@@ -154,6 +151,10 @@ After review, use \`${b} artifacts discard <id> --reason "<why no longer needed>
154
151
  Do not create a repo-root temp directory; \`${b} artifacts clean\` previews
155
152
  expired cleanup and requires \`--yes\` to delete anything.
156
153
 
154
+ **Removing local outputs.** Use \`${b} rm --root <directory> <paths...>\` instead of shell \`rm\`, which skips resolved-path, Git ownership, and peer-claim checks. Preview
155
+ is the default; \`--yes\` deletes permanently and \`--recursive\` permits directories.
156
+ Use \`git rm\` for tracked source and the artifact commands for managed evidence.
157
+
157
158
  **Local file links.** When the operator should open a local repo file, mint the
158
159
  URL with \`${b} files url <repo-relative-path>\` instead of guessing it. HTML opens
159
160
  as a real page with working scripts and relative assets; other files open in the
@@ -164,8 +165,7 @@ can't resolve from the repo, file it instead. \`${b} decision file "<question>"\
164
165
  records it and lets you proceed on a stated default; \`${b} decision search "<terms>"\`
165
166
  surfaces prior decisions, so check for precedent before re-deciding. ${decidePointer}
166
167
 
167
- **Councils.** For a hard or contested decision, convene a council of agents.
168
- \`${b} council create "<objective>"\` runs structured rounds toward a decision. ${councilPointer}`;
168
+ **Councils.** For a hard or contested decision, convene a council of agents. \`${b} council create "<objective>"\` runs structured rounds toward a decision. ${councilPointer}`;
169
169
  }
170
170
 
171
171
  // ── Skills ──────────────────────────────────────────────────────────────────
@@ -1,5 +1,5 @@
1
1
  export interface TunnelErrorPageOptions {
2
- kind: "access-denied" | "upstream-unavailable";
2
+ kind: "access-denied" | "path-denied" | "upstream-unavailable";
3
3
  incidentId: string;
4
4
  timestamp: string;
5
5
  tunnelName: string;
@@ -40,14 +40,30 @@ function diagnosticText(options: TunnelErrorPageOptions): string {
40
40
  }
41
41
 
42
42
  export function renderTunnelErrorPage(options: TunnelErrorPageOptions): string {
43
- const denied = options.kind === "access-denied";
44
- const title = denied ? "This device is not allowed yet" : "The preview is temporarily offline";
45
- const summary = denied
46
- ? "The tunnel is running, but this device's public IP is not on its access list."
47
- : "The public tunnel and access check are working, but the local preview server is not responding.";
48
- const nextStep = denied
49
- ? "Copy the diagnostic below and send it to the person running the tunnel. It includes the public IP that needs to be allowed."
50
- : "Copy the diagnostic below and send it to the person running the tunnel. The incident ID can be matched to the server log.";
43
+ const copy = {
44
+ "access-denied": {
45
+ title: "This device is not allowed yet",
46
+ summary: "The tunnel is running, but this device's public IP is not on its access list.",
47
+ nextStep:
48
+ "Copy the diagnostic below and send it to the person running the tunnel. It includes the public IP that needs to be allowed.",
49
+ },
50
+ "path-denied": {
51
+ title: "This page is not shared",
52
+ summary:
53
+ "The tunnel is running, but it shares only part of the site, and this address is outside it.",
54
+ nextStep:
55
+ "If you expected to see this page, copy the diagnostic below and send it to the person running the tunnel.",
56
+ },
57
+ "upstream-unavailable": {
58
+ title: "The preview is temporarily offline",
59
+ summary:
60
+ "The public tunnel and access check are working, but the local preview server is not responding.",
61
+ nextStep:
62
+ "Copy the diagnostic below and send it to the person running the tunnel. The incident ID can be matched to the server log.",
63
+ },
64
+ }[options.kind];
65
+ const { title, summary, nextStep } = copy;
66
+ const denied = options.kind !== "upstream-unavailable";
51
67
  const diagnostic = diagnosticText(options);
52
68
  const safeDiagnosticForScript = JSON.stringify(diagnostic).replaceAll("<", "\\u003c");
53
69
 
@@ -4,7 +4,9 @@
4
4
  // stripped (Bun's fetch auto-decompresses the body but retains the encoding
5
5
  // header, which breaks browser decoding downstream). Cloudflare provider mode
6
6
  // checks CF-Connecting-IP against an allowlist; trusted local proxy mode lets
7
- // the local exposer own access.
7
+ // the local exposer own access. In every mode the gate then refuses any path
8
+ // outside the tunnel's path scope (see path-scope.ts); an empty scope refuses
9
+ // everything.
8
10
  //
9
11
  // Runs detached, outside the CLI command framework; no command context is
10
12
  // available; stdout/stderr is captured into .cache/tunnel/gate.log by the
@@ -12,6 +14,7 @@
12
14
 
13
15
  import { renderTunnelErrorPage } from "./error-page";
14
16
  import { applyUpstreamHeaders } from "./forward-headers";
17
+ import { ALLOW_PATHS_ENV, isPathAllowed, parseAllowPathsEnv } from "./path-scope.ts";
15
18
 
16
19
  // `--port`/`--name` are also passed on argv (not just env) so the gate's port
17
20
  // and instance name show up in its process command line. That's what lets
@@ -34,6 +37,7 @@ const TARGET = process.env.HARNERY_TUNNEL_TARGET ?? "127.0.0.1:8001";
34
37
  const VHOST = process.env.HARNERY_TUNNEL_VHOST ?? "localhost";
35
38
  const PORT = Number(process.env.HARNERY_TUNNEL_PORT ?? argvFlag("--port") ?? "9001");
36
39
  const ACCESS = process.env.HARNERY_TUNNEL_ACCESS ?? "cloudflare-allowlist";
40
+ const ALLOW_PATHS = parseAllowPathsEnv(process.env[ALLOW_PATHS_ENV]);
37
41
  const NAME = argvFlag("--name") ?? "default";
38
42
 
39
43
  const UPSTREAM_HTTP = `http://${TARGET}`;
@@ -96,6 +100,22 @@ const server = Bun.serve<WsData, never>({
96
100
  }
97
101
  }
98
102
 
103
+ if (!isPathAllowed(url.pathname, ALLOW_PATHS)) {
104
+ const details = requestDetails(req, url);
105
+ console.log(
106
+ // lint-ok-emission: detached worker, see file note above
107
+ `path-deny: incident=${details.incidentId} ip=${details.clientIp || "(missing-cf-connecting-ip)"} ray=${details.cloudflareRay || "(missing)"} ${req.method} ${details.path}`,
108
+ );
109
+ return new Response(renderTunnelErrorPage({ ...details, kind: "path-denied" }), {
110
+ status: 403,
111
+ headers: {
112
+ "cache-control": "no-store",
113
+ "content-type": "text/html; charset=utf-8",
114
+ "x-harnery-tunnel-incident": details.incidentId,
115
+ },
116
+ });
117
+ }
118
+
99
119
  if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
100
120
  if (
101
121
  server.upgrade(req, {
@@ -192,4 +212,5 @@ const server = Bun.serve<WsData, never>({
192
212
  // captured into .cache/tunnel/gate.log by the spawning command.
193
213
  console.log(`harn-tunnel-gate :${server.port} -> ${UPSTREAM_HTTP} (Host: ${VHOST})`); // lint-ok-emission: detached worker, see file note above
194
214
  console.log(`access: ${ACCESS}`); // lint-ok-emission: detached worker, see file note above
215
+ console.log(`paths: ${ALLOW_PATHS.join(", ") || "(empty, every path refused)"}`); // lint-ok-emission: detached worker, see file note above
195
216
  console.log(`allow: ${[...ALLOW].join(", ") || "(empty, not used outside allowlist mode)"}`); // lint-ok-emission: detached worker, see file note above
@@ -0,0 +1,73 @@
1
+ // Path scope for the tunnel gate: the URL path prefixes a tunnel publishes.
2
+ //
3
+ // A tunnel forwards to a whole local app, but the person starting it usually
4
+ // means to share one surface of that app. The gate therefore refuses every
5
+ // request whose path is outside the scope the operator named at `tunnel up`,
6
+ // and an empty scope refuses everything. `/` is the explicit way to publish
7
+ // the whole upstream.
8
+
9
+ /** Env var that carries the scope from `tunnel up` to the detached gate. */
10
+ export const ALLOW_PATHS_ENV = "HARNERY_TUNNEL_ALLOW_PATHS";
11
+
12
+ /**
13
+ * Normalize one `--allow-path` value to a canonical prefix: a leading slash,
14
+ * no trailing slash (except `/` itself), no query or fragment, and no dot,
15
+ * empty, or percent-encoded segment. Throws on anything the gate could not
16
+ * match unambiguously, so a typo fails at `tunnel up` instead of publishing
17
+ * more or less than intended.
18
+ */
19
+ export function normalizeAllowPath(raw: string): string {
20
+ const value = raw.trim();
21
+ if (!value.startsWith("/")) {
22
+ throw new Error(`allow-path must start with "/": ${JSON.stringify(raw)}`);
23
+ }
24
+ if (/[?#%\\]/.test(value)) {
25
+ throw new Error(
26
+ `allow-path must be a plain path prefix without ?, #, %, or \\: ${JSON.stringify(raw)}`,
27
+ );
28
+ }
29
+ if (value === "/") return "/";
30
+ const trimmed = value.replace(/\/+$/, "");
31
+ const segments = trimmed.slice(1).split("/");
32
+ if (segments.some((s) => s === "" || s === "." || s === "..")) {
33
+ throw new Error(
34
+ `allow-path must not contain empty, "." or ".." segments: ${JSON.stringify(raw)}`,
35
+ );
36
+ }
37
+ return trimmed;
38
+ }
39
+
40
+ /** Normalize and de-duplicate a list of `--allow-path` values. */
41
+ export function normalizeAllowPaths(raw: readonly string[]): string[] {
42
+ return [...new Set(raw.map(normalizeAllowPath))];
43
+ }
44
+
45
+ /** Parse the gate's env value (comma-separated, already normalized by `up`). */
46
+ export function parseAllowPathsEnv(value: string | undefined): string[] {
47
+ return normalizeAllowPaths(
48
+ (value ?? "")
49
+ .split(",")
50
+ .map((s) => s.trim())
51
+ .filter(Boolean),
52
+ );
53
+ }
54
+
55
+ // Encoded slash, backslash, dot, or percent. A request path carrying one of
56
+ // these can be decoded differently by the gate and the upstream router (for
57
+ // example `/share%2F..%2Fprivate`), so the gate refuses it outright rather than
58
+ // guess which reading the upstream will use.
59
+ const AMBIGUOUS_PATH = /%(2f|5c|2e|25)|\\/i;
60
+
61
+ /**
62
+ * True when `pathname` (a WHATWG-parsed URL pathname, so `.` and `..` segments
63
+ * are already resolved) falls inside one of the allowed prefixes. A prefix
64
+ * matches itself and anything below it on a segment boundary: `/share` allows
65
+ * `/share` and `/share/x`, never `/shared`.
66
+ */
67
+ export function isPathAllowed(pathname: string, allowPaths: readonly string[]): boolean {
68
+ if (allowPaths.length === 0) return false;
69
+ if (!pathname.startsWith("/") || AMBIGUOUS_PATH.test(pathname)) return false;
70
+ return allowPaths.some(
71
+ (prefix) => prefix === "/" || pathname === prefix || pathname.startsWith(`${prefix}/`),
72
+ );
73
+ }
@@ -11,6 +11,7 @@ import {
11
11
  writeFileSync,
12
12
  } from "node:fs";
13
13
  import { resolve } from "node:path";
14
+ import { isPathAllowed } from "./path-scope.ts";
14
15
 
15
16
  // Tunnel state lives under <root>/.cache/tunnel/. Root defaults to cwd for the
16
17
  // command surface and can be supplied by callers that already resolved a repo.
@@ -81,14 +82,25 @@ export interface TunnelState {
81
82
  target: string;
82
83
  vhost: string;
83
84
  gate_port: number;
85
+ /** URL path prefixes the gate forwards; every other path is refused. */
86
+ allow_paths: string[];
84
87
  tailscale_mode?: TailscaleMode;
85
88
  tailscale_path?: string;
86
89
  tailscale_https_port?: number;
87
90
  }
88
91
 
89
- /** Normalize a parsed state blob; supply `name` for pre-multi-instance files. */
92
+ /**
93
+ * Normalize a parsed state blob; supply `name` for pre-multi-instance files.
94
+ * A state written before path scopes existed reads as an empty scope, which
95
+ * the gate treats as "refuse every path".
96
+ */
90
97
  function normalizeState(raw: TunnelState, fallbackName: string): TunnelState {
91
- return { ...raw, name: raw.name ?? fallbackName, provider: raw.provider ?? "cloudflare" };
98
+ return {
99
+ ...raw,
100
+ name: raw.name ?? fallbackName,
101
+ provider: raw.provider ?? "cloudflare",
102
+ allow_paths: Array.isArray(raw.allow_paths) ? raw.allow_paths : [],
103
+ };
92
104
  }
93
105
 
94
106
  export function readConfig(): TunnelConfig {
@@ -169,7 +181,7 @@ export function isTunnelStateLive(
169
181
  return typeof providerPid === "number" && processAlive(providerPid);
170
182
  }
171
183
 
172
- function tunnelTargetPort(state: TunnelState): number | null {
184
+ export function tunnelTargetPort(state: TunnelState): number | null {
173
185
  const value = /^[a-z][a-z\d+.-]*:\/\//i.test(state.target)
174
186
  ? state.target
175
187
  : `http://${state.target}`;
@@ -209,6 +221,11 @@ export function findLiveTunnelForOrigin(
209
221
  );
210
222
  }
211
223
 
224
+ /** True when the tunnel's path scope forwards every one of `paths`. */
225
+ export function tunnelServesPaths(state: TunnelState, paths: readonly string[]): boolean {
226
+ return paths.every((path) => isPathAllowed(path, state.allow_paths));
227
+ }
228
+
212
229
  /**
213
230
  * Ensure cloudflared is on PATH or installed at ~/.local/bin/cloudflared.
214
231
  * Auto-downloads on Linux; throws on other platforms with brew hint.