osuite 2.14.2 → 2.16.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.
@@ -139,41 +139,68 @@ function installCheck(payload, context) {
139
139
  return { authorized: false, decision: payload.decision.decision, installCheck: true, reason: 'approval_not_requested', response: payload };
140
140
  }
141
141
 
142
- export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(), beforeRelease = async () => true } = {}) {
143
- const guard = await api.request('POST', '/api/guard', context);
142
+ export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(),
143
+ beforeRelease = async () => true, rememberOperation } = {}) {
144
+ const guard = await api.request('POST', '/api/guard', rememberOperation ? { ...context, hook_dispatch: 'v1' } : context);
144
145
  if (!guard.ok) {
145
146
  // Rejection, bad evidence and unknown errors are not availability failures.
146
- if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status });
147
+ if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status,
148
+ phase: 'guard', retrySameOperation: guard.status === 429, retryAfterSeconds: guard.retryAfterSeconds });
147
149
  const failOpen = ['observe', 'enforce'].includes(config.mode)
148
150
  && config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY && !config.ruleRollout?.enabled
149
151
  && config.guardFailureMode === 'allow';
150
- return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
152
+ return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true,
153
+ phase: 'guard', retrySameOperation: !failOpen, retryAfterSeconds: guard.retryAfterSeconds };
151
154
  }
152
155
  const requestedDecision = guard.body?.decision;
153
156
  if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
154
157
  const rollout = rolloutAuthority(guard.body, context, config);
155
158
  if (!rollout.valid) return closed('rule_rollout_binding_invalid');
156
- const finish = result => rollout.binding ? { ...result, observeOnly: false, ruleRolloutBinding: rollout.binding } : result;
159
+ const operationId = rememberOperation && /^hact_[a-f0-9]{64}$/.test(guard.body.hook_action_id || '') ? guard.body.hook_action_id : null;
160
+ if (operationId && !rememberOperation(operationId)) return closed('hook_operation_binding_changed', { actionId: operationId });
161
+ const binding = operationId ? { action_id: operationId, hook_dispatch: 'v1' } : {};
162
+ const finish = result => ({
163
+ ...result,
164
+ ...(operationId ? { hookOperationId: operationId } : {}),
165
+ ...(rollout.binding ? { observeOnly: false, ruleRolloutBinding: rollout.binding } : {}),
166
+ });
167
+ const create = fields => api.request('POST', '/api/actions', { ...context, ...binding, ...fields });
168
+ if (context.hook_observation) {
169
+ if (!operationId || config.mode !== 'observe' || rollout.binding) return finish(closed('observation_posture_unconfirmed'));
170
+ const observed = await create({ status: 'running' });
171
+ const action = observed.body?.action;
172
+ if (!observed.ok || action?.status !== 'running' || action.timestamp_end != null
173
+ || action.action_envelope?.hook_observation?.revision !== context.hook_observation.revision
174
+ || !matchesAction(observed.body, context, { actionId: operationId })) {
175
+ return finish(closed('observation_registration_unconfirmed', { actionId: operationId, rejectedStatus: observed.status }));
176
+ }
177
+ return finish({ authorized: false, observeOnly: true, observeRecorded: true, actionId: operationId,
178
+ decision: observed.body.decision?.decision, response: observed.body });
179
+ }
157
180
  if (requestedDecision === 'block') {
158
181
  // Observation still persists the would-block result, but never calls it authority.
159
182
  const observeOnly = config.mode === 'observe' && !rollout.binding;
160
- if (observeOnly) {
161
- const recorded = await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
162
- if (!recorded.ok && (!isTransientFailure(recorded) || config.guardFailureMode !== 'allow')) {
163
- return closed('admission_unconfirmed', { rejectedStatus: recorded.status });
183
+ let actionId = null;
184
+ if (observeOnly || operationId) {
185
+ const recorded = await create(operationId
186
+ ? { status: 'cancelled', timestamp_end: new Date().toISOString(), error_message: 'CLIENT_BLOCKED' }
187
+ : { status: 'blocked' });
188
+ if (safeId(recorded.body?.action_id) && (!operationId || recorded.body.action_id === operationId)) actionId = recorded.body.action_id;
189
+ if (!actionId && observeOnly && !recorded.ok && (!isTransientFailure(recorded) || config.guardFailureMode !== 'allow')) {
190
+ return finish(closed('admission_unconfirmed', { rejectedStatus: recorded.status, actionId: operationId }));
164
191
  }
165
192
  }
166
- return finish({ ...closed('policy_block'), observeOnly, response: guard.body });
193
+ return finish({ ...closed('policy_block'), observeOnly, response: guard.body, actionId });
167
194
  }
168
- const created = await api.request('POST', '/api/actions', {
169
- ...context, status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running',
170
- });
171
- if (!created.ok) return closed('admission_unconfirmed', { rejectedStatus: created.status });
195
+ const created = await create({ status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running' });
196
+ if (!created.ok) return finish(closed('admission_unconfirmed', { rejectedStatus: created.status, actionId: operationId,
197
+ phase: 'action_registration', retrySameOperation: false, retryAfterSeconds: created.retryAfterSeconds }));
198
+ if (operationId && created.body?.action_id !== operationId) return finish(closed('hook_operation_binding_changed', { actionId: operationId }));
172
199
  if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
173
200
  const diagnostic = installCheck(created.body, context);
174
201
  if (diagnostic) return finish(diagnostic);
175
202
  let result = finish(actionAdmission(created.body, requestedDecision, context));
176
- if (result.authorized) return await beforeRelease(result.response) ? result : closed('action_evidence_changed');
203
+ if (result.authorized) return await beforeRelease(result.response) ? result : finish(closed('action_evidence_changed', { actionId: result.actionId }));
177
204
  if (result.decision !== 'require_approval') return result;
178
205
  if (config.mode === 'observe' && !rollout.binding) return { ...result, observeOnly: true };
179
206
 
@@ -205,11 +232,11 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
205
232
  return closed('approval_not_confirmed', { actionId: expected.actionId });
206
233
  }
207
234
  // GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
208
- const current = await api.request('POST', '/api/actions', { ...context, status: 'running' });
235
+ const current = await create({ status: 'running' });
209
236
  if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId, rejectedStatus: current.status });
210
237
  if (!rolloutAuthority(current.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
211
238
  result = finish(actionAdmission(current.body, 'allow', context, expected));
212
- if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
239
+ if (result.authorized && !await beforeRelease(result.response)) return finish(closed('action_evidence_changed', { actionId: result.actionId }));
213
240
  return result;
214
241
  }
215
242
  return result;
@@ -0,0 +1,192 @@
1
+ import { posix as path } from 'node:path';
2
+ import { isObject } from './protocol.mjs';
3
+ import { isStdoutPrintf, parseShell, unwrapShellArgv } from './shell.mjs';
4
+
5
+ const FILE_READERS = new Set(['cat', 'head', 'tail', 'less', 'more', 'sed', 'awk', 'jq', 'rg', 'grep', 'base64', 'xxd', 'od', 'openssl', 'sort', 'diff']);
6
+ const FILE_WRITERS = new Set(['rm', 'mv', 'cp', 'install', 'chmod', 'chown', 'touch', 'mkdir', 'rmdir', 'tee', 'truncate']);
7
+ const FILE_COPIERS = new Set(['cp', 'install']);
8
+ const NETWORK_COMMANDS = new Set(['curl', 'wget', 'http', 'https', 'ftp', 'sftp', 'scp', 'ssh', 'rsync', 'nc', 'ncat']);
9
+ const SHELLS = new Set(['sh', 'bash', 'dash', 'zsh']);
10
+ const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'apply_patch']);
11
+ const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'ViewImage']);
12
+ const OPAQUE_COMMANDS = new Set(['eval', 'xargs', 'source', '.']);
13
+ const SECRET_PATH = /(?:^|\/)(?:\.env(?:\.(?!(?:example|sample|template)(?:\.|$))[\w.-]+)?|\.git-credentials|\.netrc|\.npmrc|\.aws\/(?:credentials|sso\/cache(?:\/.*)?)|\.ssh\/[^/]+(?<!\.pub)|\.codex\/auth\.json|\.claude\/\.credentials\.json|\.osuite-project-credentials\/.*|id_(?:rsa|ed25519|ecdsa)|[^/]+\.(?:key|p12)|etc\/(?:shadow|gshadow))(?:$|\/)/i;
14
+ const PROJECT_MANAGED = /(?:^|\/)(?:CLAUDE\.md|AGENTS\.md|\.claude\.md|\.mcp\.json|\.claude\/(?:CLAUDE\.md|settings(?:\.local)?\.json|hooks\/.*|rules\/.*)|\.codex\/(?:config\.toml|hooks\.json|hooks\/.*|rules\/.*)|\.cursor\/(?:hooks\.json|hooks\/.*|rules\/.*)|\.osuite\/(?:hooks\/.*|rules\/.*|config\.json))$/i;
15
+ const MCP_ID = /^mcp__[a-zA-Z0-9_.-]+__[a-zA-Z0-9_.-]+$/;
16
+
17
+ function strings(values) {
18
+ return values.filter(value => typeof value === 'string' && value.length > 0 && value.length <= 512);
19
+ }
20
+
21
+ function targets(argv) {
22
+ return strings(argv).filter(arg => !arg.startsWith('-') && !arg.includes('://'));
23
+ }
24
+
25
+ function copyOperands(args, operands) {
26
+ const flag = args.findIndex(arg => arg === '-t' || arg === '--target-directory' || arg.startsWith('--target-directory='));
27
+ if (flag < 0) {
28
+ const destination = operands.at(-1);
29
+ const destinationIsDirectory = operands.length > 2 || /(?:\/|\.(?:claude|codex|cursor|osuite))$/.test(destination || '');
30
+ return { sources: operands.slice(0, -1), destination, destinationIsDirectory };
31
+ }
32
+ const option = args[flag];
33
+ const inline = option.startsWith('--target-directory=');
34
+ const remaining = args.filter((_, index) => index !== flag && (inline || index !== flag + 1));
35
+ return { sources: targets(remaining), destination: inline ? option.slice('--target-directory='.length) : args[flag + 1],
36
+ destinationIsDirectory: true };
37
+ }
38
+
39
+ function readHost(value) {
40
+ if (typeof value !== 'string') return null;
41
+ try {
42
+ const url = new URL(value.includes('://') ? value : `https://${value}`);
43
+ if (!['http:', 'https:', 'ftp:', 'ssh:', 'sftp:'].includes(url.protocol) || !url.hostname) return null;
44
+ return { host: url.hostname.toLowerCase().replace(/\.$/, ''), pathname: url.pathname.toLowerCase() };
45
+ } catch { return null; }
46
+ }
47
+
48
+ function networkFacts(values, facts) {
49
+ const decoded = values.map(readHost).filter(Boolean);
50
+ for (const { host, pathname } of decoded) {
51
+ facts.egress_domains.add(host);
52
+ if (host === 'gist.github.com' || host === 'gist.githubusercontent.com' || host === 'pastebin.com'
53
+ || (host === 'api.github.com' && /^\/gists?(?:\/|$)/.test(pathname))) facts.public_relay = true;
54
+ }
55
+ if (!decoded.length || decoded.length !== values.length) facts.unresolved_egress = true;
56
+ }
57
+
58
+ function networkArguments(executable, args, scope, facts) {
59
+ if (args.length === 1 && /^(?:--help|--version|-h|-V)$/.test(args[0])) return;
60
+ const curl = executable === 'curl';
61
+ const switches = curl ? /^-[fsShIiNvq]+$|^--(?:fail|silent|show-error|head|include|verbose|globoff)$/
62
+ : /^-[qSNv]+$|^--(?:quiet|server-response|no-verbose|spider|no-config)$/;
63
+ const withValue = curl ? new Set(['-X', '--request', '-o', '--output', '--max-time', '--connect-timeout', '-d', '--data', '--data-binary', '--data-raw', '--url'])
64
+ : new Set(['-O', '--output-document', '--timeout', '--method', '--body-data', '--max-redirect']);
65
+ const locations = [];
66
+ if (!['curl', 'wget'].includes(executable)) facts.unresolved_egress = true;
67
+ for (let index = 0; index < args.length; index += 1) {
68
+ const arg = args[index];
69
+ if (!arg.startsWith('-')) { locations.push(arg); continue; }
70
+ if (arg === '--') { locations.push(...args.slice(index + 1)); break; }
71
+ if (switches.test(arg)) continue;
72
+ const separator = arg.indexOf('=');
73
+ const option = separator < 0 ? arg : arg.slice(0, separator);
74
+ if (!withValue.has(option)) { facts.unresolved_egress = true; continue; }
75
+ const value = separator < 0 ? args[++index] : arg.slice(separator + 1);
76
+ if (!value) { facts.unresolved_egress = true; continue; }
77
+ if (option === '--url') locations.push(value);
78
+ if (['-d', '--data', '--data-binary'].includes(option) && value.startsWith('@')) trackFile(value.slice(1), scope, facts);
79
+ if (['-o', '-O', '--output', '--output-document'].includes(option) && value !== '-') trackFile(value, scope, facts, true);
80
+ }
81
+ // wget follows redirects by default. Require the explicit zero-redirect posture.
82
+ if (executable === 'wget' && !args.includes('--max-redirect=0')) facts.unresolved_egress = true;
83
+ networkFacts(locations, facts);
84
+ }
85
+
86
+ function trackFile(raw, scope, facts, write = false) {
87
+ if (typeof raw !== 'string' || !raw || raw.length > 512 || raw.includes('\0') || raw.includes('://')) return;
88
+ const file = raw.replaceAll('\\', '/');
89
+ const relative = scope.root && !file.startsWith('~')
90
+ ? path.relative(scope.root, path.resolve(scope.cwd || scope.root, file))
91
+ : path.normalize(file).replace(/^\.\//, '');
92
+ if (!write) {
93
+ if (SECRET_PATH.test(path.normalize(file)) || SECRET_PATH.test(relative)) facts.credential_read = true;
94
+ return;
95
+ }
96
+ if (PROJECT_MANAGED.test(relative) || /^~?\/(?:[^/]+\/)*\.(?:claude|codex|cursor)\/(?:settings(?:\.local)?\.json|config\.toml|hooks\.json|(?:rules|hooks)\/.*)$/i.test(file)) {
97
+ facts.managed_write = true;
98
+ }
99
+ if (relative && relative !== '..' && !relative.startsWith('../') && !path.isAbsolute(relative)) facts.write_paths.add(relative);
100
+ }
101
+
102
+ function shellFacts(command, scope, facts, depth = 0) {
103
+ if (!command || isStdoutPrintf(command)) return;
104
+ const parsed = parseShell(command);
105
+ for (const segment of parsed.segments) {
106
+ const argv = unwrapShellArgv(segment);
107
+ const executable = path.basename(argv[0] || '').toLowerCase();
108
+ const args = argv.slice(1);
109
+ const operands = targets(args);
110
+ if (!executable || OPAQUE_COMMANDS.has(executable)) facts.opaque_dispatch = true;
111
+ if (SHELLS.has(executable)) {
112
+ const flag = args.findIndex(arg => /^-[a-z]*c$/.test(arg));
113
+ if (flag >= 0 && args[flag + 1] && depth < 4) shellFacts(args[flag + 1], scope, facts, depth + 1);
114
+ else if (args.length || parsed.segments.length > 1) facts.opaque_dispatch = true;
115
+ }
116
+ if ((/^(?:python[23]?|node|ruby|perl|deno)$/.test(executable) && args.some(arg => /^-(?:c|e|p|E)$|^--eval(?:=|$)/.test(arg)))
117
+ || (executable === 'find' && args.some(arg => /^-exec(?:dir)?$/.test(arg)))) facts.opaque_dispatch = true;
118
+ if ((executable === 'cd' || executable === 'pushd') && parsed.segments.length > 1) facts.opaque_dispatch = true;
119
+ if (NETWORK_COMMANDS.has(executable)) networkArguments(executable, args, scope, facts);
120
+ if (NETWORK_COMMANDS.has(executable) && parsed.errors.length > 0) facts.unresolved_egress = true;
121
+ if (executable === 'gh' && (args[0] === 'gist' || args[0] === 'api' && args.some(arg => /(?:^|\/)gists?(?:\b|\/)/.test(arg)))) {
122
+ facts.public_relay = true;
123
+ }
124
+ if (executable === 'git' && args.some(arg => ['clone', 'fetch', 'pull', 'push'].includes(arg))) {
125
+ const locations = args.filter(arg => /^(?:https?|ssh):\/\//i.test(arg));
126
+ if (locations.length) networkFacts(locations, facts);
127
+ }
128
+ if (FILE_READERS.has(executable)) {
129
+ for (const operand of operands) trackFile(operand.split(/[<>]/)[0], scope, facts);
130
+ if (parsed.errors.includes('unsupported_glob_expansion') && args.some(arg => /(?:^|\/)\.(?:env|aws|ssh)[\w.*?/-]*/.test(arg))) {
131
+ facts.credential_read = true;
132
+ }
133
+ if (args.some(arg => arg.includes('$'))) facts.opaque_dispatch = true;
134
+ }
135
+ const inPlace = executable === 'sed' && args.some(arg => /^-i|^--in-place(?:=|$)/.test(arg));
136
+ if (FILE_COPIERS.has(executable) && !(executable === 'install' && args.some(arg => arg === '-d' || arg === '--directory'))) {
137
+ const { sources, destination, destinationIsDirectory } = copyOperands(args, operands);
138
+ for (const source of sources) trackFile(source, scope, facts);
139
+ trackFile(destination, scope, facts, true);
140
+ if (destination && destinationIsDirectory) {
141
+ for (const source of sources) trackFile(path.join(destination, path.basename(source)), scope, facts, true);
142
+ }
143
+ } else if (FILE_WRITERS.has(executable) || inPlace) {
144
+ for (const operand of operands) trackFile(operand, scope, facts, true);
145
+ }
146
+ // Redirect operands appear as ordinary tokens in the conservative shell parser.
147
+ if (parsed.errors.includes('unsupported_shell_syntax')) {
148
+ for (let index = 0; index < args.length; index += 1) {
149
+ const redirect = /^[0-9]*([<>]+)(.*)$/.exec(args[index]) || /([<>]+)(.*)$/.exec(args[index]);
150
+ if (redirect) trackFile(redirect[2] || args[index + 1], scope, facts, redirect[1].startsWith('>'));
151
+ }
152
+ }
153
+ const rmFlags = args.slice(0, args.includes('--') ? args.indexOf('--') : undefined);
154
+ const recursive = rmFlags.some(arg => arg === '--recursive' || /^-[^-]*[rR]/.test(arg));
155
+ const force = rmFlags.some(arg => arg === '--force' || /^-[^-]*f/.test(arg));
156
+ if (executable === 'rm' && recursive && force && operands.some(file => {
157
+ if (!scope.root || file.startsWith('~') || /[\$*`?\[]/.test(file)) return true;
158
+ const target = path.relative(scope.root, path.resolve(scope.cwd || scope.root, file));
159
+ return !target || target === '..' || target.startsWith('../');
160
+ })) facts.destructive = true;
161
+ const globalOptions = new Set(['-n', '--namespace', '--context', '--kubeconfig', '--server', '--cluster', '--user']);
162
+ const op = args.find((arg, index) => !arg.startsWith('-') && !globalOptions.has(args[index - 1]));
163
+ if ((executable === 'kubectl' && op === 'delete') || (executable === 'terraform' && op === 'destroy')) facts.destructive = true;
164
+ }
165
+ if (parsed.errors.includes('unsupported_expansion') && /\$\(|`|<\(|>\(/.test(command)) facts.opaque_dispatch = true;
166
+ }
167
+
168
+ export function extractCodingAgentFacts({ tool_name: tool, tool_input: value, cwd }, workspaceRoot) {
169
+ const input = isObject(value) ? value : {};
170
+ const facts = { schema_version: 'osuite.coding_agent_facts.v1', egress_domains: new Set(), write_paths: new Set() };
171
+ const scope = { root: typeof workspaceRoot === 'string' && path.isAbsolute(workspaceRoot) ? path.normalize(workspaceRoot) : '', cwd };
172
+ if (['Bash', 'Shell', 'exec_command'].includes(tool)) shellFacts(typeof input.command === 'string' ? input.command : '', scope, facts);
173
+ if (typeof tool === 'string' && tool.startsWith('mcp__')) {
174
+ facts.mcp_tool = MCP_ID.test(tool) ? tool : 'unresolved';
175
+ for (const target of strings([input.path, input.file_path, input.notebook_path])) trackFile(target, scope, facts);
176
+ }
177
+ if (['WebFetch', 'WebSearch', 'web.fetch', 'web.post', 'HttpRequest'].includes(tool)) {
178
+ networkFacts(strings([input.url, input.uri, ...(Array.isArray(input.allowed_domains) ? input.allowed_domains : [])]), facts);
179
+ } else if (facts.mcp_tool && (typeof input.url === 'string' || typeof input.uri === 'string')) {
180
+ networkFacts(strings([input.url, input.uri]), facts);
181
+ }
182
+ if (READ_TOOLS.has(tool) || WRITE_TOOLS.has(tool)) {
183
+ for (const target of strings([input.path, input.file_path, input.notebook_path])) trackFile(target, scope, facts, WRITE_TOOLS.has(tool));
184
+ }
185
+ if (tool === 'apply_patch') {
186
+ const patch = [value, input.patch, input.input, input.diff, input.command].find(item => typeof item === 'string') || '';
187
+ for (const match of patch.matchAll(/^\*\*\* (?:Update File|Delete File|Add File|Move to): (.+)$/gm)) trackFile(match[1].trim(), scope, facts, true);
188
+ }
189
+ if (facts.egress_domains.size > 32) facts.unresolved_egress = true;
190
+ if (facts.write_paths.size > 32) facts.opaque_dispatch = true;
191
+ return { ...facts, egress_domains: [...facts.egress_domains].sort().slice(0, 32), write_paths: [...facts.write_paths].sort().slice(0, 32) };
192
+ }
@@ -1,6 +1,20 @@
1
1
  import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
4
+ import { readCredentialFile } from './credentials.mjs';
5
+
6
+ function parseDotenv(body) {
7
+ const values = {};
8
+ for (const line of (body || '').split(/\r?\n/)) {
9
+ const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
10
+ if (!match) continue;
11
+ let value = match[2];
12
+ if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
13
+ else value = value.replace(/\s+#.*$/, '');
14
+ values[match[1]] = value;
15
+ }
16
+ return values;
17
+ }
4
18
 
5
19
  function readDotenv(installDir, filename = '.env') {
6
20
  let fd;
@@ -8,16 +22,7 @@ function readDotenv(installDir, filename = '.env') {
8
22
  fd = openSync(path.join(installDir, filename), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | constants.O_NONBLOCK);
9
23
  const stat = fstatSync(fd);
10
24
  if (!stat.isFile() || stat.size > 65536) return {};
11
- const values = {};
12
- for (const line of readFileSync(fd, 'utf8').split(/\r?\n/)) {
13
- const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
14
- if (!match) continue;
15
- let value = match[2];
16
- if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
17
- else value = value.replace(/\s+#.*$/, '');
18
- values[match[1]] = value;
19
- }
20
- return values;
25
+ return parseDotenv(readFileSync(fd, 'utf8'));
21
26
  } catch { return {}; }
22
27
  finally { if (fd !== undefined) closeSync(fd); }
23
28
  }
@@ -25,7 +30,11 @@ function readDotenv(installDir, filename = '.env') {
25
30
  export function loadRuntimeConfig({ installDir, env = process.env, host = 'claude', runtimeId } = {}) {
26
31
  const plugin = runtimeId === 'codex_plugin';
27
32
  const hardened = plugin || host === 'cursor';
28
- const source = { ...(installDir ? readDotenv(installDir) : {}), ...(plugin && installDir ? readDotenv(installDir, '.env.osuite') : {}), ...env };
33
+ const directory = installDir && path.basename(path.resolve(installDir));
34
+ const project = !plugin && directory === `.${host}`;
35
+ const dotenv = project ? parseDotenv(readCredentialFile(path.dirname(path.resolve(installDir)), `${directory}/.env`, { maxBytes: 65536, checkGit: false }))
36
+ : installDir ? readDotenv(installDir) : {};
37
+ const source = { ...dotenv, ...(plugin && installDir ? readDotenv(installDir, '.env.osuite') : {}), ...env };
29
38
  const get = (name, fallback = '') => source[`OSUITE_${name}`] ?? source[`DASHCLAW_${name}`] ?? fallback;
30
39
  const number = (name, fallback, min, max) => {
31
40
  const value = Number(get(name, fallback));
@@ -34,7 +43,7 @@ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claud
34
43
  const requestedMode = get('HOOK_MODE', host === 'cursor' ? 'observe' : 'enforce');
35
44
  const mode = ['observe', 'enforce', 'strict'].includes(requestedMode) ? requestedMode : 'strict';
36
45
  return {
37
- host,
46
+ host, projectRoot: project ? path.dirname(path.resolve(installDir)) : undefined,
38
47
  ruleRolloutCapability: get('SCOPED_RULE_ROLLOUT') === '1' ? RULE_ROLLOUT_CAPABILITY : undefined,
39
48
  runtimeId: get('RUNTIME_ADAPTER_ID', runtimeId || (host === 'cursor' ? 'cursor_hooks' : host === 'codex' ? 'codex_hooks' : 'claude_code_hooks')),
40
49
  agentId: get('AGENT_ID', plugin ? 'codex-plugin-runtime' : host === 'cursor' ? 'cursor' : host === 'codex' ? 'codex' : 'claude-code'),
@@ -1,6 +1,7 @@
1
1
  import { canonicalJson, isObject, safeId, sha256, toolInputDigest } from './protocol.mjs';
2
- import { classifyShell } from './shell.mjs';
2
+ import { classifyShell, isStdoutPrintf } from './shell.mjs';
3
3
  import { collectGitPublication } from './git.mjs';
4
+ import { extractCodingAgentFacts } from './coding-agent-facts.mjs';
4
5
 
5
6
  const contentKeys = new Set(['content', 'new_string', 'old_string', 'new_source', 'old_source', 'file_text', 'patch', 'diff', 'input']);
6
7
  const publicHosts = new Set(['file.io', 'transfer.sh', '0x0.st', 'pastebin.com', 'gofile.io', 'wetransfer.com', 'tmpfiles.org']);
@@ -91,7 +92,7 @@ export function buildActionContext(data, config) {
91
92
  if (publication) mapped.summary.git_publication = publication;
92
93
  // Keep the reference externality hints in addition to structural shell semantics.
93
94
  const external = genericContext(tool, input, config.captureToolInput);
94
- if (external.summary.destination_type || external.sensitive_data_categories?.length) {
95
+ if (!isStdoutPrintf(objectInput.command) && (external.summary.destination_type || external.sensitive_data_categories?.length)) {
95
96
  mapped = { ...external, ...mapped, risk_score: Math.max(mapped.risk_score, external.risk_score), summary: { ...external.summary, ...mapped.summary } };
96
97
  }
97
98
  } else if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch'].includes(tool)) {
@@ -110,13 +111,21 @@ export function buildActionContext(data, config) {
110
111
  }
111
112
  if (goal.length > 2000) throw new Error('Tool evidence exceeds declared_goal schema; not truncated');
112
113
  const { summary, reversible, ...fields } = mapped;
114
+ const facts = extractCodingAgentFacts({ ...data, cwd: objectInput.workdir || objectInput.working_directory || data.cwd }, config.projectRoot || data.cwd);
113
115
  const signal = autonomySignal(data, config);
114
116
  const context = { ...fields, ...(typeof reversible === 'boolean' ? { reversible } : {}), agent_id: config.agentId, declared_goal: goal,
115
117
  runtime_session_id: deriveSessionId(data, config), tool_use_id: deriveToolUseId(data), tool_input_digest: toolInputDigest(tool, input),
116
118
  runtime_family: 'tool_hook_runtime', adapter_mode: 'hook', install_channel: config.installChannel, settings_scope: config.settingsScope,
117
119
  trusted_project_required: config.trustedProjectRequired === true, ...signal,
118
- input_summary: JSON.stringify({ ...summary, ...signal, runtime_adapter_id: config.runtimeId, runtime_family: 'tool_hook_runtime', adapter_mode: 'hook' }) };
120
+ input_summary: JSON.stringify({ ...summary, ...signal, coding_agent_facts: facts,
121
+ runtime_adapter_id: config.runtimeId, runtime_family: 'tool_hook_runtime', adapter_mode: 'hook' }) };
119
122
  if (context.input_summary.length > 4000 || context.tool_use_id.length > 128 || !safeId(context.tool_use_id)) throw new Error('Tool evidence exceeds action schema; not truncated');
123
+ if (data.business_authority_assertion !== undefined) {
124
+ if (!isObject(data.business_authority_assertion) || Buffer.byteLength(canonicalJson(data.business_authority_assertion)) > 8192) {
125
+ throw new Error('Invalid business authority evidence');
126
+ }
127
+ context.business_authority_assertion = data.business_authority_assertion;
128
+ }
120
129
  if (config.installCheck) context.health_check = true;
121
130
  return context;
122
131
  }