@evomap/evolver-cli 2.0.0-beta.19 → 2.0.0-beta.22
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/dist/antiGeneBenchmark.js +2 -0
- package/dist/antiGeneRollout.js +2 -0
- package/dist/assetRepair.d.ts +24 -0
- package/dist/assetRepair.js +172 -0
- package/dist/autoDistillAntiGene.js +7 -5
- package/dist/autoDistillLlm.d.ts +20 -0
- package/dist/autoDistillLlm.js +77 -15
- package/dist/autoexec.d.ts +11 -0
- package/dist/autoexec.js +65 -10
- package/dist/autoexecConfig.js +2 -1
- package/dist/cliContracts.d.ts +10 -0
- package/dist/cliContracts.js +407 -81
- package/dist/commandCatalog.d.ts +72 -0
- package/dist/commandCatalog.js +120 -0
- package/dist/cycleConsumer.d.ts +9 -0
- package/dist/cycleConsumer.js +14 -3
- package/dist/dispatch.d.ts +0 -1
- package/dist/dispatch.js +10 -4
- package/dist/distillObserver.js +23 -6
- package/dist/doctor.d.ts +11 -0
- package/dist/doctor.js +81 -6
- package/dist/index.d.ts +5 -1
- package/dist/index.js +200 -68
- package/dist/lifecycle.d.ts +126 -3
- package/dist/lifecycle.js +4390 -188
- package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
- package/dist/lifecycleBootstrapTransaction.js +2182 -0
- package/dist/localMemoryGraph.d.ts +90 -3
- package/dist/localMemoryGraph.js +2031 -231
- package/dist/materialSnapshot.d.ts +2 -0
- package/dist/materialSnapshot.js +8 -0
- package/dist/memoryGraphOps.d.ts +8 -0
- package/dist/memoryGraphOps.js +140 -0
- package/dist/migrate/assetFormatMap.d.ts +61 -0
- package/dist/migrate/assetFormatMap.js +53 -0
- package/dist/migrate/envTranslate.js +2 -0
- package/dist/migrate/fieldMap.d.ts +7 -5
- package/dist/migrate/fieldMap.js +20 -14
- package/dist/migrate/v1Import.d.ts +80 -1
- package/dist/migrate/v1Import.js +961 -120
- package/dist/modelCompatibility.d.ts +10 -0
- package/dist/modelCompatibility.js +296 -0
- package/dist/recipe.d.ts +7 -1
- package/dist/recipe.js +113 -11
- package/dist/repairedAssetStore.d.ts +2 -0
- package/dist/repairedAssetStore.js +12 -0
- package/dist/reuse.d.ts +4 -1
- package/dist/reuse.js +212 -107
- package/dist/reviewFilter.d.ts +3 -1
- package/dist/reviewFilter.js +3 -1
- package/dist/runtimeSessionSource.d.ts +5 -0
- package/dist/selectionPolicyConfig.d.ts +8 -0
- package/dist/selectionPolicyConfig.js +18 -0
- package/dist/semanticIdfConfig.d.ts +2 -0
- package/dist/semanticIdfConfig.js +4 -0
- package/dist/sessionIngest.d.ts +7 -1
- package/dist/sessionIngest.js +25 -1
- package/dist/setupHooks.js +12 -6
- package/dist/skill2gep.js +57 -6
- package/dist/skillDistill.js +1 -0
- package/dist/sync.d.ts +1 -1
- package/dist/sync.js +761 -174
- package/dist/thesis.js +2 -0
- package/dist/valueDigest.js +8 -1
- package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
- package/dist/windowsLegacyTaskCleanup.js +1475 -0
- package/dist/workflowRuntime.js +7 -6
- package/package.json +7 -7
|
@@ -0,0 +1,1475 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe cleanup of legacy V1 Windows scheduled-task residue (#956).
|
|
3
|
+
*
|
|
4
|
+
* Issue #956 reports that some historical V1 builds may have registered
|
|
5
|
+
* `EvoMapEvolverProxyDaemon` / `EvoMapEvolverAutoexecDaemon` as scheduled tasks whose action
|
|
6
|
+
* invoked `powershell.exe` / `node.exe` DIRECTLY (the console window flashes at logon before
|
|
7
|
+
* `-WindowStyle Hidden` takes effect, and once the pointed-at binary is gone the task fails
|
|
8
|
+
* and retries `RestartCount` times). V2 registers the same
|
|
9
|
+
* names through a hidden `wscript.exe` VBS launcher — currently via the ABSOLUTE trusted
|
|
10
|
+
* path `<SystemRoot>\System32\wscript.exe` written by the bootstrap transaction, and in
|
|
11
|
+
* older v2 generations via the bare `wscript.exe` name (handled by the existing legacy
|
|
12
|
+
* adoption path, NOT by this module).
|
|
13
|
+
*
|
|
14
|
+
* This module is a destructive migration and obeys the lifecycle authority contract:
|
|
15
|
+
*
|
|
16
|
+
* - Fingerprint, not name match: a task can be removed only after an authoritative V1
|
|
17
|
+
* registration template and launcher/generation evidence have proved that it is residue.
|
|
18
|
+
* The repository currently carries no such evidence. Therefore a complete direct-action
|
|
19
|
+
* shape (`powershell.exe` or `node.exe`) is deliberately classified as `ambiguous` and
|
|
20
|
+
* refused; every missing, ambiguous, or otherwise unproven field fails closed
|
|
21
|
+
* (`inconclusive`). The current v2 absolute `wscript.exe` binding and older bare-`wscript`
|
|
22
|
+
* generations are kept. This module never deletes on a first-match, name-only, or
|
|
23
|
+
* shape-only basis.
|
|
24
|
+
* - Revalidation: the fingerprint is re-verified immediately before unregister, and again
|
|
25
|
+
* after stop, inside the mutation script (mirroring the bootstrap rollback unregister
|
|
26
|
+
* pattern); a task replaced between probe and mutation is left untouched.
|
|
27
|
+
* - Authority: mutation runs under the bootstrap owner lock (or an `assertOwner` seam held
|
|
28
|
+
* by the bootstrap transaction itself), so it cannot race a concurrent bootstrap.
|
|
29
|
+
* - Durable preimage: the task XML (Export-ScheduledTask) is persisted owner-only/atomic in
|
|
30
|
+
* the lifecycle state dir BEFORE any stop/unregister, and `--restore=<preimage>` can
|
|
31
|
+
* re-register it.
|
|
32
|
+
* - Trusted executable: every PowerShell invocation uses the absolute
|
|
33
|
+
* `<SystemRoot>\System32\WindowsPowerShell\v1.0\powershell.exe` path; never a PATH lookup.
|
|
34
|
+
* - Honest status: `clean` / `legacy_detected` / `cleaned` / `inconclusive` / `failed` /
|
|
35
|
+
* `skipped` are never collapsed into each other. A failed or inconclusive run is never
|
|
36
|
+
* reported as `clean`; the automatic SessionStart sweep records it in a negative
|
|
37
|
+
* backoff marker (1h base, doubling per consecutive failure, capped at 24h) so a
|
|
38
|
+
* constrained host does not re-probe on every session, and a conclusive success
|
|
39
|
+
* overwrites it, resetting the counter. The manual command exits non-zero for it.
|
|
40
|
+
* Diagnostics carry task names and bounded reasons only — never raw
|
|
41
|
+
* PowerShell output, absolute paths, or exceptions.
|
|
42
|
+
*/
|
|
43
|
+
import { randomUUID, verify as verifySignature } from 'node:crypto';
|
|
44
|
+
import { spawnSync } from 'node:child_process';
|
|
45
|
+
import { lstatSync, renameSync } from 'node:fs';
|
|
46
|
+
import { basename, dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path';
|
|
47
|
+
import { ops as coreOps } from '@evomap/evolver-core';
|
|
48
|
+
import { lifecyclePaths, trustedWindowsPowerShell } from './lifecycle.js';
|
|
49
|
+
import { acquireBootstrapOwnerLock, assertTrustedArtifactParent, removeDurableFile, readBootstrapArtifactFile, writeDurableText, } from './lifecycleBootstrapTransaction.js';
|
|
50
|
+
/** The only task names this module ever probes; nothing outside this set is ever touched. */
|
|
51
|
+
export const LEGACY_WINDOWS_TASK_NAMES = [
|
|
52
|
+
'EvoMapEvolverProxyDaemon',
|
|
53
|
+
'EvoMapEvolverAutoexecDaemon',
|
|
54
|
+
];
|
|
55
|
+
/** Direct-action leaves that require unavailable V1 provenance before any cleanup. */
|
|
56
|
+
const LEGACY_ACTION_EXECUTABLE_LEAVES = new Set(['powershell.exe', 'node.exe']);
|
|
57
|
+
/** `wscript.exe` leaf (any path form) identifies v2 generations — current or legacy v2. */
|
|
58
|
+
const V2_ACTION_EXECUTABLE_LEAF = 'wscript.exe';
|
|
59
|
+
const PROBE_TIMEOUT_MS = 20_000;
|
|
60
|
+
const EXPORT_TIMEOUT_MS = 20_000;
|
|
61
|
+
const MUTATION_TIMEOUT_MS = 40_000;
|
|
62
|
+
const MAX_PROBE_OUTPUT_BYTES = 256 * 1024;
|
|
63
|
+
const MAX_PREIMAGE_BYTES = 512 * 1024;
|
|
64
|
+
const MAX_COOLDOWN_MARKER_BYTES = 4096;
|
|
65
|
+
export const LEGACY_TASK_SKIP_ENV = 'EVOLVER_SKIP_LEGACY_TASK_PROBE';
|
|
66
|
+
export const LEGACY_TASK_COOLDOWN_FILE = 'legacy-task-cleanup.json';
|
|
67
|
+
export const LEGACY_TASK_PREIMAGE_DIR = 'legacy-task-preimages';
|
|
68
|
+
export const LEGACY_TASK_PROVENANCE_FILE = 'legacy-task-provenance.json';
|
|
69
|
+
export const LEGACY_TASK_PROVENANCE_PUBLIC_KEY_ENV = 'EVOLVER_LEGACY_TASK_PROVENANCE_PUBLIC_KEY';
|
|
70
|
+
export const LEGACY_TASK_PROVENANCE_SCHEMA = 'evolver/windows-legacy-task-provenance/v1';
|
|
71
|
+
export const LEGACY_TASK_COOLDOWN_MS = 24 * 60 * 60 * 1000;
|
|
72
|
+
/** Negative backoff for inconclusive/failed sweeps: 1h base, doubling, capped at 24h. */
|
|
73
|
+
const LEGACY_TASK_NEGATIVE_BACKOFF_BASE_MS = 60 * 60 * 1000;
|
|
74
|
+
const LEGACY_TASK_NEGATIVE_BACKOFF_MAX_MS = 24 * 60 * 60 * 1000;
|
|
75
|
+
const COOLDOWN_MARKER_SCHEMA = 'evolver/legacy-task-cleanup/v1';
|
|
76
|
+
function defaultLegacyTaskRun() {
|
|
77
|
+
const powershell = trustedWindowsPowerShell();
|
|
78
|
+
return (command, args, timeoutMs) => {
|
|
79
|
+
if (command !== powershell) {
|
|
80
|
+
return { status: null, error: new Error('legacy task probe refused a non-trusted executable') };
|
|
81
|
+
}
|
|
82
|
+
const result = spawnSync(command, [...args], {
|
|
83
|
+
encoding: 'utf8',
|
|
84
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
85
|
+
timeout: timeoutMs,
|
|
86
|
+
windowsHide: true,
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
status: result.status,
|
|
90
|
+
...(result.error ? { error: result.error } : {}),
|
|
91
|
+
...(typeof result.stdout === 'string' ? { stdout: result.stdout } : {}),
|
|
92
|
+
...(typeof result.stderr === 'string' ? { stderr: result.stderr } : {}),
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function powershellArgs(script) {
|
|
97
|
+
return ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script];
|
|
98
|
+
}
|
|
99
|
+
function boundedDetail(value, max = 240) {
|
|
100
|
+
const text = (value instanceof Error ? value.message : String(value))
|
|
101
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
|
|
102
|
+
// Diagnostic text can contain file:// or http(s):// URLs whose host, port, query,
|
|
103
|
+
// and path are all potentially sensitive. Redact the complete token before the
|
|
104
|
+
// platform-specific forms below so the slash after a URI scheme cannot leak a path.
|
|
105
|
+
.replace(/\b(?:file|https?):\/\/[^"'<>|\r\n]+/gi, '[redacted-path]')
|
|
106
|
+
// Paths may contain spaces; consume through the next quote/control delimiter rather than
|
|
107
|
+
// stopping at the first whitespace and leaking the remainder of the path.
|
|
108
|
+
.replace(/\b[A-Za-z]:[\\/][^"'<>|\r\n]+/g, '[redacted-path]')
|
|
109
|
+
.replace(/(^|[\s("'=:])\\\\[^"'<>|\r\n]+/g, '$1[redacted-path]')
|
|
110
|
+
.replace(/(^|[\s("'=:])\/[^"'<>|\r\n]+/g, '$1[redacted-path]')
|
|
111
|
+
.replace(/\s+/g, ' ')
|
|
112
|
+
.trim();
|
|
113
|
+
return text.length > max ? `${text.slice(0, max)}…` : text;
|
|
114
|
+
}
|
|
115
|
+
/** Normalize the scheduler's case-insensitive SHA-256 representation before embedding it. */
|
|
116
|
+
function normalizeDefinitionHash(value) {
|
|
117
|
+
if (value === undefined)
|
|
118
|
+
return undefined;
|
|
119
|
+
const normalized = value.toLowerCase();
|
|
120
|
+
return /^[a-f0-9]{64}$/.test(normalized) ? normalized : undefined;
|
|
121
|
+
}
|
|
122
|
+
const LEGACY_TASK_PROVENANCE_KEYS = [
|
|
123
|
+
'schema', 'taskName', 'taskPath', 'definitionHash', 'principalSid', 'issuedAt', 'expiresAt', 'signatureAlg', 'signature',
|
|
124
|
+
];
|
|
125
|
+
const LEGACY_TASK_PROVENANCE_BUNDLE_KEYS = ['schema', 'receipts'];
|
|
126
|
+
function hasOnlyKeys(value, allowed, required) {
|
|
127
|
+
const keys = Object.keys(value);
|
|
128
|
+
return keys.every((key) => allowed.includes(key)) && required.every((key) => Object.hasOwn(value, key));
|
|
129
|
+
}
|
|
130
|
+
export function canonicalLegacyTaskProvenanceBytes(payload) {
|
|
131
|
+
const canonical = {
|
|
132
|
+
schema: LEGACY_TASK_PROVENANCE_SCHEMA,
|
|
133
|
+
taskName: payload.taskName,
|
|
134
|
+
taskPath: '\\',
|
|
135
|
+
definitionHash: payload.definitionHash.toLowerCase(),
|
|
136
|
+
principalSid: payload.principalSid,
|
|
137
|
+
issuedAt: payload.issuedAt,
|
|
138
|
+
...(payload.expiresAt !== undefined ? { expiresAt: payload.expiresAt } : {}),
|
|
139
|
+
signatureAlg: 'ed25519',
|
|
140
|
+
};
|
|
141
|
+
return Buffer.from(JSON.stringify(canonical), 'utf8');
|
|
142
|
+
}
|
|
143
|
+
function parseLegacyTaskProvenanceReceipt(value, publicKey, now) {
|
|
144
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
145
|
+
return undefined;
|
|
146
|
+
const raw = value;
|
|
147
|
+
if (!hasOnlyKeys(raw, LEGACY_TASK_PROVENANCE_KEYS, [
|
|
148
|
+
'schema', 'taskName', 'taskPath', 'definitionHash', 'principalSid', 'issuedAt', 'signatureAlg', 'signature',
|
|
149
|
+
]))
|
|
150
|
+
return undefined;
|
|
151
|
+
if (raw.schema !== LEGACY_TASK_PROVENANCE_SCHEMA
|
|
152
|
+
|| typeof raw.taskName !== 'string'
|
|
153
|
+
|| !LEGACY_WINDOWS_TASK_NAMES.includes(raw.taskName)
|
|
154
|
+
|| raw.taskPath !== '\\'
|
|
155
|
+
|| typeof raw.definitionHash !== 'string'
|
|
156
|
+
|| normalizeDefinitionHash(raw.definitionHash) === undefined
|
|
157
|
+
|| typeof raw.principalSid !== 'string'
|
|
158
|
+
|| !/^S-\d-\d+(?:-\d+){1,15}$/.test(raw.principalSid)
|
|
159
|
+
|| typeof raw.issuedAt !== 'string'
|
|
160
|
+
|| !Number.isFinite(Date.parse(raw.issuedAt))
|
|
161
|
+
|| raw.signatureAlg !== 'ed25519'
|
|
162
|
+
|| typeof raw.signature !== 'string')
|
|
163
|
+
return undefined;
|
|
164
|
+
if (raw.expiresAt !== undefined
|
|
165
|
+
&& (typeof raw.expiresAt !== 'string' || !Number.isFinite(Date.parse(raw.expiresAt)) || Date.parse(raw.expiresAt) <= now)) {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
const signature = Buffer.from(raw.signature, 'base64');
|
|
169
|
+
if (signature.length !== 64 || signature.toString('base64') !== raw.signature)
|
|
170
|
+
return undefined;
|
|
171
|
+
const payload = {
|
|
172
|
+
schema: LEGACY_TASK_PROVENANCE_SCHEMA,
|
|
173
|
+
taskName: raw.taskName,
|
|
174
|
+
taskPath: '\\',
|
|
175
|
+
definitionHash: normalizeDefinitionHash(raw.definitionHash),
|
|
176
|
+
principalSid: raw.principalSid,
|
|
177
|
+
issuedAt: raw.issuedAt,
|
|
178
|
+
...(raw.expiresAt !== undefined ? { expiresAt: raw.expiresAt } : {}),
|
|
179
|
+
signatureAlg: 'ed25519',
|
|
180
|
+
};
|
|
181
|
+
try {
|
|
182
|
+
const key = coreOps.toPublicKey(publicKey);
|
|
183
|
+
if (!verifySignature(null, canonicalLegacyTaskProvenanceBytes(payload), key, signature))
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
return { ...payload, signature: raw.signature };
|
|
190
|
+
}
|
|
191
|
+
function loadLegacyTaskProvenance(stateDir, env, now) {
|
|
192
|
+
const path = join(stateDir, LEGACY_TASK_PROVENANCE_FILE);
|
|
193
|
+
// 缺少 provenance 是正常的 fail-closed 状态。先探测叶节点,避免调用方只提供尚未创建的
|
|
194
|
+
// state directory 时被错误报告为 receipt 不可读。
|
|
195
|
+
try {
|
|
196
|
+
lstatSync(path);
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (error?.code === 'ENOENT')
|
|
200
|
+
return { receipts: new Map() };
|
|
201
|
+
return { receipts: new Map(), detail: 'legacy task provenance receipt is unreadable' };
|
|
202
|
+
}
|
|
203
|
+
let bytes;
|
|
204
|
+
try {
|
|
205
|
+
assertLegacyStateArtifactPath(path);
|
|
206
|
+
bytes = readBootstrapArtifactFile(path, MAX_COOLDOWN_MARKER_BYTES * 8, { role: 'owned' }).bytes;
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return { receipts: new Map(), detail: 'legacy task provenance receipt is unreadable' };
|
|
210
|
+
}
|
|
211
|
+
const publicKey = env[LEGACY_TASK_PROVENANCE_PUBLIC_KEY_ENV]?.trim();
|
|
212
|
+
if (!publicKey)
|
|
213
|
+
return { receipts: new Map(), detail: `${LEGACY_TASK_PROVENANCE_PUBLIC_KEY_ENV} is not configured` };
|
|
214
|
+
let parsed;
|
|
215
|
+
try {
|
|
216
|
+
parsed = JSON.parse(bytes.toString('utf8'));
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return { receipts: new Map(), detail: 'legacy task provenance receipt is not valid JSON' };
|
|
220
|
+
}
|
|
221
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
222
|
+
return { receipts: new Map(), detail: 'legacy task provenance receipt has an invalid shape' };
|
|
223
|
+
}
|
|
224
|
+
const bundle = parsed;
|
|
225
|
+
if (!hasOnlyKeys(bundle, LEGACY_TASK_PROVENANCE_BUNDLE_KEYS, ['schema', 'receipts'])
|
|
226
|
+
|| bundle.schema !== LEGACY_TASK_PROVENANCE_SCHEMA
|
|
227
|
+
|| !Array.isArray(bundle.receipts)
|
|
228
|
+
|| bundle.receipts.length > LEGACY_WINDOWS_TASK_NAMES.length) {
|
|
229
|
+
return { receipts: new Map(), detail: 'legacy task provenance receipt has an invalid shape' };
|
|
230
|
+
}
|
|
231
|
+
const receipts = new Map();
|
|
232
|
+
for (const candidate of bundle.receipts) {
|
|
233
|
+
const receipt = parseLegacyTaskProvenanceReceipt(candidate, publicKey, now);
|
|
234
|
+
if (!receipt || receipts.has(receipt.taskName)) {
|
|
235
|
+
return { receipts: new Map(), detail: 'legacy task provenance receipt failed signature or identity validation' };
|
|
236
|
+
}
|
|
237
|
+
receipts.set(receipt.taskName, receipt);
|
|
238
|
+
}
|
|
239
|
+
return { receipts };
|
|
240
|
+
}
|
|
241
|
+
/** True when the automatic entry points must never cross the Task Scheduler boundary. */
|
|
242
|
+
export function legacyTaskProbeSkipped(env) {
|
|
243
|
+
const value = env[LEGACY_TASK_SKIP_ENV]?.trim();
|
|
244
|
+
return value !== undefined && value !== '' && value !== '0';
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* The probe script emits one JSON record per known task name. It only READS the Task
|
|
248
|
+
* Scheduler; names are compile-time constants, so no interpolation ever reaches it.
|
|
249
|
+
*
|
|
250
|
+
* Enumeration note: every script below enumerates with `-TaskPath '\*'` (a LIKE query)
|
|
251
|
+
* rather than the exact key `'\'` — the exact-key query throws
|
|
252
|
+
* CmdletizationQuery_NotFound_TaskPath when the root folder holds ZERO tasks (a clean
|
|
253
|
+
* host), while the LIKE form returns an empty set. `-ErrorAction Stop` is kept on every
|
|
254
|
+
* call so genuine scheduler faults still fail closed. Root-only semantics are preserved
|
|
255
|
+
* by an explicit `$_.TaskPath -eq '\'` filter on every enumeration.
|
|
256
|
+
*/
|
|
257
|
+
const PROBE_SCRIPT = `$ErrorActionPreference = 'Stop'
|
|
258
|
+
$names = @(${LEGACY_WINDOWS_TASK_NAMES.map((name) => `'${name}'`).join(', ')})
|
|
259
|
+
$results = foreach ($name in $names) {
|
|
260
|
+
$tasks = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq $name })
|
|
261
|
+
if ($tasks.Count -eq 0) { [pscustomobject]@{ name = $name; present = $false; count = 0 } }
|
|
262
|
+
elseif ($tasks.Count -ne 1) { [pscustomobject]@{ name = $name; present = $true; ambiguous = $true; count = $tasks.Count } }
|
|
263
|
+
else {
|
|
264
|
+
$task = $tasks[0]
|
|
265
|
+
$actions = if ($null -eq $task.Actions) { $null } else { @($task.Actions) }
|
|
266
|
+
$triggers = if ($null -eq $task.Triggers) { $null } else { @($task.Triggers) }
|
|
267
|
+
$principalUser = if ($null -ne $task.Principal -and $null -ne $task.Principal.UserId) { [string]$task.Principal.UserId } else { $null }
|
|
268
|
+
$principalSid = $null
|
|
269
|
+
if ($principalUser -match '^S-\\d-') { $principalSid = $principalUser }
|
|
270
|
+
elseif ($principalUser) {
|
|
271
|
+
try { $principalSid = ([System.Security.Principal.NTAccount]$principalUser).Translate([System.Security.Principal.SecurityIdentifier]).Value } catch { $principalSid = $null }
|
|
272
|
+
}
|
|
273
|
+
$definitionXml = [string](Export-ScheduledTask -TaskPath '\\' -TaskName $name -ErrorAction Stop)
|
|
274
|
+
$definitionSha = [System.Security.Cryptography.SHA256]::Create()
|
|
275
|
+
$definitionHash = ([System.BitConverter]::ToString($definitionSha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($definitionXml)))).Replace('-', '').ToLowerInvariant()
|
|
276
|
+
$definitionSha.Dispose()
|
|
277
|
+
[pscustomobject]@{
|
|
278
|
+
name = $name; present = $true; ambiguous = $false; count = 1
|
|
279
|
+
taskPath = if ($null -ne $task.TaskPath) { [string]$task.TaskPath } else { $null }
|
|
280
|
+
actionCount = if ($null -ne $actions) { $actions.Count } else { $null }
|
|
281
|
+
execute = if ($null -ne $actions -and $actions.Count -ge 1 -and $null -ne $actions[0].Execute) { [string]$actions[0].Execute } else { $null }
|
|
282
|
+
arguments = if ($null -ne $actions -and $actions.Count -ge 1 -and $null -ne $actions[0].Arguments) { [string]$actions[0].Arguments } else { $null }
|
|
283
|
+
workingDirectory = if ($null -ne $actions -and $actions.Count -ge 1 -and $null -ne $actions[0].WorkingDirectory) { [string]$actions[0].WorkingDirectory } else { $null }
|
|
284
|
+
triggerCount = if ($null -ne $triggers) { $triggers.Count } else { $null }
|
|
285
|
+
userId = $principalUser
|
|
286
|
+
principalSid = $principalSid
|
|
287
|
+
logonType = if ($null -ne $task.Principal -and $null -ne $task.Principal.LogonType) { [string]$task.Principal.LogonType } else { $null }
|
|
288
|
+
runLevel = if ($null -ne $task.Principal -and $null -ne $task.Principal.RunLevel) { [string]$task.Principal.RunLevel } else { $null }
|
|
289
|
+
enabled = if ($null -ne $task.Settings -and $null -ne $task.Settings.Enabled) { [bool]$task.Settings.Enabled } else { $null }
|
|
290
|
+
restartCount = if ($null -ne $task.Settings -and $null -ne $task.Settings.RestartCount) { [int]$task.Settings.RestartCount } else { $null }
|
|
291
|
+
description = if ($null -ne $task.Description) { [string]$task.Description } else { $null }
|
|
292
|
+
definitionHash = $definitionHash
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
ConvertTo-Json @($results) -Compress -Depth 3`;
|
|
297
|
+
/**
|
|
298
|
+
* Fingerprint revalidation + export for one task. Exit codes: 0 preimage on stdout,
|
|
299
|
+
* 3 count drift, 4 action drift, 5 execute/provenance refusal, 10 definition drift, 9
|
|
300
|
+
* scheduler error.
|
|
301
|
+
*/
|
|
302
|
+
function renderDefinitionHashGuard(name, expectedHash) {
|
|
303
|
+
if (expectedHash === undefined)
|
|
304
|
+
return '';
|
|
305
|
+
const normalizedHash = normalizeDefinitionHash(expectedHash);
|
|
306
|
+
if (normalizedHash === undefined)
|
|
307
|
+
return 'exit 10';
|
|
308
|
+
const escapedHash = normalizedHash.replace(/'/g, "''");
|
|
309
|
+
return `$definitionXml = [string](Export-ScheduledTask -TaskPath '\\' -TaskName '${name}' -ErrorAction Stop)
|
|
310
|
+
$definitionSha = [System.Security.Cryptography.SHA256]::Create()
|
|
311
|
+
$definitionHash = ([System.BitConverter]::ToString($definitionSha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($definitionXml)))).Replace('-', '').ToLowerInvariant()
|
|
312
|
+
$definitionSha.Dispose()
|
|
313
|
+
if ($definitionHash -ne '${escapedHash}') { exit 10 }`;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Defense in depth for the dormant destructive path. The classifier refuses direct
|
|
317
|
+
* powershell/node actions because this repository has no authoritative V1 provenance. Keep
|
|
318
|
+
* the same refusal in every generated export/mutation script so a future caller cannot turn
|
|
319
|
+
* a shape-only record into an unregister by bypassing the classifier.
|
|
320
|
+
*/
|
|
321
|
+
function renderV1ProvenanceGuard(receipt) {
|
|
322
|
+
if (receipt === undefined) {
|
|
323
|
+
return `# V1 provenance evidence is unavailable; direct-task cleanup is disabled
|
|
324
|
+
exit 5`;
|
|
325
|
+
}
|
|
326
|
+
if (normalizeDefinitionHash(receipt.definitionHash) === undefined)
|
|
327
|
+
return 'exit 5';
|
|
328
|
+
// Ed25519 receipt 在渲染脚本前由 Node authority 验证。PowerShell 侧仍绑定精确的任务身份和快照哈希,
|
|
329
|
+
// 因此测试调用方或未来调用方都不能把缺失 receipt 变成仅凭形状注销。
|
|
330
|
+
return `# V1 provenance receipt verified by the lifecycle owner; keep the exact task snapshot bound
|
|
331
|
+
if ($task.TaskPath -ne '\\') { exit 6 }`;
|
|
332
|
+
}
|
|
333
|
+
function renderExportScript(name, expectedHash, receipt) {
|
|
334
|
+
const definitionHashGuard = renderDefinitionHashGuard(name, expectedHash);
|
|
335
|
+
const provenanceGuard = renderV1ProvenanceGuard(receipt);
|
|
336
|
+
const exportOutput = expectedHash !== undefined ? '$definitionXml' : `(Export-ScheduledTask -TaskPath '\\' -TaskName '${name}' -ErrorAction Stop)`;
|
|
337
|
+
return `$ErrorActionPreference = 'Stop'
|
|
338
|
+
try {
|
|
339
|
+
$tasks = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
340
|
+
if ($tasks.Count -ne 1) { exit 3 }
|
|
341
|
+
$task = $tasks[0]; $actions = @($task.Actions)
|
|
342
|
+
if ($actions.Count -ne 1) { exit 4 }
|
|
343
|
+
$leaf = Split-Path -Leaf ([string]$actions[0].Execute)
|
|
344
|
+
if (($leaf -ine 'powershell.exe') -and ($leaf -ine 'node.exe')) { exit 5 }
|
|
345
|
+
${provenanceGuard}
|
|
346
|
+
${definitionHashGuard}
|
|
347
|
+
Write-Output ${exportOutput}
|
|
348
|
+
exit 0
|
|
349
|
+
} catch { exit 9 }`;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Fingerprint revalidation → stop → revalidation → unregister → absence verification for
|
|
353
|
+
* one task (the bootstrap rollback unregister pattern). Exit codes: 0 removed, 3 count
|
|
354
|
+
* drift, 4 action drift, 5 execute/provenance refusal, 6 TaskPath drift, 7 stop timeout, 8
|
|
355
|
+
* absence not confirmed, 9 scheduler error, 10 definition drift.
|
|
356
|
+
*/
|
|
357
|
+
function renderMutationScript(name, expectedHash, receipt) {
|
|
358
|
+
const definitionHashGuard = renderDefinitionHashGuard(name, expectedHash);
|
|
359
|
+
const provenanceGuard = renderV1ProvenanceGuard(receipt);
|
|
360
|
+
const fingerprint = `$task = $tasks[0]; $actions = @($task.Actions)
|
|
361
|
+
if ($actions.Count -ne 1) { exit 4 }
|
|
362
|
+
$leaf = Split-Path -Leaf ([string]$actions[0].Execute)
|
|
363
|
+
if (($leaf -ine 'powershell.exe') -and ($leaf -ine 'node.exe')) { exit 5 }
|
|
364
|
+
${provenanceGuard}
|
|
365
|
+
if ($task.TaskPath -ne '\\') { exit 6 }
|
|
366
|
+
${definitionHashGuard}`;
|
|
367
|
+
return `$ErrorActionPreference = 'Stop'
|
|
368
|
+
try {
|
|
369
|
+
$tasks = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
370
|
+
if ($tasks.Count -ne 1) { exit 3 }
|
|
371
|
+
${fingerprint}
|
|
372
|
+
if ($task.State -eq 'Running') {
|
|
373
|
+
# Stop the inspected CIM object as well, so a replacement cannot be stopped by name
|
|
374
|
+
# before the post-stop fingerprint check has a chance to reject it.
|
|
375
|
+
Stop-ScheduledTask -InputObject $task -ErrorAction Stop
|
|
376
|
+
$deadline = [DateTime]::UtcNow.AddSeconds(15)
|
|
377
|
+
do {
|
|
378
|
+
Start-Sleep -Milliseconds 100
|
|
379
|
+
$wait = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
380
|
+
if ($wait.Count -eq 0) { $task = $null; break }
|
|
381
|
+
$task = $wait[0]
|
|
382
|
+
} while ($null -ne $task -and $task.State -eq 'Running' -and [DateTime]::UtcNow -lt $deadline)
|
|
383
|
+
if ($null -ne $task -and $task.State -eq 'Running') { exit 7 }
|
|
384
|
+
}
|
|
385
|
+
$tasks = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
386
|
+
if ($tasks.Count -ne 1) { exit 3 }
|
|
387
|
+
${fingerprint}
|
|
388
|
+
# Bind unregister to the CIM object returned by the final guarded enumeration. A name-only
|
|
389
|
+
# lookup here could delete a replacement task that wins the race after the fingerprint check.
|
|
390
|
+
Unregister-ScheduledTask -InputObject $task -Confirm:$false -ErrorAction Stop | Out-Null
|
|
391
|
+
$left = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
392
|
+
if ($left.Count -ne 0) { exit 8 }
|
|
393
|
+
exit 0
|
|
394
|
+
} catch { exit 9 }`;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Restore refuses to overwrite: it re-registers a persisted preimage only when the known
|
|
398
|
+
* name is currently absent. Exit codes: 0 restored, 3 name already present, 4 registration
|
|
399
|
+
* verification failed after a guarded rollback, 5 preimage changed while restoring, 9
|
|
400
|
+
* scheduler error, 11 rollback could not prove that the just-registered generation was still
|
|
401
|
+
* present (the task is deliberately left for operator inspection).
|
|
402
|
+
*/
|
|
403
|
+
function renderRestoreScript(name, preimageReadPath, expectedHash) {
|
|
404
|
+
const escapedPath = preimageReadPath.replace(/'/g, "''");
|
|
405
|
+
const normalizedHash = normalizeDefinitionHash(expectedHash);
|
|
406
|
+
const escapedHash = normalizedHash
|
|
407
|
+
? normalizedHash.replace(/'/g, "''")
|
|
408
|
+
: undefined;
|
|
409
|
+
const hashGuard = expectedHash !== undefined && escapedHash === undefined
|
|
410
|
+
? 'exit 5'
|
|
411
|
+
: escapedHash
|
|
412
|
+
? `$preimageBytes = [System.IO.File]::ReadAllBytes('${escapedPath}')
|
|
413
|
+
if ($preimageBytes.Length -eq 0 -or $preimageBytes.Length -gt ${MAX_PREIMAGE_BYTES}) { exit 5 }
|
|
414
|
+
$preimageSha = [System.Security.Cryptography.SHA256]::Create()
|
|
415
|
+
$preimageHash = ([System.BitConverter]::ToString($preimageSha.ComputeHash($preimageBytes))).Replace('-', '').ToLowerInvariant()
|
|
416
|
+
$preimageSha.Dispose()
|
|
417
|
+
if ($preimageHash -ne '${escapedHash}') { exit 5 }
|
|
418
|
+
$xml = [System.Text.Encoding]::UTF8.GetString($preimageBytes)`
|
|
419
|
+
: `$xml = [System.IO.File]::ReadAllText('${escapedPath}')`;
|
|
420
|
+
return `$ErrorActionPreference = 'Stop'
|
|
421
|
+
function Get-CanonicalTaskXml([string]$text) {
|
|
422
|
+
$xmlSettings = New-Object System.Xml.XmlReaderSettings
|
|
423
|
+
$xmlSettings.DtdProcessing = [System.Xml.DtdProcessing]::Prohibit
|
|
424
|
+
$xmlSettings.XmlResolver = $null
|
|
425
|
+
$xmlReader = [System.Xml.XmlReader]::Create([System.IO.StringReader]::new($text), $xmlSettings)
|
|
426
|
+
try {
|
|
427
|
+
$xmlDoc = New-Object System.Xml.XmlDocument
|
|
428
|
+
$xmlDoc.PreserveWhitespace = $false
|
|
429
|
+
$xmlDoc.XmlResolver = $null
|
|
430
|
+
$xmlDoc.Load($xmlReader)
|
|
431
|
+
if ($null -eq $xmlDoc.DocumentElement -or $xmlDoc.DocumentElement.LocalName -ne 'Task') { throw 'invalid scheduled-task XML root' }
|
|
432
|
+
return [string]$xmlDoc.DocumentElement.OuterXml
|
|
433
|
+
} finally {
|
|
434
|
+
$xmlReader.Dispose()
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function Get-CanonicalTaskHash([string]$text) {
|
|
438
|
+
$canonical = Get-CanonicalTaskXml $text
|
|
439
|
+
$sha = [System.Security.Cryptography.SHA256]::Create()
|
|
440
|
+
try {
|
|
441
|
+
return ([System.BitConverter]::ToString($sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($canonical)))).Replace('-', '').ToLowerInvariant()
|
|
442
|
+
} finally {
|
|
443
|
+
$sha.Dispose()
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
function Try-RollbackRegisteredTask([string]$expectedCanonicalHash) {
|
|
447
|
+
try {
|
|
448
|
+
$current = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
449
|
+
if ($current.Count -eq 0) { return $true }
|
|
450
|
+
if ($current.Count -ne 1) { return $false }
|
|
451
|
+
$currentXml = [string](Export-ScheduledTask -TaskPath '\\' -TaskName '${name}' -ErrorAction Stop)
|
|
452
|
+
if ((Get-CanonicalTaskHash $currentXml) -ne $expectedCanonicalHash) { return $false }
|
|
453
|
+
# Use the inspected CIM object, not a second name-only lookup, so a replacement is not
|
|
454
|
+
# silently unregistered after the guarded identity check.
|
|
455
|
+
Unregister-ScheduledTask -InputObject $current[0] -Confirm:$false -ErrorAction Stop | Out-Null
|
|
456
|
+
$remaining = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
457
|
+
return $remaining.Count -eq 0
|
|
458
|
+
} catch {
|
|
459
|
+
return $false
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
$registered = $false
|
|
463
|
+
$registrationAttempted = $false
|
|
464
|
+
$expectedCanonicalHash = $null
|
|
465
|
+
try {
|
|
466
|
+
$existing = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
467
|
+
if ($existing.Count -ne 0) { exit 3 }
|
|
468
|
+
${hashGuard}
|
|
469
|
+
$expectedCanonicalHash = Get-CanonicalTaskHash $xml
|
|
470
|
+
$existingAfterRead = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
471
|
+
if ($existingAfterRead.Count -ne 0) { exit 3 }
|
|
472
|
+
# Mark the boundary before invoking the cmdlet. A provider can commit the task and then
|
|
473
|
+
# surface a timeout/transport error; the catch path must still attempt guarded cleanup.
|
|
474
|
+
$registrationAttempted = $true
|
|
475
|
+
Register-ScheduledTask -TaskPath '\\' -TaskName '${name}' -Xml $xml -ErrorAction Stop | Out-Null
|
|
476
|
+
$registered = $true
|
|
477
|
+
$verify = @(Get-ScheduledTask -TaskPath '\\*' -ErrorAction Stop | Where-Object { $_.TaskPath -eq '\\' -and $_.TaskName -eq '${name}' })
|
|
478
|
+
if ($verify.Count -ne 1) {
|
|
479
|
+
if (Try-RollbackRegisteredTask $expectedCanonicalHash) { exit 4 }
|
|
480
|
+
exit 11
|
|
481
|
+
}
|
|
482
|
+
# Export the registered generation and compare a parsed/canonical representation. This
|
|
483
|
+
# covers every action, argument, working directory, principal, trigger, setting,
|
|
484
|
+
# description, and generation field, while tolerating scheduler whitespace/encoding
|
|
485
|
+
# normalization. A command/argument-only check is insufficient because an extra action or
|
|
486
|
+
# changed principal could otherwise survive a failed restore.
|
|
487
|
+
$registeredXml = [string](Export-ScheduledTask -TaskPath '\\' -TaskName '${name}' -ErrorAction Stop)
|
|
488
|
+
if ((Get-CanonicalTaskHash $registeredXml) -ne $expectedCanonicalHash) {
|
|
489
|
+
if (Try-RollbackRegisteredTask $expectedCanonicalHash) { exit 4 }
|
|
490
|
+
exit 11
|
|
491
|
+
}
|
|
492
|
+
exit 0
|
|
493
|
+
} catch {
|
|
494
|
+
if (($registrationAttempted -or $registered) -and $null -ne $expectedCanonicalHash -and (Try-RollbackRegisteredTask $expectedCanonicalHash)) { exit 9 }
|
|
495
|
+
if ($registrationAttempted -or $registered) { exit 11 }
|
|
496
|
+
exit 9
|
|
497
|
+
}`;
|
|
498
|
+
}
|
|
499
|
+
function parseProbeRecords(stdout) {
|
|
500
|
+
const trimmed = stdout.trim();
|
|
501
|
+
if (!trimmed)
|
|
502
|
+
return undefined;
|
|
503
|
+
if (Buffer.byteLength(trimmed, 'utf8') > MAX_PROBE_OUTPUT_BYTES)
|
|
504
|
+
return undefined;
|
|
505
|
+
try {
|
|
506
|
+
const parsed = JSON.parse(trimmed);
|
|
507
|
+
const list = Array.isArray(parsed) ? parsed : [parsed];
|
|
508
|
+
if (list.length === 0)
|
|
509
|
+
return undefined;
|
|
510
|
+
return list;
|
|
511
|
+
}
|
|
512
|
+
catch {
|
|
513
|
+
return undefined;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function executeLeaf(execute) {
|
|
517
|
+
if (typeof execute !== 'string')
|
|
518
|
+
return undefined;
|
|
519
|
+
const trimmed = execute.trim();
|
|
520
|
+
if (!trimmed)
|
|
521
|
+
return undefined;
|
|
522
|
+
const leaf = trimmed.split(/[\\/]/).pop() ?? trimmed;
|
|
523
|
+
return leaf.toLowerCase();
|
|
524
|
+
}
|
|
525
|
+
function isFiniteInteger(value) {
|
|
526
|
+
return typeof value === 'number' && Number.isSafeInteger(value);
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* A present record must carry every field needed to make the conservative shape decision. A
|
|
530
|
+
* missing value is not equivalent to an empty/foreign task: it means the scheduler response
|
|
531
|
+
* was incomplete, so callers must stop before mutation. Even a complete direct-action shape
|
|
532
|
+
* remains ambiguous until a trusted V1 template is available; see `classifyProbedTask`.
|
|
533
|
+
*/
|
|
534
|
+
function hasCompleteProbeFingerprint(record) {
|
|
535
|
+
return typeof record.taskPath === 'string'
|
|
536
|
+
&& isFiniteInteger(record.actionCount)
|
|
537
|
+
&& typeof record.execute === 'string'
|
|
538
|
+
&& typeof record.arguments === 'string'
|
|
539
|
+
&& typeof record.workingDirectory === 'string'
|
|
540
|
+
&& isFiniteInteger(record.triggerCount)
|
|
541
|
+
&& typeof record.userId === 'string'
|
|
542
|
+
&& typeof record.principalSid === 'string'
|
|
543
|
+
&& typeof record.logonType === 'string'
|
|
544
|
+
&& typeof record.runLevel === 'string'
|
|
545
|
+
&& typeof record.enabled === 'boolean'
|
|
546
|
+
&& isFiniteInteger(record.restartCount)
|
|
547
|
+
&& typeof record.description === 'string'
|
|
548
|
+
&& typeof record.definitionHash === 'string'
|
|
549
|
+
&& /^[a-f0-9]{64}$/i.test(record.definitionHash);
|
|
550
|
+
}
|
|
551
|
+
export function classifyProbedTask(record, provenance) {
|
|
552
|
+
if (!record || record.present !== true)
|
|
553
|
+
return { classification: 'absent' };
|
|
554
|
+
if (typeof record.name !== 'string' || !LEGACY_WINDOWS_TASK_NAMES.includes(record.name)) {
|
|
555
|
+
return { classification: 'foreign', reason: 'task name is outside the cleanup allowlist' };
|
|
556
|
+
}
|
|
557
|
+
// The probe protocol always emits a count and an explicit ambiguous flag for present
|
|
558
|
+
// tasks; anything else is a protocol break and fails closed.
|
|
559
|
+
if (record.ambiguous !== false || record.count !== 1) {
|
|
560
|
+
return { classification: 'ambiguous', reason: 'multiple same-name tasks registered' };
|
|
561
|
+
}
|
|
562
|
+
if (!hasCompleteProbeFingerprint(record)) {
|
|
563
|
+
return { classification: 'ambiguous', reason: 'task fingerprint is incomplete' };
|
|
564
|
+
}
|
|
565
|
+
if (record.taskPath !== '\\') {
|
|
566
|
+
return { classification: 'foreign', reason: 'registered outside the root task path' };
|
|
567
|
+
}
|
|
568
|
+
if (record.actionCount !== 1) {
|
|
569
|
+
return { classification: 'foreign', reason: 'action shape does not match the v1 template' };
|
|
570
|
+
}
|
|
571
|
+
const userId = typeof record.userId === 'string' ? record.userId : '';
|
|
572
|
+
const principalSid = typeof record.principalSid === 'string' ? record.principalSid : '';
|
|
573
|
+
const logonType = typeof record.logonType === 'string' ? record.logonType : '';
|
|
574
|
+
const runLevel = typeof record.runLevel === 'string' ? record.runLevel : '';
|
|
575
|
+
const actionArguments = typeof record.arguments === 'string' ? record.arguments : '';
|
|
576
|
+
if (record.triggerCount !== 1
|
|
577
|
+
|| userId.trim() === ''
|
|
578
|
+
|| !/^S-\d-\d+(?:-\d+){1,15}$/.test(principalSid)
|
|
579
|
+
|| logonType.toLowerCase() !== 'interactive'
|
|
580
|
+
|| runLevel.toLowerCase() !== 'limited'
|
|
581
|
+
|| record.enabled !== true
|
|
582
|
+
|| record.restartCount !== 5
|
|
583
|
+
|| actionArguments.trim() === '') {
|
|
584
|
+
return { classification: 'foreign', reason: 'principal, trigger, settings, or action arguments drifted' };
|
|
585
|
+
}
|
|
586
|
+
const leaf = executeLeaf(record.execute);
|
|
587
|
+
if (leaf === undefined) {
|
|
588
|
+
return { classification: 'ambiguous', reason: 'action executable could not be read' };
|
|
589
|
+
}
|
|
590
|
+
if (LEGACY_ACTION_EXECUTABLE_LEAVES.has(leaf)) {
|
|
591
|
+
if (provenance === undefined) {
|
|
592
|
+
return { classification: 'ambiguous', reason: 'V1 provenance evidence unavailable; refusing destructive cleanup' };
|
|
593
|
+
}
|
|
594
|
+
if (provenance.taskName !== record.name
|
|
595
|
+
|| provenance.taskPath !== record.taskPath
|
|
596
|
+
|| provenance.principalSid !== principalSid
|
|
597
|
+
|| provenance.definitionHash !== String(record.definitionHash).toLowerCase()) {
|
|
598
|
+
return { classification: 'foreign', reason: 'signed V1 provenance does not match the observed task generation' };
|
|
599
|
+
}
|
|
600
|
+
return { classification: 'legacy', reason: 'signed V1 generation receipt matched' };
|
|
601
|
+
}
|
|
602
|
+
if (leaf === V2_ACTION_EXECUTABLE_LEAF) {
|
|
603
|
+
return { classification: 'current', reason: 'v2 wscript launcher binding' };
|
|
604
|
+
}
|
|
605
|
+
return { classification: 'foreign', reason: 'action executable is not an evolver shape' };
|
|
606
|
+
}
|
|
607
|
+
function runProbe(run, powershell) {
|
|
608
|
+
const result = run(powershell, powershellArgs(PROBE_SCRIPT), PROBE_TIMEOUT_MS);
|
|
609
|
+
if (result.error || result.status !== 0 || typeof result.stdout !== 'string') {
|
|
610
|
+
return { detail: result.error ? boundedDetail(result.error) : `probe exited with status ${result.status ?? 'timeout'}` };
|
|
611
|
+
}
|
|
612
|
+
const records = parseProbeRecords(result.stdout);
|
|
613
|
+
if (!records)
|
|
614
|
+
return { detail: 'probe output could not be parsed' };
|
|
615
|
+
return { records };
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* The PowerShell probe has a fixed, closed-world response contract. A missing,
|
|
619
|
+
* duplicated, malformed, or unexpected record means enumeration was incomplete;
|
|
620
|
+
* callers must not interpret it as an absent task.
|
|
621
|
+
*/
|
|
622
|
+
function probeCoverageIssue(records) {
|
|
623
|
+
const knownNames = new Set(LEGACY_WINDOWS_TASK_NAMES);
|
|
624
|
+
const names = records.map((record) => record && typeof record.name === 'string' ? record.name : undefined);
|
|
625
|
+
if (names.some((name) => name === undefined))
|
|
626
|
+
return 'probe returned a malformed task record';
|
|
627
|
+
if (names.some((name) => !knownNames.has(name)))
|
|
628
|
+
return 'probe returned an unexpected task record';
|
|
629
|
+
for (const record of records) {
|
|
630
|
+
if (!record || (record.present !== true && record.present !== false))
|
|
631
|
+
return 'probe returned a malformed task record';
|
|
632
|
+
if (record.present === false) {
|
|
633
|
+
if (record.count !== 0 || (record.ambiguous !== undefined && record.ambiguous !== false)) {
|
|
634
|
+
return 'probe returned an inconsistent absent-task record';
|
|
635
|
+
}
|
|
636
|
+
const absentFingerprintFields = [
|
|
637
|
+
'taskPath', 'actionCount', 'execute', 'arguments', 'workingDirectory', 'triggerCount',
|
|
638
|
+
'userId', 'principalSid', 'logonType', 'runLevel', 'enabled', 'restartCount',
|
|
639
|
+
'description', 'definitionHash',
|
|
640
|
+
];
|
|
641
|
+
if (absentFingerprintFields.some((field) => record[field] !== undefined)) {
|
|
642
|
+
return 'probe returned an inconsistent absent-task record';
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
const missing = LEGACY_WINDOWS_TASK_NAMES.filter((name) => !names.includes(name));
|
|
647
|
+
if (missing.length > 0)
|
|
648
|
+
return 'probe omitted a known task name';
|
|
649
|
+
const duplicate = LEGACY_WINDOWS_TASK_NAMES.find((name) => names.filter((candidate) => candidate === name).length !== 1);
|
|
650
|
+
if (duplicate)
|
|
651
|
+
return 'probe returned a duplicate known task record';
|
|
652
|
+
return undefined;
|
|
653
|
+
}
|
|
654
|
+
function preimageDirFor(stateDir) {
|
|
655
|
+
return join(stateDir, LEGACY_TASK_PREIMAGE_DIR);
|
|
656
|
+
}
|
|
657
|
+
function cooldownMarkerPath(stateDir) {
|
|
658
|
+
return join(stateDir, LEGACY_TASK_COOLDOWN_FILE);
|
|
659
|
+
}
|
|
660
|
+
/** Keep lifecycle state artifacts on the trusted, non-reparse state directory chain. */
|
|
661
|
+
function assertLegacyStateArtifactPath(path) {
|
|
662
|
+
assertTrustedArtifactParent(path, process.platform);
|
|
663
|
+
}
|
|
664
|
+
function writeLegacyStateText(path, content) {
|
|
665
|
+
assertLegacyStateArtifactPath(path);
|
|
666
|
+
writeDurableText(path, content, 0o600);
|
|
667
|
+
// Re-check the parent chain after publication so a replaced/symlinked state directory is
|
|
668
|
+
// never silently accepted as lifecycle-owned state.
|
|
669
|
+
assertLegacyStateArtifactPath(path);
|
|
670
|
+
// Validate the published leaf as well: owner-only mode, regular-file identity, no reparse
|
|
671
|
+
// link, and a stable descriptor/hash. This closes the gap between the generic durable writer
|
|
672
|
+
// and the lifecycle artifact contract used by reads.
|
|
673
|
+
readBootstrapArtifactFile(path, MAX_PREIMAGE_BYTES, { role: 'owned' });
|
|
674
|
+
}
|
|
675
|
+
function readCooldownMarker(stateDir) {
|
|
676
|
+
const path = cooldownMarkerPath(stateDir);
|
|
677
|
+
try {
|
|
678
|
+
assertLegacyStateArtifactPath(path);
|
|
679
|
+
const receipt = readBootstrapArtifactFile(path, MAX_COOLDOWN_MARKER_BYTES, { role: 'owned' });
|
|
680
|
+
const parsed = JSON.parse(receipt.bytes.toString('utf8'));
|
|
681
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
682
|
+
return undefined;
|
|
683
|
+
const marker = parsed;
|
|
684
|
+
if (marker.schema !== COOLDOWN_MARKER_SCHEMA)
|
|
685
|
+
return undefined;
|
|
686
|
+
if (typeof marker.lastConclusiveAt !== 'string' || Number.isNaN(Date.parse(marker.lastConclusiveAt)))
|
|
687
|
+
return undefined;
|
|
688
|
+
if (!Array.isArray(marker.removed) || marker.removed.some((entry) => typeof entry !== 'string'))
|
|
689
|
+
return undefined;
|
|
690
|
+
if (marker.status === 'clean' || marker.status === 'cleaned') {
|
|
691
|
+
return {
|
|
692
|
+
schema: COOLDOWN_MARKER_SCHEMA,
|
|
693
|
+
lastConclusiveAt: marker.lastConclusiveAt,
|
|
694
|
+
status: marker.status,
|
|
695
|
+
removed: marker.removed,
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
// Negative backoff markers (inconclusive/failed) are only valid with well-formed
|
|
699
|
+
// attempts + nextRetryAt; anything else falls through to the no-marker fail-safe.
|
|
700
|
+
if (marker.status === 'inconclusive' || marker.status === 'failed') {
|
|
701
|
+
if (typeof marker.attempts !== 'number' || !Number.isInteger(marker.attempts) || marker.attempts < 1)
|
|
702
|
+
return undefined;
|
|
703
|
+
if (typeof marker.nextRetryAt !== 'string' || Number.isNaN(Date.parse(marker.nextRetryAt)))
|
|
704
|
+
return undefined;
|
|
705
|
+
return {
|
|
706
|
+
schema: COOLDOWN_MARKER_SCHEMA,
|
|
707
|
+
lastConclusiveAt: marker.lastConclusiveAt,
|
|
708
|
+
status: marker.status,
|
|
709
|
+
removed: marker.removed,
|
|
710
|
+
attempts: marker.attempts,
|
|
711
|
+
nextRetryAt: marker.nextRetryAt,
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
return undefined;
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
return undefined;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
/** Negative-backoff delay for inconclusive/failed sweeps: 1h base, doubling, capped at 24h. */
|
|
721
|
+
function legacyTaskNegativeBackoffMs(attempts) {
|
|
722
|
+
const clamped = Math.max(1, Math.floor(attempts));
|
|
723
|
+
const delay = LEGACY_TASK_NEGATIVE_BACKOFF_BASE_MS * 2 ** Math.min(clamped - 1, 30);
|
|
724
|
+
return Math.min(delay, LEGACY_TASK_NEGATIVE_BACKOFF_MAX_MS);
|
|
725
|
+
}
|
|
726
|
+
function withLegacyOwnerLock(stateDir, lockOptions, operation) {
|
|
727
|
+
const lock = _legacyTaskInternalsForTest.acquireBootstrapOwnerLock(stateDir, lockOptions ?? { maxTries: 300, waitMs: 100 });
|
|
728
|
+
try {
|
|
729
|
+
lock.assertOwned();
|
|
730
|
+
return operation();
|
|
731
|
+
}
|
|
732
|
+
finally {
|
|
733
|
+
lock.release();
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
function writeCooldownMarker(stateDir, status, removed, now) {
|
|
737
|
+
const marker = {
|
|
738
|
+
schema: COOLDOWN_MARKER_SCHEMA,
|
|
739
|
+
lastConclusiveAt: new Date(now()).toISOString(),
|
|
740
|
+
status,
|
|
741
|
+
removed,
|
|
742
|
+
};
|
|
743
|
+
writeLegacyStateText(cooldownMarkerPath(stateDir), `${JSON.stringify(marker)}\n`);
|
|
744
|
+
}
|
|
745
|
+
function writeNegativeCooldownMarker(stateDir, status, attempts, now) {
|
|
746
|
+
const current = now();
|
|
747
|
+
const marker = {
|
|
748
|
+
schema: COOLDOWN_MARKER_SCHEMA,
|
|
749
|
+
lastConclusiveAt: new Date(current).toISOString(),
|
|
750
|
+
status,
|
|
751
|
+
removed: [],
|
|
752
|
+
attempts,
|
|
753
|
+
nextRetryAt: new Date(current + legacyTaskNegativeBackoffMs(attempts)).toISOString(),
|
|
754
|
+
};
|
|
755
|
+
writeLegacyStateText(cooldownMarkerPath(stateDir), `${JSON.stringify(marker)}\n`);
|
|
756
|
+
}
|
|
757
|
+
function writeCooldownMarkerWithOwner(stateDir, status, removed, attempts, now, lockOptions) {
|
|
758
|
+
withLegacyOwnerLock(stateDir, lockOptions, () => {
|
|
759
|
+
if (status === 'clean' || status === 'cleaned')
|
|
760
|
+
writeCooldownMarker(stateDir, status, removed, now);
|
|
761
|
+
else
|
|
762
|
+
writeNegativeCooldownMarker(stateDir, status, attempts ?? 1, now);
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
function clearCooldownMarker(stateDir, assertOwner) {
|
|
766
|
+
assertOwner?.();
|
|
767
|
+
const path = cooldownMarkerPath(stateDir);
|
|
768
|
+
assertLegacyStateArtifactPath(path);
|
|
769
|
+
let identity;
|
|
770
|
+
try {
|
|
771
|
+
identity = readBootstrapArtifactFile(path, MAX_COOLDOWN_MARKER_BYTES, { role: 'owned' }).identity;
|
|
772
|
+
}
|
|
773
|
+
catch (error) {
|
|
774
|
+
if (error?.code === 'ENOENT')
|
|
775
|
+
return;
|
|
776
|
+
throw error;
|
|
777
|
+
}
|
|
778
|
+
const quarantine = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.quarantine`);
|
|
779
|
+
let moved = false;
|
|
780
|
+
const sameIdentity = (left, right) => left.sha256 === right.sha256
|
|
781
|
+
&& left.size === right.size && left.device === right.device && left.inode === right.inode;
|
|
782
|
+
const entryExists = (candidate) => {
|
|
783
|
+
try {
|
|
784
|
+
lstatSync(candidate);
|
|
785
|
+
return true;
|
|
786
|
+
}
|
|
787
|
+
catch (error) {
|
|
788
|
+
if (error?.code === 'ENOENT')
|
|
789
|
+
return false;
|
|
790
|
+
throw error;
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
try {
|
|
794
|
+
const settled = readBootstrapArtifactFile(path, MAX_COOLDOWN_MARKER_BYTES, { role: 'owned' }).identity;
|
|
795
|
+
if (!sameIdentity(settled, identity))
|
|
796
|
+
throw new Error('cooldown marker changed before removal');
|
|
797
|
+
try {
|
|
798
|
+
lstatSync(quarantine);
|
|
799
|
+
throw new Error('cooldown marker quarantine is unexpectedly occupied');
|
|
800
|
+
}
|
|
801
|
+
catch (error) {
|
|
802
|
+
if (error?.code !== 'ENOENT')
|
|
803
|
+
throw error;
|
|
804
|
+
}
|
|
805
|
+
// Move the exact inspected inode out of the canonical name before deleting it. If a
|
|
806
|
+
// concurrent writer publishes a replacement, the canonical path is observed as occupied
|
|
807
|
+
// and the quarantined marker is preserved instead of deleting the replacement.
|
|
808
|
+
assertLegacyStateArtifactPath(path);
|
|
809
|
+
assertLegacyStateArtifactPath(quarantine);
|
|
810
|
+
renameSync(path, quarantine);
|
|
811
|
+
moved = true;
|
|
812
|
+
// The rename is a filesystem boundary: re-check the trusted parent chain on both names
|
|
813
|
+
// before reading or deleting the quarantined inode.
|
|
814
|
+
assertLegacyStateArtifactPath(quarantine);
|
|
815
|
+
assertLegacyStateArtifactPath(path);
|
|
816
|
+
assertOwner?.();
|
|
817
|
+
const movedIdentity = readBootstrapArtifactFile(quarantine, MAX_COOLDOWN_MARKER_BYTES, { role: 'owned' }).identity;
|
|
818
|
+
if (!sameIdentity(movedIdentity, identity))
|
|
819
|
+
throw new Error('cooldown marker changed during quarantine');
|
|
820
|
+
if (entryExists(path))
|
|
821
|
+
throw new Error('cooldown marker was replaced during quarantine');
|
|
822
|
+
const beforeDelete = readBootstrapArtifactFile(quarantine, MAX_COOLDOWN_MARKER_BYTES, { role: 'owned' }).identity;
|
|
823
|
+
if (!sameIdentity(beforeDelete, identity))
|
|
824
|
+
throw new Error('cooldown marker changed before quarantine removal');
|
|
825
|
+
removeDurableFile(quarantine);
|
|
826
|
+
assertOwner?.();
|
|
827
|
+
}
|
|
828
|
+
catch (error) {
|
|
829
|
+
if (moved) {
|
|
830
|
+
// Restore the moved inode only while the canonical path is absent; otherwise leave both
|
|
831
|
+
// generations for operator inspection rather than overwriting a newer marker.
|
|
832
|
+
try {
|
|
833
|
+
// The rename itself may have moved a newer or foreign generation if it won the race
|
|
834
|
+
// with our settled read. Preserve whichever inode was moved; never silently drop it.
|
|
835
|
+
if (!entryExists(path) && entryExists(quarantine))
|
|
836
|
+
renameSync(quarantine, path);
|
|
837
|
+
}
|
|
838
|
+
catch {
|
|
839
|
+
// The quarantine remains durable and will not be mistaken for the canonical marker.
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
throw error;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
function persistPreimage(stateDir, name, xml, now) {
|
|
846
|
+
const stamp = new Date(now()).toISOString().replaceAll(':', '').replaceAll('-', '');
|
|
847
|
+
// The clock is not an ownership primitive: two cleanup processes can observe the same
|
|
848
|
+
// millisecond, and wall clocks can move backwards. Keep the operator-readable timestamp but
|
|
849
|
+
// add a cryptographic nonce so a new preimage can never replace an older receipt by name.
|
|
850
|
+
const nonce = randomUUID().replaceAll('-', '');
|
|
851
|
+
const path = join(preimageDirFor(stateDir), `${name}.${stamp}.${nonce}.xml`);
|
|
852
|
+
writeLegacyStateText(path, xml.endsWith('\n') ? xml : `${xml}\n`);
|
|
853
|
+
return basename(path);
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* The full safe cleanup. NEVER throws: every failure surface maps onto an honest
|
|
857
|
+
* `inconclusive` / `failed` status. Non-Windows platforms are reported as `skipped` — an
|
|
858
|
+
* unprobed host is never reported clean. The `EVOLVER_SKIP_LEGACY_TASK_PROBE` opt-out is
|
|
859
|
+
* honored by the AUTOMATIC entry points (session-start sweep, bootstrap sweep, doctor
|
|
860
|
+
* probe); this function implements the explicit operator/transaction path and always
|
|
861
|
+
* probes, so an explicit `evolver lifecycle cleanup-legacy-tasks` can never be silently
|
|
862
|
+
* disabled out from under the operator.
|
|
863
|
+
*/
|
|
864
|
+
function cleanupLegacyWindowsDaemonTasksInternal(options) {
|
|
865
|
+
const platform = options.platform ?? process.platform;
|
|
866
|
+
const dryRun = options.dryRun === true;
|
|
867
|
+
if (platform !== 'win32') {
|
|
868
|
+
return { status: 'skipped', dryRun, tasks: [], detail: 'not a Windows host' };
|
|
869
|
+
}
|
|
870
|
+
const stateDir = options.stateDir ?? lifecyclePaths(options.env).stateDir;
|
|
871
|
+
const run = options.run ?? defaultLegacyTaskRun();
|
|
872
|
+
const now = options.now ?? Date.now;
|
|
873
|
+
let trackedEntries = [];
|
|
874
|
+
const removedNames = [];
|
|
875
|
+
let powershell;
|
|
876
|
+
try {
|
|
877
|
+
powershell = trustedWindowsPowerShell();
|
|
878
|
+
}
|
|
879
|
+
catch (error) {
|
|
880
|
+
return { status: 'inconclusive', dryRun, tasks: [], detail: boundedDetail(error) };
|
|
881
|
+
}
|
|
882
|
+
try {
|
|
883
|
+
const provenance = loadLegacyTaskProvenance(stateDir, options.env, now());
|
|
884
|
+
if (provenance.detail) {
|
|
885
|
+
return { status: 'inconclusive', dryRun, tasks: [], detail: provenance.detail };
|
|
886
|
+
}
|
|
887
|
+
const probed = runProbe(run, powershell);
|
|
888
|
+
if ('detail' in probed) {
|
|
889
|
+
return { status: 'inconclusive', dryRun, tasks: [], detail: probed.detail };
|
|
890
|
+
}
|
|
891
|
+
const entries = LEGACY_WINDOWS_TASK_NAMES.map((name) => {
|
|
892
|
+
const record = probed.records.find((candidate) => candidate && candidate.name === name);
|
|
893
|
+
const { classification, reason } = classifyProbedTask(record, provenance.receipts.get(name));
|
|
894
|
+
return { name, classification, ...(reason ? { reason } : {}) };
|
|
895
|
+
});
|
|
896
|
+
trackedEntries = entries;
|
|
897
|
+
// A record for a known name that the probe never returned, or any other response-shape
|
|
898
|
+
// drift, is a protocol break, not a negative result.
|
|
899
|
+
const coverageIssue = probeCoverageIssue(probed.records);
|
|
900
|
+
if (coverageIssue)
|
|
901
|
+
return { status: 'inconclusive', dryRun, tasks: entries, detail: coverageIssue };
|
|
902
|
+
if (entries.some((entry) => entry.classification === 'ambiguous')) {
|
|
903
|
+
return { status: 'inconclusive', dryRun, tasks: entries, detail: 'ambiguous task shape; refusing to mutate' };
|
|
904
|
+
}
|
|
905
|
+
const expectedDefinitionHashes = new Map();
|
|
906
|
+
for (const record of probed.records) {
|
|
907
|
+
if (record && typeof record.name === 'string' && typeof record.definitionHash === 'string') {
|
|
908
|
+
expectedDefinitionHashes.set(record.name, record.definitionHash);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
const expectedProvenanceReceipts = new Map();
|
|
912
|
+
for (const entry of entries) {
|
|
913
|
+
const receipt = provenance.receipts.get(entry.name);
|
|
914
|
+
if (receipt)
|
|
915
|
+
expectedProvenanceReceipts.set(entry.name, receipt);
|
|
916
|
+
}
|
|
917
|
+
const legacy = entries.filter((entry) => entry.classification === 'legacy');
|
|
918
|
+
if (legacy.length === 0) {
|
|
919
|
+
if (!dryRun) {
|
|
920
|
+
try {
|
|
921
|
+
if (options.assertOwner) {
|
|
922
|
+
options.assertOwner();
|
|
923
|
+
writeCooldownMarker(stateDir, 'clean', [], now);
|
|
924
|
+
}
|
|
925
|
+
else {
|
|
926
|
+
writeCooldownMarkerWithOwner(stateDir, 'clean', [], undefined, now, options.lock);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
catch {
|
|
930
|
+
// The cooldown marker is throttle state only; its loss merely retries sooner.
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
return { status: 'clean', dryRun, tasks: entries };
|
|
934
|
+
}
|
|
935
|
+
if (dryRun) {
|
|
936
|
+
return { status: 'legacy_detected', dryRun, tasks: entries };
|
|
937
|
+
}
|
|
938
|
+
return cleanupClassifiedLegacyTasks(options, powershell, entries, legacy, expectedDefinitionHashes, expectedProvenanceReceipts);
|
|
939
|
+
}
|
|
940
|
+
catch (error) {
|
|
941
|
+
const detail = boundedDetail(error);
|
|
942
|
+
const status = detail.startsWith('bootstrap owner lock unavailable')
|
|
943
|
+
? 'inconclusive'
|
|
944
|
+
: 'failed';
|
|
945
|
+
const partialPrefix = removedNames.length > 0
|
|
946
|
+
? `partial cleanup removed ${removedNames.join(', ')}; `
|
|
947
|
+
: '';
|
|
948
|
+
return { status, dryRun, tasks: trackedEntries, detail: `${partialPrefix}${detail}` };
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Manual cleanup owns the lifecycle lock before it probes. Without this outer lock a clean
|
|
953
|
+
* probe could race a concurrent bootstrap that registers a legacy-named task and then publish
|
|
954
|
+
* a positive cooldown marker, suppressing the next real sweep for 24 hours. Automatic callers
|
|
955
|
+
* already hold the same lock and pass `assertOwner`, while dry-run remains read-only.
|
|
956
|
+
*/
|
|
957
|
+
export function cleanupLegacyWindowsDaemonTasks(options) {
|
|
958
|
+
const platform = options.platform ?? process.platform;
|
|
959
|
+
const dryRun = options.dryRun === true;
|
|
960
|
+
if (platform !== 'win32' || dryRun || options.assertOwner) {
|
|
961
|
+
return cleanupLegacyWindowsDaemonTasksInternal(options);
|
|
962
|
+
}
|
|
963
|
+
const stateDir = options.stateDir ?? lifecyclePaths(options.env).stateDir;
|
|
964
|
+
let lock;
|
|
965
|
+
try {
|
|
966
|
+
try {
|
|
967
|
+
lock = _legacyTaskInternalsForTest.acquireBootstrapOwnerLock(stateDir, options.lock ?? { maxTries: 300, waitMs: 100 });
|
|
968
|
+
}
|
|
969
|
+
catch (error) {
|
|
970
|
+
// An owner lock that cannot be acquired is an authority failure, not evidence that
|
|
971
|
+
// the task set is broken. Report it as inconclusive so the manual path never turns
|
|
972
|
+
// an unavailable or untrusted state directory into a misleading hard failure.
|
|
973
|
+
return {
|
|
974
|
+
status: 'inconclusive',
|
|
975
|
+
dryRun,
|
|
976
|
+
tasks: [],
|
|
977
|
+
detail: `bootstrap owner lock unavailable: ${boundedDetail(error)}`,
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
lock.assertOwned();
|
|
981
|
+
const result = cleanupLegacyWindowsDaemonTasksInternal({
|
|
982
|
+
...options,
|
|
983
|
+
assertOwner: lock.assertOwned,
|
|
984
|
+
});
|
|
985
|
+
try {
|
|
986
|
+
lock.release();
|
|
987
|
+
}
|
|
988
|
+
catch (releaseError) {
|
|
989
|
+
if (result.status === 'cleaned' || result.status === 'clean') {
|
|
990
|
+
result.detail = `owner lock release failed: ${boundedDetail(releaseError)}`;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
lock = undefined;
|
|
994
|
+
return result;
|
|
995
|
+
}
|
|
996
|
+
catch (error) {
|
|
997
|
+
if (lock) {
|
|
998
|
+
try {
|
|
999
|
+
lock.release();
|
|
1000
|
+
}
|
|
1001
|
+
catch { /* preserve the primary bounded outcome */ }
|
|
1002
|
+
}
|
|
1003
|
+
const detail = boundedDetail(error);
|
|
1004
|
+
return {
|
|
1005
|
+
status: detail.startsWith('bootstrap owner lock unavailable') ? 'inconclusive' : 'failed',
|
|
1006
|
+
dryRun,
|
|
1007
|
+
tasks: [],
|
|
1008
|
+
detail,
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
/** Read-only probe for `evolver doctor` — never mutates, never throws. */
|
|
1013
|
+
export function probeLegacyWindowsDaemonTasks(options) {
|
|
1014
|
+
const platform = options.platform ?? process.platform;
|
|
1015
|
+
if (platform !== 'win32') {
|
|
1016
|
+
return { conclusive: false, legacy: [], detail: 'not a Windows host' };
|
|
1017
|
+
}
|
|
1018
|
+
if (legacyTaskProbeSkipped(options.env)) {
|
|
1019
|
+
return { conclusive: false, legacy: [], detail: `${LEGACY_TASK_SKIP_ENV} is set` };
|
|
1020
|
+
}
|
|
1021
|
+
let powershell;
|
|
1022
|
+
try {
|
|
1023
|
+
powershell = trustedWindowsPowerShell();
|
|
1024
|
+
}
|
|
1025
|
+
catch (error) {
|
|
1026
|
+
return { conclusive: false, legacy: [], detail: boundedDetail(error) };
|
|
1027
|
+
}
|
|
1028
|
+
const run = options.run ?? defaultLegacyTaskRun();
|
|
1029
|
+
try {
|
|
1030
|
+
const stateDir = options.stateDir ?? lifecyclePaths(options.env).stateDir;
|
|
1031
|
+
const provenance = loadLegacyTaskProvenance(stateDir, options.env, Date.now());
|
|
1032
|
+
if (provenance.detail)
|
|
1033
|
+
return { conclusive: false, legacy: [], detail: provenance.detail };
|
|
1034
|
+
const probed = runProbe(run, powershell);
|
|
1035
|
+
if ('detail' in probed) {
|
|
1036
|
+
return { conclusive: false, legacy: [], detail: probed.detail };
|
|
1037
|
+
}
|
|
1038
|
+
const coverageIssue = probeCoverageIssue(probed.records);
|
|
1039
|
+
if (coverageIssue)
|
|
1040
|
+
return { conclusive: false, legacy: [], detail: coverageIssue };
|
|
1041
|
+
const legacy = [];
|
|
1042
|
+
for (const name of LEGACY_WINDOWS_TASK_NAMES) {
|
|
1043
|
+
const record = probed.records.find((candidate) => candidate && candidate.name === name);
|
|
1044
|
+
const { classification } = classifyProbedTask(record, provenance.receipts.get(name));
|
|
1045
|
+
if (classification === 'ambiguous') {
|
|
1046
|
+
return { conclusive: false, legacy: [], detail: `ambiguous shape for ${name}` };
|
|
1047
|
+
}
|
|
1048
|
+
if (classification === 'legacy')
|
|
1049
|
+
legacy.push(name);
|
|
1050
|
+
}
|
|
1051
|
+
return { conclusive: true, legacy, detail: legacy.length > 0 ? `detected ${legacy.length} legacy v1 task(s)` : 'no legacy v1-style scheduled tasks registered' };
|
|
1052
|
+
}
|
|
1053
|
+
catch (error) {
|
|
1054
|
+
return { conclusive: false, legacy: [], detail: boundedDetail(error) };
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
/**
|
|
1058
|
+
* Automatic entry point (SessionStart hook). Throttled by the cooldown marker: after a
|
|
1059
|
+
* conclusive success the sweep skips re-probing for the cooldown window; an
|
|
1060
|
+
* inconclusive/failed run writes a NEGATIVE backoff marker (1h base, doubling per
|
|
1061
|
+
* consecutive failure, capped at 24h) and the sweep skips until `nextRetryAt`, so a
|
|
1062
|
+
* constrained host does not spawn PowerShell on every session. A conclusive success
|
|
1063
|
+
* overwrites the marker, resetting the backoff counter. Never throws.
|
|
1064
|
+
*/
|
|
1065
|
+
export function maybeCleanupLegacyWindowsDaemonTasks(options) {
|
|
1066
|
+
const platform = options.platform ?? process.platform;
|
|
1067
|
+
if (platform !== 'win32')
|
|
1068
|
+
return undefined;
|
|
1069
|
+
if (legacyTaskProbeSkipped(options.env))
|
|
1070
|
+
return undefined;
|
|
1071
|
+
const stateDir = options.stateDir ?? lifecyclePaths(options.env).stateDir;
|
|
1072
|
+
const now = options.now ?? Date.now;
|
|
1073
|
+
const cooldownMs = options.cooldownMs ?? LEGACY_TASK_COOLDOWN_MS;
|
|
1074
|
+
let ownerLock;
|
|
1075
|
+
let result;
|
|
1076
|
+
try {
|
|
1077
|
+
// Keep the owner lock across marker read, probe/mutation, and marker publication. This
|
|
1078
|
+
// prevents a stale negative result from overwriting a newer conclusive marker produced by
|
|
1079
|
+
// a concurrent SessionStart/bootstrap process.
|
|
1080
|
+
ownerLock = _legacyTaskInternalsForTest.acquireBootstrapOwnerLock(stateDir, options.lock ?? { maxTries: 30, waitMs: 100 });
|
|
1081
|
+
ownerLock.assertOwned();
|
|
1082
|
+
const marker = readCooldownMarker(stateDir);
|
|
1083
|
+
if (marker) {
|
|
1084
|
+
if (marker.status === 'inconclusive' || marker.status === 'failed') {
|
|
1085
|
+
const retryAt = Date.parse(marker.nextRetryAt ?? '');
|
|
1086
|
+
if (Number.isFinite(retryAt) && now() < retryAt)
|
|
1087
|
+
return undefined;
|
|
1088
|
+
}
|
|
1089
|
+
else {
|
|
1090
|
+
const age = now() - Date.parse(marker.lastConclusiveAt);
|
|
1091
|
+
if (Number.isFinite(age) && age >= 0 && age < cooldownMs)
|
|
1092
|
+
return undefined;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
result = cleanupLegacyWindowsDaemonTasks({
|
|
1096
|
+
env: options.env,
|
|
1097
|
+
stateDir,
|
|
1098
|
+
platform,
|
|
1099
|
+
run: options.run,
|
|
1100
|
+
now,
|
|
1101
|
+
assertOwner: ownerLock.assertOwned,
|
|
1102
|
+
});
|
|
1103
|
+
ownerLock.assertOwned();
|
|
1104
|
+
if (result.status === 'inconclusive' || result.status === 'failed') {
|
|
1105
|
+
try {
|
|
1106
|
+
const previousAttempts = marker && (marker.status === 'inconclusive' || marker.status === 'failed')
|
|
1107
|
+
? marker.attempts ?? 0
|
|
1108
|
+
: 0;
|
|
1109
|
+
writeNegativeCooldownMarker(stateDir, result.status, previousAttempts + 1, now);
|
|
1110
|
+
}
|
|
1111
|
+
catch {
|
|
1112
|
+
// The cooldown marker is throttle state only; its loss merely retries sooner.
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return result;
|
|
1116
|
+
}
|
|
1117
|
+
catch (error) {
|
|
1118
|
+
result = {
|
|
1119
|
+
status: 'inconclusive',
|
|
1120
|
+
dryRun: false,
|
|
1121
|
+
tasks: [],
|
|
1122
|
+
detail: boundedDetail(error),
|
|
1123
|
+
};
|
|
1124
|
+
return result;
|
|
1125
|
+
}
|
|
1126
|
+
finally {
|
|
1127
|
+
if (ownerLock) {
|
|
1128
|
+
try {
|
|
1129
|
+
ownerLock.release();
|
|
1130
|
+
}
|
|
1131
|
+
catch (releaseError) {
|
|
1132
|
+
if (result) {
|
|
1133
|
+
result.detail = `${result.detail ? `${result.detail}; ` : ''}owner lock release failed: ${boundedDetail(releaseError)}`;
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Post-bootstrap sweep seam: runs under the already-held bootstrap owner lock and returns
|
|
1141
|
+
* report lines for the bootstrap `actions`. Never throws and never fails the bootstrap —
|
|
1142
|
+
* but a failed/inconclusive sweep is reported honestly instead of being dropped.
|
|
1143
|
+
*/
|
|
1144
|
+
export function sweepLegacyWindowsDaemonTasksAfterBootstrap(options) {
|
|
1145
|
+
try {
|
|
1146
|
+
if (legacyTaskProbeSkipped(options.env))
|
|
1147
|
+
return [];
|
|
1148
|
+
const result = cleanupLegacyWindowsDaemonTasks({
|
|
1149
|
+
env: options.env,
|
|
1150
|
+
stateDir: options.stateDir,
|
|
1151
|
+
assertOwner: options.assertOwner,
|
|
1152
|
+
...(options.platform ? { platform: options.platform } : {}),
|
|
1153
|
+
...(options.run ? { run: options.run } : {}),
|
|
1154
|
+
});
|
|
1155
|
+
if (result.status === 'cleaned') {
|
|
1156
|
+
const names = result.tasks.filter((task) => task.outcome === 'removed').map((task) => task.name);
|
|
1157
|
+
return [`removed legacy v1 scheduled-task residue: ${names.join(', ')} (durable preimage saved under the lifecycle state dir)`];
|
|
1158
|
+
}
|
|
1159
|
+
if (result.status === 'failed' || result.status === 'inconclusive') {
|
|
1160
|
+
return [`legacy v1 scheduled-task cleanup ${result.status}${result.detail ? `: ${result.detail}` : ''}; run evolver lifecycle cleanup-legacy-tasks manually`];
|
|
1161
|
+
}
|
|
1162
|
+
return [];
|
|
1163
|
+
}
|
|
1164
|
+
catch (error) {
|
|
1165
|
+
return [`legacy v1 scheduled-task cleanup inconclusive: ${boundedDetail(error)}; run evolver lifecycle cleanup-legacy-tasks manually`];
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Manual restore of a persisted preimage. Only files named `<KnownTaskName>.<stamp>.xml`
|
|
1170
|
+
* are accepted, the target name must be currently ABSENT (restore never overwrites), and
|
|
1171
|
+
* the XML is validated before it reaches PowerShell. Never throws.
|
|
1172
|
+
*/
|
|
1173
|
+
export function restoreLegacyTaskPreimage(preimagePath, options) {
|
|
1174
|
+
const platform = options.platform ?? process.platform;
|
|
1175
|
+
if (platform !== 'win32')
|
|
1176
|
+
return { status: 'failed', detail: 'not a Windows host' };
|
|
1177
|
+
let outcome;
|
|
1178
|
+
let ownerLock;
|
|
1179
|
+
try {
|
|
1180
|
+
const stateDir = options.stateDir ?? lifecyclePaths(options.env).stateDir;
|
|
1181
|
+
const preimageRoot = resolvePath(preimageDirFor(stateDir));
|
|
1182
|
+
const requestedPath = isAbsolute(preimagePath)
|
|
1183
|
+
? resolvePath(preimagePath)
|
|
1184
|
+
: resolvePath(preimageRoot, preimagePath);
|
|
1185
|
+
const requestedRelative = relative(preimageRoot, requestedPath);
|
|
1186
|
+
const sameDirectory = dirname(requestedPath).toLowerCase() === preimageRoot.toLowerCase();
|
|
1187
|
+
if (!requestedRelative || requestedRelative.startsWith('..') || isAbsolute(requestedRelative) || !sameDirectory) {
|
|
1188
|
+
return { status: 'failed', detail: 'preimage must be a direct file in the lifecycle preimage directory' };
|
|
1189
|
+
}
|
|
1190
|
+
assertLegacyStateArtifactPath(requestedPath);
|
|
1191
|
+
const base = basename(requestedPath);
|
|
1192
|
+
const name = LEGACY_WINDOWS_TASK_NAMES.find((candidate) => base.startsWith(`${candidate}.`) && base.endsWith('.xml'));
|
|
1193
|
+
if (!name) {
|
|
1194
|
+
return { status: 'failed', detail: 'preimage file name does not encode a known task name' };
|
|
1195
|
+
}
|
|
1196
|
+
const stampPattern = new RegExp(`^${name}\\.\\d{8}T\\d{6}(?:\\.\\d{3}|\\d{3})Z(?:\\.[a-f0-9]{32})?\\.xml$`);
|
|
1197
|
+
if (!stampPattern.test(base)) {
|
|
1198
|
+
return { status: 'failed', detail: 'preimage file name does not encode a valid lifecycle timestamp' };
|
|
1199
|
+
}
|
|
1200
|
+
ownerLock = _legacyTaskInternalsForTest.acquireBootstrapOwnerLock(stateDir, options.lock);
|
|
1201
|
+
ownerLock.assertOwned();
|
|
1202
|
+
const receipt = readBootstrapArtifactFile(requestedPath, MAX_PREIMAGE_BYTES, { role: 'owned' });
|
|
1203
|
+
if (receipt.bytes.length === 0) {
|
|
1204
|
+
return { status: 'failed', detail: 'preimage file is empty' };
|
|
1205
|
+
}
|
|
1206
|
+
const xml = receipt.bytes.toString('utf8');
|
|
1207
|
+
if (!/^\s*<\?xml/.test(xml) || !/<Task\b/.test(xml) || !/<Actions\b/.test(xml)
|
|
1208
|
+
|| /<!DOCTYPE|<!ENTITY/i.test(xml)) {
|
|
1209
|
+
return { status: 'failed', detail: 'preimage is not a scheduled-task XML definition' };
|
|
1210
|
+
}
|
|
1211
|
+
if (xml.split('\n').some((line) => line.startsWith("'@"))) {
|
|
1212
|
+
return { status: 'failed', detail: 'preimage content failed embedding validation' };
|
|
1213
|
+
}
|
|
1214
|
+
const powershell = trustedWindowsPowerShell();
|
|
1215
|
+
const run = options.run ?? defaultLegacyTaskRun();
|
|
1216
|
+
const result = run(powershell, powershellArgs(renderRestoreScript(name, requestedPath, receipt.identity.sha256)), MUTATION_TIMEOUT_MS);
|
|
1217
|
+
// The scheduler script performs the absent-check, registration, and verification while
|
|
1218
|
+
// the owner lock is held. Reassert after it returns so a lost lock cannot be reported as
|
|
1219
|
+
// a successful restore.
|
|
1220
|
+
ownerLock.assertOwned();
|
|
1221
|
+
if (result.status === 0 && !result.error) {
|
|
1222
|
+
try {
|
|
1223
|
+
const settled = readBootstrapArtifactFile(requestedPath, MAX_PREIMAGE_BYTES, { role: 'owned' });
|
|
1224
|
+
if (settled.identity.sha256 !== receipt.identity.sha256
|
|
1225
|
+
|| settled.identity.size !== receipt.identity.size
|
|
1226
|
+
|| settled.identity.device !== receipt.identity.device
|
|
1227
|
+
|| settled.identity.inode !== receipt.identity.inode) {
|
|
1228
|
+
outcome = { status: 'failed', task: name, detail: 'preimage changed during restore; registration outcome is uncertain' };
|
|
1229
|
+
return outcome;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
catch (error) {
|
|
1233
|
+
outcome = { status: 'failed', task: name, detail: `preimage changed during restore: ${boundedDetail(error)}` };
|
|
1234
|
+
return outcome;
|
|
1235
|
+
}
|
|
1236
|
+
try {
|
|
1237
|
+
clearCooldownMarker(stateDir, ownerLock.assertOwned);
|
|
1238
|
+
}
|
|
1239
|
+
catch (error) {
|
|
1240
|
+
outcome = {
|
|
1241
|
+
status: 'restored',
|
|
1242
|
+
task: name,
|
|
1243
|
+
detail: `preimage re-registered and verified; cooldown marker cleanup failed: ${boundedDetail(error)}`,
|
|
1244
|
+
};
|
|
1245
|
+
return outcome;
|
|
1246
|
+
}
|
|
1247
|
+
outcome = { status: 'restored', task: name, detail: 'preimage re-registered and verified' };
|
|
1248
|
+
return outcome;
|
|
1249
|
+
}
|
|
1250
|
+
const detail = result.status === 3
|
|
1251
|
+
? 'task name is already present; restore never overwrites (remove it first)'
|
|
1252
|
+
: result.status === 4
|
|
1253
|
+
? 'registration could not be verified; guarded rollback completed'
|
|
1254
|
+
: result.status === 5
|
|
1255
|
+
? 'preimage changed while restoring; registration was refused'
|
|
1256
|
+
: result.status === 11
|
|
1257
|
+
? 'registration verification was uncertain; task was left for operator inspection'
|
|
1258
|
+
: result.error
|
|
1259
|
+
? boundedDetail(result.error)
|
|
1260
|
+
: `restore exited with status ${result.status ?? 'timeout'}`;
|
|
1261
|
+
outcome = { status: 'failed', task: name, detail };
|
|
1262
|
+
return outcome;
|
|
1263
|
+
}
|
|
1264
|
+
catch (error) {
|
|
1265
|
+
outcome = { status: 'failed', detail: boundedDetail(error) };
|
|
1266
|
+
return outcome;
|
|
1267
|
+
}
|
|
1268
|
+
finally {
|
|
1269
|
+
if (ownerLock) {
|
|
1270
|
+
try {
|
|
1271
|
+
ownerLock.release();
|
|
1272
|
+
}
|
|
1273
|
+
catch (releaseError) {
|
|
1274
|
+
// A successful registration remains durable even when cleanup of the lock handle
|
|
1275
|
+
// reports an ownership change; preserve the success but surface the bounded warning.
|
|
1276
|
+
if (outcome?.status === 'restored')
|
|
1277
|
+
outcome.detail = `owner lock release failed: ${boundedDetail(releaseError)}`;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
export const _legacyTaskInternalsForTest = {
|
|
1283
|
+
PROBE_SCRIPT,
|
|
1284
|
+
acquireBootstrapOwnerLock,
|
|
1285
|
+
defaultLegacyTaskRun,
|
|
1286
|
+
canonicalLegacyTaskProvenanceBytes,
|
|
1287
|
+
parseLegacyTaskProvenanceReceipt,
|
|
1288
|
+
loadLegacyTaskProvenance,
|
|
1289
|
+
renderExportScript,
|
|
1290
|
+
renderMutationScript,
|
|
1291
|
+
renderRestoreScript,
|
|
1292
|
+
parseProbeRecords,
|
|
1293
|
+
readCooldownMarker,
|
|
1294
|
+
writeCooldownMarker,
|
|
1295
|
+
writeNegativeCooldownMarker,
|
|
1296
|
+
negativeBackoffMs: legacyTaskNegativeBackoffMs,
|
|
1297
|
+
cooldownMarkerPath,
|
|
1298
|
+
preimageDirFor,
|
|
1299
|
+
cleanupClassifiedLegacyTasksForTest,
|
|
1300
|
+
};
|
|
1301
|
+
/**
|
|
1302
|
+
* Mutation mechanics for entries that have already passed the production classifier.
|
|
1303
|
+
*
|
|
1304
|
+
* 公开清理路径只有在可信 provenance classifier 至少返回一个 `legacy` 条目后才会进入这里。
|
|
1305
|
+
* 缺少有效签名 receipt 时,所有完整 direct-action shape 都会保持 `ambiguous`。下方测试专用
|
|
1306
|
+
* wrapper 仅接收预分类合成条目,以覆盖 preimage/revalidation 的失败机制;它不是
|
|
1307
|
+
* provenance/configuration 绕过,也不属于 package API。
|
|
1308
|
+
*/
|
|
1309
|
+
function cleanupClassifiedLegacyTasks(options, powershell, entries, legacy, expectedDefinitionHashes, expectedProvenanceReceipts = new Map()) {
|
|
1310
|
+
const dryRun = options.dryRun === true;
|
|
1311
|
+
const stateDir = options.stateDir ?? lifecyclePaths(options.env).stateDir;
|
|
1312
|
+
const run = options.run ?? defaultLegacyTaskRun();
|
|
1313
|
+
const now = options.now ?? Date.now;
|
|
1314
|
+
const removedNames = [];
|
|
1315
|
+
const trackedEntries = entries;
|
|
1316
|
+
if (legacy.some((entry) => entry.classification !== 'legacy')) {
|
|
1317
|
+
throw new Error('mutation helper requires preclassified legacy entries');
|
|
1318
|
+
}
|
|
1319
|
+
try {
|
|
1320
|
+
// Mutation phase: under lifecycle owner authority, preimage first, then unregister with
|
|
1321
|
+
// final revalidation. Lock contention means authority could not be proven; nothing is
|
|
1322
|
+
// mutated and the run reports inconclusive (never clean).
|
|
1323
|
+
const lock = options.assertOwner
|
|
1324
|
+
? undefined
|
|
1325
|
+
: (() => {
|
|
1326
|
+
try {
|
|
1327
|
+
return _legacyTaskInternalsForTest.acquireBootstrapOwnerLock(stateDir, options.lock ?? { maxTries: 300, waitMs: 100 });
|
|
1328
|
+
}
|
|
1329
|
+
catch (error) {
|
|
1330
|
+
throw new Error(`bootstrap owner lock unavailable: ${boundedDetail(error)}`);
|
|
1331
|
+
}
|
|
1332
|
+
})();
|
|
1333
|
+
const assertOwner = options.assertOwner ?? lock.assertOwned;
|
|
1334
|
+
// The computed outcome is returned by reference, so the release below can annotate a
|
|
1335
|
+
// conclusive success without ever replacing it.
|
|
1336
|
+
let computed;
|
|
1337
|
+
try {
|
|
1338
|
+
assertOwner();
|
|
1339
|
+
const removed = removedNames;
|
|
1340
|
+
let drifted = false;
|
|
1341
|
+
let failed = false;
|
|
1342
|
+
let failDetail;
|
|
1343
|
+
for (const entry of legacy) {
|
|
1344
|
+
const name = entry.name;
|
|
1345
|
+
const expectedDefinitionHash = expectedDefinitionHashes.get(name);
|
|
1346
|
+
const provenanceReceipt = expectedProvenanceReceipts.get(name);
|
|
1347
|
+
if (provenanceReceipt !== undefined
|
|
1348
|
+
&& (expectedDefinitionHash === undefined
|
|
1349
|
+
|| normalizeDefinitionHash(expectedDefinitionHash) !== normalizeDefinitionHash(provenanceReceipt.definitionHash))) {
|
|
1350
|
+
drifted = true;
|
|
1351
|
+
entry.outcome = 'removal-aborted';
|
|
1352
|
+
entry.reason = 'signed V1 provenance is not bound to the observed definition hash';
|
|
1353
|
+
continue;
|
|
1354
|
+
}
|
|
1355
|
+
const exported = run(powershell, powershellArgs(renderExportScript(name, expectedDefinitionHash, provenanceReceipt)), EXPORT_TIMEOUT_MS);
|
|
1356
|
+
if (exported.error || exported.status !== 0 || typeof exported.stdout !== 'string' || !exported.stdout.trim()) {
|
|
1357
|
+
if (exported.status === 3 || exported.status === 4 || exported.status === 5 || exported.status === 10) {
|
|
1358
|
+
drifted = true;
|
|
1359
|
+
entry.outcome = 'removal-aborted';
|
|
1360
|
+
entry.reason = exported.status === 5
|
|
1361
|
+
? 'fingerprint/provenance guard refused preimage capture'
|
|
1362
|
+
: 'fingerprint drifted before preimage capture';
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
failed = true;
|
|
1366
|
+
entry.outcome = 'removal-failed';
|
|
1367
|
+
failDetail ??= exported.error
|
|
1368
|
+
? boundedDetail(exported.error)
|
|
1369
|
+
: `preimage capture exited with status ${exported.status ?? 'timeout'}`;
|
|
1370
|
+
continue;
|
|
1371
|
+
}
|
|
1372
|
+
const xml = exported.stdout.trim();
|
|
1373
|
+
if (Buffer.byteLength(xml, 'utf8') > MAX_PREIMAGE_BYTES || xml.split('\n').some((line) => line.startsWith("'@"))) {
|
|
1374
|
+
failed = true;
|
|
1375
|
+
entry.outcome = 'removal-failed';
|
|
1376
|
+
failDetail ??= 'preimage content failed durability validation';
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
let preimage;
|
|
1380
|
+
try {
|
|
1381
|
+
preimage = persistPreimage(stateDir, name, xml, now);
|
|
1382
|
+
}
|
|
1383
|
+
catch (error) {
|
|
1384
|
+
failed = true;
|
|
1385
|
+
entry.outcome = 'removal-failed';
|
|
1386
|
+
failDetail ??= `preimage persistence failed: ${boundedDetail(error)}`;
|
|
1387
|
+
continue;
|
|
1388
|
+
}
|
|
1389
|
+
assertOwner();
|
|
1390
|
+
const mutation = run(powershell, powershellArgs(renderMutationScript(name, expectedDefinitionHash, provenanceReceipt)), MUTATION_TIMEOUT_MS);
|
|
1391
|
+
if (mutation.status === 0 && !mutation.error) {
|
|
1392
|
+
entry.outcome = 'removed';
|
|
1393
|
+
entry.preimage = preimage;
|
|
1394
|
+
removed.push(name);
|
|
1395
|
+
continue;
|
|
1396
|
+
}
|
|
1397
|
+
if (mutation.status === 3 || mutation.status === 4 || mutation.status === 5 || mutation.status === 6 || mutation.status === 10) {
|
|
1398
|
+
drifted = true;
|
|
1399
|
+
entry.outcome = 'removal-aborted';
|
|
1400
|
+
entry.reason = mutation.status === 5
|
|
1401
|
+
? 'fingerprint/provenance guard refused unregister'
|
|
1402
|
+
: 'fingerprint drifted before unregister';
|
|
1403
|
+
continue;
|
|
1404
|
+
}
|
|
1405
|
+
failed = true;
|
|
1406
|
+
entry.outcome = 'removal-failed';
|
|
1407
|
+
failDetail ??= mutation.status === 7
|
|
1408
|
+
? 'task did not stop within the budget'
|
|
1409
|
+
: mutation.status === 8
|
|
1410
|
+
? 'task still present after unregister'
|
|
1411
|
+
: mutation.error
|
|
1412
|
+
? boundedDetail(mutation.error)
|
|
1413
|
+
: `unregister exited with status ${mutation.status ?? 'timeout'}`;
|
|
1414
|
+
}
|
|
1415
|
+
assertOwner();
|
|
1416
|
+
const status = failed ? 'failed' : drifted ? 'inconclusive' : 'cleaned';
|
|
1417
|
+
const partialPrefix = removed.length > 0 ? `partial cleanup removed ${removed.join(', ')}; ` : '';
|
|
1418
|
+
const result = {
|
|
1419
|
+
status,
|
|
1420
|
+
dryRun,
|
|
1421
|
+
tasks: entries,
|
|
1422
|
+
...(failDetail
|
|
1423
|
+
? { detail: `${partialPrefix}${failDetail}` }
|
|
1424
|
+
: drifted
|
|
1425
|
+
? { detail: `${partialPrefix}task shape drifted during cleanup; residue left untouched` }
|
|
1426
|
+
: {}),
|
|
1427
|
+
};
|
|
1428
|
+
if (status === 'cleaned') {
|
|
1429
|
+
try {
|
|
1430
|
+
assertOwner();
|
|
1431
|
+
writeCooldownMarker(stateDir, status, removed, now);
|
|
1432
|
+
}
|
|
1433
|
+
catch {
|
|
1434
|
+
// The cooldown marker is throttle state only; its loss merely retries sooner.
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
computed = result;
|
|
1438
|
+
return result;
|
|
1439
|
+
}
|
|
1440
|
+
finally {
|
|
1441
|
+
// A release failure must never overwrite the computed outcome: after a conclusive
|
|
1442
|
+
// success the tasks are removed and their preimages are durable (the release failure
|
|
1443
|
+
// is bounded into the detail only), and on the error path the original error keeps
|
|
1444
|
+
// propagating unchanged.
|
|
1445
|
+
if (lock) {
|
|
1446
|
+
try {
|
|
1447
|
+
lock.release();
|
|
1448
|
+
}
|
|
1449
|
+
catch (releaseError) {
|
|
1450
|
+
if (computed?.status === 'cleaned') {
|
|
1451
|
+
computed.detail = `owner lock release failed: ${boundedDetail(releaseError)}`;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
catch (error) {
|
|
1458
|
+
const detail = boundedDetail(error);
|
|
1459
|
+
const status = detail.startsWith('bootstrap owner lock unavailable')
|
|
1460
|
+
? 'inconclusive'
|
|
1461
|
+
: 'failed';
|
|
1462
|
+
const partialPrefix = removedNames.length > 0
|
|
1463
|
+
? `partial cleanup removed ${removedNames.join(', ')}; `
|
|
1464
|
+
: '';
|
|
1465
|
+
return { status, dryRun, tasks: trackedEntries, detail: `${partialPrefix}${detail}` };
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
/** Test-only wrapper for mutation mechanics; callers must supply preclassified legacy entries. */
|
|
1469
|
+
function cleanupClassifiedLegacyTasksForTest(options, entries, expectedDefinitionHashes = new Map(), expectedProvenanceReceipts = new Map()) {
|
|
1470
|
+
if (entries.some((entry) => entry.classification !== 'legacy')) {
|
|
1471
|
+
throw new Error('test mutation helper requires preclassified legacy entries');
|
|
1472
|
+
}
|
|
1473
|
+
const powershell = trustedWindowsPowerShell();
|
|
1474
|
+
return cleanupClassifiedLegacyTasks(options, powershell, entries, entries, expectedDefinitionHashes, expectedProvenanceReceipts);
|
|
1475
|
+
}
|