@agent-watch-ai/edge 0.7.0 → 0.7.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 (82) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +4 -1
  3. package/dist/billing/session-billing.d.ts +5 -2
  4. package/dist/billing/session-billing.js +27 -6
  5. package/dist/capture/captured-step.js +24 -0
  6. package/dist/capture/constants/capture.constants.d.ts +15 -0
  7. package/dist/capture/constants/capture.constants.js +15 -0
  8. package/dist/capture/launched-runs.d.ts +27 -0
  9. package/dist/capture/launched-runs.js +15 -9
  10. package/dist/capture/python/sitecustomize.py +11 -2
  11. package/dist/capture/venv-loader.d.ts +68 -0
  12. package/dist/capture/venv-loader.js +189 -0
  13. package/dist/cli/constants/cli.constants.d.ts +21 -0
  14. package/dist/cli/constants/cli.constants.js +21 -0
  15. package/dist/cli/doctor-run-capture.d.ts +8 -0
  16. package/dist/cli/doctor-run-capture.js +14 -0
  17. package/dist/cli/doctor.js +6 -2
  18. package/dist/cli/hook-check.d.ts +7 -2
  19. package/dist/cli/hook-check.js +30 -15
  20. package/dist/cli/hook.js +44 -3
  21. package/dist/cli/npm-global.d.ts +24 -0
  22. package/dist/cli/npm-global.js +77 -0
  23. package/dist/cli/npx-install.js +22 -6
  24. package/dist/cli/replay.js +42 -7
  25. package/dist/cli/setup.js +47 -6
  26. package/dist/cli/uninstall.js +34 -1
  27. package/dist/cli/update.js +3 -2
  28. package/dist/config/config-store.d.ts +15 -4
  29. package/dist/config/config-store.js +31 -7
  30. package/dist/config/constants/config.constants.d.ts +8 -1
  31. package/dist/config/constants/config.constants.js +8 -1
  32. package/dist/config/schemas/config.schema.d.ts +2 -2
  33. package/dist/config/schemas/config.schema.js +10 -2
  34. package/dist/credentials/cloud-claim.d.ts +2 -0
  35. package/dist/credentials/cloud-claim.js +21 -2
  36. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  37. package/dist/credentials/constants/credentials.constants.js +8 -0
  38. package/dist/credentials/credential-status.js +1 -1
  39. package/dist/credentials/credentials.d.ts +3 -3
  40. package/dist/credentials/credentials.js +26 -12
  41. package/dist/credentials/identity.d.ts +2 -2
  42. package/dist/credentials/identity.js +2 -2
  43. package/dist/credentials/install-key.d.ts +31 -0
  44. package/dist/credentials/install-key.js +58 -0
  45. package/dist/credentials/migration.d.ts +9 -7
  46. package/dist/credentials/migration.js +58 -18
  47. package/dist/credentials/secret-store.d.ts +12 -0
  48. package/dist/credentials/secret-store.js +18 -1
  49. package/dist/enforcement/enforcement.js +1 -1
  50. package/dist/events/enrich.d.ts +14 -0
  51. package/dist/events/enrich.js +1 -1
  52. package/dist/git/constants/git.constants.d.ts +2 -0
  53. package/dist/git/constants/git.constants.js +9 -0
  54. package/dist/git/repo-snapshot.js +8 -2
  55. package/dist/git/types/snapshot.types.d.ts +4 -0
  56. package/dist/pipeline/hook-pipeline.js +2 -1
  57. package/dist/providers/claude/claude.provider.js +9 -5
  58. package/dist/providers/types/provider.types.d.ts +5 -5
  59. package/dist/replay/checkout-resolver.d.ts +41 -14
  60. package/dist/replay/checkout-resolver.js +134 -30
  61. package/dist/replay/replay-runner.d.ts +3 -1
  62. package/dist/replay/replay-runner.js +74 -22
  63. package/dist/replay/replay-scan.d.ts +2 -1
  64. package/dist/replay/replay-scan.js +14 -2
  65. package/dist/replay/throttle.d.ts +2 -1
  66. package/dist/replay/throttle.js +4 -1
  67. package/dist/replay/transcript-turns.js +29 -3
  68. package/dist/replay/turn-event.d.ts +4 -2
  69. package/dist/replay/turn-event.js +22 -11
  70. package/dist/replay/types/replay.types.d.ts +39 -3
  71. package/dist/replay/worktree-map.d.ts +42 -0
  72. package/dist/replay/worktree-map.js +134 -0
  73. package/dist/snapshot/snapshot-pipeline.js +15 -4
  74. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  75. package/dist/turns/constants/turns.constants.d.ts +16 -0
  76. package/dist/turns/constants/turns.constants.js +16 -0
  77. package/dist/turns/turn-state.d.ts +33 -0
  78. package/dist/turns/turn-state.js +80 -1
  79. package/dist/turns/turn-tracker.js +2 -2
  80. package/docs/DATA_HANDLING.md +8 -6
  81. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -2
  82. package/package.json +1 -1
@@ -0,0 +1,58 @@
1
+ import { detachInstallKey } from '../config/config-store.js';
2
+ import { debugLog } from '../core/logger.js';
3
+ import { INSTALL_KEY_ACCOUNT_SUFFIX } from './constants/credentials.constants.js';
4
+ import { secretStoreFor, storeVerified } from './secret-store.js';
5
+ /**
6
+ * The account (or file name) a device's install key is kept under, beside its secret.
7
+ *
8
+ * @param device - The device.
9
+ * @returns The account name.
10
+ */
11
+ function installKeyAccount(device) {
12
+ return device.id + INSTALL_KEY_ACCOUNT_SUFFIX;
13
+ }
14
+ /**
15
+ * Move an install key from the config into its device's secret store.
16
+ *
17
+ * The key is needed again only when the device secret expires, so it lives
18
+ * where the secret does, not in plain text in `config.json`. The config entry
19
+ * keeps it until the store has proven it holds the key, so a failed write never
20
+ * loses it. Never throws.
21
+ *
22
+ * @param ctx - Paths, environment, timeout and keychain runner.
23
+ * @param installKey - The key that was exchanged.
24
+ * @param device - The device it was exchanged for.
25
+ * @param waitMs - How long to wait for the config lock.
26
+ * @returns True when the store holds the key and the config was updated.
27
+ */
28
+ export async function retireInstallKey(ctx, installKey, device, waitMs) {
29
+ try {
30
+ if (!(await storeVerified(ctx, device.store, installKeyAccount(device), installKey)))
31
+ return false;
32
+ return (await detachInstallKey(ctx.paths, installKey, device.id, waitMs)) !== 'busy';
33
+ }
34
+ catch (error) {
35
+ debugLog('credentials: moving the install key out of the config failed; it stays there:', error);
36
+ return false;
37
+ }
38
+ }
39
+ /**
40
+ * The install key a device was exchanged for, from its secret store.
41
+ *
42
+ * @param ctx - Paths, environment, timeout and keychain runner.
43
+ * @param device - The device.
44
+ * @returns The key, or undefined (a sign-in device has none).
45
+ */
46
+ export async function storedInstallKey(ctx, device) {
47
+ // Outside a hook's deadline: a read cut short would look like "no key" and back the re-enrollment off for an hour.
48
+ return secretStoreFor(device.store, { ...ctx, deadline: undefined }).get(installKeyAccount(device)).catch(() => undefined);
49
+ }
50
+ /**
51
+ * Remove the install key kept for a device, if any.
52
+ *
53
+ * @param ctx - Paths, environment, timeout and keychain runner.
54
+ * @param device - The device being forgotten.
55
+ */
56
+ export async function forgetInstallKey(ctx, device) {
57
+ await secretStoreFor(device.store, ctx).remove(installKeyAccount(device));
58
+ }
@@ -8,17 +8,19 @@ import type { CredentialContext, DeviceCredentialRef } from './types/credentials
8
8
  * run — written by an older setup, by `setup --token` or from
9
9
  * `$AGENTWATCH_TOKEN`. Order matters: the secret is stored and the first token
10
10
  * cached before the config names the device, so a crash in between costs one
11
- * more exchange, never the credential. The install key stays in the config
12
- * beside the device, to enroll again when the secret expires. A failure
13
- * keeps the key in use, and the next try waits an hour.
11
+ * more exchange, never the credential. Once the device is named, the install
12
+ * key moves from the config into the device's secret store, to enroll again
13
+ * when the secret expires (`retireInstallKey`); a config written before that
14
+ * loses its key the next time this runs. A failure keeps the key in the config
15
+ * and in use, and the next try waits an hour.
14
16
  *
15
17
  * A device the gateway refused counts as no device: an expired secret is
16
18
  * enrolled again by any run, a revoked or unknown one only when setup asks
17
19
  * (`ignoreBackoff`), so a hook never undoes an admin's revocation.
18
20
  *
19
- * Never for a scope `uninstall` marked, until setup runs for it again: the key
20
- * stays in the config for a reinstall, not for re-enrolling a device just
21
- * revoked. Asked before the lock, under it, and once more before the device is
21
+ * Never for a scope `uninstall` marked, until setup runs for it again: a key
22
+ * still in the config is there for a reinstall, not for re-enrolling a device
23
+ * just revoked. Asked before the lock, under it, and once more before the device is
22
24
  * attached; a device enrolled while uninstall marked the scope is revoked and
23
25
  * forgotten here, since uninstall can no longer see it.
24
26
  *
@@ -26,7 +28,7 @@ import type { CredentialContext, DeviceCredentialRef } from './types/credentials
26
28
  * fit a hook's budget. Setup makes the exchange there.
27
29
  *
28
30
  * @param ctx - Paths, clock, timeout, fetch and keychain runner.
29
- * @param config - Effective config whose `token` is the install key.
31
+ * @param config - Effective config whose `token` is the install key, or whose device has its key in the store.
30
32
  * @param options - `ignoreBackoff` for setup, where someone asked for it now.
31
33
  * @param options.ignoreBackoff - Try even within an hour of a failed attempt.
32
34
  * @returns The device credential now standing for the key, or undefined.
@@ -7,11 +7,12 @@ import { acquireLock } from '../storage/lock.js';
7
7
  import { isUninstalled } from '../storage/uninstalled.js';
8
8
  import { BackendAuthBlock } from '../transport/auth-block.js';
9
9
  import { identityPaths } from '../transport/queue-partition.js';
10
- import { ENROLL_LOCK_PREFIX, ENROLL_RETRY_MS, REFUSAL_SECRET_EXPIRED } from './constants/credentials.constants.js';
10
+ import { DEVICE_IDENTITY_PREFIX, ENROLL_LOCK_PREFIX, ENROLL_RETRY_MS, REFUSAL_SECRET_EXPIRED } from './constants/credentials.constants.js';
11
11
  import { enrollDevice, revokeDevice } from './device-api.js';
12
12
  import { readDeviceState, writeAccessToken, writeDeviceState } from './device-state.js';
13
13
  import { withinBudget } from './budget.js';
14
- import { credentialId, deviceRefs } from './identity.js';
14
+ import { deviceRefs, identityFingerprint, identityOf } from './identity.js';
15
+ import { forgetInstallKey, retireInstallKey, storedInstallKey } from './install-key.js';
15
16
  import { saveSecret, secretStoreFor } from './secret-store.js';
16
17
  /**
17
18
  * Exchange the install key this config holds for a device credential, once.
@@ -21,17 +22,19 @@ import { saveSecret, secretStoreFor } from './secret-store.js';
21
22
  * run — written by an older setup, by `setup --token` or from
22
23
  * `$AGENTWATCH_TOKEN`. Order matters: the secret is stored and the first token
23
24
  * cached before the config names the device, so a crash in between costs one
24
- * more exchange, never the credential. The install key stays in the config
25
- * beside the device, to enroll again when the secret expires. A failure
26
- * keeps the key in use, and the next try waits an hour.
25
+ * more exchange, never the credential. Once the device is named, the install
26
+ * key moves from the config into the device's secret store, to enroll again
27
+ * when the secret expires (`retireInstallKey`); a config written before that
28
+ * loses its key the next time this runs. A failure keeps the key in the config
29
+ * and in use, and the next try waits an hour.
27
30
  *
28
31
  * A device the gateway refused counts as no device: an expired secret is
29
32
  * enrolled again by any run, a revoked or unknown one only when setup asks
30
33
  * (`ignoreBackoff`), so a hook never undoes an admin's revocation.
31
34
  *
32
- * Never for a scope `uninstall` marked, until setup runs for it again: the key
33
- * stays in the config for a reinstall, not for re-enrolling a device just
34
- * revoked. Asked before the lock, under it, and once more before the device is
35
+ * Never for a scope `uninstall` marked, until setup runs for it again: a key
36
+ * still in the config is there for a reinstall, not for re-enrolling a device
37
+ * just revoked. Asked before the lock, under it, and once more before the device is
35
38
  * attached; a device enrolled while uninstall marked the scope is revoked and
36
39
  * forgotten here, since uninstall can no longer see it.
37
40
  *
@@ -39,14 +42,15 @@ import { saveSecret, secretStoreFor } from './secret-store.js';
39
42
  * fit a hook's budget. Setup makes the exchange there.
40
43
  *
41
44
  * @param ctx - Paths, clock, timeout, fetch and keychain runner.
42
- * @param config - Effective config whose `token` is the install key.
45
+ * @param config - Effective config whose `token` is the install key, or whose device has its key in the store.
43
46
  * @param options - `ignoreBackoff` for setup, where someone asked for it now.
44
47
  * @param options.ignoreBackoff - Try even within an hour of a failed attempt.
45
48
  * @returns The device credential now standing for the key, or undefined.
46
49
  */
47
50
  export async function migrateInstallKey(ctx, config, options = {}) {
48
- const installKey = config.token;
49
- if (!installKey || !config.endpoint)
51
+ const identity = identityOf(config);
52
+ const id = identity === undefined ? undefined : identityFingerprint(identity);
53
+ if (!id || !config.endpoint)
50
54
  return undefined;
51
55
  if (ctx.hookPath && ctx.env.platform === 'win32')
52
56
  return undefined;
@@ -54,22 +58,36 @@ export async function migrateInstallKey(ctx, config, options = {}) {
54
58
  // enroll: only setup, which lifts the marker first, may.
55
59
  if (await isUninstalled(ctx.paths, ctx.scope))
56
60
  return undefined;
57
- const id = credentialId(installKey);
58
- const files = identityPaths(ctx.paths, installKey);
61
+ const files = identityPaths(ctx.paths, DEVICE_IDENTITY_PREFIX + id);
62
+ const waitMs = ctx.hookPath ? CONFIG_LOCK_HOOK_WAIT_MS : CONFIG_LOCK_WAIT_MS;
59
63
  // Cheap checks first, so a backed-off key costs a hook no lock; both are
60
64
  // asked again under the lock, where the answer can no longer change.
61
65
  const settled = await settledExchange(ctx, id, files.deviceStateFile, options);
62
- if (settled.done)
66
+ // A config written before the key left it (an older edge) still holds it beside its device.
67
+ // Only the entry that names the device beside it, which is what `detachInstallKey` clears.
68
+ const leftKey = settled.done && settled.device !== undefined && config.token !== undefined && config.device?.id === id;
69
+ if (settled.done && !leftKey)
63
70
  return settled.device;
64
71
  const release = await acquireLock(ctx.paths.locksDir, ENROLL_LOCK_PREFIX + id, ctx.env.now).catch(() => undefined);
72
+ // The device stands either way; moving the key waits for the next run.
65
73
  if (!release)
66
- return undefined;
74
+ return leftKey ? settled.device : undefined;
67
75
  try {
68
76
  const recheck = await settledExchange(ctx, id, files.deviceStateFile, options);
69
- if (recheck.done)
70
- return recheck.device;
77
+ // Under the lock, so uninstall (which takes it) cannot remove the key from the store in between.
71
78
  if (await isUninstalled(ctx.paths, ctx.scope))
72
79
  return undefined;
80
+ if (recheck.done) {
81
+ if (recheck.device && config.token && config.device?.id === id)
82
+ await retireInstallKey(ctx, config.token, recheck.device, waitMs);
83
+ return recheck.device;
84
+ }
85
+ const installKey = config.token ?? (config.device ? await storedInstallKey(ctx, config.device) : undefined);
86
+ // A device signed in through the browser has no key: back off, so a hook does not ask the keychain every turn.
87
+ if (!installKey) {
88
+ await writeDeviceState(files.deviceStateFile, { ...recheck.state, enrollAttemptAt: ctx.env.now().toISOString() });
89
+ return undefined;
90
+ }
73
91
  const now = ctx.env.now();
74
92
  const budget = withinBudget(ctx);
75
93
  if (!budget)
@@ -93,17 +111,38 @@ export async function migrateInstallKey(ctx, config, options = {}) {
93
111
  await abandonDevice(ctx, device, result.value.deviceSecret, files.accessTokenFile);
94
112
  return undefined;
95
113
  }
96
- const attached = await attachDevice(ctx.paths, installKey, device, ctx.hookPath ? CONFIG_LOCK_HOOK_WAIT_MS : CONFIG_LOCK_WAIT_MS);
114
+ const attached = await attachDevice(ctx.paths, installKey, device, waitMs);
97
115
  // Unnamed in the config (the lock was busy), the device is invisible to the
98
116
  // next run: keep the backoff, or every hook would enroll yet another one.
99
117
  await writeDeviceState(files.deviceStateFile, (await namesDevice(ctx, attached, device)) ? {} : { enrollAttemptAt: now.toISOString() });
100
118
  await new BackendAuthBlock(files.authBlockFile, ctx.env.now).clear();
119
+ // Uninstall may have overtaken the exchange since the last look: it removes the key, so it must not come back.
120
+ if (await isUninstalled(ctx.paths, ctx.scope))
121
+ return device;
122
+ await keepInstallKey(ctx, installKey, config.token === undefined ? config.device : undefined, device, waitMs);
101
123
  return device;
102
124
  }
103
125
  finally {
104
126
  await release();
105
127
  }
106
128
  }
129
+ /**
130
+ * After an exchange, keep the key in the new device's store only. A key read
131
+ * from the store is written again only when the secret moved to another store
132
+ * (a keychain that works now), and the old copy goes once the new one is proven.
133
+ *
134
+ * @param ctx - Paths, environment, timeout and keychain runner.
135
+ * @param installKey - The key just exchanged.
136
+ * @param previous - The device whose store the key was read from, when it was.
137
+ * @param device - The device it was exchanged for.
138
+ * @param waitMs - How long to wait for the config lock.
139
+ */
140
+ async function keepInstallKey(ctx, installKey, previous, device, waitMs) {
141
+ if (previous?.store === device.store)
142
+ return;
143
+ if ((await retireInstallKey(ctx, installKey, device, waitMs)) && previous)
144
+ await forgetInstallKey(ctx, previous).catch(() => undefined);
145
+ }
107
146
  /**
108
147
  * Undo an exchange uninstall overtook: revoke the device on the platform and
109
148
  * forget it here, best effort. Its secret is in hand, so no keychain read.
@@ -120,6 +159,7 @@ export async function abandonDevice(ctx, device, secret, tokenFile) {
120
159
  if (!revoked)
121
160
  warnLog('a device that was enrolled but not kept (uninstall overtook it, or setup could not save it) could not be revoked; it may still be active on the platform. An admin can revoke this machine in Settings → Install.');
122
161
  await secretStoreFor(device.store, ctx).remove(device.id).catch(() => undefined);
162
+ await forgetInstallKey(ctx, device).catch(() => undefined);
123
163
  await fs.rm(tokenFile, { force: true }).catch(() => undefined);
124
164
  debugLog('device enrollment overtaken by uninstall; revoked and forgotten');
125
165
  }
@@ -19,6 +19,18 @@ export type { SecretStore, StoreDeps } from './types/credentials.types.js';
19
19
  * @returns The store that holds it now.
20
20
  */
21
21
  export declare function saveSecret(deps: StoreDeps, id: string, secret: string): Promise<CredentialStoreKind>;
22
+ /**
23
+ * Write a value to one store and read it back, outside a hook's credential
24
+ * deadline (see `saveSecret`). `security -i` exits 0 whatever happened, so only
25
+ * the read proves the write.
26
+ *
27
+ * @param deps - Environment, paths, timeout and runner.
28
+ * @param kind - The store to write to.
29
+ * @param id - The account name.
30
+ * @param value - What to keep.
31
+ * @returns True when the store gives the value back.
32
+ */
33
+ export declare function storeVerified(deps: StoreDeps, kind: CredentialStoreKind, id: string, value: string): Promise<boolean>;
22
34
  /**
23
35
  * The OS keychain this machine offers, or the private file when it offers none.
24
36
  *
@@ -28,11 +28,28 @@ import { CREDENTIALS_DIR_NAME, DBUS_SESSION_VAR, DPAPI_FILE_SUFFIX, DPAPI_PROTEC
28
28
  export async function saveSecret(deps, id, secret) {
29
29
  const unhurried = { ...deps, deadline: undefined };
30
30
  const preferred = preferredStore(unhurried);
31
- if (preferred.kind !== 'file' && (await preferred.set(id, secret)) && (await preferred.get(id)) === secret)
31
+ if (preferred.kind !== 'file' && (await setVerified(preferred, id, secret)))
32
32
  return preferred.kind;
33
33
  await fileStore(unhurried).set(id, secret);
34
34
  return 'file';
35
35
  }
36
+ /**
37
+ * Write a value to one store and read it back, outside a hook's credential
38
+ * deadline (see `saveSecret`). `security -i` exits 0 whatever happened, so only
39
+ * the read proves the write.
40
+ *
41
+ * @param deps - Environment, paths, timeout and runner.
42
+ * @param kind - The store to write to.
43
+ * @param id - The account name.
44
+ * @param value - What to keep.
45
+ * @returns True when the store gives the value back.
46
+ */
47
+ export async function storeVerified(deps, kind, id, value) {
48
+ return setVerified(secretStoreFor(kind, { ...deps, deadline: undefined }), id, value);
49
+ }
50
+ async function setVerified(store, id, value) {
51
+ return (await store.set(id, value)) && (await store.get(id)) === value;
52
+ }
36
53
  /**
37
54
  * The OS keychain this machine offers, or the private file when it offers none.
38
55
  *
@@ -31,7 +31,7 @@ import { requestDecision } from './decision-client.js';
31
31
  */
32
32
  export async function resolveEnforcement(options) {
33
33
  const url = enforcementUrl(options.config);
34
- // A device's install key stays in the file to enroll again, but this
34
+ // An install key an older edge left beside its device is not sent: this
35
35
  // identity sends as the device: only the caller's cached access token will do.
36
36
  const token = options.bearer ?? (deviceFor(options.config) ? undefined : options.config.token);
37
37
  const developerId = options.developerId;
@@ -14,3 +14,17 @@ export type { EnrichOptions, PathRewriter } from './types/enrich.types.js';
14
14
  * @returns Enriched, sanitized events in the same order.
15
15
  */
16
16
  export declare function enrichEvents(events: readonly AgentWatchEvent[], options: EnrichOptions): Promise<AgentWatchEvent[]>;
17
+ /**
18
+ * Where a file outside every checkout lies, without the home directory's name.
19
+ *
20
+ * A spreadsheet in `~/Documents` is the target of a session with no repository,
21
+ * so it is kept — but as `~/Documents/a.xlsx`: the home directory names the
22
+ * person. A path outside home is kept as it is; with no home to compare against
23
+ * nothing is kept, since the path could be the home itself.
24
+ *
25
+ * @param filePath - Path from a tool payload.
26
+ * @param repositoryRoot - The hook's repository root, when inside one.
27
+ * @param home - Developer home directory, when known.
28
+ * @returns The path to send, or undefined when the file is in the repository or unplaceable.
29
+ */
30
+ export declare function externalPath(filePath: string, repositoryRoot: string | undefined, home: string | undefined): string | undefined;
@@ -278,7 +278,7 @@ function relativize(root, target) {
278
278
  * @param home - Developer home directory, when known.
279
279
  * @returns The path to send, or undefined when the file is in the repository or unplaceable.
280
280
  */
281
- function externalPath(filePath, repositoryRoot, home) {
281
+ export function externalPath(filePath, repositoryRoot, home) {
282
282
  if (!home || !path.isAbsolute(filePath) || (repositoryRoot && isInside(repositoryRoot, filePath)))
283
283
  return undefined;
284
284
  return isInside(home, filePath) ? HOME_PLACEHOLDER_PREFIX + path.relative(home, filePath) : filePath;
@@ -56,6 +56,8 @@ export declare const GIT_FIELD_SEPARATOR = "\u001F";
56
56
  * @returns The argument vector.
57
57
  */
58
58
  export declare function gitRecentBranchesArgs(count: number): readonly string[];
59
+ /** The same branch record as {@link gitRecentBranchesArgs}, restricted to named local branches. */
60
+ export declare function gitNamedBranchesArgs(branches: readonly string[]): readonly string[];
59
61
  /**
60
62
  * What `%(upstream:track)` prints for a branch whose upstream was deleted on
61
63
  * the remote and pruned here: the usual end of a merged or closed pull request.
@@ -64,6 +64,15 @@ export function gitRecentBranchesArgs(count) {
64
64
  `--format=%(refname:short)${GIT_FIELD_SEPARATOR}%(objectname)${GIT_FIELD_SEPARATOR}%(committerdate:iso-strict)${GIT_FIELD_SEPARATOR}%(upstream:track)`
65
65
  ];
66
66
  }
67
+ /** The same branch record as {@link gitRecentBranchesArgs}, restricted to named local branches. */
68
+ export function gitNamedBranchesArgs(branches) {
69
+ return [
70
+ 'for-each-ref',
71
+ '--sort=-committerdate',
72
+ `--format=%(refname:short)${GIT_FIELD_SEPARATOR}%(objectname)${GIT_FIELD_SEPARATOR}%(committerdate:iso-strict)${GIT_FIELD_SEPARATOR}%(upstream:track)`,
73
+ ...branches.map((branch) => `refs/heads/${branch}`)
74
+ ];
75
+ }
67
76
  /**
68
77
  * What `%(upstream:track)` prints for a branch whose upstream was deleted on
69
78
  * the remote and pruned here: the usual end of a merged or closed pull request.
@@ -1,4 +1,4 @@
1
- import { ASSUMED_DEFAULT_BRANCHES, GIT_FIELD_SEPARATOR, GIT_ORIGIN_HEAD_ARGS, GIT_TIMEOUT_MS, GIT_UPSTREAM_GONE, RE_LEADING_NEWLINE, RE_NAME_STATUS, RE_OBJECT_ID, gitBranchDeltaArgs, gitBranchFilesArgs, gitMergeTreeArgs, gitRecentBranchesArgs, gitTreeArgs, gitVerifyRefArgs } from './constants/git.constants.js';
1
+ import { ASSUMED_DEFAULT_BRANCHES, GIT_FIELD_SEPARATOR, GIT_ORIGIN_HEAD_ARGS, GIT_TIMEOUT_MS, GIT_UPSTREAM_GONE, RE_LEADING_NEWLINE, RE_NAME_STATUS, RE_OBJECT_ID, gitBranchDeltaArgs, gitBranchFilesArgs, gitMergeTreeArgs, gitNamedBranchesArgs, gitRecentBranchesArgs, gitTreeArgs, gitVerifyRefArgs } from './constants/git.constants.js';
2
2
  /** `origin/HEAD` is reported as `origin/main`; the branch is what comes after. */
3
3
  const REMOTE_PREFIX = 'origin/';
4
4
  /**
@@ -16,6 +16,12 @@ export async function collectBranchRefs(options, run) {
16
16
  const output = await run(gitRecentBranchesArgs(options.branchCount), options.cwd, GIT_TIMEOUT_MS);
17
17
  if (!output)
18
18
  return [];
19
+ const recent = parseBranchRefs(output);
20
+ const missing = (options.requiredBranches ?? []).filter((name) => !recent.some((ref) => ref.name === name));
21
+ const required = missing.length === 0 ? [] : parseBranchRefs((await run(gitNamedBranchesArgs(missing), options.cwd, GIT_TIMEOUT_MS)) ?? '');
22
+ return [...required, ...recent];
23
+ }
24
+ function parseBranchRefs(output) {
19
25
  return output
20
26
  .split('\n')
21
27
  .map((line) => parseBranchRef(line))
@@ -82,7 +88,7 @@ export async function collectBranchCommits(branch, options, run) {
82
88
  .filter((commit) => commit !== undefined);
83
89
  if (commits.length === 0)
84
90
  return commits;
85
- if (await alreadyOnTrunk(delta.base, branch, options.cwd, run))
91
+ if (!options.includeMerged && (await alreadyOnTrunk(delta.base, branch, options.cwd, run)))
86
92
  return undefined;
87
93
  if (options.withFiles === false)
88
94
  return commits;
@@ -26,6 +26,8 @@ export interface SnapshotBranch extends BranchRef {
26
26
  export interface CollectRefsOptions {
27
27
  readonly cwd: string;
28
28
  readonly branchCount: number;
29
+ /** Branches that must be returned even when they are older than the recent window. */
30
+ readonly requiredBranches?: readonly string[];
29
31
  }
30
32
  export interface CollectCommitsOptions {
31
33
  readonly cwd: string;
@@ -33,6 +35,8 @@ export interface CollectCommitsOptions {
33
35
  readonly withFiles?: boolean;
34
36
  readonly defaultBranch?: string;
35
37
  readonly commitCount: number;
38
+ /** Historical replay evidence stays useful after a squash/rebase puts the same tree on trunk. */
39
+ readonly includeMerged?: boolean;
36
40
  }
37
41
  /** One source file of a default-branch tree: its path and its top-level declaration names. */
38
42
  export interface TreeFile {
@@ -507,7 +507,8 @@ async function trackTurnStage(state) {
507
507
  async function billingFactSafely(state) {
508
508
  try {
509
509
  const surface = await resolveSurface(state.provider, state.env, state.payload);
510
- return await sessionBillingFact(new TurnStateStore(state.paths.turnsDir), state.events, state.provider, state.env, surface);
510
+ const rooted = Object.keys(state.globalConfig.config.roots ?? {}).length > 0;
511
+ return await sessionBillingFact(new TurnStateStore(state.paths.turnsDir), state.events, state.provider, state.env, surface, rooted);
511
512
  }
512
513
  catch (error) {
513
514
  debugLog('session billing fact failed:', error);
@@ -1,5 +1,5 @@
1
1
  import { claudeBillingMode } from '../../billing/billing-mode.js';
2
- import { asRecord } from '../../core/object.js';
2
+ import { asRecord, firstStringOf } from '../../core/object.js';
3
3
  import { hookNotice, hookRefusal } from '../shared/hook-refusal.js';
4
4
  import { readClaudeSessionTitles, readTurnUsage } from '../../turns/claude-transcript.js';
5
5
  import { CLAUDE_DETACHED_EVENTS, CLAUDE_ENTRYPOINT_VAR, CLAUDE_INTERACTIVE_ENTRYPOINTS, CLAUDE_PROMPT_SUBMIT_EVENTS } from './constants/claude.constants.js';
@@ -30,11 +30,15 @@ export const claudeProvider = {
30
30
  /** A line for the developer after a shell run, as `systemMessage`; never plain stdout. */
31
31
  getNoticeResponse: (payload, message) => hookNotice(payload, message),
32
32
  /**
33
- * Stop and SubagentStop of a terminal session; anywhere else the session may end at once and its `SessionEnd` would race the close.
34
- * ponytail: an interactive `/exit` or `/clear` within the ~0.3 s the detached close takes can still race
35
- * its `SessionEnd`; upgrade path is a pending-close marker that `SessionEnd` waits on.
33
+ * Stop and SubagentStop of a terminal session; anywhere else the session may end at once.
34
+ * An `/exit` or `/clear` right after the Stop finds the pending-close marker and leaves the clear to the close.
36
35
  */
37
- runsDetached: (payload, env) => CLAUDE_DETACHED_EVENTS.has(String(asRecord(payload)?.['hook_event_name'])) && CLAUDE_INTERACTIVE_ENTRYPOINTS.has(env.vars[CLAUDE_ENTRYPOINT_VAR] ?? ''),
36
+ detachedSession: (payload, env) => {
37
+ const record = asRecord(payload);
38
+ if (!CLAUDE_DETACHED_EVENTS.has(String(record?.['hook_event_name'])) || !CLAUDE_INTERACTIVE_ENTRYPOINTS.has(env.vars[CLAUDE_ENTRYPOINT_VAR] ?? ''))
39
+ return undefined;
40
+ return firstStringOf(record?.['session_id']);
41
+ },
38
42
  shellCall: claudeShellCall,
39
43
  readTurnUsage,
40
44
  billingMode: claudeBillingMode,
@@ -148,12 +148,12 @@ export interface AgentProvider extends TurnProvider {
148
148
  */
149
149
  getNoticeResponse?(payload: unknown, message: string): ProviderHookResponse | undefined;
150
150
  /**
151
- * Whether this payload is processed by a detached `agentwatch hook`, so the
152
- * agent is answered at once instead of waiting on the send. Only for a hook
153
- * that answers nothing, and only where nothing that follows at once (a
154
- * session end clearing its state) would race the detached process.
151
+ * The session whose turn close this payload hands to a detached `agentwatch
152
+ * hook`, so the agent is answered at once instead of waiting on the send.
153
+ * Undefined processes it in place. Only for a hook that answers nothing; the
154
+ * session is named so its `SessionEnd` can see the close is still pending.
155
155
  */
156
- runsDetached?(payload: unknown, env: Env): boolean;
156
+ detachedSession?(payload: unknown, env: Env): string | undefined;
157
157
  /**
158
158
  * Working directory this payload was produced in, when the provider does not
159
159
  * report it as a top-level `cwd`. Git context, repository config and ticket
@@ -1,29 +1,56 @@
1
- import type { ReplayCheckout, ReplayTurn } from './types/replay.types.js';
1
+ import type { ReplayCheckout, ReplayTool, ReplayTurn } from './types/replay.types.js';
2
+ import { type WorktreeMap } from './worktree-map.js';
2
3
  /** Answers "which repository is this folder in?" for a transcript's folders, asking git once per folder. */
3
4
  export type CheckoutResolver = (cwd: string) => Promise<ReplayCheckout | undefined>;
4
5
  /**
5
6
  * A resolver that remembers its answers for the run.
6
7
  *
7
- * Two git processes per distinct folder, however many turns ran there; a
8
- * folder that no longer exists answers nothing, and so do the turns that ran
9
- * in it (their tokens still count, with no repository). Not the whole git
10
- * context the hooks take: no branch, commit or status, because the branch is
11
- * the transcript's and the commit is not known.
8
+ * Three git processes per distinct folder, however many turns ran there. A
9
+ * folder that no longer exists answers from the worktrees the transcripts
10
+ * recorded, and otherwise nothing, and so do the turns that ran in it (their
11
+ * tokens still count, with no repository). Not the whole git context the hooks
12
+ * take: no commit or status, because the commit is not known.
12
13
  *
14
+ * @param worktrees - What the transcripts recorded about worktrees; filled before the first answer.
13
15
  * @returns The resolver.
14
16
  */
15
- export declare function createCheckoutResolver(): CheckoutResolver;
17
+ export declare function createCheckoutResolver(worktrees?: WorktreeMap): CheckoutResolver;
16
18
  /**
17
- * The checkout a turn ran in: its folder's, or else the first one its tool files lie in.
19
+ * The checkout a turn reports, by the live hook's ladder as far as a transcript allows: `changed`, `carried`, then its folder.
18
20
  *
19
- * Mirrors the live hook's `changed → carried → referenced → cwd` ladder as far as a
20
- * transcript allows: a folder that is no checkout (an umbrella folder) or is gone
21
- * still leaves tool calls naming absolute files inside real repositories.
22
- * A file the turn edited says it `changed` that checkout; reads alone name none.
21
+ * The checkout that holds the most of the turn's edits wins (first seen on a tie), so an edit in another worktree
22
+ * is no longer dropped for the folder the session sat in. A turn with no edit in any checkout falls to the checkout
23
+ * the session last changed, then its folder; a turn whose edits all lie elsewhere reports neither, as live
24
+ * (`fileEvidenceAllows`: a session that wrote files elsewhere is not working in the one its shell sits in).
25
+ * Reads name no checkout: the live `referenced` rung is weaker than `changed` and would send that repository's snapshot.
23
26
  *
24
27
  * @param turn - The turn.
25
28
  * @param resolve - The run's resolver.
26
29
  * @param accept - Whether a tool file's checkout may be used (it may belong to another root's identity); a refused one is passed over.
27
- * @returns The checkout and whether its `root` still makes the tool paths relative; undefined when none resolves.
30
+ * @param carried - The checkout the session last changed.
31
+ * @returns The checkout and how it was known (no `evidence`: the folder); undefined when none resolves.
28
32
  */
29
- export declare function checkoutOfTurn(turn: Pick<ReplayTurn, 'cwd' | 'tools'>, resolve: CheckoutResolver, accept?: (checkout: ReplayCheckout) => boolean): Promise<ReplayCheckout | undefined>;
33
+ export declare function checkoutOfTurn(turn: Pick<ReplayTurn, 'cwd' | 'tools' | 'branch' | 'startedAt'>, resolve: CheckoutResolver, accept?: (checkout: ReplayCheckout) => boolean, carried?: ReplayCheckout): Promise<ReplayCheckout | undefined>;
34
+ /**
35
+ * Whether a tool call edited a file at a known place.
36
+ *
37
+ * @param tool - The call.
38
+ * @returns True for an edit with an absolute path.
39
+ */
40
+ export declare function isEdit(tool: ReplayTool): boolean;
41
+ /**
42
+ * The turn's tools with every file that lies in no checkout marked, as the live hook tells them apart.
43
+ *
44
+ * A folder that is gone answers nothing, so its files read as outside too, unless the path belongs to another
45
+ * identity's root or an ignored one, whose files are left out.
46
+ * ponytail: a root-scoped replay also leaves out files beyond its root, which a live hook would send. Ceiling: a
47
+ * root-scoped identity loses that outside-repo evidence; upgrade path: a scope port that tells "no root" from "another root".
48
+ * ponytail: asks git once per distinct folder of the run (the resolver remembers), with no per-turn cap. Ceiling:
49
+ * a machine whose agents touch tens of thousands of folders; the replay is niced and paced, so it only runs longer.
50
+ *
51
+ * @param tools - The turn's tools.
52
+ * @param resolve - The run's resolver.
53
+ * @param inScope - Whether a folder belongs to this identity.
54
+ * @returns A new list; a file inside some checkout is left unmarked.
55
+ */
56
+ export declare function markFilesOutsideCheckouts(tools: readonly ReplayTool[], resolve: CheckoutResolver, inScope?: (folder: string) => boolean): Promise<ReplayTool[]>;