@octopi-agent/engine 0.97.15 → 0.98.4

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 (100) hide show
  1. package/dist/config-schema/agent.d.ts +2 -0
  2. package/dist/config-schema/engine.d.ts +4 -0
  3. package/dist/config-schema/governance.d.ts +2 -0
  4. package/dist/config-schema/governance.js +30 -0
  5. package/dist/harness/agent/builder.d.ts +11 -0
  6. package/dist/harness/agent/builder.js +59 -32
  7. package/dist/harness/agent/config-integrity.d.ts +66 -0
  8. package/dist/harness/agent/config-integrity.js +89 -0
  9. package/dist/harness/agent/wire-agent-builder.js +5 -0
  10. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  11. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  12. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  13. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  14. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  15. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  16. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  17. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  18. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  19. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  20. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  21. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  22. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  23. package/dist/harness/context/layers.d.ts +2 -4
  24. package/dist/harness/context/layers.js +9 -11
  25. package/dist/harness/context/summarize.d.ts +1 -1
  26. package/dist/harness/context/summarize.js +2 -2
  27. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  28. package/dist/harness/context/system-prompt-assembler.js +1 -0
  29. package/dist/harness/extension/execution-environment/effect-policy.d.ts +24 -2
  30. package/dist/harness/extension/execution-environment/effect-policy.js +30 -0
  31. package/dist/harness/extension/execution-environment/ops-audit.d.ts +6 -2
  32. package/dist/harness/extension/execution-environment/ops-audit.js +11 -12
  33. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  34. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  35. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +17 -24
  36. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  37. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  38. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  39. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  40. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  41. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  42. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  43. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  44. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  45. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  46. package/dist/harness/governance/security/default-security-guard.js +9 -0
  47. package/dist/harness/governance/security/index.d.ts +1 -0
  48. package/dist/harness/governance/security/index.js +2 -0
  49. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  50. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  51. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  52. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  53. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  54. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  55. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  56. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  57. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  58. package/dist/harness/governance/security/shell-parser.js +37 -496
  59. package/dist/harness/governance/security/vendor/README.md +24 -0
  60. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  61. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  62. package/dist/harness/memory/index.d.ts +6 -2
  63. package/dist/harness/memory/index.js +4 -1
  64. package/dist/harness/memory/memory-events.d.ts +25 -0
  65. package/dist/harness/memory/memory-events.js +38 -0
  66. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  67. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  68. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  69. package/dist/harness/memory/steward-policy.d.ts +3 -0
  70. package/dist/harness/memory/steward-policy.js +1 -1
  71. package/dist/harness/memory/types.d.ts +41 -3
  72. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  73. package/dist/harness/memory/wisdom-attribution.js +287 -0
  74. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  75. package/dist/harness/memory/wisdom-events.js +61 -0
  76. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  77. package/dist/harness/memory/wisdom-formation.js +55 -21
  78. package/dist/harness/memory/wisdom.d.ts +7 -2
  79. package/dist/harness/memory/wisdom.js +40 -2
  80. package/dist/harness/run/run-scope.d.ts +4 -0
  81. package/dist/harness/run/runner.d.ts +27 -2
  82. package/dist/harness/run/runner.js +48 -4
  83. package/dist/harness/shared/paths/glob.d.ts +52 -0
  84. package/dist/harness/shared/paths/glob.js +218 -0
  85. package/dist/harness/shared/paths/index.d.ts +84 -0
  86. package/dist/harness/shared/paths/index.js +179 -0
  87. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  88. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  89. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  90. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  91. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  92. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  93. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  94. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  95. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  96. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  97. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  98. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  99. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  100. package/package.json +7 -2
@@ -5,50 +5,146 @@
5
5
  * 或硬编码 `/bin/bash` 导致 Windows 行为分裂。
6
6
  */
7
7
  import { accessSync, constants, existsSync, statSync } from 'node:fs';
8
- import { delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
8
+ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
+ import { isPathUnderRoots, lexicalUnderRoots, realpathAllowMissing, } from '../../../shared/paths/index.js';
10
+ import { matchesDenyPattern } from '../../../shared/paths/glob.js';
11
+ export { isPathUnderRoots };
12
+ /**
13
+ * Build containment options from a tool context.
14
+ *
15
+ * Every tool used to spell these fields out by hand, which is how a newly added
16
+ * policy field gets silently dropped (the same failure that hid
17
+ * `refuseFinalSymlink` from the tool surface). One constructor, one place to add
18
+ * the next field.
19
+ *
20
+ * @param context - tool execution context
21
+ * @returns options for {@link resolveToolPath}
22
+ */
23
+ export function containmentOptions(context) {
24
+ return {
25
+ allowRoots: context?.pathRoots,
26
+ containment: context?.pathContainment,
27
+ denyPatterns: context?.pathDenylist,
28
+ };
29
+ }
30
+ /**
31
+ * Apply L2 path containment against real (symlink-resolved) paths.
32
+ *
33
+ * Both sides are resolved: comparing a resolved target against an unresolved
34
+ * root would deny legitimate paths whenever the root is itself an alias
35
+ * (macOS `/var` → `/private/var`). The resolved target is returned so callers
36
+ * act on the same path that was checked; otherwise a link swapped between the
37
+ * check and the following fs call would still escape.
38
+ *
39
+ * @param absPath - absolute, lexically normalized candidate
40
+ * @param rawPath - original caller-supplied path, for error messages
41
+ * @param options - containment level and allowed roots
42
+ * @returns path to operate on
43
+ */
44
+ function containPath(absPath, rawPath, options) {
45
+ const containment = options?.containment ?? 'none';
46
+ const denyPatterns = options?.denyPatterns ?? [];
47
+ const roots = options?.allowRoots ?? [];
48
+ // The denylist is an independent deny layer: if a deployment declares these
49
+ // patterns forbidden, they are forbidden at every containment level. The
50
+ // lexical spelling is checked first because it needs no syscalls.
51
+ if (denyPatterns.length > 0) {
52
+ denyPath(absPath, rawPath, options, denyPatterns);
53
+ }
54
+ // `none` stays syscall-free unless a denylist is declared: then the resolved
55
+ // target must be checked too, or an innocuously named link reads a denied file.
56
+ if (containment === 'none') {
57
+ if (denyPatterns.length > 0)
58
+ denyResolvedTarget(absPath, rawPath, options, denyPatterns);
59
+ return absPath;
60
+ }
61
+ if (roots.length === 0) {
62
+ // strict 无 root = fail-closed(与 isPathAllowed 一致);soft 仅审计
63
+ if (containment === 'strict') {
64
+ throw new Error(`path_forbidden: "${rawPath}" effect roots not configured`);
65
+ }
66
+ if (denyPatterns.length > 0)
67
+ denyResolvedTarget(absPath, rawPath, options, denyPatterns);
68
+ return absPath;
69
+ }
70
+ const realRoots = roots
71
+ .map((root) => realpathAllowMissing(resolve(root)))
72
+ .filter((root) => root !== null);
73
+ const realTarget = realpathAllowMissing(absPath);
74
+ // Re-check the resolved path *before* the root verdict: the caller's spelling
75
+ // may be innocuous while the link target is denied, and that must also hold for
76
+ // paths that end up escaping the roots (soft mode passes those through).
77
+ if (denyPatterns.length > 0 && realTarget !== null && realTarget !== absPath) {
78
+ denyPath(realTarget, rawPath, options, denyPatterns);
79
+ }
80
+ // An unresolvable target or a set of vanished roots is a denial, not a pass.
81
+ // Both sides are already real here, so compare them lexically: re-resolving
82
+ // them would only repeat the syscalls.
83
+ if (realTarget === null || realRoots.length === 0 || !lexicalUnderRoots(realTarget, realRoots)) {
84
+ if (containment === 'strict') {
85
+ throw new Error(`path_forbidden: "${rawPath}" escapes effect roots`);
86
+ }
87
+ // soft:放行(审计由调用方/Observer 负责),保留词法答案以免改变既有语义
88
+ return absPath;
89
+ }
90
+ return realTarget;
91
+ }
92
+ /**
93
+ * Apply the denylist to the symlink-resolved target of a path.
94
+ *
95
+ * Only the resolved spelling is tested: the lexical one was already checked by
96
+ * the caller, and this exists for the "harmless name → denied target" case.
97
+ *
98
+ * @param absPath - absolute, lexically normalized candidate
99
+ * @param rawPath - caller spelling, for the error message
100
+ * @param options - containment options (roots)
101
+ * @param denyPatterns - denylist globs
102
+ */
103
+ function denyResolvedTarget(absPath, rawPath, options, denyPatterns) {
104
+ const realTarget = realpathAllowMissing(absPath);
105
+ if (realTarget !== null && realTarget !== absPath)
106
+ denyPath(realTarget, rawPath, options, denyPatterns);
107
+ }
108
+ /**
109
+ * Throw when the path matches the denylist.
110
+ *
111
+ * Matching happens against the path relative to the containing root, so a
112
+ * pattern like `.git/**` means "inside a root", not "anywhere on the host".
113
+ * When no root contains it the absolute path is used, which still catches
114
+ * name-based patterns such as `*.pem`.
115
+ *
116
+ * @param absPath - absolute path to test
117
+ * @param rawPath - caller spelling, for the error message
118
+ * @param options - containment options (roots)
119
+ * @param denyPatterns - denylist globs
120
+ */
121
+ function denyPath(absPath, rawPath, options, denyPatterns) {
122
+ const roots = options?.allowRoots ?? [];
123
+ const candidates = [];
124
+ for (const root of roots) {
125
+ const realRoot = realpathAllowMissing(resolve(root)) ?? resolve(root);
126
+ if (lexicalUnderRoots(absPath, [realRoot])) {
127
+ candidates.push(relative(realRoot, absPath).split(sep).join('/'));
128
+ }
129
+ }
130
+ candidates.push(absPath.split(sep).join('/'));
131
+ if (candidates.some((candidate) => matchesDenyPattern(candidate, denyPatterns))) {
132
+ throw new Error(`path_forbidden: "${rawPath}" matches pathDenylist`);
133
+ }
134
+ }
9
135
  /**
10
136
  * 解析工具入参路径:绝对路径原样返回,相对路径相对 cwd
11
137
  *
12
138
  * 使用 path.isAbsolute,同时覆盖 POSIX /foo、Windows 盘符与 UNC。
13
139
  *
14
140
  * @param rawPath - 工具入参路径
15
- * @param cwd - 工作目录;缺省为 process.cwd()
141
+ * @param cwd - 工具 cwd;缺省为 process.cwd()
16
142
  * @param options - L2 路径包含(ToolEffectPolicy)
17
- * @returns 规范化后的绝对路径
143
+ * @returns 规范化后的绝对路径;containment 生效时为符号链接解析后的真实路径
18
144
  */
19
145
  export function resolveToolPath(rawPath, cwd, options) {
20
146
  const abs = isAbsolute(rawPath) ? resolve(rawPath) : resolve(cwd ?? process.cwd(), rawPath);
21
- const containment = options?.containment ?? 'none';
22
- if (containment !== 'none') {
23
- const roots = options?.allowRoots ?? [];
24
- if (roots.length === 0) {
25
- // strict 无 root = fail-closed(与 isPathAllowed 一致);soft 仅审计
26
- if (containment === 'strict') {
27
- throw new Error(`path_forbidden: "${rawPath}" effect roots not configured`);
28
- }
29
- return abs;
30
- }
31
- if (!isPathUnderRoots(abs, roots)) {
32
- if (containment === 'strict') {
33
- throw new Error(`path_forbidden: "${rawPath}" escapes effect roots`);
34
- }
35
- // soft:放行(审计由调用方/Observer 负责)
36
- }
37
- }
38
- return abs;
39
- }
40
- /** 路径是否落在任一 root 之下(含 root 本身) */
41
- export function isPathUnderRoots(absPath, roots) {
42
- const win = process.platform === 'win32';
43
- const norm = (s) => {
44
- const r = resolve(s);
45
- return win ? r.toLowerCase() : r;
46
- };
47
- const p = norm(absPath);
48
- return roots.some((root) => {
49
- const r = norm(root);
50
- return p === r || p.startsWith(r.endsWith(sep) ? r : r + sep);
51
- });
147
+ return containPath(abs, rawPath, options);
52
148
  }
53
149
  /**
54
150
  * 只读附件根内解析(OP-15):相对名优先贴到 attachmentRoots
@@ -64,13 +160,31 @@ export function resolveReadableToolPath(rawPath, cwd, attachmentRoots, options)
64
160
  if (!isAbsolute(rawPath) && roots.length > 0) {
65
161
  const cleaned = rawPath.replace(/^[/\\]+/, '');
66
162
  for (const root of roots) {
67
- const candidate = resolve(root, cleaned);
68
163
  const rootResolved = resolve(root);
69
- const prefix = rootResolved.endsWith(sep) ? rootResolved : rootResolved + sep;
70
- if (candidate === rootResolved || candidate.startsWith(prefix)) {
71
- if (existsSync(candidate))
72
- return candidate;
164
+ const candidate = resolve(rootResolved, cleaned);
165
+ // Lexical guard against `cleaned` climbing out of the root; shares the
166
+ // win32 case-folding rule with every other containment check.
167
+ if (candidate !== rootResolved && !lexicalUnderRoots(candidate, [rootResolved]))
168
+ continue;
169
+ if (!existsSync(candidate))
170
+ continue;
171
+ // Attachment roots sit outside the effect roots by design, so they carry
172
+ // their own containment: a link planted in the attachment tree would
173
+ // otherwise be a straight read out of the read-only sandbox.
174
+ // Both sides are resolved here, so compare lexically rather than making
175
+ // isPathUnderRoots resolve them a second time.
176
+ const realRoot = realpathAllowMissing(rootResolved);
177
+ const realCandidate = realpathAllowMissing(candidate);
178
+ if (realRoot === null || realCandidate === null)
179
+ continue;
180
+ if (!lexicalUnderRoots(realCandidate, [realRoot]))
181
+ continue;
182
+ // Attachment roots are outside the effect roots, so they would otherwise
183
+ // skip the denylist entirely: "read-only" is not "allowed to read".
184
+ if (options?.denyPatterns && options.denyPatterns.length > 0) {
185
+ denyPath(realCandidate, rawPath, options, options.denyPatterns);
73
186
  }
187
+ return realCandidate;
74
188
  }
75
189
  }
76
190
  // attachments 命中后返回;其余走 L2
@@ -85,17 +199,11 @@ export function resolveReadableToolPath(rawPath, cwd, attachmentRoots, options)
85
199
  export function isUnderAttachmentRoot(path, attachmentRoots) {
86
200
  if (!attachmentRoots?.length)
87
201
  return false;
88
- // Windows 路径比较须大小写不敏感,否则可绕过 startsWith 写保护
89
- const win = process.platform === 'win32';
90
- const norm = (s) => (win ? resolve(s).toLowerCase() : resolve(s));
91
- const p = norm(path);
92
- for (const root of attachmentRoots) {
93
- const r = norm(root);
94
- const prefix = r.endsWith(sep) ? r : r + sep;
95
- if (p === r || p.startsWith(prefix))
96
- return true;
97
- }
98
- return false;
202
+ // `path` now arrives resolved (`resolveToolPath` returns the real path), so a
203
+ // purely lexical comparison against a configured root would report false
204
+ // whenever the root is an alias (macOS /var, symlinked HOME) — turning a
205
+ // write-protection guard into a fail-open. Resolve both sides.
206
+ return isPathUnderRoots(path, attachmentRoots);
99
207
  }
100
208
  function isExecutableFile(filePath) {
101
209
  try {
@@ -374,17 +482,15 @@ export function defaultPathEnv() {
374
482
  * @returns whether the path is protected undo ledger
375
483
  */
376
484
  export function isUnderSessionUndoRoot(target, undoRoots) {
377
- const resolved = resolve(target);
378
485
  const roots = (undoRoots ?? []).map((r) => r?.trim()).filter(Boolean);
379
- const fold = (p) => process.platform === 'win32' ? p.toLowerCase() : p;
380
- if (roots.length > 0) {
381
- const norm = (p) => fold(resolve(p).replace(/\\/g, '/'));
382
- const tNorm = norm(resolved);
383
- return roots.some((root) => {
384
- const r = norm(root);
385
- return tNorm === r || tNorm.startsWith(r.endsWith('/') ? r : r + '/');
386
- });
387
- }
388
- const norm = fold(resolved.replace(/\\/g, '/'));
389
- return /\/sessions\/[^/]+\/undo(\/|$)/i.test(norm);
486
+ // Same coordinate problem as isUnderAttachmentRoot: the target arrives as a
487
+ // real path while the configured roots keep their lexical spelling.
488
+ if (roots.length > 0)
489
+ return isPathUnderRoots(target, roots);
490
+ // No configured roots: recognise the default layout instead. Resolve first so
491
+ // a symlinked sessions directory still matches the same rule.
492
+ const resolved = realpathAllowMissing(resolve(target)) ?? resolve(target);
493
+ const converted = resolved.replace(/\\/g, '/');
494
+ const folded = process.platform === 'win32' ? converted.toLowerCase() : converted;
495
+ return /\/sessions\/[^/]+\/undo(\/|$)/i.test(folded);
390
496
  }
@@ -62,5 +62,6 @@ export declare class DefaultToolCallRiskPolicy implements ToolCallRiskPolicy {
62
62
  steps?: string[];
63
63
  };
64
64
  reason: string;
65
+ uncertain?: boolean;
65
66
  };
66
67
  }
@@ -60,6 +60,7 @@ export class DefaultToolCallRiskPolicy {
60
60
  })),
61
61
  alternative,
62
62
  reason: decision.reason,
63
+ uncertain: decision.uncertain,
63
64
  };
64
65
  }
65
66
  }
@@ -423,6 +423,15 @@ export class DefaultSecurityGuard {
423
423
  });
424
424
  return { isClean: hardViolations.length === 0, violations: hardViolations, riskUnknown: true };
425
425
  }
426
+ // 强不确定(解析结构性不确定):正交通知安全智能体过目,
427
+ // 等级判定与拦截行为照常(不因不确定放行,也不因不确定加拦)
428
+ if (decision.uncertain) {
429
+ this.emitRunEvent({
430
+ type: 'tool_call.risk_unknown',
431
+ timestamp: Date.now(),
432
+ data: { toolCall: call, decision },
433
+ });
434
+ }
426
435
  const riskViolations = [];
427
436
  if (decision.level !== 'low') {
428
437
  const severityMap = {
@@ -5,6 +5,7 @@
5
5
  * SecurityGuard 接口定义在 Core 层。
6
6
  */
7
7
  export { DefaultSecurityGuard } from './default-security-guard.js';
8
+ export { initShellParser, isShellParserReady, getShellParserEngine, } from './shell-parser.js';
8
9
  export { isValidSecurityGuard, severityToAction } from '@octopi-agent/core/security-guard.js';
9
10
  export type { SecurityGuard, SecurityCheckResult, SecurityViolation, SecurityViolationType, SecurityAction, BehaviorContext, SecurityGuardConfig, } from '@octopi-agent/core/interfaces/security-guard.js';
10
11
  export type { ToolCallRiskPolicy } from '@octopi-agent/core/interfaces/security-guard.js';
@@ -6,5 +6,7 @@
6
6
  */
7
7
  // ── DefaultSecurityGuard 实现(canonical 位置) ──
8
8
  export { DefaultSecurityGuard } from './default-security-guard.js';
9
+ // ── Shell 解析引擎(自装配方需自行 await initShellParser) ──
10
+ export { initShellParser, isShellParserReady, getShellParserEngine, } from './shell-parser.js';
9
11
  // ── Core 接口 re-export(方便 harness 消费者) ──
10
12
  export { isValidSecurityGuard, severityToAction } from '@octopi-agent/core/security-guard.js';
@@ -255,6 +255,7 @@ export function evaluateShellCommand(command, cwd) {
255
255
  level: 'unknown',
256
256
  factors: [{ source: 'method', description: '命令解析失败', level: 'unknown' }],
257
257
  reason: '命令结构过于复杂,无法确定性解析',
258
+ uncertain: true,
258
259
  };
259
260
  }
260
261
  // 1. 检测特殊模式(管道到解释器、内联代码、子 shell)
@@ -306,12 +307,24 @@ export function evaluateShellCommand(command, cwd) {
306
307
  });
307
308
  }
308
309
  }
310
+ // 4.5 解析不确定(tree-sitter 报错回退 fallback 引擎):
311
+ // 结构可能被低估,显式计入 unknown 因子——有确定性高风险仍照常抬升,
312
+ // 全低风险时整体落 unknown 通道(放行 + 事件),不把不确定静默当安全。
313
+ if (parsed.uncertain) {
314
+ factors.push({
315
+ source: 'method',
316
+ description: '命令结构不确定(存在解析器无法确定性解析的片段)',
317
+ level: 'unknown',
318
+ });
319
+ }
309
320
  // 5. 计算整体风险等级
310
321
  const level = computeOverallRisk(factors);
311
322
  return {
312
323
  level,
313
324
  factors,
314
325
  reason: buildReason(level, factors),
326
+ // 强不确定与等级正交:无论等级高低都标记,供守卫上报安全智能体
327
+ ...(parsed.uncertain ? { uncertain: true } : {}),
315
328
  };
316
329
  }
317
330
  // ── 段评估 ──
@@ -42,6 +42,13 @@ export interface ParsedCommand {
42
42
  hasSubshell: boolean;
43
43
  /** 是否包含后台执行(&) */
44
44
  hasBackground: boolean;
45
+ /**
46
+ * 解析不确定:tree-sitter 无法确定性解析(语法树含 ERROR)后回退 fallback 引擎。
47
+ * 风险分档应附加「结构不确定」因子,不允许静默当正常结果。
48
+ */
49
+ uncertain?: boolean;
50
+ /** 未挂载到命令段的重定向(如 `> file` 单独成句):目标仍参与路径风险评估 */
51
+ orphanRedirects?: Redirect[];
45
52
  }
46
53
  export type RiskLevel = 'low' | 'medium' | 'high' | 'critical' | 'unknown';
47
54
  export interface RiskFactor {
@@ -69,6 +76,11 @@ export interface RiskDecision {
69
76
  alternative?: SafeAlternative;
70
77
  /** 决策理由(人类可读) */
71
78
  reason: string;
79
+ /**
80
+ * 强不确定(解析结构性不确定等):需安全智能体过目。
81
+ * 与等级正交——始终触发 risk_unknown 事件上报,但不改变等级判定与拦截行为。
82
+ */
83
+ uncertain?: boolean;
72
84
  }
73
85
  export type PathRisk = 'safe' | 'normal' | 'sensitive' | 'protected';
74
86
  export type ToolCategory = 'shell' | 'file' | 'http' | 'eval' | 'other';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Shell Parser (fallback) — 轻量级 Shell 命令解析器(回退引擎)
3
+ *
4
+ * 纯字符串解析。主引擎是 tree-sitter 适配层(shell-parser-treesitter.ts);
5
+ * 本解析器在 tree-sitter 不可用或解析报错时回退使用。
6
+ * 入口统一走 shell-parser.ts 的 parseShellCommand。
7
+ *
8
+ * 四层解析:
9
+ * 1. 按 |, &&, ||, ; 拆分 → 命令段
10
+ * 2. 每个命令段 → [wrapper...] + [command, ...args]
11
+ * 3. 识别 >, >>, < 重定向 → 提取目标路径
12
+ * 4. 识别 sudo, env, exec 等 wrapper → 解包实际命令
13
+ *
14
+ * 设计原则:宁可解析不完整,不可解析错误。
15
+ * 遇到无法解析的复杂结构,标记为 parsed: false,交给 LLM 判断。
16
+ */
17
+ import type { ParsedCommand } from './risk-types.js';
18
+ /**
19
+ * 解析 Shell 命令(fallback 引擎)
20
+ *
21
+ * @param raw - 原始命令字符串
22
+ * @returns 解析结果(parsed: true/false 表示解析是否成功)
23
+ */
24
+ export declare function parseShellCommandFallback(raw: string): ParsedCommand & {
25
+ parsed: boolean;
26
+ };
27
+ /**
28
+ * 检测内联代码执行(共享实现,见 shell-parser-shared.ts)
29
+ */