@agent-watch-ai/edge 0.4.0 → 0.6.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 (109) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +8 -7
  3. package/SECURITY.md +1 -1
  4. package/dist/config/config-store.js +1 -1
  5. package/dist/config/repo-config.js +1 -1
  6. package/dist/config/schemas/config.schema.d.ts +93 -857
  7. package/dist/config/schemas/config.schema.js +5 -5
  8. package/dist/credentials/credentials.js +2 -2
  9. package/dist/credentials/schemas/device-api.schema.d.ts +4 -51
  10. package/dist/credentials/schemas/device-state.schema.d.ts +3 -38
  11. package/dist/events/constants/events.constants.d.ts +5 -2
  12. package/dist/events/constants/events.constants.js +4 -1
  13. package/dist/events/index.d.ts +1 -0
  14. package/dist/events/product-event.d.ts +7 -4
  15. package/dist/events/types/repo-snapshot.types.d.ts +1 -4
  16. package/dist/events/types/repo-tree.types.d.ts +24 -0
  17. package/dist/events/types/repo-tree.types.js +1 -0
  18. package/dist/git/code-state.d.ts +33 -0
  19. package/dist/git/code-state.js +44 -0
  20. package/dist/git/constants/git.constants.d.ts +6 -0
  21. package/dist/git/constants/git.constants.js +6 -0
  22. package/dist/git/constants/tree.constants.d.ts +71 -0
  23. package/dist/git/constants/tree.constants.js +92 -0
  24. package/dist/git/git-context.d.ts +1 -0
  25. package/dist/git/git-context.js +3 -2
  26. package/dist/git/index.d.ts +2 -1
  27. package/dist/git/index.js +1 -0
  28. package/dist/git/repo-tree.d.ts +69 -0
  29. package/dist/git/repo-tree.js +130 -0
  30. package/dist/git/types/git.types.d.ts +11 -2
  31. package/dist/git/types/snapshot.types.d.ts +12 -0
  32. package/dist/pipeline/hook-pipeline.js +40 -24
  33. package/dist/privacy/command-fingerprint.d.ts +42 -0
  34. package/dist/privacy/command-fingerprint.js +249 -0
  35. package/dist/privacy/constants/command-fingerprint.constants.d.ts +34 -0
  36. package/dist/privacy/constants/command-fingerprint.constants.js +38 -0
  37. package/dist/privacy/index.d.ts +3 -1
  38. package/dist/privacy/index.js +2 -0
  39. package/dist/privacy/product-capture.js +53 -6
  40. package/dist/privacy/types/privacy.types.d.ts +7 -0
  41. package/dist/providers/antigravity/antigravity.adapter.js +3 -0
  42. package/dist/providers/antigravity/schemas/antigravity.schema.d.ts +18 -492
  43. package/dist/providers/claude/claude.adapter.js +12 -1
  44. package/dist/providers/claude/constants/claude.constants.d.ts +6 -0
  45. package/dist/providers/claude/constants/claude.constants.js +6 -0
  46. package/dist/providers/claude/schemas/claude.schema.d.ts +1 -43
  47. package/dist/providers/codex/codex.adapter.js +14 -0
  48. package/dist/providers/codex/schemas/codex.schema.d.ts +1 -41
  49. package/dist/providers/cursor/cursor.adapter.js +5 -2
  50. package/dist/providers/cursor/schemas/cursor.schema.d.ts +5 -85
  51. package/dist/providers/gemini/constants/gemini.constants.d.ts +2 -0
  52. package/dist/providers/gemini/constants/gemini.constants.js +2 -0
  53. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +10 -1
  54. package/dist/providers/gemini/constants/gemini.otel.constants.js +11 -2
  55. package/dist/providers/gemini/gemini.detect.d.ts +11 -0
  56. package/dist/providers/gemini/gemini.detect.js +14 -1
  57. package/dist/providers/gemini/gemini.hooks.d.ts +3 -3
  58. package/dist/providers/gemini/gemini.hooks.js +5 -5
  59. package/dist/providers/gemini/gemini.otel.d.ts +6 -6
  60. package/dist/providers/gemini/gemini.otel.js +392 -121
  61. package/dist/providers/gemini/schemas/gemini.schema.d.ts +1 -49
  62. package/dist/providers/shared/event-builder.d.ts +17 -2
  63. package/dist/providers/shared/event-builder.js +43 -3
  64. package/dist/providers/shared/install-record.d.ts +2 -0
  65. package/dist/providers/shared/install-record.js +3 -2
  66. package/dist/providers/shared/tooling.d.ts +7 -0
  67. package/dist/providers/shared/tooling.js +10 -1
  68. package/dist/providers/shared/types/adapter.types.d.ts +18 -0
  69. package/dist/snapshot/branch-selection.js +3 -1
  70. package/dist/snapshot/budget.js +2 -2
  71. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +8 -0
  72. package/dist/snapshot/constants/snapshot-stages.constants.js +8 -0
  73. package/dist/snapshot/constants/snapshot.constants.d.ts +6 -0
  74. package/dist/snapshot/constants/snapshot.constants.js +6 -0
  75. package/dist/snapshot/index.d.ts +5 -0
  76. package/dist/snapshot/index.js +2 -0
  77. package/dist/snapshot/snapshot-event.d.ts +7 -0
  78. package/dist/snapshot/snapshot-event.js +8 -5
  79. package/dist/snapshot/snapshot-state.js +19 -1
  80. package/dist/snapshot/tree-event.d.ts +14 -0
  81. package/dist/snapshot/tree-event.js +91 -0
  82. package/dist/snapshot/tree-pipeline.d.ts +12 -0
  83. package/dist/snapshot/tree-pipeline.js +153 -0
  84. package/dist/snapshot/types/snapshot.types.d.ts +44 -1
  85. package/dist/storage/schemas/storage.schema.d.ts +11 -175
  86. package/dist/storage/schemas/storage.schema.js +7 -1
  87. package/dist/transport/constants/transport.constants.d.ts +5 -0
  88. package/dist/transport/constants/transport.constants.js +5 -0
  89. package/dist/transport/queue.js +40 -6
  90. package/dist/transport/schemas/queue.schema.d.ts +1 -16
  91. package/dist/transport/schemas/queue.schema.js +1 -1
  92. package/dist/turns/constants/turns.constants.d.ts +17 -0
  93. package/dist/turns/constants/turns.constants.js +17 -0
  94. package/dist/turns/index.d.ts +3 -2
  95. package/dist/turns/index.js +1 -0
  96. package/dist/turns/tool-events.d.ts +15 -0
  97. package/dist/turns/tool-events.js +59 -0
  98. package/dist/turns/turn-state.js +2 -2
  99. package/dist/turns/turn-summary.d.ts +1 -1
  100. package/dist/turns/turn-summary.js +4 -4
  101. package/dist/turns/turn-tracker.js +138 -7
  102. package/dist/turns/types/turn-state.types.d.ts +28 -1
  103. package/dist/turns/types/turn-summary.types.d.ts +33 -5
  104. package/dist/turns/types/turn-tracker.types.d.ts +10 -0
  105. package/docs/AUDIT_PROMPT.md +11 -0
  106. package/docs/DATA_HANDLING.md +132 -33
  107. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -1
  108. package/docs/PERFORMANCE.md +17 -0
  109. package/package.json +9 -8
@@ -0,0 +1,69 @@
1
+ import type { GitRunner } from './types/git.types.js';
2
+ import type { RepoTree } from './types/snapshot.types.js';
3
+ export type { RepoTree, TreeFile } from './types/snapshot.types.js';
4
+ /**
5
+ * The tree of the default branch as the remote knows it, else as the clone has it.
6
+ *
7
+ * The same rule as a branch delta: the local trunk only when `origin/<trunk>`
8
+ * is absent, never because reading it failed — a stale local `main` would
9
+ * describe a product nobody ships.
10
+ *
11
+ * @param cwd - Repository directory.
12
+ * @param defaultBranch - The trunk's name.
13
+ * @param run - Git runner.
14
+ * @returns The tree oid, or undefined when there is none or git failed.
15
+ */
16
+ export declare function resolveTreeSha(cwd: string, defaultBranch: string, run: GitRunner): Promise<string | undefined>;
17
+ /**
18
+ * Every source file of one tree with its top-level declaration names.
19
+ *
20
+ * Read from git's object store only — `ls-tree` and `git grep <tree>` — so no
21
+ * checkout state, uncommitted file or working-copy secret can reach it, and no
22
+ * body ever leaves git: `grep -o` prints the declaration text alone.
23
+ *
24
+ * Three searches run side by side: the spike's declarations and the route
25
+ * paths over every source file, and the extra languages' declarations over
26
+ * their own files only, so the TS, Python and Go names stay exactly what the
27
+ * naming result was measured on.
28
+ *
29
+ * @param cwd - Repository directory.
30
+ * @param treeSha - The tree to read.
31
+ * @param run - Git runner; the caller's budgeted one bounds every search.
32
+ * @returns The tree, or undefined when it could not be listed. A search that
33
+ * failed or found nothing leaves its files with no names; the caller tells a
34
+ * search cut short by the budget from one that matched nothing.
35
+ */
36
+ export declare function collectRepoTree(cwd: string, treeSha: string, run: GitRunner): Promise<RepoTree | undefined>;
37
+ /**
38
+ * Whether a path is source core's naming pass reads: `isNamingSourceFile`, mirrored.
39
+ *
40
+ * @param filePath - Repository-relative path.
41
+ * @returns True for a source file outside tests, vendored trees, docs and migrations.
42
+ */
43
+ export declare function isTreeSourceFile(filePath: string): boolean;
44
+ /**
45
+ * The source blobs of one `ls-tree -r -l -z` listing, in its order.
46
+ *
47
+ * Submodules (`commit`) and symlinks are not blobs worth naming and fall out of
48
+ * the record pattern; a symlink is a blob but carries a target, not code, and
49
+ * reads as one with no declarations.
50
+ *
51
+ * @param listing - The NUL-terminated listing.
52
+ * @returns Path and size per source file.
53
+ */
54
+ export declare function parseTreeListing(listing: string): {
55
+ path: string;
56
+ size: number;
57
+ }[];
58
+ /**
59
+ * Declaration names per path out of `git grep -o -z <tree>` output.
60
+ *
61
+ * A record is `<tree>:<path>\0<match>\n`. Each match ends with what it declares:
62
+ * a quoted route path, or the identifier. De-duplicated per file in first-seen
63
+ * order, the spike's searches before the extra languages'.
64
+ *
65
+ * @param output - One or more searches' output, newline-joined.
66
+ * @param prefix - `<tree>:`, which git puts before every path.
67
+ * @returns Names by path.
68
+ */
69
+ export declare function parseDeclarations(output: string, prefix: string): Map<string, string[]>;
@@ -0,0 +1,130 @@
1
+ import { GIT_TIMEOUT_MS, gitVerifyRefArgs } from './constants/git.constants.js';
2
+ import { TREE_DECLARATION_PATTERN, TREE_EXTRA_DECLARATION_PATTERN, TREE_EXTRA_PATHSPECS, TREE_MAX_BUFFER_BYTES, TREE_MAX_NAMED_BLOB_BYTES, TREE_RE_QUOTED_NAME, TREE_RE_SKIP, TREE_RE_TRAILING_NAME, TREE_ROUTE_PATTERN, TREE_SALVAGE_MARGIN_BYTES, TREE_SOURCE_EXTENSIONS, gitDeclarationGrepArgs, gitListTreeArgs, gitTreeShaArgs } from './constants/tree.constants.js';
3
+ /** `ls-tree -l` record: `<mode> <type> <sha> <size>\t<path>`. The sha is not kept: nothing reads it. */
4
+ const RE_TREE_ENTRY = /^\d+ blob ([0-9a-f]{40}|[0-9a-f]{64}) +(\d+)\t/;
5
+ /** Every source pathspec at once: `git grep` must not read what the catalog will not send. */
6
+ const SOURCE_PATHSPECS = TREE_SOURCE_EXTENSIONS.map((extension) => `*${extension}`);
7
+ /**
8
+ * The tree of the default branch as the remote knows it, else as the clone has it.
9
+ *
10
+ * The same rule as a branch delta: the local trunk only when `origin/<trunk>`
11
+ * is absent, never because reading it failed — a stale local `main` would
12
+ * describe a product nobody ships.
13
+ *
14
+ * @param cwd - Repository directory.
15
+ * @param defaultBranch - The trunk's name.
16
+ * @param run - Git runner.
17
+ * @returns The tree oid, or undefined when there is none or git failed.
18
+ */
19
+ export async function resolveTreeSha(cwd, defaultBranch, run) {
20
+ const remoteBase = `origin/${defaultBranch}`;
21
+ const remote = await run(gitTreeShaArgs(remoteBase), cwd, GIT_TIMEOUT_MS);
22
+ if (remote)
23
+ return remote;
24
+ if (await run(gitVerifyRefArgs(remoteBase), cwd, GIT_TIMEOUT_MS))
25
+ return undefined;
26
+ return run(gitTreeShaArgs(defaultBranch), cwd, GIT_TIMEOUT_MS);
27
+ }
28
+ /**
29
+ * Every source file of one tree with its top-level declaration names.
30
+ *
31
+ * Read from git's object store only — `ls-tree` and `git grep <tree>` — so no
32
+ * checkout state, uncommitted file or working-copy secret can reach it, and no
33
+ * body ever leaves git: `grep -o` prints the declaration text alone.
34
+ *
35
+ * Three searches run side by side: the spike's declarations and the route
36
+ * paths over every source file, and the extra languages' declarations over
37
+ * their own files only, so the TS, Python and Go names stay exactly what the
38
+ * naming result was measured on.
39
+ *
40
+ * @param cwd - Repository directory.
41
+ * @param treeSha - The tree to read.
42
+ * @param run - Git runner; the caller's budgeted one bounds every search.
43
+ * @returns The tree, or undefined when it could not be listed. A search that
44
+ * failed or found nothing leaves its files with no names; the caller tells a
45
+ * search cut short by the budget from one that matched nothing.
46
+ */
47
+ export async function collectRepoTree(cwd, treeSha, run) {
48
+ const listing = await run(gitListTreeArgs(treeSha), cwd, GIT_TIMEOUT_MS, undefined, TREE_MAX_BUFFER_BYTES);
49
+ if (listing === undefined)
50
+ return undefined;
51
+ const entries = parseTreeListing(listing);
52
+ if (entries.length === 0)
53
+ return { treeSha, files: [], partial: false };
54
+ const searches = await Promise.all([
55
+ run(gitDeclarationGrepArgs(treeSha, '-E', TREE_DECLARATION_PATTERN, SOURCE_PATHSPECS), cwd, GIT_TIMEOUT_MS, undefined, TREE_MAX_BUFFER_BYTES),
56
+ run(gitDeclarationGrepArgs(treeSha, '-P', TREE_ROUTE_PATTERN, SOURCE_PATHSPECS), cwd, GIT_TIMEOUT_MS, undefined, TREE_MAX_BUFFER_BYTES),
57
+ run(gitDeclarationGrepArgs(treeSha, '-E', TREE_EXTRA_DECLARATION_PATTERN, TREE_EXTRA_PATHSPECS), cwd, GIT_TIMEOUT_MS, undefined, TREE_MAX_BUFFER_BYTES)
58
+ ]);
59
+ const names = parseDeclarations(searches.join('\n'), `${treeSha}:`);
60
+ const files = [];
61
+ for (const entry of entries) {
62
+ const named = entry.size <= TREE_MAX_NAMED_BLOB_BYTES ? names.get(entry.path) : undefined;
63
+ files.push({ path: entry.path, names: named ?? [] });
64
+ }
65
+ // The runner salvages an overrun up to its last newline, so a cut listing
66
+ // looks complete: anything within a line of the ceiling is taken as cut.
67
+ const partial = [listing, ...searches].some((output) => Buffer.byteLength(output ?? '') > TREE_MAX_BUFFER_BYTES - TREE_SALVAGE_MARGIN_BYTES);
68
+ return { treeSha, files, partial };
69
+ }
70
+ /**
71
+ * Whether a path is source core's naming pass reads: `isNamingSourceFile`, mirrored.
72
+ *
73
+ * @param filePath - Repository-relative path.
74
+ * @returns True for a source file outside tests, vendored trees, docs and migrations.
75
+ */
76
+ export function isTreeSourceFile(filePath) {
77
+ return TREE_SOURCE_EXTENSIONS.some((extension) => filePath.endsWith(extension)) && !TREE_RE_SKIP.test(filePath);
78
+ }
79
+ /**
80
+ * The source blobs of one `ls-tree -r -l -z` listing, in its order.
81
+ *
82
+ * Submodules (`commit`) and symlinks are not blobs worth naming and fall out of
83
+ * the record pattern; a symlink is a blob but carries a target, not code, and
84
+ * reads as one with no declarations.
85
+ *
86
+ * @param listing - The NUL-terminated listing.
87
+ * @returns Path and size per source file.
88
+ */
89
+ export function parseTreeListing(listing) {
90
+ const entries = [];
91
+ for (const record of listing.split('\0')) {
92
+ const match = RE_TREE_ENTRY.exec(record);
93
+ if (!match)
94
+ continue;
95
+ const filePath = record.slice(match[0].length);
96
+ if (!isTreeSourceFile(filePath))
97
+ continue;
98
+ entries.push({ path: filePath, size: Number(match[2]) });
99
+ }
100
+ return entries;
101
+ }
102
+ /**
103
+ * Declaration names per path out of `git grep -o -z <tree>` output.
104
+ *
105
+ * A record is `<tree>:<path>\0<match>\n`. Each match ends with what it declares:
106
+ * a quoted route path, or the identifier. De-duplicated per file in first-seen
107
+ * order, the spike's searches before the extra languages'.
108
+ *
109
+ * @param output - One or more searches' output, newline-joined.
110
+ * @param prefix - `<tree>:`, which git puts before every path.
111
+ * @returns Names by path.
112
+ */
113
+ export function parseDeclarations(output, prefix) {
114
+ const byPath = new Map();
115
+ for (const line of output.split('\n')) {
116
+ const split = line.indexOf('\0');
117
+ if (split === -1 || !line.startsWith(prefix))
118
+ continue;
119
+ const filePath = line.slice(prefix.length, split);
120
+ const text = line.slice(split + 1);
121
+ const name = TREE_RE_QUOTED_NAME.exec(text)?.[1] ?? TREE_RE_TRAILING_NAME.exec(text)?.[1];
122
+ if (!name)
123
+ continue;
124
+ const names = byPath.get(filePath) ?? [];
125
+ if (!names.includes(name))
126
+ names.push(name);
127
+ byPath.set(filePath, names);
128
+ }
129
+ return byPath;
130
+ }
@@ -22,8 +22,11 @@ export interface GitContextOptions {
22
22
  */
23
23
  readonly rootOnly?: boolean;
24
24
  }
25
- /** Runs one git command and returns its trimmed stdout, or undefined. */
26
- export type GitRunner = (args: readonly string[], cwd: string, timeoutMs: number, home?: string) => Promise<string | undefined>;
25
+ /**
26
+ * Runs one git command and returns its trimmed stdout, or undefined.
27
+ * `maxBufferBytes` raises the stdout ceiling for the one listing that needs it (a whole tree).
28
+ */
29
+ export type GitRunner = (args: readonly string[], cwd: string, timeoutMs: number, home?: string, maxBufferBytes?: number) => Promise<string | undefined>;
27
30
  export interface GitUserEmailOptions {
28
31
  readonly timeoutMs?: number;
29
32
  readonly home?: string;
@@ -89,3 +92,9 @@ export interface ContentHash {
89
92
  readonly path: string;
90
93
  readonly blob_sha: string;
91
94
  }
95
+ /** The code a check ran on (workflow SPEC §11.2): HEAD plus a digest of the working tree. */
96
+ export interface CodeState {
97
+ readonly commit: string;
98
+ /** sha256 of `git diff HEAD --binary`; absent when git could not say. */
99
+ readonly diffFp?: string;
100
+ }
@@ -32,3 +32,15 @@ export interface CollectCommitsOptions {
32
32
  readonly defaultBranch?: string;
33
33
  readonly commitCount: number;
34
34
  }
35
+ /** One source file of a default-branch tree: its path and its top-level declaration names. */
36
+ export interface TreeFile {
37
+ readonly path: string;
38
+ readonly names: readonly string[];
39
+ }
40
+ /** One default-branch tree's source files, in `ls-tree` order, before any cap. */
41
+ export interface RepoTree {
42
+ readonly treeSha: string;
43
+ readonly files: readonly TreeFile[];
44
+ /** A listing or search reached the output ceiling and was salvaged: some files or names are missing. */
45
+ readonly partial: boolean;
46
+ }
@@ -7,7 +7,7 @@ import { next, runFlow, step, stop } from '../core/pipe.js';
7
7
  import { loadEffectiveConfig } from '../config/repo-config.js';
8
8
  import { CREDENTIAL_BUDGET_SHARE, NOT_SIGNED_IN } from '../credentials/constants/credentials.constants.js';
9
9
  import { cachedBearer, resolveBearer } from '../credentials/credentials.js';
10
- import { awaitingSignIn, deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
10
+ import { awaitingSignIn, deviceFor, hasCredential, identityFingerprint, identityOf } from '../credentials/identity.js';
11
11
  import { cachedAccessToken } from '../credentials/token-refresher.js';
12
12
  import { credentialScope, inheritedRootConfig, selectRoot, servesMultipleIdentities } from '../config/root-config.js';
13
13
  import { DECISION_BLOCK } from '../enforcement/constants/enforcement.constants.js';
@@ -22,6 +22,7 @@ import { rewriteNativeBearers } from '../providers/shared/bearer-rewrite.js';
22
22
  import { isUninstalled } from '../storage/uninstalled.js';
23
23
  import { shellDirectories } from '../providers/shared/shell-directories.js';
24
24
  import { runSnapshotPipeline } from '../snapshot/snapshot-pipeline.js';
25
+ import { runTreePipeline } from '../snapshot/tree-pipeline.js';
25
26
  import { SnapshotStateStore } from '../snapshot/snapshot-state.js';
26
27
  import { SNAPSHOT_BUDGET_MS } from '../snapshot/constants/snapshot.constants.js';
27
28
  import { BackendAuthBlock } from '../transport/auth-block.js';
@@ -575,31 +576,46 @@ async function snapshot(state) {
575
576
  const capture = state.workCapture ?? state.config.capture;
576
577
  if (!repository || state.summary?.work_evidence === 'inherited' || !capture.git)
577
578
  return stop(state, STOP_NO_SNAPSHOT);
578
- await runSnapshotPipeline({
579
- input: {
580
- // The checkout the summary named, which need not be the folder the agent sits in.
581
- cwd: state.workRoot ?? state.cwd,
582
- // The repository's own policy, which may lower the global one: file names
583
- // off means the files listing never runs, not that it is emptied later.
584
- files: capture.files !== false,
585
- repository,
586
- provider: state.summary?.provider ?? state.provider.id,
587
- surface: state.summary?.surface ?? state.provider.id,
588
- agentName: state.summary?.agent.name ?? state.provider.id,
589
- developerId: state.summary?.developer_id,
590
- installationId: state.config.installationId,
591
- sessionId: state.summary?.session_id,
592
- capturedAt: state.env.now().toISOString(),
593
- // Real time, deliberately, where the line above uses the injected clock:
594
- // this bounds subprocess timeouts, which are measured against the wall.
595
- deadline: Date.now() + SNAPSHOT_BUDGET_MS,
596
- run: runGit
597
- },
598
- store: new SnapshotStateStore(state.paths.snapshotsDir),
599
- queue: buildQueue(state)
600
- });
579
+ const input = {
580
+ // The checkout the summary named, which need not be the folder the agent sits in.
581
+ cwd: state.workRoot ?? state.cwd,
582
+ // The repository's own policy, which may lower the global one: file names
583
+ // off means the files listing never runs, not that it is emptied later.
584
+ files: capture.files !== false,
585
+ // A digest, never the credential: the tree is owed once per repository and identity.
586
+ identity: treeIdentity(state),
587
+ repository,
588
+ provider: state.summary?.provider ?? state.provider.id,
589
+ surface: state.summary?.surface ?? state.provider.id,
590
+ agentName: state.summary?.agent.name ?? state.provider.id,
591
+ developerId: state.summary?.developer_id,
592
+ installationId: state.config.installationId,
593
+ sessionId: state.summary?.session_id,
594
+ capturedAt: state.env.now().toISOString(),
595
+ // Real time, deliberately, where the line above uses the injected clock:
596
+ // this bounds subprocess timeouts, which are measured against the wall.
597
+ deadline: Date.now() + SNAPSHOT_BUDGET_MS,
598
+ run: runGit
599
+ };
600
+ const store = new SnapshotStateStore(state.paths.snapshotsDir);
601
+ const queue = buildQueue(state);
602
+ await runSnapshotPipeline({ input, store, queue });
603
+ // The trunk's paths and declaration names, once per repository and identity,
604
+ // inside the same deadline. File names off means no listing at all.
605
+ if (input.files)
606
+ await runTreePipeline({ input, store, queue });
601
607
  return next(state);
602
608
  }
609
+ /**
610
+ * The identity a tree is recorded as sent for: a re-setup with a new credential owes it again.
611
+ *
612
+ * @param state - Current flow state.
613
+ * @returns The identity's on-disk fingerprint, or undefined with no credential.
614
+ */
615
+ function treeIdentity(state) {
616
+ const identity = identityOf(state.config);
617
+ return identity ? identityFingerprint(identity) : undefined;
618
+ }
603
619
  /**
604
620
  * The offline queue for this run, partitioned by the identity it sends as.
605
621
  * `deliver` settles a pre-partition backlog before the first build.
@@ -0,0 +1,42 @@
1
+ import type { CommandFingerprint } from './types/privacy.types.js';
2
+ /**
3
+ * The command as the fingerprint sees it: split into segments on `&&`, `||`,
4
+ * `;`, `|`, `&` and line breaks; quotes and escapes undone; comments,
5
+ * redirections with their targets, leading `VAR=value` words and `cd` segments
6
+ * dropped; each segment's words joined by one space and the segments by LF.
7
+ *
8
+ * ponytail: a lexer, not a shell. `$(…)` and backticks stay literal text, a
9
+ * heredoc body reads as further segments, and `"a b"` meets `a b`. Two
10
+ * commands that differ only there share a digest, which is the direction to
11
+ * err in: a repeated status poll must still look repeated.
12
+ *
13
+ * @param command - The command text; anything else reads as empty.
14
+ * @returns The normalised command, `''` when nothing is left.
15
+ */
16
+ export declare function normaliseCommand(command: unknown): string;
17
+ /**
18
+ * The first segment on the check allowlist, normalised as {@link normaliseCommand} does.
19
+ *
20
+ * @param command - The command text.
21
+ * @returns The segment, or null when no segment is a check.
22
+ */
23
+ export declare function checkSegment(command: unknown): string | null;
24
+ /**
25
+ * The digest the edge sends for a shell call. A check is fingerprinted on its
26
+ * matching segment only, so `cd pkg && npm test` and `npm test 2>&1 | tail`
27
+ * are the same run of the same check. Unkeyed: core stores only its re-key
28
+ * under the tenant's key.
29
+ *
30
+ * @param command - The command text, read in memory and dropped.
31
+ * @returns The digest and whether a segment is on the check allowlist.
32
+ */
33
+ export declare function commandFingerprint(command: unknown): CommandFingerprint;
34
+ /**
35
+ * The command a shell tool's input states: a string, or an argv whose
36
+ * `bash -lc <script>` wrapper is unwrapped and any other words joined, as core
37
+ * reads Codex's argv.
38
+ *
39
+ * @param value - The command field as the payload carries it.
40
+ * @returns The command text, or undefined when there is none.
41
+ */
42
+ export declare function commandText(value: unknown): string | undefined;
@@ -0,0 +1,249 @@
1
+ import { sha256Hex } from '../events/event-id.js';
2
+ import { CHECK_PROGRAMS, CHECK_SCRIPTS, DOUBLE_QUOTE_ESCAPES, MAX_COMMAND_CODE_POINTS, RE_ASSIGNMENT, RE_DUPLICATION_CHAR, RE_FD_PREFIX, RE_PYTHON, RE_SCRIPT_VARIANT, RUN_SCRIPT_WORDS, SCRIPT_RUNNERS, SHELL_SCRIPT_FLAGS, SHELL_WRAPPERS, SUBCOMMAND_CHECKS } from './constants/command-fingerprint.constants.js';
3
+ /*
4
+ * A port of core's `@agent-watch/fingerprint` command scheme (AWT-674). Core
5
+ * fingerprints the same call from the agent's OTLP export, so the two must
6
+ * agree to the byte: `tests/command-fingerprint.test.ts` replays core's golden
7
+ * vectors against this file. Change a rule there first, never here alone.
8
+ */
9
+ /**
10
+ * The command as the fingerprint sees it: split into segments on `&&`, `||`,
11
+ * `;`, `|`, `&` and line breaks; quotes and escapes undone; comments,
12
+ * redirections with their targets, leading `VAR=value` words and `cd` segments
13
+ * dropped; each segment's words joined by one space and the segments by LF.
14
+ *
15
+ * ponytail: a lexer, not a shell. `$(…)` and backticks stay literal text, a
16
+ * heredoc body reads as further segments, and `"a b"` meets `a b`. Two
17
+ * commands that differ only there share a digest, which is the direction to
18
+ * err in: a repeated status poll must still look repeated.
19
+ *
20
+ * @param command - The command text; anything else reads as empty.
21
+ * @returns The normalised command, `''` when nothing is left.
22
+ */
23
+ export function normaliseCommand(command) {
24
+ return segmentsOf(command)
25
+ .map((words) => words.join(' '))
26
+ .join('\n');
27
+ }
28
+ /**
29
+ * The first segment on the check allowlist, normalised as {@link normaliseCommand} does.
30
+ *
31
+ * @param command - The command text.
32
+ * @returns The segment, or null when no segment is a check.
33
+ */
34
+ export function checkSegment(command) {
35
+ const segment = segmentsOf(command).find(isCheckCommand);
36
+ return segment === undefined ? null : segment.join(' ');
37
+ }
38
+ /**
39
+ * The digest the edge sends for a shell call. A check is fingerprinted on its
40
+ * matching segment only, so `cd pkg && npm test` and `npm test 2>&1 | tail`
41
+ * are the same run of the same check. Unkeyed: core stores only its re-key
42
+ * under the tenant's key.
43
+ *
44
+ * @param command - The command text, read in memory and dropped.
45
+ * @returns The digest and whether a segment is on the check allowlist.
46
+ */
47
+ export function commandFingerprint(command) {
48
+ const check = checkSegment(command);
49
+ if (check !== null)
50
+ return { digest: sha256Hex(check), matchesCheck: true };
51
+ const normalised = normaliseCommand(command);
52
+ return { digest: normalised === '' ? null : sha256Hex(normalised), matchesCheck: false };
53
+ }
54
+ /**
55
+ * The command a shell tool's input states: a string, or an argv whose
56
+ * `bash -lc <script>` wrapper is unwrapped and any other words joined, as core
57
+ * reads Codex's argv.
58
+ *
59
+ * @param value - The command field as the payload carries it.
60
+ * @returns The command text, or undefined when there is none.
61
+ */
62
+ export function commandText(value) {
63
+ if (typeof value === 'string')
64
+ return value || undefined;
65
+ if (!Array.isArray(value))
66
+ return undefined;
67
+ const argv = value.filter((word) => typeof word === 'string');
68
+ const [program = '', flag = '', script] = argv;
69
+ if (argv.length === 0)
70
+ return undefined;
71
+ const wrapped = SHELL_WRAPPERS.has(basename(program)) && SHELL_SCRIPT_FLAGS.has(flag);
72
+ return wrapped && argv.length === 3 && script !== undefined ? script : argv.join(' ');
73
+ }
74
+ function segmentsOf(command) {
75
+ if (typeof command !== 'string')
76
+ return [];
77
+ return new CommandLexer(clampCodePoints(command.normalize('NFC'), MAX_COMMAND_CODE_POINTS))
78
+ .segments()
79
+ .map(withoutAssignments)
80
+ .filter((words) => words.length > 0 && words[0] !== 'cd');
81
+ }
82
+ /** Drops the `VAR=value` words that set a command's environment; a bare assignment leaves nothing. */
83
+ function withoutAssignments(words) {
84
+ const first = words.findIndex((word) => !RE_ASSIGNMENT.test(word));
85
+ return first === -1 ? [] : words.slice(first);
86
+ }
87
+ function isCheckCommand(words) {
88
+ const program = basename(words[0] ?? '');
89
+ const args = words.slice(1).filter((word) => !word.startsWith('-'));
90
+ if (CHECK_PROGRAMS.has(program))
91
+ return true;
92
+ if (program === 'npx')
93
+ return isCheckCommand(args);
94
+ if (RE_PYTHON.test(program) && words[1] === '-m')
95
+ return isCheckCommand(words.slice(2));
96
+ if (SCRIPT_RUNNERS.has(program))
97
+ return isCheckScript(args);
98
+ return SUBCOMMAND_CHECKS.get(program)?.has(args[0] ?? '') ?? false;
99
+ }
100
+ /** `npm test`, `npm run lint`, `pnpm run test:unit`. A flag's separate value can hide the script. */
101
+ function isCheckScript(args) {
102
+ const script = RUN_SCRIPT_WORDS.has(args[0] ?? '') ? args[1] : args[0];
103
+ return script !== undefined && CHECK_SCRIPTS.has(script.replace(RE_SCRIPT_VARIANT, ''));
104
+ }
105
+ function basename(word) {
106
+ return word.slice(word.lastIndexOf('/') + 1);
107
+ }
108
+ /**
109
+ * Words per segment, in one pass. Operators are recognised outside quotes
110
+ * only. The rules, in the order they are tried at each character, are the
111
+ * vectors file's `rules.lexer`.
112
+ */
113
+ class CommandLexer {
114
+ text;
115
+ done = [];
116
+ words = [];
117
+ word = null;
118
+ /** The next word is a redirection target and is dropped. */
119
+ dropNext = false;
120
+ constructor(text) {
121
+ this.text = text;
122
+ }
123
+ segments() {
124
+ let i = 0;
125
+ while (i < this.text.length)
126
+ i = this.step(i);
127
+ this.endSegment();
128
+ return this.done;
129
+ }
130
+ /** Reads one token's worth from `i` and returns where the next one starts. */
131
+ step(i) {
132
+ const char = this.text.charAt(i);
133
+ if (char === '\\')
134
+ return this.escaped(i);
135
+ if (char === "'")
136
+ return this.singleQuoted(i);
137
+ if (char === '"')
138
+ return this.doubleQuoted(i);
139
+ if (char === '#' && this.word === null)
140
+ return this.lineEnd(i);
141
+ return this.operator(i, char);
142
+ }
143
+ operator(i, char) {
144
+ const next = this.text[i + 1];
145
+ if (char === '&' && next === '>')
146
+ return this.redirection(i + 1);
147
+ if (char === '>' || char === '<')
148
+ return this.redirection(i);
149
+ const separator = separatorLength(char, next);
150
+ if (separator > 0) {
151
+ this.endSegment();
152
+ return i + separator;
153
+ }
154
+ if (char === ' ' || char === '\t') {
155
+ this.endWord();
156
+ return i + 1;
157
+ }
158
+ this.append(char);
159
+ return i + 1;
160
+ }
161
+ escaped(i) {
162
+ const next = this.text[i + 1];
163
+ if (next !== '\n')
164
+ this.append(next ?? '\\');
165
+ return i + 2;
166
+ }
167
+ singleQuoted(i) {
168
+ const close = this.text.indexOf("'", i + 1);
169
+ const end = close === -1 ? this.text.length : close;
170
+ this.append(this.text.slice(i + 1, end));
171
+ return end + 1;
172
+ }
173
+ doubleQuoted(i) {
174
+ let j = i + 1;
175
+ this.append('');
176
+ while (j < this.text.length && this.text[j] !== '"')
177
+ j = this.doubleQuotedStep(j);
178
+ return j + 1;
179
+ }
180
+ doubleQuotedStep(j) {
181
+ const char = this.text.charAt(j);
182
+ const next = this.text.charAt(j + 1);
183
+ if (char === '\\' && next === '\n')
184
+ return j + 2;
185
+ if (char === '\\' && DOUBLE_QUOTE_ESCAPES.has(next)) {
186
+ this.append(next);
187
+ return j + 2;
188
+ }
189
+ this.append(char);
190
+ return j + 1;
191
+ }
192
+ lineEnd(i) {
193
+ const newline = this.text.indexOf('\n', i);
194
+ return newline === -1 ? this.text.length : newline;
195
+ }
196
+ /** `i` is at the first `<` or `>`. */
197
+ redirection(i) {
198
+ if (this.word !== null && RE_FD_PREFIX.test(this.word))
199
+ this.word = null;
200
+ this.endWord();
201
+ let j = i + 1;
202
+ while (this.text[j] === '>' || this.text[j] === '<')
203
+ j += 1;
204
+ if (this.text[j] !== '&') {
205
+ this.dropNext = true;
206
+ return this.text[j] === '|' ? j + 1 : j;
207
+ }
208
+ const start = j + 1;
209
+ let end = start;
210
+ while (end < this.text.length && RE_DUPLICATION_CHAR.test(this.text.charAt(end)))
211
+ end += 1;
212
+ // `>&file` names a target the way `>file` does.
213
+ this.dropNext = end === start;
214
+ return end;
215
+ }
216
+ append(text) {
217
+ this.word = (this.word ?? '') + text;
218
+ }
219
+ endWord() {
220
+ const word = this.word;
221
+ if (word === null)
222
+ return;
223
+ this.word = null;
224
+ if (this.dropNext) {
225
+ this.dropNext = false;
226
+ return;
227
+ }
228
+ this.words.push(word);
229
+ }
230
+ endSegment() {
231
+ this.endWord();
232
+ this.dropNext = false;
233
+ if (this.words.length > 0)
234
+ this.done.push(this.words);
235
+ this.words = [];
236
+ }
237
+ }
238
+ /** How many characters a segment separator at this position spans; 0 when there is none. */
239
+ function separatorLength(char, next) {
240
+ if (char === '|' || char === '&')
241
+ return next === '|' || next === '&' ? 2 : 1;
242
+ return char === ';' || char === '\n' ? 1 : 0;
243
+ }
244
+ /** The first `max` code points, so no port cuts a surrogate pair: Python's `text[:max]`. */
245
+ function clampCodePoints(text, max) {
246
+ if (text.length <= max)
247
+ return text;
248
+ return Array.from(text).slice(0, max).join('');
249
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Names the rules in `tests/fixtures/command-vectors.json`, a byte copy of
3
+ * core's `packages/fingerprint/test/command-vectors.json`. Command digests
4
+ * from different schemes never compare.
5
+ */
6
+ export declare const COMMAND_SCHEME = "agent-watch-command/1";
7
+ /**
8
+ * A check is an allowlisted command that ran this long (workflow SPEC §12.1).
9
+ * The edge decides the flag, since only it holds the duration and the command
10
+ * together; core sees the flag alone.
11
+ */
12
+ export declare const CHECK_MIN_DURATION_MS = 60000;
13
+ /** Bounds the lexer's work on hostile input; core cuts at the same code point. */
14
+ export declare const MAX_COMMAND_CODE_POINTS = 16384;
15
+ /** `npm`, `pnpm` and `yarn` scripts that are checks, alone or as `name:variant` (`test:unit`). */
16
+ export declare const CHECK_SCRIPTS: ReadonlySet<string>;
17
+ export declare const CHECK_PROGRAMS: ReadonlySet<string>;
18
+ export declare const SCRIPT_RUNNERS: ReadonlySet<string>;
19
+ /** `go test`, `cargo test`, `make test`, `make check`: the first argument decides. */
20
+ export declare const SUBCOMMAND_CHECKS: ReadonlyMap<string, ReadonlySet<string>>;
21
+ /** The `npm run` words that name a script as their next argument. */
22
+ export declare const RUN_SCRIPT_WORDS: ReadonlySet<string>;
23
+ /** Inside `"…"`, a backslash escapes only these. */
24
+ export declare const DOUBLE_QUOTE_ESCAPES: ReadonlySet<string>;
25
+ /** Shells whose `-c` / `-lc` script is the command an argv runs. */
26
+ export declare const SHELL_WRAPPERS: ReadonlySet<string>;
27
+ export declare const SHELL_SCRIPT_FLAGS: ReadonlySet<string>;
28
+ export declare const RE_ASSIGNMENT: RegExp;
29
+ export declare const RE_FD_PREFIX: RegExp;
30
+ export declare const RE_PYTHON: RegExp;
31
+ /** What may follow `>&` in a duplication (`2>&1`, `>&-`). */
32
+ export declare const RE_DUPLICATION_CHAR: RegExp;
33
+ /** A script's `:variant` suffix (`test:unit`). */
34
+ export declare const RE_SCRIPT_VARIANT: RegExp;