@octopi-agent/engine 0.86.38 → 0.90.11

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 (83) hide show
  1. package/dist/config-schema/agent.js +12 -5
  2. package/dist/config-schema/context.d.ts +1 -1
  3. package/dist/config-schema/engine.d.ts +4 -4
  4. package/dist/config-schema/governance.js +3 -2
  5. package/dist/config-schema/models.d.ts +2 -2
  6. package/dist/config-schema/shared.d.ts +3 -0
  7. package/dist/config-schema/shared.js +12 -0
  8. package/dist/config-schema/substrate.d.ts +1 -1
  9. package/dist/config.d.ts +31 -9
  10. package/dist/config.js +66 -74
  11. package/dist/harness/agent/builder.d.ts +3 -2
  12. package/dist/harness/agent/builder.js +11 -7
  13. package/dist/harness/agent/config-bridge.js +4 -1
  14. package/dist/harness/agent/tool-purpose.d.ts +9 -1
  15. package/dist/harness/agent/tool-purpose.js +11 -2
  16. package/dist/harness/agent/wire-agent-builder.js +9 -2
  17. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.d.ts +11 -1
  18. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +11 -1
  19. package/dist/harness/collaboration/autonomous-subsystem/loader.d.ts +13 -0
  20. package/dist/harness/collaboration/autonomous-subsystem/loader.js +16 -1
  21. package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +4 -0
  22. package/dist/harness/collaboration/autonomous-subsystem/runtime.js +3 -1
  23. package/dist/harness/context/default-context-engine.js +4 -4
  24. package/dist/harness/context/layer-types.d.ts +36 -0
  25. package/dist/harness/context/layer-types.js +38 -0
  26. package/dist/harness/context/root-instructions.js +1 -1
  27. package/dist/harness/context/system-prompt-assembler.js +10 -4
  28. package/dist/harness/context/tool-result-aging.js +2 -2
  29. package/dist/harness/context/turn-envelope.d.ts +1 -1
  30. package/dist/harness/context/turn-envelope.js +1 -1
  31. package/dist/harness/extension/execution-environment/effect-policy.d.ts +11 -1
  32. package/dist/harness/extension/execution-environment/effect-policy.js +24 -0
  33. package/dist/harness/extension/execution-environment/index.d.ts +1 -1
  34. package/dist/harness/extension/execution-environment/index.js +1 -1
  35. package/dist/harness/extension/execution-environment/isolation.js +5 -1
  36. package/dist/harness/extension/execution-environment/sandbox.js +36 -8
  37. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.d.ts +6 -0
  38. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +17 -0
  39. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +10 -17
  40. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.d.ts +31 -0
  41. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.js +104 -0
  42. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.d.ts +111 -0
  43. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.js +197 -0
  44. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.d.ts +8 -8
  45. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +9 -100
  46. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +4 -0
  47. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  48. package/dist/harness/index.d.ts +2 -0
  49. package/dist/harness/index.js +1 -0
  50. package/dist/harness/knowledge/file-identity.d.ts +8 -0
  51. package/dist/harness/knowledge/file-identity.js +26 -1
  52. package/dist/harness/knowledge/grounding.js +5 -5
  53. package/dist/harness/knowledge/index-store.d.ts +31 -4
  54. package/dist/harness/knowledge/index-store.js +121 -39
  55. package/dist/harness/knowledge/ingest.d.ts +115 -115
  56. package/dist/harness/knowledge/ingest.js +150 -150
  57. package/dist/harness/knowledge/knowledge-serve-child.js +1 -1
  58. package/dist/harness/knowledge/purge.js +4 -1
  59. package/dist/harness/memory/backfill-coverage.js +3 -1
  60. package/dist/harness/observability/observer/hub.js +30 -1
  61. package/dist/harness/observability/observer/types.d.ts +23 -0
  62. package/dist/harness/run/runner.d.ts +16 -0
  63. package/dist/harness/run/runner.js +139 -26
  64. package/dist/harness/session/history/port.js +15 -5
  65. package/dist/harness/session/in-memory-store.d.ts +5 -0
  66. package/dist/harness/session/in-memory-store.js +33 -2
  67. package/dist/harness/session/title.js +25 -9
  68. package/dist/harness/shared/events/agent-event-map.d.ts +26 -0
  69. package/dist/harness/shared/events/agent-event-map.js +2 -0
  70. package/dist/index.d.ts +4 -2
  71. package/dist/index.js +3 -2
  72. package/dist/integration/observability/run-telemetry.d.ts +8 -0
  73. package/dist/integration/observability/run-telemetry.js +31 -8
  74. package/dist/integration/observability/trace-collector.js +26 -4
  75. package/dist/integration/observability/trace-events.d.ts +1 -0
  76. package/dist/integration/observability/trace-events.js +2 -0
  77. package/dist/integration/observability/trace-logger.js +27 -17
  78. package/dist/integration/storage/jsonl.d.ts +19 -1
  79. package/dist/integration/storage/jsonl.js +96 -3
  80. package/dist/paths.d.ts +19 -0
  81. package/dist/paths.js +38 -1
  82. package/dist/subsystems/safety-guard/config.yaml +3 -1
  83. package/package.json +2 -2
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Shared safe-git runner — the single hardened `git` execution path used by the
3
+ * git_* dedicated tools and the UI git-status snapshot.
4
+ *
5
+ * Not a shell: fixed argv allowlist (never a command string). Isolation here:
6
+ * nonexistent `core.hooksPath`, `--no-ext-diff`, command-line `-c` overrides
7
+ * (diff.external/gpg/pager/ssh), `GIT_CONFIG_GLOBAL/SYSTEM` at NUL//dev/null,
8
+ * and filter.* pinned to `cat`. Mutating callers add their own flags (e.g.
9
+ * `--no-verify`/`--no-gpg-sign` on commit, in git-tools.ts).
10
+ * User `-c`/alias flags are rejected. `--no-optional-locks` keeps polling
11
+ * readers from fighting real git operations over the index lock.
12
+ */
13
+ import type { ToolExecutionContext } from '@octopi-agent/core/types.js';
14
+ import { type AllowlistedRunResult } from './allowlisted-run.js';
15
+ export interface RunGitOptions {
16
+ timeoutMs?: number;
17
+ /** Journal write effects via shell-journal (default true for mutating tools) */
18
+ journal?: boolean;
19
+ /** Apply the tool output gate (default true). Structured consumers pass false. */
20
+ applyOutputGate?: boolean;
21
+ }
22
+ /**
23
+ * Run one fixed git argv vector through the hardened runner.
24
+ *
25
+ * @param context - tool context (optional; gates journalling/limits)
26
+ * @param cwd - repository directory (caller has resolved/contained it)
27
+ * @param args - git argv after the safety prefix
28
+ * @param options - timeout / journal / output-gate controls
29
+ * @returns capped stdout/stderr + honest isolation
30
+ */
31
+ export declare function runGit(context: ToolExecutionContext | undefined, cwd: string, args: string[], options?: RunGitOptions): Promise<AllowlistedRunResult>;
@@ -0,0 +1,104 @@
1
+ import { tmpdir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { requireExecutable, runAllowlistedArgv, } from './allowlisted-run.js';
4
+ /**
5
+ * Nonexistent hooks dir (empty core.hooksPath is version-fragile: some gits
6
+ * treat it as `./` and still run cwd hooks).
7
+ */
8
+ function noHooksDir() {
9
+ return join(tmpdir(), 'octopi-nohooks');
10
+ }
11
+ /**
12
+ * Fixed git safety prefix. Command-line `-c` outranks local `.git/config`, so
13
+ * these neutralize repo-config RCE vectors (diff.external, gpg.program, …).
14
+ * `--no-optional-locks` avoids index lock fights. Never pass user `-c`.
15
+ */
16
+ function gitSafePrefix() {
17
+ const hooks = noHooksDir();
18
+ return [
19
+ '--no-optional-locks',
20
+ '-c', `core.hooksPath=${hooks}`,
21
+ '-c', 'core.fsmonitor=',
22
+ '-c', 'core.pager=cat',
23
+ '-c', 'diff.external=',
24
+ '-c', 'diff.tool=',
25
+ '-c', 'merge.tool=',
26
+ '-c', 'merge.prompt=false',
27
+ '-c', 'gpg.program=true',
28
+ '-c', 'commit.gpgsign=false',
29
+ '-c', 'core.sshCommand=',
30
+ '-c', 'core.askpass=',
31
+ '-c', 'credential.helper=',
32
+ '-c', 'core.attributesFile=',
33
+ '-c', 'core.excludesFile=',
34
+ ];
35
+ }
36
+ /**
37
+ * Isolate global/system gitconfig. Local `.git/config` is still read; dangerous
38
+ * keys there are overridden by the `-c` prefix above (command line wins).
39
+ * On Windows use `NUL`, elsewhere `/dev/null` — a missing file is also fine.
40
+ */
41
+ function gitIsolationEnv() {
42
+ const nullPath = process.platform === 'win32' ? 'NUL' : '/dev/null';
43
+ return {
44
+ GIT_CONFIG_NOSYSTEM: '1',
45
+ GIT_CONFIG_SYSTEM: nullPath,
46
+ GIT_CONFIG_GLOBAL: nullPath,
47
+ GIT_TERMINAL_PROMPT: '0',
48
+ GIT_OPTIONAL_LOCKS: '0',
49
+ GIT_ASKPASS: '',
50
+ SSH_ASKPASS: '',
51
+ };
52
+ }
53
+ /**
54
+ * Discover filter.* drivers from repo/user config and pin them to `cat`.
55
+ * Command-line `-c` outranks local `.git/config`, so a malicious
56
+ * .gitattributes cannot run clean/smudge/process during `git add` — nor while
57
+ * `git status` re-hashes dirty stat entries through the clean filter.
58
+ */
59
+ async function filterNeutralizers(context, cwd) {
60
+ const git = requireExecutable('git');
61
+ const res = await runAllowlistedArgv({
62
+ executable: git,
63
+ args: [...gitSafePrefix(), 'config', '--name-only', '--get-regexp', '^filter\\.'],
64
+ cwd,
65
+ context,
66
+ env: gitIsolationEnv(),
67
+ journal: false,
68
+ });
69
+ if (res.exitCode !== 0)
70
+ return [];
71
+ const names = new Set();
72
+ for (const line of res.stdout.split(/\r?\n/)) {
73
+ const m = /^filter\.(.+)\.(clean|smudge|process)$/.exec(line.trim());
74
+ if (m && /^[A-Za-z0-9._-]+$/.test(m[1]))
75
+ names.add(m[1]);
76
+ }
77
+ const out = [];
78
+ for (const n of names) {
79
+ out.push('-c', `filter.${n}.clean=cat`, '-c', `filter.${n}.smudge=cat`, '-c', `filter.${n}.process=cat`);
80
+ }
81
+ return out;
82
+ }
83
+ /**
84
+ * Run one fixed git argv vector through the hardened runner.
85
+ *
86
+ * @param context - tool context (optional; gates journalling/limits)
87
+ * @param cwd - repository directory (caller has resolved/contained it)
88
+ * @param args - git argv after the safety prefix
89
+ * @param options - timeout / journal / output-gate controls
90
+ * @returns capped stdout/stderr + honest isolation
91
+ */
92
+ export async function runGit(context, cwd, args, options) {
93
+ const git = requireExecutable('git');
94
+ return runAllowlistedArgv({
95
+ executable: git,
96
+ args: [...gitSafePrefix(), ...(await filterNeutralizers(context, cwd)), ...args],
97
+ cwd,
98
+ context,
99
+ env: gitIsolationEnv(),
100
+ timeoutMs: options?.timeoutMs ?? 60_000,
101
+ journal: options?.journal ?? false,
102
+ applyOutputGate: options?.applyOutputGate,
103
+ });
104
+ }
@@ -0,0 +1,111 @@
1
+ /** How an entry is rendered/grouped in UI surfaces. */
2
+ export type GitStatusGroup = 'conflicted' | 'staged' | 'unstaged' | 'untracked';
3
+ /** Record kind behind an entry. */
4
+ export type GitStatusKind = 'changed' | 'renamed' | 'copied' | 'untracked' | 'conflicted';
5
+ /**
6
+ * One display row. A partially-staged file (`1 MM …`) yields TWO rows — one in
7
+ * `staged`, one in `unstaged` — matching `git status` section semantics; its
8
+ * x/y pair is repeated on each row so the UI can show the real codes.
9
+ */
10
+ export interface GitStatusEntry {
11
+ kind: GitStatusKind;
12
+ group: GitStatusGroup;
13
+ /** Staged status char ('.' = unchanged in the index). */
14
+ x: string;
15
+ /** Unstaged status char ('.' = unchanged in the worktree). */
16
+ y: string;
17
+ path: string;
18
+ /** Rename/copy source path (record type 2 only). */
19
+ origPath?: string;
20
+ }
21
+ /** Branch header block from `# branch.*` records. */
22
+ export interface GitStatusBranch {
23
+ /** HEAD oid; null before the first commit (`(initial)`). */
24
+ oid: string | null;
25
+ /** Branch name; null when detached (`(detached)`). */
26
+ head: string | null;
27
+ detached: boolean;
28
+ /** True when the repo has no commits yet. */
29
+ initial: boolean;
30
+ /** Upstream ref name; null when no upstream is configured. */
31
+ upstream: string | null;
32
+ /** Commits ahead of upstream; null without upstream. */
33
+ ahead: number | null;
34
+ /** Commits behind upstream; null without upstream. */
35
+ behind: number | null;
36
+ }
37
+ /** Full-precision counts (computed over all rows, not just returned entries). */
38
+ export interface GitStatusCounts {
39
+ conflicted: number;
40
+ staged: number;
41
+ unstaged: number;
42
+ untracked: number;
43
+ }
44
+ /** Parsed body of a status snapshot (no repo resolution). */
45
+ export interface GitStatusSnapshotBody {
46
+ /** null when the stream carried no `# branch.*` headers at all. */
47
+ branch: GitStatusBranch | null;
48
+ counts: GitStatusCounts;
49
+ entries: GitStatusEntry[];
50
+ /** True when entries were capped by maxEntries; counts stay full. */
51
+ truncated: boolean;
52
+ /** Records that matched a known type but failed to parse (format drift). */
53
+ skippedRecords: number;
54
+ }
55
+ /** Full snapshot for one directory. */
56
+ export interface GitStatusSnapshot extends GitStatusSnapshotBody {
57
+ /** False when the directory is not inside any git work tree. */
58
+ isRepo: boolean;
59
+ /** Work-tree top level (`git rev-parse --show-toplevel`); null when not a repo. */
60
+ repoRoot: string | null;
61
+ /** ISO timestamp taken after the status read completed. */
62
+ generatedAt: string;
63
+ }
64
+ export interface GitStatusSnapshotOptions {
65
+ /** Max entries returned (counts stay full). Default 500. */
66
+ maxEntries?: number;
67
+ /**
68
+ * Untracked granularity. 'normal' (default) collapses untracked directories,
69
+ * 'all' lists every untracked file (parity with the git_status tool).
70
+ */
71
+ untracked?: 'normal' | 'all';
72
+ /**
73
+ * Hard-jail demand (untrusted parity with the git_* tools): a jail backend is
74
+ * always used when available — this flag turns jail-setup failure into a hard
75
+ * error instead of the supervised fallback (fail-open → fail-closed). Derive
76
+ * it via effect-policy's `requiresJail(resolvedPolicy)`.
77
+ */
78
+ requireJail?: boolean;
79
+ /**
80
+ * Roots visible inside the process jail (`context.pathRoots`). A jailed read
81
+ * only sees `cwd` without them — on bwrap (namespace binds listed roots only)
82
+ * a repo whose `.git` sits above `cwd` would silently look like isRepo:false.
83
+ * Pass the caller's allow-root set (the fence set).
84
+ */
85
+ jailRoots?: string[];
86
+ }
87
+ /**
88
+ * Parse `git status --porcelain=v2 -z [--branch]` output.
89
+ *
90
+ * Record grammar (NUL-separated): `# key value` headers; `1 XY sub mH mI mW hH
91
+ * hI path`; `2 XY sub mH mI mW hH hI Xscore path` + separate origPath field;
92
+ * `u XY sub m1 m2 m3 mW h1 h2 h3 path`; `? path`; `! path` (skipped — we never
93
+ * pass --ignored). Paths are raw bytes decoded as UTF-8; no quoting in -z mode.
94
+ *
95
+ * @param raw - NUL-separated porcelain v2 stream
96
+ * @param options - maxEntries / untracked granularity (untracked only affects readers)
97
+ * @returns branch block (null without headers), full counts, capped entries,
98
+ * skippedRecords for known-type records that failed to parse
99
+ */
100
+ export declare function parsePorcelainV2(raw: string, options?: GitStatusSnapshotOptions): GitStatusSnapshotBody;
101
+ /**
102
+ * Read a structured git status snapshot for `cwd`.
103
+ *
104
+ * @param cwd - repository (or subdirectory) path; caller has contained it
105
+ * @param options - maxEntries / untracked granularity
106
+ * @returns isRepo=false when cwd is not inside a git work tree (a state, not an
107
+ * error); throws `git_status_failed: …` on real git failures, on
108
+ * output-cap kills (never partial-as-success), and `git_not_found: …`
109
+ * when git is not on PATH
110
+ */
111
+ export declare function readGitStatusSnapshot(cwd: string, options?: GitStatusSnapshotOptions): Promise<GitStatusSnapshot>;
@@ -0,0 +1,197 @@
1
+ import { runGit } from './git-runner.js';
2
+ const DEFAULT_MAX_ENTRIES = 500;
3
+ const EMPTY_COUNTS = () => ({
4
+ conflicted: 0,
5
+ staged: 0,
6
+ unstaged: 0,
7
+ untracked: 0,
8
+ });
9
+ /** Group render order: conflicts first, then staged, unstaged, untracked. */
10
+ const GROUP_RANK = {
11
+ conflicted: 0,
12
+ staged: 1,
13
+ unstaged: 2,
14
+ untracked: 3,
15
+ };
16
+ /**
17
+ * Parse `git status --porcelain=v2 -z [--branch]` output.
18
+ *
19
+ * Record grammar (NUL-separated): `# key value` headers; `1 XY sub mH mI mW hH
20
+ * hI path`; `2 XY sub mH mI mW hH hI Xscore path` + separate origPath field;
21
+ * `u XY sub m1 m2 m3 mW h1 h2 h3 path`; `? path`; `! path` (skipped — we never
22
+ * pass --ignored). Paths are raw bytes decoded as UTF-8; no quoting in -z mode.
23
+ *
24
+ * @param raw - NUL-separated porcelain v2 stream
25
+ * @param options - maxEntries / untracked granularity (untracked only affects readers)
26
+ * @returns branch block (null without headers), full counts, capped entries,
27
+ * skippedRecords for known-type records that failed to parse
28
+ */
29
+ export function parsePorcelainV2(raw, options) {
30
+ const maxEntries = Math.max(1, options?.maxEntries ?? DEFAULT_MAX_ENTRIES);
31
+ const branch = {
32
+ oid: null,
33
+ head: null,
34
+ detached: false,
35
+ initial: false,
36
+ upstream: null,
37
+ ahead: null,
38
+ behind: null,
39
+ };
40
+ let sawBranchHeader = false;
41
+ let skippedRecords = 0;
42
+ const rows = [];
43
+ const counts = EMPTY_COUNTS();
44
+ const pushRow = (entry, idx) => {
45
+ counts[entry.group] += 1;
46
+ rows.push({ entry, idx });
47
+ };
48
+ const tokens = raw.split('\0');
49
+ for (let i = 0; i < tokens.length; i += 1) {
50
+ const tok = tokens[i];
51
+ if (!tok)
52
+ continue;
53
+ if (tok.startsWith('# ')) {
54
+ sawBranchHeader = true;
55
+ const rest = tok.slice(2);
56
+ if (rest.startsWith('branch.oid ')) {
57
+ const v = rest.slice('branch.oid '.length);
58
+ branch.initial = v === '(initial)';
59
+ branch.oid = branch.initial ? null : v;
60
+ }
61
+ else if (rest.startsWith('branch.head ')) {
62
+ const v = rest.slice('branch.head '.length);
63
+ branch.detached = v === '(detached)';
64
+ branch.head = branch.detached ? null : v;
65
+ }
66
+ else if (rest.startsWith('branch.upstream ')) {
67
+ branch.upstream = rest.slice('branch.upstream '.length);
68
+ }
69
+ else if (rest.startsWith('branch.ab ')) {
70
+ const m = /^\+(-?\d+) -(-?\d+)$/.exec(rest.slice('branch.ab '.length));
71
+ if (m) {
72
+ branch.ahead = Number(m[1]);
73
+ branch.behind = Number(m[2]);
74
+ }
75
+ }
76
+ continue;
77
+ }
78
+ const kindCh = tok[0];
79
+ if (kindCh === '1') {
80
+ const m = /^1 (\S)(\S) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) ([\s\S]*)$/.exec(tok);
81
+ if (!m) {
82
+ skippedRecords += 1;
83
+ continue;
84
+ }
85
+ const base = { kind: 'changed', x: m[1], y: m[2], path: m[9] };
86
+ if (base.x !== '.')
87
+ pushRow({ ...base, group: 'staged' }, i);
88
+ if (base.y !== '.' || base.x === '.')
89
+ pushRow({ ...base, group: 'unstaged' }, i);
90
+ }
91
+ else if (kindCh === '2') {
92
+ const m = /^2 (\S)(\S) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) ([A-Z][0-9]*) ([\s\S]*)$/.exec(tok);
93
+ if (!m) {
94
+ skippedRecords += 1;
95
+ continue;
96
+ }
97
+ const origPath = tokens[i + 1] ?? '';
98
+ if (origPath)
99
+ i += 1;
100
+ const base = {
101
+ kind: (m[9].startsWith('R') ? 'renamed' : 'copied'),
102
+ x: m[1],
103
+ y: m[2],
104
+ path: m[10],
105
+ ...(origPath ? { origPath } : {}),
106
+ };
107
+ if (base.x !== '.')
108
+ pushRow({ ...base, group: 'staged' }, i);
109
+ if (base.y !== '.' || base.x === '.')
110
+ pushRow({ ...base, group: 'unstaged' }, i);
111
+ }
112
+ else if (kindCh === 'u') {
113
+ // u <XY> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path> — sub + 7 modes/hashes
114
+ const m = /^u (\S)(\S) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) ([\s\S]*)$/.exec(tok);
115
+ if (!m) {
116
+ skippedRecords += 1;
117
+ continue;
118
+ }
119
+ pushRow({ kind: 'conflicted', group: 'conflicted', x: m[1], y: m[2], path: m[11] }, i);
120
+ }
121
+ else if (kindCh === '?') {
122
+ pushRow({ kind: 'untracked', group: 'untracked', x: '?', y: '?', path: tok.slice(2) }, i);
123
+ }
124
+ else if (kindCh !== '!') {
125
+ // Unknown record type: count it so format drift never looks like "clean".
126
+ skippedRecords += 1;
127
+ }
128
+ // '!' (ignored) records are skipped by design: readers never pass --ignored.
129
+ }
130
+ // Stable group order (conflicted → staged → unstaged → untracked); git's own
131
+ // path order is preserved inside a group.
132
+ const sorted = rows
133
+ .sort((a, b) => GROUP_RANK[a.entry.group] - GROUP_RANK[b.entry.group] || a.idx - b.idx)
134
+ .map((s) => s.entry);
135
+ return {
136
+ branch: sawBranchHeader ? branch : null,
137
+ counts,
138
+ entries: sorted.slice(0, maxEntries),
139
+ truncated: sorted.length > maxEntries,
140
+ skippedRecords,
141
+ };
142
+ }
143
+ /**
144
+ * Read a structured git status snapshot for `cwd`.
145
+ *
146
+ * @param cwd - repository (or subdirectory) path; caller has contained it
147
+ * @param options - maxEntries / untracked granularity
148
+ * @returns isRepo=false when cwd is not inside a git work tree (a state, not an
149
+ * error); throws `git_status_failed: …` on real git failures, on
150
+ * output-cap kills (never partial-as-success), and `git_not_found: …`
151
+ * when git is not on PATH
152
+ */
153
+ export async function readGitStatusSnapshot(cwd, options) {
154
+ const untracked = options?.untracked ?? 'normal';
155
+ // 最小上下文:只带 jail 诉求与 jail 根(快照本就 context-free——journal=false、
156
+ // 网络默认 deny)。pathRoots 决定 jail 内可见根(allowRoots = [cwd, ...pathRoots])。
157
+ const context = options?.requireJail || options?.jailRoots?.length
158
+ ? {
159
+ ...(options?.requireJail ? { requireJail: true } : {}),
160
+ ...(options?.jailRoots?.length ? { pathRoots: options.jailRoots } : {}),
161
+ }
162
+ : undefined;
163
+ const top = await runGit(context, cwd, ['rev-parse', '--show-toplevel'], {
164
+ journal: false,
165
+ applyOutputGate: false,
166
+ timeoutMs: 15_000,
167
+ });
168
+ if (top.exitCode !== 0) {
169
+ if (/not a git repository/i.test(top.stderr)) {
170
+ return {
171
+ isRepo: false,
172
+ repoRoot: null,
173
+ branch: null,
174
+ counts: EMPTY_COUNTS(),
175
+ entries: [],
176
+ truncated: false,
177
+ skippedRecords: 0,
178
+ generatedAt: new Date().toISOString(),
179
+ };
180
+ }
181
+ throw new Error(`git_status_failed: ${top.stderr.trim().slice(0, 200) || `rev-parse exited ${top.exitCode}`}`);
182
+ }
183
+ const st = await runGit(context, cwd, ['status', '--porcelain=v2', '-z', '--branch', `--untracked-files=${untracked}`], { journal: false, applyOutputGate: false, timeoutMs: 30_000 });
184
+ // A killed/truncated stream would parse as a partial record set — surface it
185
+ // as a failure instead of a plausible-looking clean/partial status.
186
+ if (st.exitCode !== 0 || st.truncated || st.terminated) {
187
+ throw new Error(`git_status_failed: ${st.terminateReason ??
188
+ st.stderr.trim().slice(0, 200) ??
189
+ `status exited ${st.exitCode}`}`);
190
+ }
191
+ return {
192
+ isRepo: true,
193
+ repoRoot: top.stdout.trim(),
194
+ ...parsePorcelainV2(st.stdout, options),
195
+ generatedAt: new Date().toISOString(),
196
+ };
197
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * git_* dedicated tools 鈥?local VCS porcelain without a shell.
2
+ * git_* dedicated tools — local VCS porcelain without a shell.
3
3
  *
4
4
  * Spawn `git` with a fixed argv allowlist (never a command string). Isolation:
5
5
  * nonexistent `core.hooksPath`, `--no-verify`/`--no-gpg-sign` on commit,
@@ -9,19 +9,19 @@
9
9
  * workspace/untrusted agents can still status/diff/commit without `shell`.
10
10
  */
11
11
  import type { RegisteredTool } from '@octopi-agent/core/types.js';
12
- /** git_status 鈥?porcelain working tree status */
12
+ /** git_status — porcelain working tree status */
13
13
  export declare function createGitStatusTool(): RegisteredTool;
14
- /** git_diff 鈥?unstaged / staged / vs-ref diff */
14
+ /** git_diff — unstaged / staged / vs-ref diff */
15
15
  export declare function createGitDiffTool(): RegisteredTool;
16
- /** git_log 鈥?commit history */
16
+ /** git_log — commit history */
17
17
  export declare function createGitLogTool(): RegisteredTool;
18
- /** git_show 鈥?show a commit / tree / blob */
18
+ /** git_show — show a commit / tree / blob */
19
19
  export declare function createGitShowTool(): RegisteredTool;
20
- /** git_commit 鈥?add paths + commit (hooks disabled) */
20
+ /** git_commit — add paths + commit (hooks disabled) */
21
21
  export declare function createGitCommitTool(): RegisteredTool;
22
- /** git_branch 鈥?list / create / switch / delete */
22
+ /** git_branch — list / create / switch / delete */
23
23
  export declare function createGitBranchTool(): RegisteredTool;
24
- /** git_restore 鈥?restore working tree / index paths */
24
+ /** git_restore — restore working tree / index paths */
25
25
  export declare function createGitRestoreTool(): RegisteredTool;
26
26
  /** All git_* tools (read + write). */
27
27
  export declare function createGitTools(): RegisteredTool[];
@@ -1,58 +1,8 @@
1
1
  import { gateEffect } from '../../execution-environment/effect-policy.js';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
2
  import { resolveToolPath, isUnderAttachmentRoot, isUnderSessionUndoRoot } from './platform.js';
5
3
  import { detectEol, toEol } from './eol.js';
6
- import { assertSafeRef, requireExecutable, runAllowlistedArgv, } from './allowlisted-run.js';
7
- /**
8
- * Nonexistent hooks dir (empty core.hooksPath is version-fragile: some gits
9
- * treat it as `./` and still run cwd hooks).
10
- */
11
- function noHooksDir() {
12
- return join(tmpdir(), 'octopi-nohooks');
13
- }
14
- /**
15
- * Fixed git safety prefix. Command-line `-c` outranks local `.git/config`, so
16
- * these neutralize repo-config RCE vectors (diff.external, gpg.program, …).
17
- * `--no-optional-locks` avoids index lock fights. Never pass user `-c`.
18
- */
19
- function gitSafePrefix() {
20
- const hooks = noHooksDir();
21
- return [
22
- '--no-optional-locks',
23
- '-c', `core.hooksPath=${hooks}`,
24
- '-c', 'core.fsmonitor=',
25
- '-c', 'core.pager=cat',
26
- '-c', 'diff.external=',
27
- '-c', 'diff.tool=',
28
- '-c', 'merge.tool=',
29
- '-c', 'merge.prompt=false',
30
- '-c', 'gpg.program=true',
31
- '-c', 'commit.gpgsign=false',
32
- '-c', 'core.sshCommand=',
33
- '-c', 'core.askpass=',
34
- '-c', 'credential.helper=',
35
- '-c', 'core.attributesFile=',
36
- '-c', 'core.excludesFile=',
37
- ];
38
- }
39
- /**
40
- * Isolate global/system gitconfig. Local `.git/config` is still read; dangerous
41
- * keys there are overridden by the `-c` prefix above (command line wins).
42
- * On Windows use `NUL`, elsewhere `/dev/null` — a missing file is also fine.
43
- */
44
- function gitIsolationEnv() {
45
- const nullPath = process.platform === 'win32' ? 'NUL' : '/dev/null';
46
- return {
47
- GIT_CONFIG_NOSYSTEM: '1',
48
- GIT_CONFIG_SYSTEM: nullPath,
49
- GIT_CONFIG_GLOBAL: nullPath,
50
- GIT_TERMINAL_PROMPT: '0',
51
- GIT_OPTIONAL_LOCKS: '0',
52
- GIT_ASKPASS: '',
53
- SSH_ASKPASS: '',
54
- };
55
- }
4
+ import { assertSafeRef } from './allowlisted-run.js';
5
+ import { runGit } from './git-runner.js';
56
6
  function resolveCwd(context, raw) {
57
7
  const cwd = raw ?? context?.cwd ?? process.cwd();
58
8
  const abs = resolveToolPath(cwd, context?.cwd, {
@@ -106,47 +56,6 @@ function toGitPathspec(raw, context, label) {
106
56
  }
107
57
  return raw;
108
58
  }
109
- /**
110
- * Discover filter.* drivers from repo/user config and pin them to `cat`.
111
- * Command-line `-c` outranks local `.git/config`, so a malicious
112
- * .gitattributes cannot run clean/smudge/process during `git add`.
113
- */
114
- async function filterNeutralizers(context, cwd) {
115
- const git = requireExecutable('git');
116
- const res = await runAllowlistedArgv({
117
- executable: git,
118
- args: [...gitSafePrefix(), 'config', '--name-only', '--get-regexp', '^filter\\.'],
119
- cwd,
120
- context,
121
- env: gitIsolationEnv(),
122
- journal: false,
123
- });
124
- if (res.exitCode !== 0)
125
- return [];
126
- const names = new Set();
127
- for (const line of res.stdout.split(/\r?\n/)) {
128
- const m = /^filter\.(.+)\.(clean|smudge|process)$/.exec(line.trim());
129
- if (m && /^[A-Za-z0-9._-]+$/.test(m[1]))
130
- names.add(m[1]);
131
- }
132
- const out = [];
133
- for (const n of names) {
134
- out.push('-c', `filter.${n}.clean=cat`, '-c', `filter.${n}.smudge=cat`, '-c', `filter.${n}.process=cat`);
135
- }
136
- return out;
137
- }
138
- async function runGit(context, cwd, args, options) {
139
- const git = requireExecutable('git');
140
- return runAllowlistedArgv({
141
- executable: git,
142
- args: [...gitSafePrefix(), ...(await filterNeutralizers(context, cwd)), ...args],
143
- cwd,
144
- context,
145
- env: gitIsolationEnv(),
146
- timeoutMs: options?.timeoutMs ?? 60_000,
147
- journal: options?.journal ?? false,
148
- });
149
- }
150
59
  function toText(result) {
151
60
  return {
152
61
  stdout: result.stdout,
@@ -159,7 +68,7 @@ function toText(result) {
159
68
  isolation: result.isolation,
160
69
  };
161
70
  }
162
- /** git_status 鈥?porcelain working tree status */
71
+ /** git_status — porcelain working tree status */
163
72
  export function createGitStatusTool() {
164
73
  return {
165
74
  definition: {
@@ -190,7 +99,7 @@ export function createGitStatusTool() {
190
99
  },
191
100
  };
192
101
  }
193
- /** git_diff 鈥?unstaged / staged / vs-ref diff */
102
+ /** git_diff — unstaged / staged / vs-ref diff */
194
103
  export function createGitDiffTool() {
195
104
  return {
196
105
  definition: {
@@ -242,7 +151,7 @@ export function createGitDiffTool() {
242
151
  },
243
152
  };
244
153
  }
245
- /** git_log 鈥?commit history */
154
+ /** git_log — commit history */
246
155
  export function createGitLogTool() {
247
156
  return {
248
157
  definition: {
@@ -285,7 +194,7 @@ export function createGitLogTool() {
285
194
  },
286
195
  };
287
196
  }
288
- /** git_show 鈥?show a commit / tree / blob */
197
+ /** git_show — show a commit / tree / blob */
289
198
  export function createGitShowTool() {
290
199
  return {
291
200
  definition: {
@@ -310,7 +219,7 @@ export function createGitShowTool() {
310
219
  },
311
220
  };
312
221
  }
313
- /** git_commit 鈥?add paths + commit (hooks disabled) */
222
+ /** git_commit — add paths + commit (hooks disabled) */
314
223
  export function createGitCommitTool() {
315
224
  return {
316
225
  definition: {
@@ -415,7 +324,7 @@ export function createGitCommitTool() {
415
324
  },
416
325
  };
417
326
  }
418
- /** git_branch 鈥?list / create / switch / delete */
327
+ /** git_branch — list / create / switch / delete */
419
328
  export function createGitBranchTool() {
420
329
  return {
421
330
  definition: {
@@ -482,7 +391,7 @@ export function createGitBranchTool() {
482
391
  },
483
392
  };
484
393
  }
485
- /** git_restore 鈥?restore working tree / index paths */
394
+ /** git_restore — restore working tree / index paths */
486
395
  export function createGitRestoreTool() {
487
396
  return {
488
397
  definition: {
@@ -1,5 +1,9 @@
1
1
  export { getBuiltinTools } from './builtin.js';
2
2
  export { createGitTools } from './git-tools.js';
3
+ export { runGit } from './git-runner.js';
4
+ export type { RunGitOptions } from './git-runner.js';
5
+ export { readGitStatusSnapshot, parsePorcelainV2 } from './git-status-snapshot.js';
6
+ export type { GitStatusSnapshot, GitStatusSnapshotBody, GitStatusSnapshotOptions, GitStatusEntry, GitStatusBranch, GitStatusCounts, GitStatusGroup, GitStatusKind, } from './git-status-snapshot.js';
3
7
  export { createPackageTools } from './package-tools.js';
4
8
  export { createDocumentReadTool, createDocumentProbeTool } from './document-tools.js';
5
9
  export { createFileEditTool } from './file-edit.js';
@@ -1,5 +1,7 @@
1
1
  export { getBuiltinTools } from './builtin.js';
2
2
  export { createGitTools } from './git-tools.js';
3
+ export { runGit } from './git-runner.js';
4
+ export { readGitStatusSnapshot, parsePorcelainV2 } from './git-status-snapshot.js';
3
5
  export { createPackageTools } from './package-tools.js';
4
6
  export { createDocumentReadTool, createDocumentProbeTool } from './document-tools.js';
5
7
  export { createFileEditTool } from './file-edit.js';
@@ -58,6 +58,8 @@ export { validateManifest, parseManifest } from './extension/plugin-ecosystem/pl
58
58
  export type { PluginManifest, PluginContracts, ActivationConfig } from './extension/plugin-ecosystem/plugins/manifest.js';
59
59
  export { DefaultToolBus } from './extension/plugin-ecosystem/tools/tool-bus.js';
60
60
  export { getBuiltinTools, createShellTool, createFileReadTool, createFileWriteTool, createFileDeleteTool, createFileListTool } from './extension/plugin-ecosystem/tools/builtin.js';
61
+ export { readGitStatusSnapshot, parsePorcelainV2 } from './extension/plugin-ecosystem/tools/git-status-snapshot.js';
62
+ export type { GitStatusSnapshot, GitStatusSnapshotBody, GitStatusSnapshotOptions, GitStatusEntry, GitStatusBranch, GitStatusCounts, GitStatusGroup, GitStatusKind, } from './extension/plugin-ecosystem/tools/git-status-snapshot.js';
61
63
  export { DefaultSkillManager, FileSystemSkillSource } from './extension/plugin-ecosystem/skills/manager.js';
62
64
  export type { SkillSource, DiscoveredSkill } from './extension/plugin-ecosystem/skills/manager.js';
63
65
  export type { SkillDefinition, SkillManager } from './extension/plugin-ecosystem/skills/types.js';