@optimuslabs/harness-map-staging 1.5.16
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.
- package/README.md +46 -0
- package/dist/apply_deferred_vscdb.js +38 -0
- package/dist/bootstrap_constants.js +15 -0
- package/dist/cli/bash_script_generator.js +95 -0
- package/dist/cli.js +144 -0
- package/dist/cli_invocation_match.js +30 -0
- package/dist/compliance_check_runner.js +57 -0
- package/dist/compliance_prompt_gate.js +396 -0
- package/dist/dialog_prefs_cli.js +109 -0
- package/dist/endpoint_client/compress_payload.js +25 -0
- package/dist/endpoint_client/http_transport.js +90 -0
- package/dist/endpoint_client/index.js +3 -0
- package/dist/endpoint_client/registry_api.js +41 -0
- package/dist/endpoint_client/startup_api.js +44 -0
- package/dist/endpoint_client/types.js +4 -0
- package/dist/execute_trusted_restarts.js +60 -0
- package/dist/log_config_files/auth/auth_flow.js +22 -0
- package/dist/log_config_files/auth/auth_key_store.js +14 -0
- package/dist/log_config_files/collection/claude_desktop_extensions_collector.js +248 -0
- package/dist/log_config_files/collection/claude_known_projects_collector.js +42 -0
- package/dist/log_config_files/collection/claude_token_usage_collector.js +203 -0
- package/dist/log_config_files/collection/codex_token_usage_collector.js +342 -0
- package/dist/log_config_files/collection/config_collector.js +245 -0
- package/dist/log_config_files/collection/copilot_token_usage_collector.js +167 -0
- package/dist/log_config_files/collection/cowork_desktop_version_collector.js +60 -0
- package/dist/log_config_files/collection/cowork_session_whitelist.js +89 -0
- package/dist/log_config_files/collection/cursor_project_mcp_collector.js +230 -0
- package/dist/log_config_files/collection/cursor_project_workspace_activity.js +73 -0
- package/dist/log_config_files/collection/cursor_token_usage_collector.js +192 -0
- package/dist/log_config_files/collection/directory_collector.js +126 -0
- package/dist/log_config_files/collection/enrichment_helpers.js +53 -0
- package/dist/log_config_files/collection/ensure_cursor_user_settings_snapshot.js +50 -0
- package/dist/log_config_files/collection/file_type_rules.js +47 -0
- package/dist/log_config_files/collection/grok_cli_version_collector.js +53 -0
- package/dist/log_config_files/collection/hermes_token_usage_collector.js +241 -0
- package/dist/log_config_files/collection/mcp_tool_collector.js +106 -0
- package/dist/log_config_files/collection/metadata_merge.js +43 -0
- package/dist/log_config_files/collection/openclaw_helpers.js +55 -0
- package/dist/log_config_files/collection/openclaw_token_usage_collector.js +223 -0
- package/dist/log_config_files/collection/opencode_token_usage_collector.js +177 -0
- package/dist/log_config_files/collection/pi_token_usage_collector.js +239 -0
- package/dist/log_config_files/collection/plugin_collector.js +223 -0
- package/dist/log_config_files/collection/plugin_version_helpers.js +37 -0
- package/dist/log_config_files/collection/skills_cli_collector.js +162 -0
- package/dist/log_config_files/index.js +19 -0
- package/dist/log_config_files/paths/path_constants_helpers.js +71 -0
- package/dist/log_config_files/paths/pattern_resolver.js +326 -0
- package/dist/log_config_files/readers/composer_shadow_merge.js +67 -0
- package/dist/log_config_files/readers/cursor_shadow_merge_ruleset.js +46 -0
- package/dist/log_config_files/readers/file_readers.js +196 -0
- package/dist/log_config_files/readers/vscdb_config_builder.js +148 -0
- package/dist/log_config_files/readers/vscdb_reactive_storage.js +62 -0
- package/dist/log_config_files/readers/vscdb_reader.js +337 -0
- package/dist/log_config_files/runtime/client_event_reporter.js +347 -0
- package/dist/log_config_files/runtime/compliance_check.js +1013 -0
- package/dist/log_config_files/runtime/compliance_session_log.js +378 -0
- package/dist/log_config_files/runtime/dialog_preferences.js +31 -0
- package/dist/log_config_files/runtime/hardware_uuid.js +36 -0
- package/dist/log_config_files/runtime/hook_logger.js +267 -0
- package/dist/log_config_files/runtime/hook_type_for_request.js +30 -0
- package/dist/log_config_files/runtime/log_metadata.js +122 -0
- package/dist/log_config_files/runtime/main_runner.js +376 -0
- package/dist/log_config_files/runtime/management_storage.js +144 -0
- package/dist/log_config_files/runtime/ops_target_path.js +18 -0
- package/dist/log_config_files/runtime/remediation_apply_tracking.js +152 -0
- package/dist/log_config_files/runtime/remediation_config_path.js +140 -0
- package/dist/log_config_files/runtime/remediation_sync.js +1705 -0
- package/dist/log_config_files/runtime/secret_regex_scan.js +126 -0
- package/dist/log_config_files/runtime/sqlite_binary.js +124 -0
- package/dist/log_config_files/runtime/trusted_restarts.js +113 -0
- package/dist/log_config_files/runtime/workspace_repo.js +170 -0
- package/dist/log_config_files/runtime/worktree_absent.js +50 -0
- package/dist/log_config_files/runtime/worktree_scanner.js +137 -0
- package/dist/log_config_files/sender/batch_sender.js +283 -0
- package/dist/log_config_files/sender/endpoint_config.js +24 -0
- package/dist/log_config_files/sender/signing.js +1 -0
- package/dist/log_sensitive_paths_audit.js +89 -0
- package/dist/log_uuid/auth_key_store.js +37 -0
- package/dist/log_uuid/hardware_uuid.js +35 -0
- package/dist/log_uuid/index.js +11 -0
- package/dist/log_uuid/log_uuid_helper.js +30 -0
- package/dist/log_uuid/startup_sender.js +131 -0
- package/dist/log_uuid/user_profile.js +192 -0
- package/dist/remediation_change_preview.js +182 -0
- package/dist/tofu.js +22 -0
- package/dist/tofu_environment.js +36 -0
- package/dist/types/config_file_types.js +1 -0
- package/package.json +67 -0
package/README.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
## log-llm-config (`@optimuslabs/harness-map-staging`)
|
|
2
|
+
|
|
3
|
+
CLI helpers for Optimus Security startup workflows.
|
|
4
|
+
|
|
5
|
+
### Prerequisites
|
|
6
|
+
|
|
7
|
+
- Node.js 18+
|
|
8
|
+
- `OPTIMUS_ENDPOINT` defined in `optimus.env` (e.g. `http://localhost:8080/endpoint_security/`)
|
|
9
|
+
|
|
10
|
+
### Commands
|
|
11
|
+
|
|
12
|
+
#### `log_uuid`
|
|
13
|
+
|
|
14
|
+
Collects the machine hardware UUID (or uses the `OPTIMUS_HARDWARE_UUID` env variable), prints it, and POSTs a startup payload to `OPTIMUS_ENDPOINT/startup/`. If the server responds with a key, it stores it at `~/.optimuslabs/management/auth_key.txt`.
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
OPTIMUS_ENDPOINT=http://localhost:8080/endpoint_security/ \
|
|
18
|
+
npx --yes --package=@optimuslabs/harness-map-staging@latest log_uuid-staging
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- **Optional flags** (for git context, similar to `optimus-init`):
|
|
22
|
+
- `--uuid <hw_uuid>` – override hardware UUID
|
|
23
|
+
- `--user <git_user>` – e.g. `$(git config user.name)`
|
|
24
|
+
- `--repo <git_remote>` – e.g. `$(git remote -v)`
|
|
25
|
+
- `--branch <git_branch>` – e.g. `$(git branch --show-current)`
|
|
26
|
+
- `--agent <agent_name>` – e.g. `Cursor`
|
|
27
|
+
|
|
28
|
+
#### `log-llm-config`
|
|
29
|
+
|
|
30
|
+
Legacy helper that logs local Optimus/Cursor configuration files to `configs.txt`.
|
|
31
|
+
|
|
32
|
+
You can also pass the UUID explicitly:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npx --yes --package=@optimuslabs/harness-map-staging@latest log_uuid-staging --uuid "DUMMY-LOCAL-UUID"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Development
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm install
|
|
42
|
+
npm run build
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
> Proprietary package. Do not publish to public registries.
|
|
46
|
+
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Runs after Cursor SIGKILL: applies queued state.vscdb patches, then immediately runs
|
|
3
|
+
// post-restart verification so the server gets `verified` without waiting for the next prompt.
|
|
4
|
+
import { applyDeferredVscdbFromDisk } from './log_config_files/runtime/remediation_sync.js';
|
|
5
|
+
import { runPostApplyVerification } from './log_config_files/runtime/compliance_check.js';
|
|
6
|
+
import { hookRunLog } from './log_config_files/runtime/hook_logger.js';
|
|
7
|
+
import { finalizeAndUploadComplianceSessionLog, setActiveComplianceLogPath, } from './log_config_files/runtime/compliance_session_log.js';
|
|
8
|
+
const complianceLogPath = process.env.OPTIMUS_COMPLIANCE_LOG?.trim() || null;
|
|
9
|
+
if (complianceLogPath) {
|
|
10
|
+
setActiveComplianceLogPath(complianceLogPath);
|
|
11
|
+
}
|
|
12
|
+
applyDeferredVscdbFromDisk()
|
|
13
|
+
.then(async (ok) => {
|
|
14
|
+
if (ok) {
|
|
15
|
+
try {
|
|
16
|
+
const outcomes = await runPostApplyVerification();
|
|
17
|
+
if (outcomes.length > 0) {
|
|
18
|
+
hookRunLog(`apply_deferred_vscdb: post_apply_verification count=${outcomes.length} ` +
|
|
19
|
+
`verified=${outcomes.filter((o) => o.status === 'verified').length}`);
|
|
20
|
+
}
|
|
21
|
+
if (complianceLogPath) {
|
|
22
|
+
await finalizeAndUploadComplianceSessionLog(complianceLogPath);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
catch (e) {
|
|
26
|
+
hookRunLog(`apply_deferred_vscdb: post_apply_verification error: ${e instanceof Error ? e.message : String(e)}`);
|
|
27
|
+
if (complianceLogPath) {
|
|
28
|
+
await finalizeAndUploadComplianceSessionLog(complianceLogPath, 'failures');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
else if (complianceLogPath) {
|
|
33
|
+
hookRunLog('apply_deferred_vscdb: apply failed');
|
|
34
|
+
await finalizeAndUploadComplianceSessionLog(complianceLogPath, 'failures');
|
|
35
|
+
}
|
|
36
|
+
process.exit(ok ? 0 : 1);
|
|
37
|
+
})
|
|
38
|
+
.catch(() => process.exit(1));
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bootstrap-level path constants — known before the API response is available.
|
|
3
|
+
* Used by auth, hook logging, and audit output. Do not add agent-specific paths here.
|
|
4
|
+
*/
|
|
5
|
+
export const OPTIMUSLABS_MANAGEMENT_REL = '.optimuslabs/management';
|
|
6
|
+
/**
|
|
7
|
+
* All hook-written log files live under this subdirectory, grouped by type
|
|
8
|
+
* (see LOG_GROUP_* below). Keeping logs in one subtree leaves the management
|
|
9
|
+
* root limited to secrets/identity/state (auth_key, organization-uuid, contracts).
|
|
10
|
+
*/
|
|
11
|
+
export const OPTIMUSLABS_LOGS_REL = `${OPTIMUSLABS_MANAGEMENT_REL}/logs`;
|
|
12
|
+
/** Log group subdirectories under {@link OPTIMUSLABS_LOGS_REL}. */
|
|
13
|
+
export const LOG_GROUP_HOOK = 'hook';
|
|
14
|
+
export const LOG_GROUP_COMPLIANCE = 'compliance';
|
|
15
|
+
export const LOG_GROUP_AUDIT = 'audit';
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { readFileCollectionVscdbContract } from '../log_config_files/runtime/management_storage.js';
|
|
2
|
+
/** Reactive ItemTable key from backend-derived cache (written on log-config); same path as remediations. */
|
|
3
|
+
function readReactiveStorageItemKeyFromDisk() {
|
|
4
|
+
const k = readFileCollectionVscdbContract()?.reactive_storage_item_key;
|
|
5
|
+
return typeof k === 'string' && k.trim() !== '' ? k.trim() : null;
|
|
6
|
+
}
|
|
7
|
+
const fileCategories = [
|
|
8
|
+
{ label: 'Cursor: mcp.json', targets: ['./.cursor/mcp.json', '$HOME/.cursor/mcp.json'] },
|
|
9
|
+
{ label: 'Claude: .mcp.json', targets: ['./mcp.json', './.mcp.json', '/Library/Application Support/ClaudeCode/managed-mcp.json'] },
|
|
10
|
+
{ label: 'Claude: settings.json', targets: ['./.claude/settings.json', './.claude/settings.local.json', '$HOME/.claude/settings.json', '/Library/Application Support/ClaudeCode/managed-settings.json'] },
|
|
11
|
+
{ label: 'Cursor: hooks.json', targets: ['./.cursor/hooks.json', '$HOME/.cursor/hooks.json', '/Library/Application Support/Cursor/hooks.json'] },
|
|
12
|
+
{ label: 'Cursor: User/settings.json (user-level)', targets: ['$HOME/Library/Application Support/Cursor/User/settings.json'] },
|
|
13
|
+
];
|
|
14
|
+
function buildSqliteCategories() {
|
|
15
|
+
const key = readReactiveStorageItemKeyFromDisk();
|
|
16
|
+
if (!key)
|
|
17
|
+
return [];
|
|
18
|
+
return [
|
|
19
|
+
{
|
|
20
|
+
label: 'Cursor: state.vscdb (reactive blob / composerState)',
|
|
21
|
+
dbPath: '$HOME/Library/Application Support/Cursor/User/globalStorage/state.vscdb',
|
|
22
|
+
table: 'ItemTable',
|
|
23
|
+
key,
|
|
24
|
+
jsonPaths: [['composerState'], []],
|
|
25
|
+
},
|
|
26
|
+
];
|
|
27
|
+
}
|
|
28
|
+
function buildFileCategoryLines(category) {
|
|
29
|
+
return [
|
|
30
|
+
`echo "===== ${category.label} ====="`,
|
|
31
|
+
'files=(', ...category.targets.map((t) => ` "${t}"`), ')',
|
|
32
|
+
'expanded_files=()', 'paths=()', 'display_paths=()',
|
|
33
|
+
'for f in "${files[@]}"; do',
|
|
34
|
+
' expanded=$(eval echo "$f")',
|
|
35
|
+
' expanded_dir=$(dirname "$expanded")', ' expanded_base=$(basename "$expanded")',
|
|
36
|
+
' abs_dir=$(cd "$expanded_dir" 2>/dev/null && pwd || echo "$expanded_dir")',
|
|
37
|
+
' abs_path="$abs_dir/$expanded_base"', ' expanded_files+=("$abs_path")',
|
|
38
|
+
' relative_path="$(to_relative "$abs_path")"', ' paths+=("$relative_path")', ' display_paths+=("$relative_path")',
|
|
39
|
+
'done', 'echo ""',
|
|
40
|
+
'if [ ${#paths[@]} -gt 0 ]; then', ' echo "Paths:"',
|
|
41
|
+
' printf "%s\\n" "${paths[@]}" | awk \'!seen[$0]++\' | while IFS= read -r dir; do', ' echo "$dir"', ' done',
|
|
42
|
+
' echo ""', 'else', ' echo "Paths: (none)"', 'fi', 'echo ""',
|
|
43
|
+
'for idx in "${!expanded_files[@]}"; do', ' expanded="${expanded_files[$idx]}"', ' display="${display_paths[$idx]}"',
|
|
44
|
+
' if [ -f "$expanded" ]; then',
|
|
45
|
+
` echo "===== ${category.label}: $display ====="`, ' cat "$expanded"',
|
|
46
|
+
' else', ` echo "===== ${category.label}: missing: $display ====="`, ' fi',
|
|
47
|
+
'done', 'echo ""',
|
|
48
|
+
];
|
|
49
|
+
}
|
|
50
|
+
function buildSqliteCategoryLines(category) {
|
|
51
|
+
const jsonPathsLiteral = JSON.stringify(category.jsonPaths);
|
|
52
|
+
const safeSqlKey = category.key.replace(/'/g, "''");
|
|
53
|
+
return [
|
|
54
|
+
`echo "===== ${category.label} ====="`, `db_path="${category.dbPath}"`,
|
|
55
|
+
'expanded=$(eval echo "$db_path")',
|
|
56
|
+
'if [ -f "$expanded" ]; then', ' if command -v sqlite3 >/dev/null 2>&1; then',
|
|
57
|
+
' echo "===== $expanded ====="',
|
|
58
|
+
` query_result=$(sqlite3 "$expanded" "SELECT value FROM ${category.table} WHERE key='${safeSqlKey}'")`,
|
|
59
|
+
' if [ -n "$query_result" ]; then',
|
|
60
|
+
` echo "===== key: ${category.key} ====="`,
|
|
61
|
+
` LOG_CONFIG_JSON_VALUE="$query_result" python3 - <<'PY'`,
|
|
62
|
+
'import json', 'import os', '',
|
|
63
|
+
'raw = os.environ.get("LOG_CONFIG_JSON_VALUE", "")',
|
|
64
|
+
'if not raw:', ' print("{}")', ' raise SystemExit',
|
|
65
|
+
`paths = ${jsonPathsLiteral}`,
|
|
66
|
+
'try:', ' data = json.loads(raw)',
|
|
67
|
+
'except json.JSONDecodeError as exc:', ' print(f"failed to parse JSON: {exc}")', ' raise SystemExit',
|
|
68
|
+
'def walk(obj, path):', ' cur = obj',
|
|
69
|
+
' for segment in path:', ' if isinstance(cur, dict):', ' cur = cur.get(segment)', ' else:', ' return None',
|
|
70
|
+
' return cur',
|
|
71
|
+
'selected_value = None', 'selected_label = None',
|
|
72
|
+
'for path in paths:', ' value = walk(data, path)',
|
|
73
|
+
' if value is not None:', ' selected_value = value', ' selected_label = ".".join(path) if path else "root"', ' break',
|
|
74
|
+
'if selected_value is None:', ' print("{}")',
|
|
75
|
+
'else:', ' print(f"[path: {selected_label}]")', ' print(json.dumps(selected_value, indent=2, sort_keys=True))',
|
|
76
|
+
'PY',
|
|
77
|
+
' else', ` echo "===== key not found: ${category.key} ====="`, ' fi',
|
|
78
|
+
' else', ' echo "===== sqlite3 not found; skipping ====="', ' fi',
|
|
79
|
+
'else', ' echo "===== missing: $expanded ====="', 'fi', 'echo ""',
|
|
80
|
+
];
|
|
81
|
+
}
|
|
82
|
+
function renderBashScript() {
|
|
83
|
+
const scriptLines = [
|
|
84
|
+
'#!/usr/bin/env bash', 'set -euo pipefail',
|
|
85
|
+
'output_file="$(pwd)/configs.txt"', ': > "$output_file"', 'exec >"$output_file"', 'exec 2>&1', '',
|
|
86
|
+
'repo_root="$(pwd)"',
|
|
87
|
+
'to_relative() {', ' local path="$1"', ' if [[ "$path" == "$repo_root"* ]]; then',
|
|
88
|
+
' local suffix="${path#"$repo_root"}"', ' if [ -z "$suffix" ]; then', ' echo "<project_root>"',
|
|
89
|
+
' else', ' echo "<project_root>${suffix}"', ' fi', ' else', ' echo "$path"', ' fi', '}', '',
|
|
90
|
+
...fileCategories.flatMap(buildFileCategoryLines),
|
|
91
|
+
...buildSqliteCategories().flatMap(buildSqliteCategoryLines),
|
|
92
|
+
];
|
|
93
|
+
return scriptLines.join('\n');
|
|
94
|
+
}
|
|
95
|
+
export { renderBashScript };
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { renderBashScript } from './cli/bash_script_generator.js';
|
|
3
|
+
const args = process.argv.slice(2);
|
|
4
|
+
const main = async () => {
|
|
5
|
+
if (args[0] === 'log_uuid') {
|
|
6
|
+
parseAndSetLogUuidEnvVars();
|
|
7
|
+
await import('./log_uuid/index.js');
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
if (args[0] === 'log_config_files') {
|
|
11
|
+
const { main, logSingleFile } = await import('./log_config_files/index.js');
|
|
12
|
+
const filePathArg = args.find((arg, idx) => idx > 0 && !arg.startsWith('-') && (arg.includes('/') || arg.endsWith('.json') || arg.endsWith('.md')));
|
|
13
|
+
if (filePathArg) {
|
|
14
|
+
const success = await logSingleFile(filePathArg);
|
|
15
|
+
try {
|
|
16
|
+
process.exit(success ? 0 : 1);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// process.exit may be mocked in tests (throws instead of exiting); allow process to continue
|
|
20
|
+
}
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
await main();
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (args[0] === 'log_sensitive_paths_audit') {
|
|
27
|
+
const { main } = await import('./log_sensitive_paths_audit.js');
|
|
28
|
+
await main();
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (args[0] === 'compliance_prompt_gate') {
|
|
32
|
+
const { runCompliancePromptGateCli } = await import('./compliance_prompt_gate.js');
|
|
33
|
+
await runCompliancePromptGateCli();
|
|
34
|
+
process.exit(0);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (args[0] === 'compliance_check_runner') {
|
|
38
|
+
await import('./compliance_check_runner.js');
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (args[0] === 'dialog_prefs' ||
|
|
42
|
+
args[0] === 'is_suppressed' ||
|
|
43
|
+
args[0] === 'set_suppress' ||
|
|
44
|
+
args[0] === 'show') {
|
|
45
|
+
const { runDialogPrefsCli } = await import('./dialog_prefs_cli.js');
|
|
46
|
+
await runDialogPrefsCli();
|
|
47
|
+
process.exit(0);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
// `npx --package=@optimuslabs/harness-map-staging@latest <name>` runs this file (default bin) with args[0] set — not the named bin file.
|
|
51
|
+
if (args[0] === 'execute-trusted-restarts') {
|
|
52
|
+
const { runExecuteTrustedRestartsFromStdin } = await import('./execute_trusted_restarts.js');
|
|
53
|
+
try {
|
|
54
|
+
runExecuteTrustedRestartsFromStdin();
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
console.error(e instanceof Error ? e.message : String(e));
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
process.exit(0);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (args[0] === 'apply-deferred-vscdb') {
|
|
64
|
+
await import('./apply_deferred_vscdb.js');
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
// No command matched — output legacy bash script
|
|
68
|
+
console.log(renderBashScript());
|
|
69
|
+
};
|
|
70
|
+
function parseAndSetLogUuidEnvVars() {
|
|
71
|
+
let uuidArg;
|
|
72
|
+
let userArg;
|
|
73
|
+
let repoArg;
|
|
74
|
+
let branchArg;
|
|
75
|
+
let agentArg;
|
|
76
|
+
for (let i = 1; i < args.length; i++) {
|
|
77
|
+
const arg = args[i];
|
|
78
|
+
if (arg === '--uuid' || arg === '-u') {
|
|
79
|
+
uuidArg = args[++i];
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (arg === '--user') {
|
|
83
|
+
userArg = args[++i];
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (arg === '--repo') {
|
|
87
|
+
repoArg = args[++i];
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (arg === '--branch') {
|
|
91
|
+
branchArg = args[++i];
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (arg === '--agent') {
|
|
95
|
+
agentArg = args[++i];
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (!arg.startsWith('-') && !uuidArg)
|
|
99
|
+
uuidArg = arg;
|
|
100
|
+
}
|
|
101
|
+
if (uuidArg)
|
|
102
|
+
process.env.OPTIMUS_HARDWARE_UUID = uuidArg;
|
|
103
|
+
if (userArg)
|
|
104
|
+
process.env.GITHUB_USER = userArg;
|
|
105
|
+
if (repoArg) {
|
|
106
|
+
process.env.OPTIMUS_WORKSPACE_REPO = repoArg;
|
|
107
|
+
process.env.GITHUB_REPOSITORY = repoArg;
|
|
108
|
+
}
|
|
109
|
+
if (branchArg)
|
|
110
|
+
process.env.GITHUB_REF_NAME = branchArg;
|
|
111
|
+
if (agentArg)
|
|
112
|
+
process.env.OPTIMUS_AGENT = agentArg;
|
|
113
|
+
}
|
|
114
|
+
/** Map each cli command to its functional unit for failure telemetry. */
|
|
115
|
+
const COMMAND_UNIT = {
|
|
116
|
+
log_uuid: 'auth_version',
|
|
117
|
+
log_config_files: 'inventory',
|
|
118
|
+
log_sensitive_paths_audit: 'inventory',
|
|
119
|
+
compliance_prompt_gate: 'compliance',
|
|
120
|
+
compliance_check_runner: 'compliance',
|
|
121
|
+
'apply-deferred-vscdb': 'compliance',
|
|
122
|
+
'execute-trusted-restarts': 'compliance',
|
|
123
|
+
dialog_prefs: 'compliance',
|
|
124
|
+
};
|
|
125
|
+
main().catch(async (err) => {
|
|
126
|
+
// Top-level safety net: any uncaught error in a cli command is reported as a failed
|
|
127
|
+
// FunctionalRun (awaited so the POST lands before exit), then surfaced + non-zero exit.
|
|
128
|
+
try {
|
|
129
|
+
const cmd = args[0] || '';
|
|
130
|
+
const unit = COMMAND_UNIT[cmd] || 'inventory';
|
|
131
|
+
const { reportFunctionalFailureAwait } = await import('./log_config_files/runtime/client_event_reporter.js');
|
|
132
|
+
await reportFunctionalFailureAwait(unit, cmd, err);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
/* never let telemetry mask the original error */
|
|
136
|
+
}
|
|
137
|
+
console.error(err instanceof Error ? err.stack || err.message : String(err));
|
|
138
|
+
try {
|
|
139
|
+
process.exit(1);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
/* process.exit may be mocked in tests */
|
|
143
|
+
}
|
|
144
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { basename } from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
function toFsPath(scriptPathOrFileUrl) {
|
|
4
|
+
if (scriptPathOrFileUrl.startsWith('file://')) {
|
|
5
|
+
return fileURLToPath(scriptPathOrFileUrl);
|
|
6
|
+
}
|
|
7
|
+
return scriptPathOrFileUrl;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Basename of the invoked script, normalized so npm `bin` names (hyphens) match compiled
|
|
11
|
+
* artifacts (underscores), e.g. `execute-trusted-restarts` → `execute_trusted_restarts`.
|
|
12
|
+
*/
|
|
13
|
+
export function normalizedCliScriptBasename(scriptPathOrFileUrl) {
|
|
14
|
+
return basename(toFsPath(scriptPathOrFileUrl))
|
|
15
|
+
.replace(/\.[cm]?js$/, '')
|
|
16
|
+
.replace(/-/g, '_');
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* True when this process was started as the given module's CLI entrypoint.
|
|
20
|
+
* Handles npx bin shims (symlink paths) and hyphen vs underscore bin/file naming.
|
|
21
|
+
*/
|
|
22
|
+
export function isThisCliModule(argv1, thisImportMetaUrl) {
|
|
23
|
+
if (!argv1)
|
|
24
|
+
return false;
|
|
25
|
+
const entry = normalizedCliScriptBasename(argv1);
|
|
26
|
+
const self = normalizedCliScriptBasename(thisImportMetaUrl);
|
|
27
|
+
if (entry === '' || self === '')
|
|
28
|
+
return false;
|
|
29
|
+
return entry === self || entry === `${self}_staging`;
|
|
30
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { complianceRunnerRunnerLine, hookLogAppendSection } from './log_config_files/runtime/hook_logger.js';
|
|
3
|
+
import { normalizeAgentToken, runComplianceCheck, } from './log_config_files/runtime/compliance_check.js';
|
|
4
|
+
import { finalizeAndUploadComplianceSessionLog, initComplianceSessionForRunner, isFinalizeComplianceSessionArgv, isInflightComplianceLogPath, parseComplianceLogArg, resolveComplianceSessionLogPath, } from './log_config_files/runtime/compliance_session_log.js';
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import { getStoryId, flushBufferedClientEvents, reportFunctionalRun, reportFunctionalFailureAwait, } from './log_config_files/runtime/client_event_reporter.js';
|
|
7
|
+
function parseAgentArg() {
|
|
8
|
+
const eq = process.argv.find((a) => a.startsWith('--agent='));
|
|
9
|
+
if (!eq)
|
|
10
|
+
return undefined;
|
|
11
|
+
const normalized = normalizeAgentToken(eq.slice('--agent='.length));
|
|
12
|
+
return normalized ? normalized : undefined;
|
|
13
|
+
}
|
|
14
|
+
(async () => {
|
|
15
|
+
let complianceLogPath = parseComplianceLogArg(process.argv);
|
|
16
|
+
if (isFinalizeComplianceSessionArgv(process.argv)) {
|
|
17
|
+
if (complianceLogPath) {
|
|
18
|
+
await finalizeAndUploadComplianceSessionLog(complianceLogPath);
|
|
19
|
+
}
|
|
20
|
+
process.exit(0);
|
|
21
|
+
}
|
|
22
|
+
if (complianceLogPath) {
|
|
23
|
+
const resolved = resolveComplianceSessionLogPath(complianceLogPath);
|
|
24
|
+
if (existsSync(resolved) && isInflightComplianceLogPath(resolved)) {
|
|
25
|
+
complianceLogPath = initComplianceSessionForRunner(resolved);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
complianceLogPath = null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
hookLogAppendSection('compliance_check_runner (background sync + check)');
|
|
33
|
+
}
|
|
34
|
+
complianceRunnerRunnerLine('compliance_check_runner: start');
|
|
35
|
+
// Background runner: opportunistically flush any telemetry the (non-blocking) gate buffered.
|
|
36
|
+
getStoryId();
|
|
37
|
+
await flushBufferedClientEvents();
|
|
38
|
+
try {
|
|
39
|
+
await runComplianceCheck(parseAgentArg());
|
|
40
|
+
complianceRunnerRunnerLine('compliance_check_runner: finished ok');
|
|
41
|
+
await reportFunctionalRun({ unit: 'compliance', command: 'compliance_check_runner', outcome: 'ok' });
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
const detail = err instanceof Error ? err.stack ?? err.message : String(err);
|
|
45
|
+
complianceRunnerRunnerLine(`compliance_check_runner: uncaught error — ${err instanceof Error ? err.message : String(err)}`);
|
|
46
|
+
complianceRunnerRunnerLine(`compliance_check_runner: stack_or_detail ${detail.slice(0, 4000)}`);
|
|
47
|
+
process.stderr.write(`compliance_check_runner error: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
48
|
+
if (complianceLogPath) {
|
|
49
|
+
await finalizeAndUploadComplianceSessionLog(complianceLogPath, 'failures');
|
|
50
|
+
}
|
|
51
|
+
await reportFunctionalFailureAwait('compliance', 'compliance_check_runner', err);
|
|
52
|
+
process.exit(1);
|
|
53
|
+
}
|
|
54
|
+
if (complianceLogPath) {
|
|
55
|
+
await finalizeAndUploadComplianceSessionLog(complianceLogPath);
|
|
56
|
+
}
|
|
57
|
+
})();
|