@neuralnomads/codenomad 0.18.0 → 0.19.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.
- package/README.md +12 -0
- package/THIRD_PARTY_NOTICES.md +26 -0
- package/dist/auth/manager.js +1 -1
- package/dist/background-processes/manager.js +15 -30
- package/dist/background-processes/manager.test.js +123 -0
- package/dist/config/schema.js +2 -1
- package/dist/config/schema.test.js +13 -0
- package/dist/events/bus.js +17 -0
- package/dist/events/bus.test.js +37 -0
- package/dist/filesystem/__tests__/search-cache.test.js +20 -8
- package/dist/filesystem/__tests__/search.test.js +53 -0
- package/dist/filesystem/search-cache.js +6 -10
- package/dist/filesystem/search.js +22 -9
- package/dist/index.js +77 -58
- package/dist/index.test.js +62 -0
- package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
- package/dist/opencode-update/service.js +150 -0
- package/dist/opencode-update/service.test.js +107 -0
- package/dist/permissions/auto-accept-manager.js +380 -0
- package/dist/permissions/auto-accept-manager.test.js +736 -0
- package/dist/permissions/auto-accept-store.js +118 -0
- package/dist/permissions/auto-accept-store.test.js +157 -0
- package/dist/permissions/opencode-replier.js +31 -0
- package/dist/permissions/opencode-yolo-metadata.js +81 -0
- package/dist/permissions/opencode-yolo-metadata.test.js +54 -0
- package/dist/server/__tests__/listener-retry.test.js +15 -0
- package/dist/server/__tests__/remote-proxy.test.js +151 -47
- package/dist/server/http-server.js +22 -9
- package/dist/server/remote-proxy.js +91 -34
- package/dist/server/routes/auth-pages/login.html +3 -3
- package/dist/server/routes/auth.js +1 -1
- package/dist/server/routes/auth.test.js +21 -0
- package/dist/server/routes/opencode-update.js +37 -0
- package/dist/server/routes/opencode-update.test.js +34 -0
- package/dist/server/routes/remote-servers.js +1 -1
- package/dist/server/routes/settings.js +48 -2
- package/dist/server/routes/settings.test.js +58 -0
- package/dist/server/routes/usage.js +18 -0
- package/dist/server/routes/usage.test.js +26 -0
- package/dist/server/routes/workspaces.js +34 -2
- package/dist/server/routes/workspaces.test.js +113 -0
- package/dist/server/routes/worktrees.js +19 -0
- package/dist/server/routes/yolo.js +13 -0
- package/dist/server/tls.js +2 -2
- package/dist/settings/binaries.js +4 -1
- package/dist/settings/binaries.test.js +19 -0
- package/dist/settings/public-config.js +14 -0
- package/dist/settings/public-config.test.js +56 -0
- package/dist/settings/service.js +17 -5
- package/dist/settings/service.test.js +51 -0
- package/dist/settings/yaml-doc-store.js +55 -4
- package/dist/settings/yaml-doc-store.test.js +78 -0
- package/dist/shutdown.js +83 -0
- package/dist/shutdown.test.js +148 -0
- package/dist/sidecars/manager.js +26 -3
- package/dist/sidecars/manager.test.js +42 -0
- package/dist/speech/service.js +121 -10
- package/dist/speech/service.test.js +247 -0
- package/dist/ui/remote-ui.js +2 -2
- package/dist/usage/providers/api-key.js +171 -0
- package/dist/usage/providers/google.js +171 -0
- package/dist/usage/providers/minimax.js +109 -0
- package/dist/usage/providers/oauth.js +76 -0
- package/dist/usage/providers/special.js +148 -0
- package/dist/usage/service.js +83 -0
- package/dist/usage/service.test.js +61 -0
- package/dist/usage/shared.js +130 -0
- package/dist/usage/shared.test.js +33 -0
- package/dist/usage/types.js +1 -0
- package/dist/workspaces/__tests__/spawn.test.js +64 -7
- package/dist/workspaces/__tests__/workspace-identity.test.js +163 -0
- package/dist/workspaces/binary-path.test.js +10 -0
- package/dist/workspaces/instance-client.js +42 -0
- package/dist/workspaces/instance-client.test.js +149 -0
- package/dist/workspaces/instance-events.js +2 -2
- package/dist/workspaces/launch-cleanup.test.js +29 -0
- package/dist/workspaces/loopback.js +8 -0
- package/dist/workspaces/manager.js +473 -128
- package/dist/workspaces/manager.test.js +335 -0
- package/dist/workspaces/process-identity.darwin.test.js +88 -0
- package/dist/workspaces/process-identity.js +449 -0
- package/dist/workspaces/process-identity.test.js +140 -0
- package/dist/workspaces/runtime.js +471 -138
- package/dist/workspaces/runtime.test.js +286 -0
- package/dist/workspaces/spawn.js +86 -15
- package/dist/workspaces/workspace-identity.js +27 -0
- package/package.json +2 -1
- package/public/assets/FilesTab-Cbs7b7y9.js +2 -0
- package/public/assets/{GitChangesTab-DyRStL3G.js → GitChangesTab-D3H4cqJJ.js} +2 -2
- package/public/assets/{SplitFilePanel-C4FztlTR.js → SplitFilePanel-C_Bcle0r.js} +1 -1
- package/public/assets/StatusTab-D1-tfkgN.js +1 -0
- package/public/assets/{align-justify-GNs_d9nT.js → align-justify-B5HUL_LR.js} +1 -1
- package/public/assets/{bundle-full-B0vc8NGv.js → bundle-full-CEFzES5w.js} +1 -1
- package/public/assets/{diff-viewer-BmSzmlPC.js → diff-viewer-BBC2_yI1.js} +1 -1
- package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
- package/public/assets/{index-ChDVvMF4.js → index-B81f0aWL.js} +1 -1
- package/public/assets/index-BHlYVddm.js +1 -0
- package/public/assets/index-Best16ZB.js +2 -0
- package/public/assets/index-Boq37ErX.js +1 -0
- package/public/assets/index-By9pgzQk.css +1 -0
- package/public/assets/index-C0caoeJg.js +1 -0
- package/public/assets/index-Dqg2UVvS.js +1 -0
- package/public/assets/index-it6EGJV6.js +1 -0
- package/public/assets/{index-Bv867yIC.js → index-lORR8OnW.js} +1 -1
- package/public/assets/index-ppe6yWaU.js +1 -0
- package/public/assets/index-wEqeBwqT.js +1 -0
- package/public/assets/index-yEcajWX_.js +1 -0
- package/public/assets/{loading-DRzViX8M.js → loading-CbUWFqQ_.js} +1 -1
- package/public/assets/main-DfSREDgt.js +69 -0
- package/public/assets/{markdown-BlxzERp2.js → markdown-CEtfpKK-.js} +60 -47
- package/public/assets/monaco-viewer-NKl8kwH2.js +26 -0
- package/public/assets/terminal-square-q-by1uT7.js +1 -0
- package/public/assets/tool-call-CZL2uqIM.js +59 -0
- package/public/assets/unified-picker-CvJXD-j8.js +1 -0
- package/public/assets/{wrap-text-CMFBVbBi.js → wrap-text-Bo7xr74P.js} +1 -1
- package/public/index.html +5 -5
- package/public/loading.html +5 -5
- package/public/sw.js +1 -1
- package/public/ui-version.json +1 -1
- package/public/assets/FilesTab-CFF9uJuc.js +0 -2
- package/public/assets/StatusTab-CcoPFya8.js +0 -1
- package/public/assets/index--bYE3fA1.js +0 -1
- package/public/assets/index-B-9c-wPM.css +0 -1
- package/public/assets/index-BDJqHo1E.js +0 -1
- package/public/assets/index-BEXDNmDA.js +0 -1
- package/public/assets/index-BWX6Cyx3.js +0 -2
- package/public/assets/index-CUB1cngT.js +0 -1
- package/public/assets/index-CyGPk9Qx.js +0 -1
- package/public/assets/index-D9T8sYiH.js +0 -1
- package/public/assets/index-DQ8RfkwK.js +0 -1
- package/public/assets/index-udaOwtFG.js +0 -1
- package/public/assets/main-DUP17Bqi.js +0 -68
- package/public/assets/monaco-viewer-BbohfXZk.js +0 -26
- package/public/assets/tool-call-B0Ri40qI.js +0 -59
- package/public/assets/unified-picker-CGg8mlSo.js +0 -1
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
export const LAUNCH_CLEANUP_TOKEN_ENV = "CODENOMAD_LAUNCH_CLEANUP_TOKEN";
|
|
2
|
+
const SHELL_DOLLAR = "$";
|
|
3
|
+
const LINUX_IDENTITY_FUNCTIONS = String.raw `
|
|
4
|
+
IFS= read -r boot 2>/dev/null < /proc/sys/kernel/random/boot_id || exit 20
|
|
5
|
+
read_stat() {
|
|
6
|
+
line=
|
|
7
|
+
while IFS= read -r chunk || test -n "$chunk"; do line=$line$chunk; done 2>/dev/null < "/proc/$1/stat"
|
|
8
|
+
test -n "$line" || return 1
|
|
9
|
+
stat_pid=$1; rest=${SHELL_DOLLAR}{line##*) }; set -- $rest
|
|
10
|
+
test "$#" -ge 20 || return 1
|
|
11
|
+
stat_ppid=$2; stat_group=$3; shift 19; stat_start=$1
|
|
12
|
+
}
|
|
13
|
+
emit_linux() {
|
|
14
|
+
test -n "$1" && printf '%s|' "$1"
|
|
15
|
+
printf '%s|%s|%s|%s|%s|%s\n' "$stat_pid" "$stat_ppid" "$stat_group" "$stat_start" "$boot" "$stat_start"
|
|
16
|
+
}
|
|
17
|
+
`;
|
|
18
|
+
const LINUX_SNAPSHOT_SCRIPT = String.raw `${LINUX_IDENTITY_FUNCTIONS}
|
|
19
|
+
for stat in /proc/[0-9]*/stat; do
|
|
20
|
+
directory=${SHELL_DOLLAR}{stat%/stat}; pid=${SHELL_DOLLAR}{directory##*/}; read_stat "$pid" && emit_linux ""
|
|
21
|
+
done
|
|
22
|
+
exit 0
|
|
23
|
+
`;
|
|
24
|
+
const LINUX_LAUNCH_GROUP_SNAPSHOT_SCRIPT = String.raw `${LINUX_IDENTITY_FUNCTIONS}
|
|
25
|
+
leader_pid=$1; read_stat "$leader_pid" || exit 22; expected_group=$stat_group; emit_linux ""
|
|
26
|
+
for stat in /proc/[0-9]*/stat; do
|
|
27
|
+
directory=${SHELL_DOLLAR}{stat%/stat}; pid=${SHELL_DOLLAR}{directory##*/}; test "$pid" = "$leader_pid" && continue
|
|
28
|
+
read_stat "$pid" && test "$stat_group" = "$expected_group" && emit_linux ""
|
|
29
|
+
done
|
|
30
|
+
exit 0
|
|
31
|
+
`;
|
|
32
|
+
const LINUX_GUARDED_SIGNAL_SCRIPT = String.raw `${LINUX_IDENTITY_FUNCTIONS}
|
|
33
|
+
leader_pid=$1; leader_start=$2; leader_boot=$3; expected_group=$4; requested_signal=$5
|
|
34
|
+
shift 5; matched=0; cutoff=; signal_sent=0
|
|
35
|
+
if read_stat "$leader_pid" && test "$boot" = "$leader_boot" && test "$stat_start" = "$leader_start" && test "$stat_group" = "$expected_group"; then
|
|
36
|
+
matched=1
|
|
37
|
+
for stat in /proc/[0-9]*/stat; do
|
|
38
|
+
directory=${SHELL_DOLLAR}{stat%/stat}; candidate=${SHELL_DOLLAR}{directory##*/}; read_stat "$candidate" && test "$stat_group" = "$expected_group" && emit_linux CODENOMAD_TARGET
|
|
39
|
+
done
|
|
40
|
+
if kill "-$requested_signal" -- "-$expected_group" 2>/dev/null; then
|
|
41
|
+
signal_sent=1
|
|
42
|
+
hz=$(getconf CLK_TCK 2>/dev/null) || exit 21
|
|
43
|
+
uptime=$(cut -d' ' -f1 /proc/uptime 2>/dev/null) || exit 21
|
|
44
|
+
cutoff=$(awk -v uptime="$uptime" -v hz="$hz" 'BEGIN { printf "%.0f", uptime * hz }')
|
|
45
|
+
fi
|
|
46
|
+
else
|
|
47
|
+
while test "$#" -ge 3; do
|
|
48
|
+
expected_pid=$1; expected_start=$2; expected_boot=$3; shift 3
|
|
49
|
+
if read_stat "$expected_pid" && test "$boot" = "$expected_boot" && test "$stat_start" = "$expected_start"; then
|
|
50
|
+
emit_linux CODENOMAD_TARGET
|
|
51
|
+
if kill "-$requested_signal" "$expected_pid" 2>/dev/null; then signal_sent=1; fi
|
|
52
|
+
fi
|
|
53
|
+
done
|
|
54
|
+
fi
|
|
55
|
+
printf 'CODENOMAD_RESULT|%s|%s|%s\n' "$matched" "$cutoff" "$signal_sent"
|
|
56
|
+
`;
|
|
57
|
+
const POSIX_IDENTITY_FUNCTIONS = String.raw `
|
|
58
|
+
LC_ALL=C; export LC_ALL; set -f
|
|
59
|
+
encode() { printf '%s' "$1" | base64 | tr -d '\r\n'; }
|
|
60
|
+
read_identity() {
|
|
61
|
+
current_meta=$(ps -p "$1" -o ppid= -o pgid= -o lstart= -o comm= 2>/dev/null) || return 1
|
|
62
|
+
current_verify=$(ps -p "$1" -o ppid= -o pgid= -o lstart= -o comm= 2>/dev/null) || return 1
|
|
63
|
+
test "$current_meta" = "$current_verify" || return 1
|
|
64
|
+
set -- $current_meta; test "$#" -ge 7 || return 1
|
|
65
|
+
current_ppid=$1; current_group=$2; shift 2; current_start="$1 $2 $3 $4 $5"
|
|
66
|
+
shift 5; current_command="$*"; test -n "$current_command" || return 1
|
|
67
|
+
current_identity=$(printf '%s\t%s' "$current_start" "$current_command")
|
|
68
|
+
}
|
|
69
|
+
emit_target() {
|
|
70
|
+
printf 'CODENOMAD_TARGET_B64|%s|%s|%s|' "$current_pid" "$current_ppid" "$current_group"
|
|
71
|
+
encode "$current_start"; printf '|'; encode "$current_command"; printf '\n'
|
|
72
|
+
}
|
|
73
|
+
group_pids() { ps -axo pid=,pgid= 2>/dev/null | awk -v group="$1" '$2 == group { print $1 }'; }
|
|
74
|
+
has_cleanup_token() {
|
|
75
|
+
test -n "$cleanup_token" || return 1
|
|
76
|
+
ps eww -p "$1" -o command= 2>/dev/null | tr ' ' '\n' | grep -Fqx -- "${LAUNCH_CLEANUP_TOKEN_ENV}=$cleanup_token"
|
|
77
|
+
}
|
|
78
|
+
`;
|
|
79
|
+
const LINUX_TOKEN_SCRIPT = String.raw `${LINUX_IDENTITY_FUNCTIONS}
|
|
80
|
+
key=$1; expected=$2; requested_signal=$3
|
|
81
|
+
matches_token() { test -r "/proc/$1/environ" && tr '\0' '\n' < "/proc/$1/environ" 2>/dev/null | grep -Fqx -- "$key=$expected"; }
|
|
82
|
+
signal_sent=0; passes=1; test -n "$requested_signal" && passes=3
|
|
83
|
+
pass=0
|
|
84
|
+
while test "$pass" -lt "$passes"; do
|
|
85
|
+
pass=$((pass + 1))
|
|
86
|
+
for environ in /proc/[0-9]*/environ; do
|
|
87
|
+
directory=${SHELL_DOLLAR}{environ%/environ}; pid=${SHELL_DOLLAR}{directory##*/}
|
|
88
|
+
if matches_token "$pid" && read_stat "$pid"; then
|
|
89
|
+
test -n "$requested_signal" && prefix=CODENOMAD_TARGET || prefix=CODENOMAD_PROCESS
|
|
90
|
+
emit_linux "$prefix"
|
|
91
|
+
if test -n "$requested_signal" && matches_token "$pid" && read_stat "$pid" && kill "-$requested_signal" "$pid" 2>/dev/null; then signal_sent=1; fi
|
|
92
|
+
fi
|
|
93
|
+
done
|
|
94
|
+
done
|
|
95
|
+
if test -n "$requested_signal"; then printf 'CODENOMAD_RESULT|%s\n' "$signal_sent"; fi
|
|
96
|
+
exit 0
|
|
97
|
+
`;
|
|
98
|
+
const POSIX_GUARDED_SIGNAL_SCRIPT = String.raw `${POSIX_IDENTITY_FUNCTIONS}
|
|
99
|
+
leader_pid=$1; leader_start=$2; expected_group=$3; requested_signal=$4; allow_leaderless=$5; cleanup_token=$6; shift 6
|
|
100
|
+
matched=0; signal_sent=0
|
|
101
|
+
if read_identity "$leader_pid" && test "$current_group" = "$expected_group" && test "$current_identity" = "$leader_start"; then
|
|
102
|
+
matched=1
|
|
103
|
+
for current_pid in $(group_pids "$expected_group"); do
|
|
104
|
+
read_identity "$current_pid" && test "$current_group" = "$expected_group" && emit_target
|
|
105
|
+
done
|
|
106
|
+
if kill "-$requested_signal" -- "-$expected_group" 2>/dev/null; then signal_sent=1; fi
|
|
107
|
+
elif test "$allow_leaderless" = 1 && ! read_identity "$expected_group"; then
|
|
108
|
+
anchor=0
|
|
109
|
+
while test "$#" -ge 2; do
|
|
110
|
+
expected_pid=$1; expected_start=$2; shift 2; current_pid=$expected_pid
|
|
111
|
+
if read_identity "$expected_pid" && test "$current_group" = "$expected_group" && test "$current_identity" = "$expected_start"; then anchor=1; fi
|
|
112
|
+
done
|
|
113
|
+
if test "$anchor" = 0; then
|
|
114
|
+
for current_pid in $(group_pids "$expected_group"); do
|
|
115
|
+
if has_cleanup_token "$current_pid" && read_identity "$current_pid" && test "$current_group" = "$expected_group"; then anchor=1; break; fi
|
|
116
|
+
done
|
|
117
|
+
fi
|
|
118
|
+
if test "$anchor" = 1; then
|
|
119
|
+
matched=1
|
|
120
|
+
for current_pid in $(group_pids "$expected_group"); do
|
|
121
|
+
read_identity "$current_pid" && test "$current_group" = "$expected_group" && emit_target
|
|
122
|
+
done
|
|
123
|
+
if kill "-$requested_signal" -- "-$expected_group" 2>/dev/null; then signal_sent=1; fi
|
|
124
|
+
fi
|
|
125
|
+
else
|
|
126
|
+
while test "$#" -ge 2; do
|
|
127
|
+
expected_pid=$1; expected_start=$2; shift 2; current_pid=$expected_pid
|
|
128
|
+
if read_identity "$expected_pid" && test "$current_group" = "$expected_group" && test "$current_identity" = "$expected_start"; then
|
|
129
|
+
emit_target; if kill "-$requested_signal" "$expected_pid" 2>/dev/null; then signal_sent=1; fi
|
|
130
|
+
fi
|
|
131
|
+
done
|
|
132
|
+
fi
|
|
133
|
+
printf 'CODENOMAD_RESULT|%s||%s\n' "$matched" "$signal_sent"
|
|
134
|
+
`;
|
|
135
|
+
const POSIX_OWNED_GROUP_SIGNAL_SCRIPT = String.raw `${POSIX_IDENTITY_FUNCTIONS}
|
|
136
|
+
root_pid=$1; requested_signal=$2; matched=0; signal_sent=0
|
|
137
|
+
if read_identity "$root_pid" && test "$current_group" = "$root_pid"; then
|
|
138
|
+
matched=1
|
|
139
|
+
for current_pid in $(group_pids "$root_pid"); do
|
|
140
|
+
read_identity "$current_pid" && test "$current_group" = "$root_pid" && emit_target
|
|
141
|
+
done
|
|
142
|
+
if kill "-$requested_signal" -- "-$root_pid" 2>/dev/null; then signal_sent=1; fi
|
|
143
|
+
for current_pid in $(group_pids "$root_pid"); do
|
|
144
|
+
read_identity "$current_pid" && test "$current_group" = "$root_pid" && emit_target
|
|
145
|
+
done
|
|
146
|
+
fi
|
|
147
|
+
printf 'CODENOMAD_RESULT|%s||%s\n' "$matched" "$signal_sent"
|
|
148
|
+
`;
|
|
149
|
+
const commandError = (result) => result.error?.message || String(result.stderr ?? result.stdout ?? "").trim() || `exit code ${result.status}`;
|
|
150
|
+
function parseDelimitedSnapshot(output, requireBootId = false) {
|
|
151
|
+
const processes = new Map();
|
|
152
|
+
for (const line of output.split(/\r?\n/)) {
|
|
153
|
+
if (!line)
|
|
154
|
+
continue;
|
|
155
|
+
const fields = line.split("|");
|
|
156
|
+
if (fields.length !== 6)
|
|
157
|
+
return null;
|
|
158
|
+
const [pidText, parentPidText, groupIdText, startTime = "", bootId = "", startOrder = ""] = fields;
|
|
159
|
+
const pid = Number.parseInt(pidText ?? "", 10);
|
|
160
|
+
const parentPid = Number.parseInt(parentPidText ?? "", 10);
|
|
161
|
+
const groupId = Number.parseInt(groupIdText ?? "", 10);
|
|
162
|
+
if (!/^\d+$/.test(pidText ?? "") || !/^\d+$/.test(parentPidText ?? "") || !/^\d+$/.test(groupIdText ?? "") ||
|
|
163
|
+
!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(parentPid) || !startTime || (requireBootId && !bootId))
|
|
164
|
+
return null;
|
|
165
|
+
processes.set(pid, { pid, parentPid, groupId: Number.isInteger(groupId) && groupId > 0 ? groupId : pid, startTime,
|
|
166
|
+
...(bootId ? { bootId } : {}), ...(startOrder ? { startOrder } : {}) });
|
|
167
|
+
}
|
|
168
|
+
return processes;
|
|
169
|
+
}
|
|
170
|
+
function decodeBase64Field(value) {
|
|
171
|
+
if (value.length === 0 || value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
const bytes = Buffer.from(value, "base64");
|
|
176
|
+
if (bytes.toString("base64") !== value)
|
|
177
|
+
return null;
|
|
178
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function parseBase64Snapshot(output, prefix = "CODENOMAD_B64|") {
|
|
185
|
+
const processes = new Map();
|
|
186
|
+
for (const line of output.split(/\r?\n/)) {
|
|
187
|
+
if (!line)
|
|
188
|
+
continue;
|
|
189
|
+
if (!line.startsWith(prefix))
|
|
190
|
+
return null;
|
|
191
|
+
const fields = line.slice(prefix.length).split("|");
|
|
192
|
+
if (fields.length !== 5)
|
|
193
|
+
return null;
|
|
194
|
+
const [pidText = "", parentPidText = "", groupIdText = "", startEncoded = "", commandEncoded = ""] = fields;
|
|
195
|
+
if (!/^\d+$/.test(pidText) || !/^\d+$/.test(parentPidText) || !/^\d+$/.test(groupIdText))
|
|
196
|
+
return null;
|
|
197
|
+
const pid = Number.parseInt(pidText, 10);
|
|
198
|
+
const parentPid = Number.parseInt(parentPidText, 10);
|
|
199
|
+
const groupId = Number.parseInt(groupIdText, 10);
|
|
200
|
+
const start = decodeBase64Field(startEncoded);
|
|
201
|
+
const command = decodeBase64Field(commandEncoded);
|
|
202
|
+
if (pid <= 0 || parentPid < 0 || groupId <= 0 || start === null || command === null)
|
|
203
|
+
return null;
|
|
204
|
+
processes.set(pid, { pid, parentPid, groupId, startTime: `${start}\t${command}` });
|
|
205
|
+
}
|
|
206
|
+
return processes;
|
|
207
|
+
}
|
|
208
|
+
function parsePortablePosixSnapshot(output, filter) {
|
|
209
|
+
const processes = new Map();
|
|
210
|
+
const requestedPids = filter?.pids ? new Set(filter.pids) : undefined;
|
|
211
|
+
for (const line of output.split(/\r?\n/)) {
|
|
212
|
+
if (!line.trim())
|
|
213
|
+
continue;
|
|
214
|
+
const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/);
|
|
215
|
+
if (!match) {
|
|
216
|
+
const numeric = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+/);
|
|
217
|
+
if (!filter || !numeric || requestedPids?.has(Number(numeric[1])) || Number(numeric[3]) === filter.groupId)
|
|
218
|
+
return null;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const [, pidText = "", parentPidText = "", groupIdText = "", start = "", command = ""] = match;
|
|
222
|
+
const pid = Number.parseInt(pidText, 10);
|
|
223
|
+
const parentPid = Number.parseInt(parentPidText, 10);
|
|
224
|
+
const groupId = Number.parseInt(groupIdText, 10);
|
|
225
|
+
if (pid <= 0 || parentPid < 0 || groupId <= 0)
|
|
226
|
+
return null;
|
|
227
|
+
if (filter && !requestedPids?.has(pid) && groupId !== filter.groupId)
|
|
228
|
+
continue;
|
|
229
|
+
processes.set(pid, { pid, parentPid, groupId, startTime: `${start}\t${command}` });
|
|
230
|
+
}
|
|
231
|
+
return processes;
|
|
232
|
+
}
|
|
233
|
+
function querySnapshot(run, parse, options = {}) {
|
|
234
|
+
const sanitize = options.redact ?? ((error) => error);
|
|
235
|
+
try {
|
|
236
|
+
const result = run();
|
|
237
|
+
if (result.status !== 0)
|
|
238
|
+
return { ok: false, error: sanitize(commandError(result)) };
|
|
239
|
+
const processes = parse(String(result.stdout ?? ""));
|
|
240
|
+
if (processes && (options.allowEmpty || processes.size > 0))
|
|
241
|
+
return { ok: true, processes };
|
|
242
|
+
return { ok: false, error: options.malformedError ?? "process identity query returned no parseable processes" };
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
return { ok: false, error: sanitize(error instanceof Error ? error.message : String(error)) };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function parsePrefixedSnapshot(output, prefix) {
|
|
249
|
+
const records = [];
|
|
250
|
+
for (const line of output.split(/\r?\n/)) {
|
|
251
|
+
if (!line)
|
|
252
|
+
continue;
|
|
253
|
+
if (!line.startsWith(prefix))
|
|
254
|
+
return null;
|
|
255
|
+
records.push(line.slice(prefix.length));
|
|
256
|
+
}
|
|
257
|
+
return parseDelimitedSnapshot(records.join("\n"), true);
|
|
258
|
+
}
|
|
259
|
+
function parseGuardedResult(result) {
|
|
260
|
+
const signaled = new Map();
|
|
261
|
+
const failure = (error) => ({ ok: false, error,
|
|
262
|
+
...(signaled.size > 0 ? { observed: Array.from(signaled.values()) } : {}) });
|
|
263
|
+
let matched;
|
|
264
|
+
let signalSent = false;
|
|
265
|
+
let cutoff;
|
|
266
|
+
for (const line of String(result.stdout ?? "").split(/\r?\n/)) {
|
|
267
|
+
if (line.startsWith("CODENOMAD_TARGET|") || line.startsWith("CODENOMAD_TARGET_B64|")) {
|
|
268
|
+
const parsed = line.startsWith("CODENOMAD_TARGET_B64|")
|
|
269
|
+
? parseBase64Snapshot(line, "CODENOMAD_TARGET_B64|")
|
|
270
|
+
: parseDelimitedSnapshot(line.slice("CODENOMAD_TARGET|".length));
|
|
271
|
+
if (!parsed)
|
|
272
|
+
return failure("guarded signal command returned a malformed target record");
|
|
273
|
+
for (const identity of parsed.values())
|
|
274
|
+
signaled.set(identity.pid, identity);
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
if (line.startsWith("CODENOMAD_RESULT|")) {
|
|
278
|
+
const fields = line.split("|");
|
|
279
|
+
if (fields.length !== 4 || !/^[01]$/.test(fields[1] ?? "") || !/^[01]$/.test(fields[3] ?? "")) {
|
|
280
|
+
return failure("guarded signal command returned a malformed result record");
|
|
281
|
+
}
|
|
282
|
+
const [, matchedText, cutoffText, signalSentText] = fields;
|
|
283
|
+
matched = matchedText === "1";
|
|
284
|
+
cutoff = cutoffText || undefined;
|
|
285
|
+
signalSent = signalSentText === "1";
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (line)
|
|
289
|
+
return failure("guarded signal command returned unexpected output");
|
|
290
|
+
}
|
|
291
|
+
if (result.status !== 0)
|
|
292
|
+
return failure(commandError(result));
|
|
293
|
+
return matched === undefined
|
|
294
|
+
? failure("guarded signal command returned no structured result")
|
|
295
|
+
: { ok: true, matched, signalSent, signaled: Array.from(signaled.values()), ...(cutoff ? { cutoff } : {}) };
|
|
296
|
+
}
|
|
297
|
+
function runGuardedCommand(run) {
|
|
298
|
+
try {
|
|
299
|
+
return parseGuardedResult(run());
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const signalName = (signal) => signal === "SIGKILL" ? "KILL" : "TERM";
|
|
306
|
+
function runLinuxScript(spawnCommand, script, args, timeoutMs, label, distro) {
|
|
307
|
+
return distro
|
|
308
|
+
? spawnCommand("wsl.exe", ["--distribution", distro, "--exec", "sh", "-c", script, label, ...args], { encoding: "utf8", timeout: timeoutMs })
|
|
309
|
+
: spawnCommand("sh", ["-c", script, label, ...args], { encoding: "utf8", timeout: timeoutMs });
|
|
310
|
+
}
|
|
311
|
+
const redactToken = (value, token) => value.split(token).join("[REDACTED]");
|
|
312
|
+
function shellGuardArgs(request, linux) {
|
|
313
|
+
const leader = request.leader;
|
|
314
|
+
const args = linux
|
|
315
|
+
? [String(leader?.pid ?? 0), leader?.startTime ?? "", leader?.bootId ?? "", String(request.groupId ?? 0), signalName(request.signal)]
|
|
316
|
+
: [String(leader?.pid ?? 0), leader?.startTime ?? "", String(request.groupId ?? 0), signalName(request.signal),
|
|
317
|
+
request.allowLeaderlessGroup ? "1" : "0", request.cleanupToken ?? ""];
|
|
318
|
+
for (const member of request.members) {
|
|
319
|
+
args.push(String(member.pid), member.startTime);
|
|
320
|
+
if (linux)
|
|
321
|
+
args.push(member.bootId ?? "");
|
|
322
|
+
}
|
|
323
|
+
return args;
|
|
324
|
+
}
|
|
325
|
+
const quotePowerShell = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
326
|
+
function buildWindowsGuardedScript(request) {
|
|
327
|
+
const leaderPid = request.leader?.pid ?? 0;
|
|
328
|
+
const leaderStart = quotePowerShell(request.leader?.startTime ?? "");
|
|
329
|
+
const expected = request.members.map((identity) => `@{ Pid = ${identity.pid}; Start = ${quotePowerShell(identity.startTime)} }`).join(", ");
|
|
330
|
+
return [
|
|
331
|
+
"$ErrorActionPreference = 'Stop'",
|
|
332
|
+
`$leaderPid = ${leaderPid}`,
|
|
333
|
+
`$leaderStart = ${leaderStart}`,
|
|
334
|
+
`$expected = @(${expected})`,
|
|
335
|
+
"function Get-CodeNomadStart($process) { return ([datetime]$process.CreationDate).ToUniversalTime().Ticks.ToString() }",
|
|
336
|
+
"$all = @(Get-CimInstance Win32_Process -ErrorAction Stop)",
|
|
337
|
+
"$byPid = @{}; $all | ForEach-Object { $byPid[[int]$_.ProcessId] = $_ }",
|
|
338
|
+
"$leader = $byPid[$leaderPid]",
|
|
339
|
+
"$matched = $null -ne $leader -and (Get-CodeNomadStart $leader) -eq $leaderStart",
|
|
340
|
+
"$selected = @()",
|
|
341
|
+
"if ($matched) {",
|
|
342
|
+
" $ids = @($leaderPid); $changed = $true",
|
|
343
|
+
" while ($changed) { $changed = $false; foreach ($process in $all) { if ($ids -contains [int]$process.ParentProcessId -and $ids -notcontains [int]$process.ProcessId) { $ids += [int]$process.ProcessId; $changed = $true } } }",
|
|
344
|
+
" $selected = @($all | Where-Object { $ids -contains [int]$_.ProcessId } | Sort-Object ProcessId -Descending)",
|
|
345
|
+
"} else {",
|
|
346
|
+
" foreach ($item in $expected) { $process = $byPid[[int]$item.Pid]; if ($null -ne $process -and (Get-CodeNomadStart $process) -eq [string]$item.Start) { $selected += $process } }",
|
|
347
|
+
"}",
|
|
348
|
+
"foreach ($process in $selected) {",
|
|
349
|
+
" $start = Get-CodeNomadStart $process",
|
|
350
|
+
" '{0}|{1}|0|{2}||{2}' -f [int]$process.ProcessId, [int]$process.ParentProcessId, $start | ForEach-Object { 'CODENOMAD_TARGET|' + $_ }",
|
|
351
|
+
"}",
|
|
352
|
+
"foreach ($process in $selected) {",
|
|
353
|
+
" Invoke-CimMethod -InputObject $process -MethodName Terminate -Arguments @{ Reason = 1 } -ErrorAction Stop | Out-Null",
|
|
354
|
+
"}",
|
|
355
|
+
"'CODENOMAD_RESULT|' + ($(if ($matched) { '1' } else { '0' })) + '||' + ($(if ($selected.Count -gt 0) { '1' } else { '0' }))",
|
|
356
|
+
].join("; ");
|
|
357
|
+
}
|
|
358
|
+
export function sameProcess(left, right) {
|
|
359
|
+
return Boolean(left && right && left.pid === right.pid && left.startTime === right.startTime &&
|
|
360
|
+
(!left.bootId || !right.bootId || left.bootId === right.bootId));
|
|
361
|
+
}
|
|
362
|
+
export function startedNoLaterThan(identity, cutoff) {
|
|
363
|
+
const startOrder = identity.startOrder ?? identity.startTime;
|
|
364
|
+
if (!/^\d+$/.test(startOrder) || !/^\d+$/.test(cutoff))
|
|
365
|
+
return false;
|
|
366
|
+
try {
|
|
367
|
+
return BigInt(startOrder) <= BigInt(cutoff);
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
return false;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
export function descendantsOf(processes, rootPid) {
|
|
374
|
+
const descendants = [];
|
|
375
|
+
const pending = [rootPid];
|
|
376
|
+
const seen = new Set(pending);
|
|
377
|
+
while (pending.length > 0) {
|
|
378
|
+
const parentPid = pending.shift();
|
|
379
|
+
for (const process of processes.values()) {
|
|
380
|
+
if (process.parentPid !== parentPid || seen.has(process.pid))
|
|
381
|
+
continue;
|
|
382
|
+
seen.add(process.pid);
|
|
383
|
+
pending.push(process.pid);
|
|
384
|
+
descendants.push(process);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return descendants;
|
|
388
|
+
}
|
|
389
|
+
export function probePosixProcesses(spawnCommand, timeoutMs, platform = process.platform, filter) {
|
|
390
|
+
if (platform === "linux") {
|
|
391
|
+
const pids = filter?.pids?.filter((pid) => Number.isInteger(pid) && pid > 0).map(String) ?? [];
|
|
392
|
+
const launchGroupProbe = pids.length === 1 && filter?.groupId === Number(pids[0]);
|
|
393
|
+
return querySnapshot(() => runLinuxScript(spawnCommand, launchGroupProbe ? LINUX_LAUNCH_GROUP_SNAPSHOT_SCRIPT : LINUX_SNAPSHOT_SCRIPT, launchGroupProbe ? pids : [], timeoutMs, "codenomad-posix-identity"), (output) => parseDelimitedSnapshot(output, true), { allowEmpty: Boolean(filter) });
|
|
394
|
+
}
|
|
395
|
+
// POSIX has no portable pidfd/start ticks; collect one coherent table instead of probing every PID.
|
|
396
|
+
return querySnapshot(() => spawnCommand("ps", ["-axo", "pid=,ppid=,pgid=,lstart=,comm="], {
|
|
397
|
+
encoding: "utf8", timeout: timeoutMs, env: { ...process.env, LC_ALL: "C", LANG: "C" },
|
|
398
|
+
}), (output) => parsePortablePosixSnapshot(output, filter), { allowEmpty: Boolean(filter) });
|
|
399
|
+
}
|
|
400
|
+
export function probeWindowsProcesses(spawnCommand, timeoutMs) {
|
|
401
|
+
const script = [
|
|
402
|
+
"$all = @(Get-CimInstance Win32_Process -ErrorAction Stop)",
|
|
403
|
+
"$all | Where-Object { [int]$_.ProcessId -gt 0 } | ForEach-Object { $start = ([datetime]$_.CreationDate).ToUniversalTime().Ticks.ToString(); '{0}|{1}|0|{2}||{2}' -f [int]$_.ProcessId, [int]$_.ParentProcessId, $start }",
|
|
404
|
+
].join("; ");
|
|
405
|
+
return querySnapshot(() => spawnCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: timeoutMs }), parseDelimitedSnapshot);
|
|
406
|
+
}
|
|
407
|
+
export function probeWslProcesses(spawnCommand, distro, timeoutMs) {
|
|
408
|
+
return querySnapshot(() => runLinuxScript(spawnCommand, LINUX_SNAPSHOT_SCRIPT, [], timeoutMs, "codenomad-wsl-identity", distro), (output) => parseDelimitedSnapshot(output, true));
|
|
409
|
+
}
|
|
410
|
+
export function signalPosixProcesses(spawnCommand, request, timeoutMs, platform) {
|
|
411
|
+
const linux = platform === "linux";
|
|
412
|
+
return runGuardedCommand(() => spawnCommand("sh", ["-c", linux ? LINUX_GUARDED_SIGNAL_SCRIPT : POSIX_GUARDED_SIGNAL_SCRIPT, "codenomad-guarded-signal", ...shellGuardArgs(request, linux)], { encoding: "utf8", timeout: timeoutMs }));
|
|
413
|
+
}
|
|
414
|
+
export function signalOwnedPosixProcessGroup(spawnCommand, rootPid, signal, timeoutMs) {
|
|
415
|
+
return runGuardedCommand(() => spawnCommand("sh", ["-c", POSIX_OWNED_GROUP_SIGNAL_SCRIPT, "codenomad-owned-group-cleanup", String(rootPid), signalName(signal)], { encoding: "utf8", timeout: timeoutMs }));
|
|
416
|
+
}
|
|
417
|
+
export function signalWslProcesses(spawnCommand, distro, request, timeoutMs) {
|
|
418
|
+
return runGuardedCommand(() => runLinuxScript(spawnCommand, LINUX_GUARDED_SIGNAL_SCRIPT, shellGuardArgs(request, true), timeoutMs, "codenomad-wsl-guarded-signal", distro));
|
|
419
|
+
}
|
|
420
|
+
export function signalWindowsProcesses(spawnCommand, request, timeoutMs) {
|
|
421
|
+
return runGuardedCommand(() => spawnCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", buildWindowsGuardedScript(request)], { encoding: "utf8", timeout: timeoutMs }));
|
|
422
|
+
}
|
|
423
|
+
export function probeLaunchCleanupToken(spawnCommand, token, timeoutMs, distro) {
|
|
424
|
+
return querySnapshot(() => runLinuxScript(spawnCommand, LINUX_TOKEN_SCRIPT, [LAUNCH_CLEANUP_TOKEN_ENV, token, ""], timeoutMs, "codenomad-token-cleanup", distro), (output) => parsePrefixedSnapshot(output, "CODENOMAD_PROCESS|"), {
|
|
425
|
+
allowEmpty: true,
|
|
426
|
+
malformedError: "launch cleanup probe returned malformed or unexpected output",
|
|
427
|
+
redact: (error) => redactToken(error, token),
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
export function signalLaunchCleanupToken(spawnCommand, token, signal, timeoutMs, distro) {
|
|
431
|
+
const failed = (error) => ({ ok: false, signalSent: false, targets: [], error });
|
|
432
|
+
try {
|
|
433
|
+
const result = runLinuxScript(spawnCommand, LINUX_TOKEN_SCRIPT, [LAUNCH_CLEANUP_TOKEN_ENV, token, signalName(signal)], timeoutMs, "codenomad-token-cleanup", distro);
|
|
434
|
+
if (result.status !== 0)
|
|
435
|
+
return failed(redactToken(commandError(result), token));
|
|
436
|
+
const lines = String(result.stdout ?? "").split(/\r?\n/).filter(Boolean);
|
|
437
|
+
const resultLines = lines.filter((line) => line.startsWith("CODENOMAD_RESULT|"));
|
|
438
|
+
if (resultLines.length !== 1 || !/^CODENOMAD_RESULT\|[01]$/.test(resultLines[0] ?? "")) {
|
|
439
|
+
return failed("launch cleanup signal returned no valid structured result");
|
|
440
|
+
}
|
|
441
|
+
const targets = parsePrefixedSnapshot(lines.filter((line) => !line.startsWith("CODENOMAD_RESULT|")).join("\n"), "CODENOMAD_TARGET|");
|
|
442
|
+
return targets
|
|
443
|
+
? { ok: true, signalSent: resultLines[0].endsWith("1"), targets: Array.from(targets.values()) }
|
|
444
|
+
: failed("launch cleanup signal returned malformed or unexpected output");
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
return failed(redactToken(error instanceof Error ? error.message : String(error), token));
|
|
448
|
+
}
|
|
449
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn as spawnChild, spawnSync } from "node:child_process";
|
|
3
|
+
import { once } from "node:events";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { describe, it } from "node:test";
|
|
6
|
+
import { probePosixProcesses, probeWindowsProcesses, probeWslProcesses, sameProcess, signalOwnedPosixProcessGroup, signalPosixProcesses, signalWindowsProcesses, startedNoLaterThan, } from "./process-identity";
|
|
7
|
+
const output = (stdout = "", status = 0, stderr = "") => ({ pid: 1, output: [null, stdout, stderr], stdout, stderr, status, signal: null });
|
|
8
|
+
const spawn = (stdout, call, status = 0, stderr = "") => ((command, args) => {
|
|
9
|
+
if (call)
|
|
10
|
+
Object.assign(call, { command, args, script: command === "powershell.exe" ? args.at(-1) ?? "" : args[args.indexOf("-c") + 1] ?? "" });
|
|
11
|
+
return output(stdout, status, stderr);
|
|
12
|
+
});
|
|
13
|
+
const b64 = (value) => Buffer.from(value).toString("base64");
|
|
14
|
+
const identity = (startTime = "123456") => ({ pid: 42, parentPid: 1, groupId: 42, startTime, bootId: "boot-a", startOrder: startTime });
|
|
15
|
+
describe("process identity probes", () => {
|
|
16
|
+
it("parses immutable Linux identities", () => {
|
|
17
|
+
const call = {};
|
|
18
|
+
const probe = probePosixProcesses(spawn("42|1|42|123456|boot-a|123456\n", call), 25, "linux");
|
|
19
|
+
assert.deepEqual([call.command, call.args.includes("codenomad-posix-identity"), call.script.trimEnd().endsWith("exit 0")], ["sh", true, true]);
|
|
20
|
+
assert.deepEqual(probe.ok && probe.processes.get(42), identity());
|
|
21
|
+
});
|
|
22
|
+
it("queries the requested Linux launch group without per-process subprocesses", () => {
|
|
23
|
+
const call = {};
|
|
24
|
+
const probe = probePosixProcesses(spawn("42|1|42|123456|boot-a|123456\n", call), 25, "linux", { pids: [42], groupId: 42 });
|
|
25
|
+
assert.deepEqual(call.args.slice(-1), ["42"]);
|
|
26
|
+
assert.match(call.script, /expected_group=\$stat_group/);
|
|
27
|
+
assert.doesNotMatch(call.script, /\b(?:cat|cut|sed|basename|dirname)\b/);
|
|
28
|
+
assert.deepEqual(probe.ok && probe.processes.get(42), identity());
|
|
29
|
+
});
|
|
30
|
+
it("captures real Linux start ticks and launch-group members within the deadline", { skip: process.platform !== "linux" }, async () => {
|
|
31
|
+
const child = spawnChild("sh", ["-c", "sleep 5"], { stdio: "ignore" });
|
|
32
|
+
await once(child, "spawn");
|
|
33
|
+
try {
|
|
34
|
+
const stat = readFileSync(`/proc/${process.pid}/stat`, "utf8");
|
|
35
|
+
const expectedStart = stat.slice(stat.lastIndexOf(") ") + 2).split(" ")[19];
|
|
36
|
+
const probe = probePosixProcesses(spawnSync, 1_000, "linux", { pids: [process.pid], groupId: process.pid });
|
|
37
|
+
assert.equal(probe.ok && probe.processes.get(process.pid)?.startTime, expectedStart);
|
|
38
|
+
assert.equal(probe.ok && probe.processes.has(child.pid), true);
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
42
|
+
const exited = once(child, "exit");
|
|
43
|
+
child.kill();
|
|
44
|
+
await exited;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
it("uses one delimiter-safe process-table query on portable POSIX", () => {
|
|
49
|
+
const call = {};
|
|
50
|
+
const command = "/opt/opencode 'pipe|value'\t\"quoted\" café";
|
|
51
|
+
const start = "Fri Jul 10 12:34:56 2026";
|
|
52
|
+
const probe = probePosixProcesses(spawn(`42 1 42 ${start} ${command}\n`, call), 25, "darwin");
|
|
53
|
+
assert.deepEqual([call.command, call.args], ["ps", ["-axo", "pid=,ppid=,pgid=,lstart=,comm="]]);
|
|
54
|
+
assert.equal(probe.ok && probe.processes.get(42)?.startTime, `${start}\t${command}`);
|
|
55
|
+
});
|
|
56
|
+
it("ignores malformed unrelated portable rows but fails for a malformed requested identity", () => {
|
|
57
|
+
const start = "Fri Jul 10 12:34:56 2026";
|
|
58
|
+
const unrelated = `77 1 77 malformed identity\n42 1 42 ${start} opencode\n`;
|
|
59
|
+
const filtered = probePosixProcesses(spawn(unrelated), 25, "darwin", { pids: [42], groupId: 42 });
|
|
60
|
+
assert.equal(filtered.ok && filtered.processes.get(42)?.startTime, `${start}\topencode`);
|
|
61
|
+
assert.equal(probePosixProcesses(spawn(unrelated), 25, "darwin", { pids: [77] }).ok, false);
|
|
62
|
+
});
|
|
63
|
+
it("preserves delimiter-heavy identities through POSIX escalation and rescan", () => {
|
|
64
|
+
const command = "/opt/opencode pipe|value\nnext\t'quoted'";
|
|
65
|
+
const row = `CODENOMAD_TARGET_B64|42|1|42|${b64("Fri Jul 10 12:34:56 2026")}|${b64(command)}\nCODENOMAD_RESULT|1||1\n`;
|
|
66
|
+
const expected = `Fri Jul 10 12:34:56 2026\t${command}`;
|
|
67
|
+
const guardedCall = {};
|
|
68
|
+
const guarded = signalPosixProcesses(spawn(row, guardedCall), { leader: identity(expected), groupId: 42, members: [identity(expected)], signal: "SIGKILL" }, 25, "darwin");
|
|
69
|
+
const call = {};
|
|
70
|
+
const owned = signalOwnedPosixProcessGroup(spawn(row, call), 42, "SIGTERM", 25);
|
|
71
|
+
assert.deepEqual([guarded.ok, guarded.ok && guarded.signaled[0]?.startTime], [true, expected]);
|
|
72
|
+
assert.deepEqual([owned.ok && owned.matched, owned.ok && owned.signaled[0]?.startTime], [true, expected]);
|
|
73
|
+
assert.ok(call.script.indexOf('kill "-$requested_signal"') < call.script.lastIndexOf("for current_pid"));
|
|
74
|
+
assert.match(call.script, /group_pids\(\).*pid=,pgid=/);
|
|
75
|
+
assert.doesNotMatch(call.script, /ps -eo pid=/);
|
|
76
|
+
assert.match(guardedCall.script, /test "\$current_group" = "\$expected_group"/);
|
|
77
|
+
});
|
|
78
|
+
it("marks a retained portable group request for leaderless guarded cleanup", () => {
|
|
79
|
+
const call = {};
|
|
80
|
+
const guarded = signalPosixProcesses(spawn("CODENOMAD_RESULT|1||1\n", call), {
|
|
81
|
+
leader: identity("gone"), groupId: 42, members: [identity("member")], signal: "SIGTERM",
|
|
82
|
+
allowLeaderlessGroup: true, cleanupToken: "secret-token",
|
|
83
|
+
}, 25, "darwin");
|
|
84
|
+
assert.equal(guarded.ok, true);
|
|
85
|
+
assert.equal(call.args[7], "1");
|
|
86
|
+
assert.equal(call.args[8], "secret-token");
|
|
87
|
+
assert.match(call.script, /anchor=0/);
|
|
88
|
+
assert.match(call.script, /has_cleanup_token/);
|
|
89
|
+
});
|
|
90
|
+
it("queries WSL identities in the selected distro", () => {
|
|
91
|
+
const call = {};
|
|
92
|
+
const probe = probeWslProcesses(spawn("99|1|99|123456|boot-a|123456\n101|99|99|123460|boot-a|123460\n", call), "Ubuntu Test", 25);
|
|
93
|
+
assert.deepEqual([call.command, call.args.slice(0, 4), call.args.includes("codenomad-wsl-identity"), call.script.trimEnd().endsWith("exit 0")], ["wsl.exe", ["--distribution", "Ubuntu Test", "--exec", "sh"], true, true]);
|
|
94
|
+
assert.equal(probe.ok && probe.processes.get(101)?.startTime, "123460");
|
|
95
|
+
});
|
|
96
|
+
it("uses Windows CIM CreationDate as the immutable identity", () => {
|
|
97
|
+
const call = {};
|
|
98
|
+
const probe = probeWindowsProcesses(spawn("4242|100|0|20260710123456.123456+000||20260710123456\n", call), 25);
|
|
99
|
+
assert.match(call.script, /Get-CimInstance Win32_Process/);
|
|
100
|
+
assert.match(call.script, /ProcessId -gt 0/);
|
|
101
|
+
assert.equal(probe.ok && probe.processes.get(4242)?.startTime, "20260710123456.123456+000");
|
|
102
|
+
});
|
|
103
|
+
it("rejects PID reuse and invalid start ordering", () => {
|
|
104
|
+
const original = identity("9");
|
|
105
|
+
for (const [candidate, expected] of [[{ ...original }, true], [{ ...original, startTime: "10" }, false], [{ ...original, pid: 43 }, false]])
|
|
106
|
+
assert.equal(sameProcess(original, candidate), expected);
|
|
107
|
+
assert.equal(startedNoLaterThan(original, "10"), true);
|
|
108
|
+
assert.equal(startedNoLaterThan({ ...original, startOrder: "11" }, "10"), false);
|
|
109
|
+
assert.equal(startedNoLaterThan({ ...original, startOrder: "Fri Jul 10" }, "10"), false);
|
|
110
|
+
});
|
|
111
|
+
it("returns a POSIX mismatch without a second signal command", () => {
|
|
112
|
+
const call = {};
|
|
113
|
+
const guarded = signalPosixProcesses(spawn("CODENOMAD_RESULT|0||0\n", call), { leader: identity(), groupId: 42, members: [identity()], signal: "SIGTERM" }, 25, "linux");
|
|
114
|
+
assert.deepEqual(guarded, { ok: true, matched: false, signalSent: false, signaled: [] });
|
|
115
|
+
assert.deepEqual([call.command, call.args[2], call.args.includes("123456")], ["sh", "codenomad-guarded-signal", true]);
|
|
116
|
+
assert.ok(call.script.indexOf('kill "-$requested_signal"') < call.script.indexOf("uptime=$(cut"));
|
|
117
|
+
});
|
|
118
|
+
it("selects and terminates Windows identities in one guarded CIM invocation", () => {
|
|
119
|
+
const call = {};
|
|
120
|
+
const guarded = signalWindowsProcesses(spawn("CODENOMAD_TARGET|4242|1|0|created||99\nCODENOMAD_RESULT|1||1\n", call), { leader: identity("created"), groupId: 42, members: [identity("created")], signal: "SIGKILL" }, 25);
|
|
121
|
+
assert.equal(guarded.ok && guarded.matched, true);
|
|
122
|
+
assert.equal(call.command, "powershell.exe");
|
|
123
|
+
assert.match(call.script, /CreationDate.*Invoke-CimMethod -InputObject/s);
|
|
124
|
+
assert.equal(call.script.match(/foreach \(\$process in \$selected\)/g)?.length, 2);
|
|
125
|
+
assert.ok(call.script.indexOf("CODENOMAD_TARGET|") < call.script.indexOf("Invoke-CimMethod"));
|
|
126
|
+
assert.doesNotMatch(call.script, /taskkill/i);
|
|
127
|
+
});
|
|
128
|
+
it("retains observed Windows identities after partial termination failure", () => {
|
|
129
|
+
const rows = "CODENOMAD_TARGET|4242|1|0|created||99\nCODENOMAD_TARGET|4243|4242|0|descendant||100";
|
|
130
|
+
const guarded = signalWindowsProcesses(spawn(rows, undefined, 1, "termination failed"), { leader: identity("created"), groupId: 42, members: [identity("created")], signal: "SIGTERM" }, 25);
|
|
131
|
+
assert.equal(guarded.ok, false);
|
|
132
|
+
assert.deepEqual(!guarded.ok && guarded.observed?.map(({ pid }) => pid), [4242, 4243]);
|
|
133
|
+
});
|
|
134
|
+
it("fails conservatively for command, malformed, and empty probe output", () => {
|
|
135
|
+
assert.deepEqual(probeWindowsProcesses(spawn("", undefined, 1, "CIM unavailable"), 25), { ok: false, error: "CIM unavailable" });
|
|
136
|
+
assert.deepEqual(probePosixProcesses(spawn("", undefined, 20, "proc unavailable"), 25, "linux"), { ok: false, error: "proc unavailable" });
|
|
137
|
+
for (const probe of [probePosixProcesses(spawn("42 malformed process row\n"), 25, "darwin"), probeWslProcesses(spawn("not an identity"), "Ubuntu", 25)])
|
|
138
|
+
assert.equal(probe.ok, false);
|
|
139
|
+
});
|
|
140
|
+
});
|