@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
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Path glob compilation — shared by tool glob filters and path denylists.
3
+ *
4
+ * Semantics follow rg/git so that `file_search`'s `glob` argument and
5
+ * `effectPolicy.pathDenylist` cannot drift apart:
6
+ * - `**` crosses directories; `*` and `?` do not cross `/`
7
+ * - a pattern without `/` (for example `*.md`) matches at any depth
8
+ * - `{a,b}` alternatives are supported, including nesting
9
+ */
10
+ /**
11
+ * Compile a path glob into a regular expression over root-relative paths.
12
+ *
13
+ * @param glob - glob pattern
14
+ * @returns anchored, case-insensitive matcher for a root-relative path
15
+ */
16
+ export function globToPathRegex(glob) {
17
+ const trimmed = glob.trim();
18
+ if (!trimmed)
19
+ throw new Error('glob must be non-empty');
20
+ // Compiled patterns are pure functions of the pattern text, and denylists are
21
+ // re-evaluated for every walked file, so memoize instead of recompiling.
22
+ const cached = COMPILED.get(trimmed);
23
+ if (cached)
24
+ return cached;
25
+ const normalized = trimmed.includes('/') ? trimmed : `**/${trimmed}`;
26
+ const regex = new RegExp(`^${globToSource(normalized)}$`, 'i');
27
+ if (COMPILED.size >= COMPILE_CACHE_LIMIT)
28
+ COMPILED.clear();
29
+ COMPILED.set(trimmed, regex);
30
+ return regex;
31
+ }
32
+ const COMPILED = new Map();
33
+ const COMPILE_CACHE_LIMIT = 512;
34
+ /**
35
+ * Normalize a deny pattern into the path dialect the matcher speaks.
36
+ *
37
+ * Windows deployments write separators the way their shell does, so `\` is
38
+ * always a separator here. That makes an escaped literal (`.git\**` meaning
39
+ * "a file literally named `.git*`") impossible to express — acceptable, since a
40
+ * separator is what every real denylist entry means.
41
+ *
42
+ * @param pattern - raw deny pattern from configuration
43
+ * @returns pattern using `/` separators
44
+ */
45
+ export function normalizeDenyPattern(pattern) {
46
+ return pattern.trim().split('\\').join('/');
47
+ }
48
+ /**
49
+ * Reject deny patterns that can never match a root-relative path.
50
+ *
51
+ * A pattern that silently matches nothing is worse than a startup error: the
52
+ * deployment keeps believing it is protected. Shapes rejected here are all
53
+ * spellings that look meaningful but cannot match (`/x` anchors outside the
54
+ * root, `x/` never matches a resolved file, `../x` has no candidate).
55
+ *
56
+ * @param pattern - raw deny pattern from configuration
57
+ */
58
+ export function validateDenyPattern(pattern) {
59
+ const normalized = normalizeDenyPattern(pattern);
60
+ if (!normalized)
61
+ throw new Error('pathDenylist: pattern must be non-empty');
62
+ if (normalized.startsWith('/')) {
63
+ throw new Error(`pathDenylist: "${pattern}" must be root-relative (drop the leading "/")`);
64
+ }
65
+ if (normalized.endsWith('/')) {
66
+ throw new Error(`pathDenylist: "${pattern}" must not end with a separator`);
67
+ }
68
+ if (normalized.split('/').some((segment) => segment === '..' || segment === '.')) {
69
+ throw new Error(`pathDenylist: "${pattern}" must not contain "." or ".." segments`);
70
+ }
71
+ }
72
+ /**
73
+ * Compile a normalized glob fragment into regex source.
74
+ *
75
+ * @param glob - glob containing path separators
76
+ * @returns regex source without anchors
77
+ */
78
+ function globToSource(glob) {
79
+ let out = '';
80
+ let index = 0;
81
+ while (index < glob.length) {
82
+ const char = glob[index];
83
+ // `\*`, `\?` and friends are literals.
84
+ if (char === '\\' && index + 1 < glob.length && '*?[]{}\\/!'.includes(glob[index + 1])) {
85
+ out += escapeRegex(glob[index + 1]);
86
+ index += 2;
87
+ continue;
88
+ }
89
+ if (char === '*' && glob[index + 1] === '*') {
90
+ index += 2;
91
+ if (glob[index] === '/') {
92
+ index += 1;
93
+ // `**/` → any depth prefix, including zero segments
94
+ out += '(?:.*/)?';
95
+ }
96
+ else {
97
+ out += '.*';
98
+ }
99
+ continue;
100
+ }
101
+ if (char === '*') {
102
+ index += 1;
103
+ out += '[^/]*';
104
+ continue;
105
+ }
106
+ if (char === '?') {
107
+ index += 1;
108
+ out += '[^/]';
109
+ continue;
110
+ }
111
+ if (char === '{') {
112
+ const end = findBraceEnd(glob, index);
113
+ if (end === -1) {
114
+ out += '\\{';
115
+ index += 1;
116
+ continue;
117
+ }
118
+ const alternatives = splitBraceAlternatives(glob.slice(index + 1, end));
119
+ out += `(?:${alternatives.map((alt) => globToSource(alt)).join('|')})`;
120
+ index = end + 1;
121
+ continue;
122
+ }
123
+ if ('.+^$()|[]'.includes(char)) {
124
+ out += `\\${char}`;
125
+ }
126
+ else {
127
+ out += char;
128
+ }
129
+ index += 1;
130
+ }
131
+ return out;
132
+ }
133
+ /**
134
+ * Find the `}` matching the `{` at `openIndex`, skipping nesting.
135
+ *
136
+ * @param glob - glob string
137
+ * @param openIndex - index of `{`
138
+ * @returns index of the matching `}`; -1 when unbalanced
139
+ */
140
+ function findBraceEnd(glob, openIndex) {
141
+ let depth = 0;
142
+ for (let index = openIndex; index < glob.length; index += 1) {
143
+ if (glob[index] === '{')
144
+ depth += 1;
145
+ else if (glob[index] === '}') {
146
+ depth -= 1;
147
+ if (depth === 0)
148
+ return index;
149
+ }
150
+ }
151
+ return -1;
152
+ }
153
+ /**
154
+ * Split top-level comma alternatives inside braces.
155
+ *
156
+ * @param body - contents between braces
157
+ * @returns alternatives
158
+ */
159
+ function splitBraceAlternatives(body) {
160
+ const alternatives = [];
161
+ let depth = 0;
162
+ let current = '';
163
+ for (const char of body) {
164
+ if (char === '{')
165
+ depth += 1;
166
+ if (char === '}')
167
+ depth -= 1;
168
+ if (char === ',' && depth === 0) {
169
+ alternatives.push(current);
170
+ current = '';
171
+ continue;
172
+ }
173
+ current += char;
174
+ }
175
+ alternatives.push(current);
176
+ return alternatives;
177
+ }
178
+ /**
179
+ * Escape a single character for use in a regex literal.
180
+ *
181
+ * @param char - character to escape
182
+ * @returns escaped character
183
+ */
184
+ function escapeRegex(char) {
185
+ return char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
186
+ }
187
+ /**
188
+ * Whether a root-relative path matches any denylist pattern.
189
+ *
190
+ * Both the full relative path and the file name are tested, so `.env*` and
191
+ * `.git/**` can coexist without the caller deciding which form a pattern means.
192
+ * Invalid patterns are the caller's mistake and throw: silently ignoring a
193
+ * typo'd security pattern would leave the deployment believing it is protected.
194
+ *
195
+ * @param relativePath - path relative to the containing root, using `/`
196
+ * @param patterns - denylist globs
197
+ * @returns true when any pattern matches
198
+ */
199
+ export function matchesDenyPattern(relativePath, patterns) {
200
+ if (patterns.length === 0)
201
+ return false;
202
+ const normalized = relativePath.split('\\').join('/');
203
+ const segments = normalized.split('/').filter(Boolean);
204
+ // Test the full path *and every suffix*, so a pattern like `.git/**` denies a
205
+ // `.git` directory at any depth. Anchoring only at the root would let
206
+ // `pkg/.git/config` through, which for a security denylist is a silent hole.
207
+ const candidates = [normalized];
208
+ for (let index = 1; index < segments.length; index += 1) {
209
+ candidates.push(segments.slice(index).join('/'));
210
+ }
211
+ const name = segments[segments.length - 1] ?? normalized;
212
+ if (!candidates.includes(name))
213
+ candidates.push(name);
214
+ return patterns.some((pattern) => {
215
+ const matcher = globToPathRegex(normalizeDenyPattern(pattern));
216
+ return candidates.some((candidate) => matcher.test(candidate));
217
+ });
218
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Path containment primitives — shared by tool execution and effect auditing
3
+ *
4
+ * Containment is a cross-cutting mechanism, not a policy owned by one domain:
5
+ * the tools domain decides *what* may be touched (`pathRoots`, `containment`),
6
+ * while the execution-environment domain decides *what gets recorded*. Both
7
+ * need the same answer to "is this path under that root", and both need it in
8
+ * real coordinates — a purely lexical comparison lets a symlink inside a root
9
+ * reach outside it.
10
+ *
11
+ * These helpers live in `shared/` so that no domain has to import another
12
+ * domain's internals to get correct containment. They are foundation code:
13
+ * no policy defaults, no product decisions.
14
+ */
15
+ /**
16
+ * Resolve a path that may not exist yet to its real location.
17
+ *
18
+ * `realpathSync` throws for a missing target, but creating a new file is a
19
+ * normal operation. Walk up to the deepest existing ancestor, resolve that,
20
+ * and re-append the remaining segments. `resolve()` already folded `..`, so the
21
+ * appended tail cannot introduce a new escape.
22
+ *
23
+ * A missing segment that *does* exist as a directory entry is not treated as
24
+ * "about to be created": that is a dangling symlink or a link loop, and letting
25
+ * it through would allow the following open/write to follow it out of the root.
26
+ * `lstatSync` does not follow the final component, which separates the cases.
27
+ *
28
+ * @param abs - absolute, lexically normalized path
29
+ * @returns real path, or null when it cannot be resolved safely
30
+ */
31
+ export declare function realpathAllowMissing(abs: string): string | null;
32
+ /**
33
+ * Containment over already-normalized paths (no filesystem access).
34
+ *
35
+ * Use this only when both sides are already real paths; otherwise prefer
36
+ * {@link isPathUnderRoots}, which resolves them first.
37
+ *
38
+ * Windows drive letters are compared case-insensitively, matching how the
39
+ * effect policy treats volume names.
40
+ *
41
+ * @param absPath - path already resolved to its real form
42
+ * @param roots - roots already resolved to their real form
43
+ * @returns whether the path is one of the roots or under one
44
+ */
45
+ export declare function lexicalUnderRoots(absPath: string, roots: string[]): boolean;
46
+ /**
47
+ * Whether a path falls under any of the given roots, in real coordinates.
48
+ *
49
+ * Both sides are resolved: comparing a resolved target against an unresolved
50
+ * root would wrongly deny legitimate paths whenever the root is itself an alias
51
+ * (macOS `/var` → `/private/var`, a symlinked `$HOME`). A path that cannot be
52
+ * resolved falls back to its lexical form, so this only ever answers "is it
53
+ * inside", never "is it safe to operate on" — callers that need the resolved
54
+ * path must use their own resolution step.
55
+ *
56
+ * @param absPath - path to test
57
+ * @param roots - allowed roots
58
+ * @returns true when the path is one of the roots or under one
59
+ */
60
+ export declare function isPathUnderRoots(absPath: string, roots: readonly string[]): boolean;
61
+ /**
62
+ * Whether the final path component is a symbolic link, without following it.
63
+ *
64
+ * `lstat` inspects the entry itself, so a dangling link still reports `true` —
65
+ * which is what a write guard needs: an unresolvable link is exactly the case
66
+ * where a later open would follow it somewhere unintended.
67
+ *
68
+ * @param path - path to inspect
69
+ * @returns true when the entry exists and is a symlink
70
+ */
71
+ export declare function isFinalSymlink(path: string): boolean;
72
+ /**
73
+ * Read a file refusing to traverse a symlink at the final component.
74
+ *
75
+ * Resolving containment already returns a real path, so normally the final
76
+ * component is not a link. If it is one at open time, something replaced it
77
+ * between the containment check and this open; `O_NOFOLLOW` makes the kernel
78
+ * refuse instead of following it (`ELOOP`).
79
+ *
80
+ * @param path - absolute path, normally already resolved
81
+ * @param encoding - text encoding
82
+ * @returns file contents
83
+ */
84
+ export declare function readFileNoFollow(path: string, encoding: 'utf8'): Promise<string>;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Path containment primitives — shared by tool execution and effect auditing
3
+ *
4
+ * Containment is a cross-cutting mechanism, not a policy owned by one domain:
5
+ * the tools domain decides *what* may be touched (`pathRoots`, `containment`),
6
+ * while the execution-environment domain decides *what gets recorded*. Both
7
+ * need the same answer to "is this path under that root", and both need it in
8
+ * real coordinates — a purely lexical comparison lets a symlink inside a root
9
+ * reach outside it.
10
+ *
11
+ * These helpers live in `shared/` so that no domain has to import another
12
+ * domain's internals to get correct containment. They are foundation code:
13
+ * no policy defaults, no product decisions.
14
+ */
15
+ import { lstatSync, realpathSync } from 'node:fs';
16
+ import { basename, dirname, join, resolve, sep } from 'node:path';
17
+ /**
18
+ * Resolve a path that may not exist yet to its real location.
19
+ *
20
+ * `realpathSync` throws for a missing target, but creating a new file is a
21
+ * normal operation. Walk up to the deepest existing ancestor, resolve that,
22
+ * and re-append the remaining segments. `resolve()` already folded `..`, so the
23
+ * appended tail cannot introduce a new escape.
24
+ *
25
+ * A missing segment that *does* exist as a directory entry is not treated as
26
+ * "about to be created": that is a dangling symlink or a link loop, and letting
27
+ * it through would allow the following open/write to follow it out of the root.
28
+ * `lstatSync` does not follow the final component, which separates the cases.
29
+ *
30
+ * @param abs - absolute, lexically normalized path
31
+ * @returns real path, or null when it cannot be resolved safely
32
+ */
33
+ export function realpathAllowMissing(abs) {
34
+ let current = abs;
35
+ const tail = [];
36
+ for (;;) {
37
+ try {
38
+ const real = realpathSync(current);
39
+ return tail.length ? join(real, ...tail) : real;
40
+ }
41
+ catch (error) {
42
+ const code = error.code;
43
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
44
+ return null;
45
+ if (existsLstat(current))
46
+ return null;
47
+ const parent = dirname(current);
48
+ if (parent === current)
49
+ return null;
50
+ tail.unshift(basename(current));
51
+ current = parent;
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Whether anything exists at this path, without following a final symlink.
57
+ *
58
+ * @param path - absolute path
59
+ * @returns true when an entry exists (including a dangling link)
60
+ */
61
+ function existsLstat(path) {
62
+ try {
63
+ lstatSync(path);
64
+ return true;
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ /**
71
+ * Containment over already-normalized paths (no filesystem access).
72
+ *
73
+ * Use this only when both sides are already real paths; otherwise prefer
74
+ * {@link isPathUnderRoots}, which resolves them first.
75
+ *
76
+ * Windows drive letters are compared case-insensitively, matching how the
77
+ * effect policy treats volume names.
78
+ *
79
+ * @param absPath - path already resolved to its real form
80
+ * @param roots - roots already resolved to their real form
81
+ * @returns whether the path is one of the roots or under one
82
+ */
83
+ export function lexicalUnderRoots(absPath, roots) {
84
+ const win = process.platform === 'win32';
85
+ const norm = (s) => (win ? s.toLowerCase() : s);
86
+ const target = norm(absPath);
87
+ return roots.some((root) => {
88
+ const r = norm(root);
89
+ return target === r || target.startsWith(r.endsWith(sep) ? r : r + sep);
90
+ });
91
+ }
92
+ /**
93
+ * Whether a path falls under any of the given roots, in real coordinates.
94
+ *
95
+ * Both sides are resolved: comparing a resolved target against an unresolved
96
+ * root would wrongly deny legitimate paths whenever the root is itself an alias
97
+ * (macOS `/var` → `/private/var`, a symlinked `$HOME`). A path that cannot be
98
+ * resolved falls back to its lexical form, so this only ever answers "is it
99
+ * inside", never "is it safe to operate on" — callers that need the resolved
100
+ * path must use their own resolution step.
101
+ *
102
+ * @param absPath - path to test
103
+ * @param roots - allowed roots
104
+ * @returns true when the path is one of the roots or under one
105
+ */
106
+ export function isPathUnderRoots(absPath, roots) {
107
+ const lexical = roots.map((root) => resolve(root));
108
+ const target = resolve(absPath);
109
+ const real = (s) => realpathAllowMissing(s) ?? s;
110
+ const realTarget = realpathAllowMissing(target);
111
+ if (realTarget !== null) {
112
+ // Compare in real coordinates: a resolved target against an unresolved root
113
+ // would deny legitimate paths whenever the root is itself an alias.
114
+ return lexicalUnderRoots(realTarget, lexical.map(real));
115
+ }
116
+ // The target exists but cannot be resolved (dangling symlink or link loop).
117
+ // Comparing a lexical target against resolved roots would mix coordinate
118
+ // systems and report an in-root link as outside. Stay lexical on both sides.
119
+ // This answers containment only; callers that act on the path must take
120
+ // realpathAllowMissing's null and refuse, which is what containPath does.
121
+ return lexicalUnderRoots(target, lexical);
122
+ }
123
+ /**
124
+ * Whether the final path component is a symbolic link, without following it.
125
+ *
126
+ * `lstat` inspects the entry itself, so a dangling link still reports `true` —
127
+ * which is what a write guard needs: an unresolvable link is exactly the case
128
+ * where a later open would follow it somewhere unintended.
129
+ *
130
+ * @param path - path to inspect
131
+ * @returns true when the entry exists and is a symlink
132
+ */
133
+ export function isFinalSymlink(path) {
134
+ try {
135
+ return lstatSync(path).isSymbolicLink();
136
+ }
137
+ catch {
138
+ // ENOENT / ENOTDIR: nothing at that name, so nothing to follow.
139
+ return false;
140
+ }
141
+ }
142
+ /**
143
+ * Read a file refusing to traverse a symlink at the final component.
144
+ *
145
+ * Resolving containment already returns a real path, so normally the final
146
+ * component is not a link. If it is one at open time, something replaced it
147
+ * between the containment check and this open; `O_NOFOLLOW` makes the kernel
148
+ * refuse instead of following it (`ELOOP`).
149
+ *
150
+ * @param path - absolute path, normally already resolved
151
+ * @param encoding - text encoding
152
+ * @returns file contents
153
+ */
154
+ export async function readFileNoFollow(path, encoding) {
155
+ const { open, constants } = await import('node:fs/promises');
156
+ // O_NOFOLLOW is POSIX-only. On Windows it is absent, and `0 | undefined` is
157
+ // `0` — which would silently mean "follow the link", the opposite of intent.
158
+ // Fall back to an lstat pre-check there: it keeps refusing dangling links
159
+ // (the common planted case) at the cost of a narrower TOCTOU window.
160
+ if (constants.O_NOFOLLOW === undefined) {
161
+ if (isFinalSymlink(path)) {
162
+ throw new Error(`path_forbidden: "${path}" final component is a symlink (no O_NOFOLLOW on this platform)`);
163
+ }
164
+ const handle = await open(path, 'r');
165
+ try {
166
+ return await handle.readFile({ encoding });
167
+ }
168
+ finally {
169
+ await handle.close();
170
+ }
171
+ }
172
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
173
+ try {
174
+ return await handle.readFile({ encoding });
175
+ }
176
+ finally {
177
+ await handle.close();
178
+ }
179
+ }
@@ -11,7 +11,8 @@ sense:
11
11
  isolation: isolated
12
12
 
13
13
  think:
14
- implementation: llm
14
+ # code = 调 handler.ts 确定性实现(llm 模式是自由 decide,handler 从未执行——2026-10-30 修复)
15
+ implementation: code
15
16
  strategy: single
16
17
  maxIterations: 1
17
18
 
@@ -36,7 +37,7 @@ session:
36
37
 
37
38
  lifecycle:
38
39
  maxConcurrent: 1
39
- maxDurationMs: 30000
40
+ maxDurationMs: 120000
40
41
 
41
42
  runtimeInject:
42
43
  requires: ['conceptGraphStore']
@@ -48,3 +49,4 @@ metadata:
48
49
  config:
49
50
  maxNodesPerProposition: 6
50
51
  maxEdgesPerProposition: 12
52
+ maxTokens: 8192
@@ -7,7 +7,7 @@
7
7
  import { readFileSync } from 'node:fs';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
- import { DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, } from '@octopi-agent/engine/harness/collaboration/autonomous-subsystem/index.js';
10
+ import { DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, chatForCompleteOutput, } from '@octopi-agent/engine/harness/collaboration/autonomous-subsystem/index.js';
11
11
  import { conceptualizeAndAdmit, parseConceptualizerJson, } from '../../../harness/memory/conceptualizer.js';
12
12
  const DEP_CONCEPT_GRAPH = 'conceptGraphStore';
13
13
  const DEP_CONFIG = '__subsystem_config__';
@@ -66,26 +66,18 @@ async function handler(input, deps) {
66
66
  `evidence: ${evidence}`,
67
67
  `contextSlice: ${contextSlice}`,
68
68
  ].join('\n');
69
- let llmText = '';
70
- try {
71
- const res = await llmPort.chat({
72
- systemPrompt: systemPrompt || undefined,
73
- messages: [{ role: 'user', content: userText }],
74
- // 温度留空:由模型配置(ModelInfo.temperature)或服务端默认决定
75
- maxTokens: 2048,
76
- });
77
- if (res.finishReason === 'error') {
78
- return failOutput(res.content || 'llm chat error', 'llm_error');
79
- }
80
- llmText = res.content ?? '';
81
- }
82
- catch (err) {
83
- return failOutput(err instanceof Error ? err.message : String(err), 'llm_error');
84
- }
85
- const parsed = parseConceptualizerJson(llmText);
86
- if (!parsed) {
87
- return failOutput('parse_failed', 'parse_failed');
69
+ // maxTokens 只是生成配额(LLM 传参):截断(finish=length)或解析失败都放大配额重试
70
+ // 一次,仍失败显式上报——业务完整性优先,禁止静默半截结果
71
+ const config = deps?.[DEP_CONFIG] ?? {};
72
+ const outcome = await chatForCompleteOutput(llmPort, {
73
+ systemPrompt: systemPrompt || undefined,
74
+ messages: [{ role: 'user', content: userText }],
75
+ maxTokens: config.maxTokens ?? 8192,
76
+ }, (text) => parseConceptualizerJson(text));
77
+ if (!outcome.ok) {
78
+ return failOutput(outcome.message, outcome.reason);
88
79
  }
80
+ const parsed = outcome.parsed;
89
81
  const result = await conceptualizeAndAdmit(parsed, {
90
82
  proposition,
91
83
  memoryId,
@@ -36,11 +36,12 @@ session:
36
36
 
37
37
  lifecycle:
38
38
  maxConcurrent: 1
39
- maxDurationMs: 60000
39
+ maxDurationMs: 120000
40
40
 
41
41
  runtimeInject:
42
42
  # backfillCoverage 可选:未注入时 handler 跳过覆盖回写(协调器仍可自记 pending)
43
- requires: ['memoryStore', 'sessionStore', 'constitution', 'backfillCoverage']
43
+ # eventBus 可选:memory.stored 增量信号(未注入时静默跳过)
44
+ requires: ['memoryStore', 'sessionStore', 'constitution', 'backfillCoverage', 'eventBus']
44
45
 
45
46
  observability:
46
47
  eventPrefix: memory.steward.backfill
@@ -48,4 +49,5 @@ observability:
48
49
  metadata:
49
50
  config:
50
51
  maxCandidatesPerSession: 8
52
+ maxTokens: 8192
51
53
  maxEvidenceChars: 8000