@cotal-ai/cli 0.101.0 → 0.101.1
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/commands/spawn.d.ts.map +1 -1
- package/dist/commands/spawn.js +44 -2
- package/dist/commands/spawn.js.map +1 -1
- package/dist/commands/stack-down.d.ts.map +1 -1
- package/dist/commands/stack-down.js +4 -0
- package/dist/commands/stack-down.js.map +1 -1
- package/dist/lib/broker-service.d.ts.map +1 -1
- package/dist/lib/broker-service.js +8 -3
- package/dist/lib/broker-service.js.map +1 -1
- package/dist/lib/control.d.ts.map +1 -1
- package/dist/lib/control.js +19 -4
- package/dist/lib/control.js.map +1 -1
- package/dist/lib/manager-choice.d.ts +47 -0
- package/dist/lib/manager-choice.d.ts.map +1 -1
- package/dist/lib/manager-choice.js +134 -9
- package/dist/lib/manager-choice.js.map +1 -1
- package/dist/lib/service-custody-win32.d.ts +25 -0
- package/dist/lib/service-custody-win32.d.ts.map +1 -0
- package/dist/lib/service-custody-win32.js +67 -0
- package/dist/lib/service-custody-win32.js.map +1 -0
- package/dist/lib/service-instances.d.ts +35 -6
- package/dist/lib/service-instances.d.ts.map +1 -1
- package/dist/lib/service-instances.js +61 -11
- package/dist/lib/service-instances.js.map +1 -1
- package/dist/lib/service-journal.js +1 -1
- package/dist/lib/service-journal.js.map +1 -1
- package/dist/lib/service-process.d.ts +3 -8
- package/dist/lib/service-process.d.ts.map +1 -1
- package/dist/lib/service-process.js +155 -45
- package/dist/lib/service-process.js.map +1 -1
- package/dist/lib/service-systemd-install.js +1 -1
- package/dist/lib/service-systemd-install.js.map +1 -1
- package/package.json +4 -4
|
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, renameSync, unlinkSync } from "node:fs";
|
|
4
4
|
import { basename, isAbsolute, join, resolve } from "node:path";
|
|
5
|
-
import { CommandFailure, assertRecordIdentity, shellPath, boundedValue, canonicalRoot, commandIsCotalSupervisor, isCommandFailure, maintenanceAdmitsStackWork, readMaintenanceJournal, readProcessCommand, readServiceStopRequest, resolveNativeServiceTarget, loopbackListeners, processGroupMembers, processGroupOf, serviceAdapterReadiness, serviceMetadataDigest, spaceKey, serviceAdapterKernelStopPlan, serviceAdapterKernelStopResult, serviceAdapterStopPlan, serviceAdapterStopAbandonment, serviceAdapterStopRefusal, serviceAdapterStopResult, isWorkspaceTargetError, oneLine, targetErrorCode, workspaceErrorParts } from "@cotal-ai/workspace";
|
|
5
|
+
import { CommandFailure, assertRecordIdentity, shellPath, boundedValue, canonicalRoot, commandIsCotalSupervisor, isCommandFailure, maintenanceAdmitsStackWork, readMaintenanceJournal, readProcessCommand, readServiceStopRequest, resolveNativeServiceTarget, loopbackListeners, processGroupMembers, processGroupOf, serviceAdapterReadiness, serviceMetadataDigest, spaceKey, serviceAdapterKernelStopPlan, serviceAdapterKernelStopResult, serviceAdapterStopPlan, serviceAdapterStopAbandonment, serviceAdapterStopRefusal, serviceAdapterStopResult, isWorkspaceTargetError, oneLine, targetErrorCode, workspaceErrorParts, localRecordAccess } from "@cotal-ai/workspace";
|
|
6
6
|
import { refuseRecordedSupervisor } from "./service-supervision.js";
|
|
7
7
|
import { serviceInstallIntents } from "./service-install-intent.js";
|
|
8
8
|
import { serviceUninstallIntents } from "./service-uninstall-intent.js";
|
|
@@ -12,11 +12,15 @@ import { loadServiceAdapter, resolveServiceAdapter, sameServiceAdapterPin } from
|
|
|
12
12
|
import { serviceDefinitionStore, validateServiceDefinition } from "./service-definitions.js";
|
|
13
13
|
import { instanceProjection, observeServiceProcess, processServiceHost, requireProcessIdentity, serviceInstances, serviceInstanceStore } from "./service-instances.js";
|
|
14
14
|
import { maintenanceStackView, STACK_DEFINITION, stackMemberRecord } from "./stack-journal.js";
|
|
15
|
+
import { askCustodian, custodiedPlatform, custodyLog, removeCustodyCapability, startCustodiedService } from "./service-custody-win32.js";
|
|
15
16
|
export const PROCESS_SERVICE_CAPABILITIES = Object.freeze({ multiInstance: true, foreground: true, logs: true, install: false });
|
|
16
17
|
const delay = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
17
18
|
/** How long a launch with process readiness waits for an immediate exit before it reports the process running. */
|
|
18
19
|
const PROCESS_SETTLE_MS = 1000;
|
|
19
20
|
const gone = (state) => state === "gone" || state === "previous-boot" || state === "foreign-pid";
|
|
21
|
+
/** A log this account may read and append to. Windows protects it with the access list Cotal sets
|
|
22
|
+
* when it creates the file and has no POSIX owner or mode to check, as for every local record. */
|
|
23
|
+
const privateLog = (info) => info.isFile() && (localRecordAccess() === "windows-acl" || info.uid === process.getuid() && (info.mode & 0o077) === 0);
|
|
20
24
|
/** A record with no creation pin whose own state says no child exists: its launch failed before
|
|
21
25
|
* a process did. There is nothing to stop. */
|
|
22
26
|
const neverLaunched = (value) => !value.process && gone(observeServiceProcess(value));
|
|
@@ -255,7 +259,8 @@ function executable(definition) {
|
|
|
255
259
|
}
|
|
256
260
|
function environment(definition) {
|
|
257
261
|
const env = {};
|
|
258
|
-
|
|
262
|
+
// LOCALAPPDATA locates Cotal's own folder on Windows when COTAL_HOME is unset, as HOME does elsewhere.
|
|
263
|
+
for (const key of ["PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "LANG", "LC_ALL", "TERM", "COLORTERM", "NO_COLOR", "FORCE_COLOR", "COTAL_HOME", "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "XDG_RUNTIME_DIR"])
|
|
259
264
|
if (process.env[key] !== undefined)
|
|
260
265
|
env[key] = process.env[key];
|
|
261
266
|
// Variable names are not secrets, so a missing one is named with the child variable it feeds.
|
|
@@ -292,7 +297,7 @@ function rotateServiceLog(path) {
|
|
|
292
297
|
return;
|
|
293
298
|
throw error;
|
|
294
299
|
}
|
|
295
|
-
if (!
|
|
300
|
+
if (!privateLog(info))
|
|
296
301
|
throw new Error("unprotected log target");
|
|
297
302
|
if (info.size >= LOG_ROTATE_BYTES)
|
|
298
303
|
renameSync(path, `${path}.1`);
|
|
@@ -551,10 +556,12 @@ export async function startProcessService(definition, options, held) {
|
|
|
551
556
|
if (options.replacement && (options.brokerInstance || options.newInstance || options.instance !== undefined))
|
|
552
557
|
throw new CommandFailure("refused", "UNSUPPORTED", "a journaled stack replacement is started only under its own IDs; no launch was allocated");
|
|
553
558
|
const { program, adapter: declaredAdapter, cliInvocation, env, launcher } = prepareProcessService(definition);
|
|
559
|
+
if (options.foreground && custodiedPlatform())
|
|
560
|
+
throw new CommandFailure("refused", "UNSUPPORTED", "on Windows a service runs in the background under the custodian that holds its job; a terminal-attached foreground child was not substituted", { remedy: `start it in the background with cotal service start ${definition.name} --space ${value.space}` });
|
|
554
561
|
if (declaredAdapter && (options.newInstance && !declaredAdapter.declaration.capabilities.multiInstance || options.foreground && !declaredAdapter.declaration.capabilities.foreground))
|
|
555
562
|
throw new CommandFailure("refused", "UNSUPPORTED", "the selected adapter does not declare this multi-instance or foreground capability; no launch was allocated");
|
|
556
563
|
const hold = held ?? serviceDefinitionStore(value.space).pin(definition);
|
|
557
|
-
let child, unpinned;
|
|
564
|
+
let child, unpinned, spawnedCustody;
|
|
558
565
|
try {
|
|
559
566
|
assertNoServiceUnitAttempts(value.space, definition.name);
|
|
560
567
|
const rows = serviceInstances(value.space, definition.name);
|
|
@@ -615,9 +622,16 @@ export async function startProcessService(definition, options, held) {
|
|
|
615
622
|
const instance = { schemaVersion: 1, instanceId: id, definition: definition.name, definitionRevision: definition.record.revision, space: value.space, host: processServiceHost(), requestId: launchRequestId, launchRequestId, state: "starting", launcher, readiness: "not-checked", supervisor: "none", ...(options.attempt ? { attempt: { attemptId: options.attempt.attemptId } } : {}), ...(declaredAdapter ? { adapter: declaredAdapter.pin, ...(declaredAdapter.declaration.stop === "native" ? { nativeStopRequired: true } : declaredAdapter.declaration.stop === "kernel-exit" ? { kernelStopRequired: true } : {}) } : {}), foreground: options.foreground === true, createdAt: selected?.record.value.createdAt ?? now, updatedAt: now };
|
|
616
623
|
const store = serviceInstanceStore(value.space);
|
|
617
624
|
store.commit(id, selected, instance);
|
|
625
|
+
// The replaced incarnation's custodian is gone, so its capability opens nothing.
|
|
626
|
+
removeCustodyCapability(value.space, selected?.record.value.custody);
|
|
618
627
|
let row = store.read(id);
|
|
619
|
-
// Until the child's identity is recorded, an interrupt records this launch on its way out.
|
|
628
|
+
// Until the child's identity is recorded, an interrupt records this launch on its way out. On
|
|
629
|
+
// Windows that is its custodian, which can still be asked for the job once it is recorded.
|
|
620
630
|
unpinned = () => {
|
|
631
|
+
if (spawnedCustody) {
|
|
632
|
+
row = transition(row, { custody: spawnedCustody, state: "unknown", readiness: "not-checked" });
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
621
635
|
if (child?.pid === undefined) {
|
|
622
636
|
row = transition(row, { state: "failed", readiness: "not-checked" });
|
|
623
637
|
return;
|
|
@@ -683,44 +697,78 @@ export async function startProcessService(definition, options, held) {
|
|
|
683
697
|
let exited = false;
|
|
684
698
|
let done;
|
|
685
699
|
const exit = new Promise((resolve) => { done = resolve; });
|
|
686
|
-
|
|
687
|
-
|
|
700
|
+
let identity;
|
|
701
|
+
if (custodiedPlatform()) {
|
|
702
|
+
// Windows: a custodian creates the program inside a kill-on-close job and reports its pin.
|
|
703
|
+
let started;
|
|
704
|
+
try {
|
|
688
705
|
rotateServiceLog(path);
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077) !== 0)
|
|
692
|
-
throw new Error("unprotected log target");
|
|
693
|
-
logFrom = info.size;
|
|
706
|
+
logFrom = custodyLog(path);
|
|
707
|
+
started = await startCustodiedService(row.record.value, { ...launch, env }, path, (custody) => { spawnedCustody = custody; });
|
|
694
708
|
}
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
child.
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
709
|
+
catch (error) {
|
|
710
|
+
row = transition(row, spawnedCustody ? { custody: spawnedCustody, state: "unknown", readiness: "not-checked" } : { state: "failed", readiness: "not-checked" });
|
|
711
|
+
throw new CommandFailure(spawnedCustody ? "unknown" : "failed", spawnedCustody ? "OPERATION_UNKNOWN" : "OPERATION_FAILED", `the custodied process launch did not report a running service child (${error.message}); its instance receipt was retained`, { target: instanceProjection(row) });
|
|
712
|
+
}
|
|
713
|
+
identity = started.process;
|
|
714
|
+
row = transition(row, { process: identity, custody: started.custody });
|
|
715
|
+
unpinnedLaunches.delete(unpinned);
|
|
716
|
+
// The custodian holds the program; this launch watches its pin to notice an early exit.
|
|
717
|
+
const pinned = identity;
|
|
718
|
+
const watch = setInterval(() => {
|
|
719
|
+
if (assertRecordIdentity(pinned).kind === "match")
|
|
720
|
+
return;
|
|
721
|
+
clearInterval(watch);
|
|
722
|
+
exited = true;
|
|
723
|
+
done();
|
|
724
|
+
}, 100);
|
|
725
|
+
watch.unref();
|
|
726
|
+
exit.then(async () => {
|
|
727
|
+
try {
|
|
728
|
+
exitCode = (await askCustodian(row, { op: "status" })).root.exit;
|
|
729
|
+
}
|
|
730
|
+
catch { /* The custodian already left with its job; the log keeps the cause. */ }
|
|
731
|
+
});
|
|
714
732
|
}
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
733
|
+
else {
|
|
734
|
+
try {
|
|
735
|
+
if (!options.foreground) {
|
|
736
|
+
rotateServiceLog(path);
|
|
737
|
+
log = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
|
|
738
|
+
const info = fstatSync(log);
|
|
739
|
+
if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077) !== 0)
|
|
740
|
+
throw new Error("unprotected log target");
|
|
741
|
+
logFrom = info.size;
|
|
742
|
+
}
|
|
743
|
+
child = spawn(launch.program, [...launch.args], { cwd: launch.cwd, env, shell: false, detached: !options.foreground, stdio: options.foreground ? "inherit" : ["ignore", log, log] });
|
|
744
|
+
if (!options.foreground)
|
|
745
|
+
child.unref();
|
|
746
|
+
child.once("exit", (code, signal) => { exited = true; exitCode = code; exitSignal = signal; done(); });
|
|
747
|
+
await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
|
|
748
|
+
}
|
|
749
|
+
catch {
|
|
750
|
+
row = transition(row, { state: "failed", readiness: "not-checked" });
|
|
751
|
+
throw new CommandFailure("failed", "OPERATION_FAILED", "the native process launch failed before a service child was established; its instance receipt was retained", { target: instanceProjection(row) });
|
|
752
|
+
}
|
|
753
|
+
finally {
|
|
754
|
+
if (log !== undefined)
|
|
755
|
+
closeSync(log);
|
|
756
|
+
}
|
|
757
|
+
if (!child.pid)
|
|
758
|
+
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the launch has no confirmed process ID; its instance intent was retained and no retry was made", { target: instanceProjection(row) });
|
|
759
|
+
try {
|
|
760
|
+
identity = requireProcessIdentity(child.pid);
|
|
761
|
+
}
|
|
762
|
+
catch {
|
|
763
|
+
if (!exited)
|
|
764
|
+
child.kill("SIGTERM");
|
|
765
|
+
await Promise.race([exit, delay(3000)]);
|
|
766
|
+
row = transition(row, { state: exited ? "failed" : "unknown", ...(exited ? { exit: { code: exitCode, signal: exitSignal } } : {}) });
|
|
767
|
+
throw new CommandFailure(exited ? "failed" : "unknown", exited ? "OPERATION_FAILED" : "OPERATION_UNKNOWN", "the child could not be creation-pinned; its native child handle was asked to exit, and no replacement was launched", { target: instanceProjection(row) });
|
|
768
|
+
}
|
|
769
|
+
row = transition(row, { process: identity });
|
|
770
|
+
unpinnedLaunches.delete(unpinned);
|
|
721
771
|
}
|
|
722
|
-
row = transition(row, { process: identity });
|
|
723
|
-
unpinnedLaunches.delete(unpinned);
|
|
724
772
|
// A process that exits at once never ran: process readiness first gives it a moment to do so,
|
|
725
773
|
// and that exit is then settled below with the code this parent observed.
|
|
726
774
|
if (value.readiness.type === "process")
|
|
@@ -839,6 +887,44 @@ export function preflightProcessServiceStop(definition, selected) {
|
|
|
839
887
|
}
|
|
840
888
|
/** How long a process stop waits after SIGTERM before it sends SIGKILL. */
|
|
841
889
|
export const PROCESS_STOP_GRACE_MS = 15_000;
|
|
890
|
+
/** Windows generic stop: the custodian terminates the instance's whole job, so a program that already
|
|
891
|
+
* exited is stopped with the members it left. The receipt names the program only when it was still
|
|
892
|
+
* running; the stop completes once the custodian, which holds the job, has exited. */
|
|
893
|
+
async function stopCustodiedProcess(current, initial) {
|
|
894
|
+
let row = current;
|
|
895
|
+
if ((initial !== "running" && initial !== "members-running") || !row.record.value.process)
|
|
896
|
+
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "the selected process is foreign, unreadable or unresolved; it was not signalled", { target: instanceProjection(row) });
|
|
897
|
+
const held = await askCustodian(row, { op: "status" });
|
|
898
|
+
if (commandIsCotalSupervisor([held.program, ...held.args].join(" ")))
|
|
899
|
+
throw new CommandFailure("refused", "UNSUPPORTED", "generic process stop cannot bypass manager agent-impact guards; use its supported service adapter. No job was terminated", { target: instanceProjection(row) });
|
|
900
|
+
const program = { ...row.record.value.process }, custodian = row.record.value.custody.custodian;
|
|
901
|
+
row = transition(row, { state: "stopping", requestId: randomUUID() });
|
|
902
|
+
const ended = await askCustodian(row, { op: "terminate", code: 1 });
|
|
903
|
+
for (const deadline = Date.now() + 5000; assertRecordIdentity(custodian).kind === "match" && Date.now() < deadline;)
|
|
904
|
+
await delay(100);
|
|
905
|
+
if (ended.members.length || ended.root.exit === null || assertRecordIdentity(custodian).kind === "match")
|
|
906
|
+
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", `the service's job did not confirm it emptied${ended.members.length ? `; process ${ended.members.join(", ")} still ran in it` : ""}; its record was retained and no restart was attempted`, { target: instanceProjection(row) });
|
|
907
|
+
removeCustodyCapability(row.record.value.space, row.record.value.custody);
|
|
908
|
+
const processStop = initial === "running" ? { processStop: { kind: "process-exit", requestId: row.record.value.requestId, process: program, signal: "job-terminate", observedAt: new Date().toISOString() } } : {};
|
|
909
|
+
return { instance: transition(row, { state: "stopped", readiness: "not-checked", ...processStop }), noOp: false };
|
|
910
|
+
}
|
|
911
|
+
/** Windows: a program with a native or kernel-exit stop policy exited on its own, and its job still
|
|
912
|
+
* holds processes. Those end with the job, so a manager's agents end only on `--with-agents`. The
|
|
913
|
+
* custodian terminates the job to empty, and the record settles as an exit no stop explains. */
|
|
914
|
+
async function endLeftoverJob(current, membersMayEnd) {
|
|
915
|
+
const row = current;
|
|
916
|
+
const held = await askCustodian(row, { op: "status" });
|
|
917
|
+
if (!membersMayEnd && held.members.length)
|
|
918
|
+
throw new CommandFailure("refused", "UNSUPPORTED", `the service's program exited while its job still holds process ${held.members.join(", ")}, which would end with it; nothing was stopped`, { target: instanceProjection(row), remedy: `end them with cotal service stop ${row.record.value.definition} --instance ${row.name} --space ${row.record.value.space} --with-agents --yes` });
|
|
919
|
+
const custodian = row.record.value.custody.custodian;
|
|
920
|
+
const ended = await askCustodian(row, { op: "terminate", code: 1 });
|
|
921
|
+
for (const deadline = Date.now() + 5000; assertRecordIdentity(custodian).kind === "match" && Date.now() < deadline;)
|
|
922
|
+
await delay(100);
|
|
923
|
+
if (ended.members.length || assertRecordIdentity(custodian).kind === "match")
|
|
924
|
+
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", `the service's job did not confirm it emptied${ended.members.length ? `; process ${ended.members.join(", ")} still ran in it` : ""}; its record was retained`, { target: instanceProjection(row) });
|
|
925
|
+
removeCustodyCapability(row.record.value.space, row.record.value.custody);
|
|
926
|
+
return { instance: settleExitedInstance(row), noOp: false };
|
|
927
|
+
}
|
|
842
928
|
/** Only the stored creation-pinned process is signalled. Every escalation rechecks its identity. */
|
|
843
929
|
export async function stopProcessService(definition, selected, held, native, kernel) {
|
|
844
930
|
const hold = held ?? serviceDefinitionStore(definition.record.value.space).pin(definition);
|
|
@@ -863,6 +949,8 @@ export async function stopProcessService(definition, selected, held, native, ker
|
|
|
863
949
|
// Already gone without a stop of ours: record that exit under this lock; nothing is signalled.
|
|
864
950
|
if (goneWithoutStop(row.record.value))
|
|
865
951
|
return { instance: settleExitedInstance(row), noOp: true };
|
|
952
|
+
if (initial === "members-running")
|
|
953
|
+
return await endLeftoverJob(row, native?.withAgents === true);
|
|
866
954
|
if (initial !== "running" || !row.record.value.process)
|
|
867
955
|
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "native stop has no current attributable process or retained returned receipt; disappearance was not treated as completion", { target: instanceProjection(row) });
|
|
868
956
|
if (!native?.plan)
|
|
@@ -876,16 +964,26 @@ export async function stopProcessService(definition, selected, held, native, ker
|
|
|
876
964
|
if (native.preserved && !native.requestId)
|
|
877
965
|
throw new CommandFailure("refused", "USAGE_INVALID", "a preserved-exit stop needs its journaled attempt's request ID; no request was published");
|
|
878
966
|
const requestId = native.requestId ?? randomUUID(), target = { ...row.record.value.process }, began = Date.now();
|
|
967
|
+
if (custodiedPlatform() && !native.withAgents) {
|
|
968
|
+
// A Windows manager's agents run in its job and end with it, so a stop that keeps them refuses.
|
|
969
|
+
const others = (await askCustodian(row, { op: "status" })).members.filter((pid) => pid !== target.pid);
|
|
970
|
+
if (others.length)
|
|
971
|
+
throw new CommandFailure("refused", "UNSUPPORTED", `on Windows the manager's job also holds process ${others.join(", ")}, which would end with it; nothing was stopped`, { target: instanceProjection(row), remedy: `stop it with its agents, cotal service stop ${definition.name} --instance ${row.name} --space ${row.record.value.space} --with-agents --yes` });
|
|
972
|
+
}
|
|
879
973
|
row = transition(row, { state: "stopping", requestId });
|
|
880
974
|
let returned = false;
|
|
881
975
|
try {
|
|
882
976
|
const raw = await adapterCall((signal) => provider.stop({ ...adapterContext(definition, row.record.value), process: target, withAgents: native.withAgents, ...(native.preserved ? { preserved: { ...native.preserved } } : {}), requestId, plan, signal }), 45000);
|
|
883
977
|
returned = true;
|
|
884
978
|
const result = serviceAdapterStopResult(raw);
|
|
979
|
+
// A Windows custodian exits a moment after the job it held empties.
|
|
980
|
+
for (const deadline = Date.now() + 5000; custodiedPlatform() && observeServiceProcess(row.record.value) === "members-running" && Date.now() < deadline;)
|
|
981
|
+
await delay(100);
|
|
885
982
|
// The terminal kind must answer the submitted request: a preserved stop returns only
|
|
886
983
|
// `preserved-exit-returned`, an ordinary stop only `returned`.
|
|
887
984
|
if (result.nativeStop !== (native.preserved ? "preserved-exit-returned" : "returned") || result.requestId !== requestId || result.scopeSha256 !== plan.scopeSha256 || result.process.pid !== target.pid || result.process.token !== target.token || Date.parse(result.observedAt) < began - 1000 || Date.parse(result.observedAt) > Date.now() + 1000 || !gone(observeServiceProcess(row.record.value)))
|
|
888
985
|
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the native service did not confirm both its original returned stop and the exact process exit");
|
|
986
|
+
removeCustodyCapability(row.record.value.space, row.record.value.custody);
|
|
889
987
|
return { instance: transition(row, { state: "stopped", readiness: "not-checked", nativeStop: result }), noOp: false, nativeStop: result };
|
|
890
988
|
}
|
|
891
989
|
catch (error) {
|
|
@@ -910,6 +1008,8 @@ export async function stopProcessService(definition, selected, held, native, ker
|
|
|
910
1008
|
throw new CommandFailure("refused", "UNSUPPORTED", "generic process stop does not accept an agent-reap policy");
|
|
911
1009
|
if (gone(initial))
|
|
912
1010
|
return { instance: transition(row, { state: "stopped", readiness: "not-checked" }), noOp: true };
|
|
1011
|
+
if (custodiedPlatform())
|
|
1012
|
+
return await stopCustodiedProcess(row, initial);
|
|
913
1013
|
if (initial !== "running" || !row.record.value.process)
|
|
914
1014
|
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "the selected process is foreign, unreadable or unresolved; it was not signalled", { target: instanceProjection(row) });
|
|
915
1015
|
const command = readProcessCommand(row.record.value.process.pid);
|
|
@@ -999,6 +1099,8 @@ async function stopKernelService(definition, current, hold, declared, initial, n
|
|
|
999
1099
|
return { instance: settleExitedInstance(row), noOp: true };
|
|
1000
1100
|
if (value.state === "stopping")
|
|
1001
1101
|
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "an earlier broker stop request is retained without its exact-exit receipt; it was not resubmitted", { target: instanceProjection(row) });
|
|
1102
|
+
if (initial === "members-running")
|
|
1103
|
+
return await endLeftoverJob(row, true);
|
|
1002
1104
|
if (initial !== "running" || !value.process)
|
|
1003
1105
|
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the broker has no current attributable process or retained exact-exit receipt; disappearance was not treated as a completed stop", { target: instanceProjection(row) });
|
|
1004
1106
|
if (!kernel?.plan)
|
|
@@ -1011,7 +1113,8 @@ async function stopKernelService(definition, current, hold, declared, initial, n
|
|
|
1011
1113
|
if (fresh.scopeSha256 !== confirmed.scopeSha256 || serviceMetadataDigest(fresh.binding) !== serviceMetadataDigest(confirmed.binding))
|
|
1012
1114
|
throw new CommandFailure("refused", "CONFLICT", "the broker binding or dependant scope changed after confirmation; no signal was sent", { target: instanceProjection(row) });
|
|
1013
1115
|
hold.check();
|
|
1014
|
-
|
|
1116
|
+
// On Windows the custodian reports the exact program it launched, which is the broker's role.
|
|
1117
|
+
const role = custodiedPlatform() ? await askCustodian(row, { op: "status" }).then((held) => ({ kind: "command", command: [held.program, ...held.args].join(" ") }), () => ({ kind: "unreadable" })) : readProcessCommand(target.pid);
|
|
1015
1118
|
if (role.kind !== "command" || commandIsCotalSupervisor(role.command) || assertRecordIdentity(target).kind !== "match")
|
|
1016
1119
|
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "the broker process identity or role could not be re-established immediately before the signal; no signal was sent", { target: instanceProjection(row) });
|
|
1017
1120
|
const requestId = randomUUID();
|
|
@@ -1019,7 +1122,11 @@ async function stopKernelService(definition, current, hold, declared, initial, n
|
|
|
1019
1122
|
try {
|
|
1020
1123
|
if (assertRecordIdentity(target).kind !== "match")
|
|
1021
1124
|
throw new Error("identity changed");
|
|
1022
|
-
|
|
1125
|
+
// Windows has no SIGTERM to deliver: the custodian terminates the broker's job.
|
|
1126
|
+
if (custodiedPlatform())
|
|
1127
|
+
await askCustodian(row, { op: "terminate", code: 1 });
|
|
1128
|
+
else
|
|
1129
|
+
process.kill(target.pid, "SIGTERM");
|
|
1023
1130
|
}
|
|
1024
1131
|
catch {
|
|
1025
1132
|
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the exact broker signal was not confirmed delivered to the pinned process; its stop request was retained and no exit was attributed to it", { target: instanceProjection(row) });
|
|
@@ -1034,9 +1141,11 @@ async function stopKernelService(definition, current, hold, declared, initial, n
|
|
|
1034
1141
|
}
|
|
1035
1142
|
catch { /* The observed exit stands; an unreadable trace is reported as retained, never removed. */ }
|
|
1036
1143
|
const kernelStop = serviceAdapterKernelStopResult({ kind: "kernel-exit", requestId, scopeSha256: confirmed.scopeSha256, process: target, observation: "exact-process-exit", brokerShutdownTrace: trace, cleanup: "not-checked", observedAt: new Date().toISOString() });
|
|
1144
|
+
removeCustodyCapability(row.record.value.space, row.record.value.custody);
|
|
1037
1145
|
return { instance: transition(row, { state: "stopped", readiness: "not-checked", kernelStop }), noOp: false, kernelStop };
|
|
1038
1146
|
}
|
|
1039
|
-
|
|
1147
|
+
// A Windows custodian outlives its emptied job by a moment before it exits.
|
|
1148
|
+
if (state !== "running" && state !== "members-running")
|
|
1040
1149
|
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the broker exit could not be attributed; its stop request was retained", { target: instanceProjection(row) });
|
|
1041
1150
|
await delay(100);
|
|
1042
1151
|
}
|
|
@@ -1102,6 +1211,7 @@ export function removeStoppedInstanceRecords(space, name) {
|
|
|
1102
1211
|
try {
|
|
1103
1212
|
for (const row of rows) {
|
|
1104
1213
|
serviceInstanceStore(space).commit(row.name, row, undefined);
|
|
1214
|
+
removeCustodyCapability(space, row.record.value.custody);
|
|
1105
1215
|
removed.push(row.name);
|
|
1106
1216
|
}
|
|
1107
1217
|
}
|
|
@@ -1144,7 +1254,7 @@ export function readOwnedLogTail(path, tail) {
|
|
|
1144
1254
|
const info = fstatSync(fd);
|
|
1145
1255
|
if (![info.size, info.dev, info.ino].every((number) => Number.isSafeInteger(number) && number >= 0))
|
|
1146
1256
|
throw new CommandFailure("refused", "UNSUPPORTED", "this log's native file coordinates cannot be represented safely; no approximate byte offsets were reported");
|
|
1147
|
-
if (!
|
|
1257
|
+
if (!privateLog(info))
|
|
1148
1258
|
throw new CommandFailure("refused", "PERMISSION_DENIED", "the service log is not an owned private regular file");
|
|
1149
1259
|
// Read back 1 MiB at a time until the bytes hold `tail` whole lines, the file's start or the bound.
|
|
1150
1260
|
const limit = Math.min(info.size, LOG_TAIL_BYTES), chunks = [];
|
|
@@ -1189,7 +1299,7 @@ function lastLoggedLine(path, from) {
|
|
|
1189
1299
|
}
|
|
1190
1300
|
try {
|
|
1191
1301
|
const info = fstatSync(fd);
|
|
1192
|
-
if (!
|
|
1302
|
+
if (!privateLog(info) || info.size <= from)
|
|
1193
1303
|
return undefined;
|
|
1194
1304
|
const length = Math.min(info.size - from, 8192), bytes = Buffer.alloc(length);
|
|
1195
1305
|
let read = 0;
|
|
@@ -1231,7 +1341,7 @@ export function serviceLogSlice(space, id, position, tail) {
|
|
|
1231
1341
|
const info = fstatSync(fd);
|
|
1232
1342
|
if (![info.size, info.dev, info.ino].every((number) => Number.isSafeInteger(number) && number >= 0))
|
|
1233
1343
|
throw new CommandFailure("refused", "UNSUPPORTED", "this log's native file coordinates cannot be represented safely; no approximate byte offsets were reported");
|
|
1234
|
-
if (!
|
|
1344
|
+
if (!privateLog(info))
|
|
1235
1345
|
throw new CommandFailure("refused", "PERMISSION_DENIED", "the selected service log is not an owned private regular file");
|
|
1236
1346
|
const replaced = position !== undefined && (position.dev !== info.dev || position.ino !== info.ino);
|
|
1237
1347
|
const truncated = position !== undefined && !replaced && info.size < position.offset;
|