@songsid/agend 2.4.0-beta.24 → 2.4.0-beta.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/README.zh-TW.md +1 -1
- package/dist/agend-home.js +5 -5
- package/dist/agend-home.js.map +1 -1
- package/dist/agent-endpoint.js +10 -0
- package/dist/agent-endpoint.js.map +1 -1
- package/dist/agent-workspace.d.ts +18 -2
- package/dist/agent-workspace.js +15 -4
- package/dist/agent-workspace.js.map +1 -1
- package/dist/backend/antigravity.js +8 -6
- package/dist/backend/antigravity.js.map +1 -1
- package/dist/backend/claude-code.js +17 -0
- package/dist/backend/claude-code.js.map +1 -1
- package/dist/backend/claude-usage-credits.d.ts +8 -0
- package/dist/backend/claude-usage-credits.js +121 -0
- package/dist/backend/claude-usage-credits.js.map +1 -0
- package/dist/backend/types.d.ts +30 -0
- package/dist/backend/types.js.map +1 -1
- package/dist/build-provenance.json +1 -1
- package/dist/channel/adapters/discord.js +7 -1
- package/dist/channel/adapters/discord.js.map +1 -1
- package/dist/channel/tool-router.js +1 -0
- package/dist/channel/tool-router.js.map +1 -1
- package/dist/cli-audited.js +9 -4
- package/dist/cli-audited.js.map +1 -1
- package/dist/cli.js +184 -21
- package/dist/cli.js.map +1 -1
- package/dist/config-validator.js +11 -1
- package/dist/config-validator.js.map +1 -1
- package/dist/config.js +2 -0
- package/dist/config.js.map +1 -1
- package/dist/contact-auth-store.d.ts +18 -0
- package/dist/contact-auth-store.js +55 -8
- package/dist/contact-auth-store.js.map +1 -1
- package/dist/contact-auth-types.d.ts +3 -0
- package/dist/contact-auth-types.js.map +1 -1
- package/dist/contact-change-proposals.d.ts +34 -0
- package/dist/contact-change-proposals.js +1 -1
- package/dist/contact-change-proposals.js.map +1 -1
- package/dist/cross-instance-notice.d.ts +1 -0
- package/dist/cross-instance-notice.js +9 -8
- package/dist/cross-instance-notice.js.map +1 -1
- package/dist/daemon.d.ts +35 -0
- package/dist/daemon.js +234 -19
- package/dist/daemon.js.map +1 -1
- package/dist/delivery-outbox.d.ts +42 -1
- package/dist/delivery-outbox.js +194 -20
- package/dist/delivery-outbox.js.map +1 -1
- package/dist/fleet-context.d.ts +8 -0
- package/dist/fleet-lock.d.ts +67 -2
- package/dist/fleet-lock.js +236 -2
- package/dist/fleet-lock.js.map +1 -1
- package/dist/fleet-manager.d.ts +163 -6
- package/dist/fleet-manager.js +1136 -75
- package/dist/fleet-manager.js.map +1 -1
- package/dist/fleet-windows-runtime.d.ts +20 -1
- package/dist/fleet-windows-runtime.js +98 -18
- package/dist/fleet-windows-runtime.js.map +1 -1
- package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +7 -0
- package/dist/general-knowledge/skills/web-dashboard/SKILL.md +14 -4
- package/dist/home-update-lock.d.ts +35 -0
- package/dist/home-update-lock.js +81 -0
- package/dist/home-update-lock.js.map +1 -0
- package/dist/hub/compose/member.d.ts +5 -1
- package/dist/hub/compose/member.js +9 -5
- package/dist/hub/compose/member.js.map +1 -1
- package/dist/hub/member/room-ask.d.ts +5 -0
- package/dist/hub/member/room-ask.js +43 -16
- package/dist/hub/member/room-ask.js.map +1 -1
- package/dist/hub/member/room-mention-feedback.d.ts +2 -0
- package/dist/hub/member/room-mention-feedback.js +1 -1
- package/dist/hub/member/room-mention-feedback.js.map +1 -1
- package/dist/hub/member/room-post-answers.d.ts +2 -0
- package/dist/hub/member/room-post-answers.js +1 -1
- package/dist/hub/member/room-post-answers.js.map +1 -1
- package/dist/hub/member/room-post.d.ts +5 -0
- package/dist/hub/member/room-post.js +4 -1
- package/dist/hub/member/room-post.js.map +1 -1
- package/dist/hub/member/updates.d.ts +7 -1
- package/dist/hub/member/updates.js +7 -1
- package/dist/hub/member/updates.js.map +1 -1
- package/dist/hub/representative.d.ts +7 -0
- package/dist/hub/representative.js +38 -5
- package/dist/hub/representative.js.map +1 -1
- package/dist/install-lock.d.ts +15 -1
- package/dist/install-lock.js +16 -8
- package/dist/install-lock.js.map +1 -1
- package/dist/install-ownership.d.ts +165 -0
- package/dist/install-ownership.js +404 -0
- package/dist/install-ownership.js.map +1 -0
- package/dist/instance-config-impact.js +2 -0
- package/dist/instance-config-impact.js.map +1 -1
- package/dist/instructions.d.ts +4 -0
- package/dist/instructions.js +4 -0
- package/dist/instructions.js.map +1 -1
- package/dist/local-pane-endpoint.d.ts +4 -1
- package/dist/local-pane-endpoint.js +12 -2
- package/dist/local-pane-endpoint.js.map +1 -1
- package/dist/locale.js +160 -4
- package/dist/locale.js.map +1 -1
- package/dist/native-agent-admission.d.ts +7 -0
- package/dist/native-agent-admission.js +46 -3
- package/dist/native-agent-admission.js.map +1 -1
- package/dist/native-mcp.d.ts +16 -1
- package/dist/native-mcp.js +38 -5
- package/dist/native-mcp.js.map +1 -1
- package/dist/native-pane-lifecycle.d.ts +9 -0
- package/dist/native-pane-lifecycle.js +23 -0
- package/dist/native-pane-lifecycle.js.map +1 -1
- package/dist/native-pane-manager.d.ts +19 -6
- package/dist/native-pane-manager.js +79 -4
- package/dist/native-pane-manager.js.map +1 -1
- package/dist/needs-you.d.ts +8 -0
- package/dist/needs-you.js +1 -0
- package/dist/needs-you.js.map +1 -1
- package/dist/outbound-handlers.d.ts +12 -0
- package/dist/outbound-handlers.js +30 -2
- package/dist/outbound-handlers.js.map +1 -1
- package/dist/package-preimage.js +4 -0
- package/dist/package-preimage.js.map +1 -1
- package/dist/pane-port.d.ts +1 -0
- package/dist/plist-args.d.ts +9 -0
- package/dist/plist-args.js +22 -0
- package/dist/plist-args.js.map +1 -0
- package/dist/public-preview.d.ts +4 -6
- package/dist/public-preview.js +5 -2
- package/dist/public-preview.js.map +1 -1
- package/dist/public-web-gateway.js +8 -3
- package/dist/public-web-gateway.js.map +1 -1
- package/dist/public-web-link.d.ts +13 -1
- package/dist/public-web-link.js +28 -1
- package/dist/public-web-link.js.map +1 -1
- package/dist/recover.cjs +2452 -0
- package/dist/remote-card-prompt.d.ts +6 -2
- package/dist/remote-card-prompt.js +12 -3
- package/dist/remote-card-prompt.js.map +1 -1
- package/dist/reply-draft.d.ts +12 -0
- package/dist/reply-draft.js +81 -0
- package/dist/reply-draft.js.map +1 -0
- package/dist/request-contact-api.d.ts +15 -0
- package/dist/request-contact-api.js +120 -0
- package/dist/request-contact-api.js.map +1 -0
- package/dist/request-contact-card.d.ts +36 -0
- package/dist/request-contact-card.js +206 -0
- package/dist/request-contact-card.js.map +1 -0
- package/dist/request-contact-gate.d.ts +79 -0
- package/dist/request-contact-gate.js +262 -0
- package/dist/request-contact-gate.js.map +1 -0
- package/dist/request-contact-native.d.ts +52 -0
- package/dist/request-contact-native.js +83 -0
- package/dist/request-contact-native.js.map +1 -0
- package/dist/request-contact-types.d.ts +86 -0
- package/dist/request-contact-types.js +7 -0
- package/dist/request-contact-types.js.map +1 -0
- package/dist/request-context-call-protocol.d.ts +12 -0
- package/dist/request-context-call-protocol.js +14 -0
- package/dist/request-context-call-protocol.js.map +1 -0
- package/dist/request-context-call.d.ts +22 -0
- package/dist/request-context-call.js +35 -0
- package/dist/request-context-call.js.map +1 -0
- package/dist/request-context-drain.d.ts +39 -0
- package/dist/request-context-drain.js +159 -0
- package/dist/request-context-drain.js.map +1 -0
- package/dist/request-context-fence.d.ts +28 -0
- package/dist/request-context-fence.js +58 -0
- package/dist/request-context-fence.js.map +1 -0
- package/dist/request-context-migration.d.ts +64 -0
- package/dist/request-context-migration.js +158 -0
- package/dist/request-context-migration.js.map +1 -0
- package/dist/request-context-pane.d.ts +25 -0
- package/dist/request-context-pane.js +48 -0
- package/dist/request-context-pane.js.map +1 -0
- package/dist/request-context-policy.d.ts +74 -0
- package/dist/request-context-policy.js +116 -0
- package/dist/request-context-policy.js.map +1 -0
- package/dist/request-context-recovery.d.ts +14 -0
- package/dist/request-context-recovery.js +56 -0
- package/dist/request-context-recovery.js.map +1 -0
- package/dist/request-context-relay.d.ts +19 -0
- package/dist/request-context-relay.js +63 -0
- package/dist/request-context-relay.js.map +1 -0
- package/dist/request-context-returns.d.ts +67 -0
- package/dist/request-context-returns.js +211 -0
- package/dist/request-context-returns.js.map +1 -0
- package/dist/request-context-store.d.ts +2 -1
- package/dist/request-context-store.js +8 -1
- package/dist/request-context-store.js.map +1 -1
- package/dist/request-context-turns.d.ts +99 -0
- package/dist/request-context-turns.js +215 -0
- package/dist/request-context-turns.js.map +1 -0
- package/dist/request-context-view.d.ts +33 -0
- package/dist/request-context-view.js +36 -0
- package/dist/request-context-view.js.map +1 -0
- package/dist/request-hub-context.d.ts +130 -0
- package/dist/request-hub-context.js +89 -0
- package/dist/request-hub-context.js.map +1 -0
- package/dist/request-hub-output.d.ts +11 -0
- package/dist/request-hub-output.js +21 -0
- package/dist/request-hub-output.js.map +1 -0
- package/dist/runtime-cli-install.js +13 -11
- package/dist/runtime-cli-install.js.map +1 -1
- package/dist/runtime-client.d.ts +2 -0
- package/dist/runtime-client.js +17 -4
- package/dist/runtime-client.js.map +1 -1
- package/dist/runtime-coordinator.d.ts +4 -1
- package/dist/runtime-coordinator.js +10 -3
- package/dist/runtime-coordinator.js.map +1 -1
- package/dist/runtime-pane-assets.d.ts +1 -1
- package/dist/runtime-pane-assets.js +1 -1
- package/dist/runtime-pane-assets.js.map +1 -1
- package/dist/runtime-pane-host.d.ts +3 -0
- package/dist/runtime-pane-host.js +39 -21
- package/dist/runtime-pane-host.js.map +1 -1
- package/dist/runtime-pane-link.d.ts +6 -2
- package/dist/runtime-pane-link.js +17 -4
- package/dist/runtime-pane-link.js.map +1 -1
- package/dist/runtime-pane-mcp-relay.d.ts +11 -1
- package/dist/runtime-pane-mcp-relay.js +69 -3
- package/dist/runtime-pane-mcp-relay.js.map +1 -1
- package/dist/runtime-pane-mcp.d.ts +28 -1
- package/dist/runtime-pane-mcp.js +92 -15
- package/dist/runtime-pane-mcp.js.map +1 -1
- package/dist/runtime-pane-port.d.ts +6 -0
- package/dist/runtime-pane-port.js +23 -4
- package/dist/runtime-pane-port.js.map +1 -1
- package/dist/runtime-pane-protocol.d.ts +4 -0
- package/dist/runtime-pane-protocol.js +11 -4
- package/dist/runtime-pane-protocol.js.map +1 -1
- package/dist/runtime-pane-service.d.ts +1 -0
- package/dist/runtime-pane-service.js +25 -9
- package/dist/runtime-pane-service.js.map +1 -1
- package/dist/runtime-pane-stdio-protocol.d.ts +4 -0
- package/dist/runtime-pane-stdio-protocol.js +12 -5
- package/dist/runtime-pane-stdio-protocol.js.map +1 -1
- package/dist/runtime-pane-stdio.js +5 -5
- package/dist/runtime-pane-stdio.js.map +1 -1
- package/dist/runtime-protocol.d.ts +3 -0
- package/dist/runtime-protocol.js.map +1 -1
- package/dist/scheduler/scheduler.d.ts +6 -0
- package/dist/scheduler/scheduler.js +19 -1
- package/dist/scheduler/scheduler.js.map +1 -1
- package/dist/scheduler/task-board.d.ts +4 -0
- package/dist/scheduler/task-board.js +6 -0
- package/dist/scheduler/task-board.js.map +1 -1
- package/dist/scheduler/types.d.ts +1 -1
- package/dist/service-activation.js +3 -13
- package/dist/service-activation.js.map +1 -1
- package/dist/service-lock.d.ts +28 -0
- package/dist/service-lock.js +85 -0
- package/dist/service-lock.js.map +1 -0
- package/dist/settings-api.d.ts +6 -0
- package/dist/settings-api.js +35 -0
- package/dist/settings-api.js.map +1 -1
- package/dist/settings-change.js +1 -1
- package/dist/settings-change.js.map +1 -1
- package/dist/state-lease.d.ts +24 -0
- package/dist/state-lease.js +103 -0
- package/dist/state-lease.js.map +1 -0
- package/dist/tmux-binary.js +1 -1
- package/dist/tmux-binary.js.map +1 -1
- package/dist/tool-receipt-output.d.ts +2 -0
- package/dist/topic-commands.js +21 -1
- package/dist/topic-commands.js.map +1 -1
- package/dist/transcript-monitor.js +3 -0
- package/dist/transcript-monitor.js.map +1 -1
- package/dist/tunnel/named-link-test.d.ts +27 -0
- package/dist/tunnel/named-link-test.js +41 -0
- package/dist/tunnel/named-link-test.js.map +1 -1
- package/dist/types.d.ts +7 -0
- package/dist/ui/chat-store.js +5 -4
- package/dist/ui/fleet-office-card.js +15 -2
- package/dist/ui/fleet-office-skin.js +33 -9
- package/dist/ui/fleet-office-zones.js +8 -3
- package/dist/ui/fleet-office.js +136 -18
- package/dist/ui/fleet-task-files.js +1 -1
- package/dist/ui/panel-chat.js +15 -2
- package/dist/ui/panel-needs.js +22 -2
- package/dist/ui/panel-settings.js +22 -8
- package/dist/ui/settings-preview-address.js +156 -0
- package/dist/ui/settings-registry.js +2 -0
- package/dist/ui/settings-strings.js +6 -6
- package/dist/ui/shared/app.css +76 -2
- package/dist/ui/shared/chat-strings.js +6 -2
- package/dist/ui/shared/chat-thread.js +7 -1
- package/dist/ui/shared/preview-panel.js +1 -1
- package/dist/ui/shared/preview.js +11 -2
- package/dist/ui/shared/tokens.css +18 -3
- package/dist/ui/shared/ui-confirm.js +5 -4
- package/dist/ui/shared/workspace.css +7 -0
- package/dist/ui/usage-credits-card.js +84 -0
- package/dist/ui/workspace-ignored-strings.js +16 -0
- package/dist/ui/workspace-panel.js +15 -6
- package/dist/update-card.d.ts +193 -0
- package/dist/update-card.js +620 -0
- package/dist/update-card.js.map +1 -0
- package/dist/update-dispatch.d.ts +16 -1
- package/dist/update-dispatch.js +12 -4
- package/dist/update-dispatch.js.map +1 -1
- package/dist/update-forward.d.ts +73 -0
- package/dist/update-forward.js +283 -0
- package/dist/update-forward.js.map +1 -0
- package/dist/update-idle.d.ts +1 -0
- package/dist/update-idle.js +12 -3
- package/dist/update-idle.js.map +1 -1
- package/dist/update-install.d.ts +2 -1
- package/dist/update-install.js +18 -10
- package/dist/update-install.js.map +1 -1
- package/dist/update-journal.d.ts +351 -0
- package/dist/update-journal.js +717 -0
- package/dist/update-journal.js.map +1 -0
- package/dist/update-launch.js +1 -1
- package/dist/update-launch.js.map +1 -1
- package/dist/update-npm-env.d.ts +45 -12
- package/dist/update-npm-env.js +48 -0
- package/dist/update-npm-env.js.map +1 -1
- package/dist/update-package-restore.d.ts +75 -0
- package/dist/update-package-restore.js +318 -0
- package/dist/update-package-restore.js.map +1 -0
- package/dist/update-quiescence.d.ts +192 -0
- package/dist/update-quiescence.js +330 -0
- package/dist/update-quiescence.js.map +1 -0
- package/dist/update-readiness-host.d.ts +61 -0
- package/dist/update-readiness-host.js +297 -0
- package/dist/update-readiness-host.js.map +1 -0
- package/dist/update-readiness.d.ts +83 -0
- package/dist/update-readiness.js +459 -0
- package/dist/update-readiness.js.map +1 -0
- package/dist/update-recovery/kit.d.ts +35 -0
- package/dist/update-recovery/kit.js +99 -0
- package/dist/update-recovery/kit.js.map +1 -0
- package/dist/update-recovery/pre-start.d.ts +34 -0
- package/dist/update-recovery/pre-start.js +103 -0
- package/dist/update-recovery/pre-start.js.map +1 -0
- package/dist/update-recovery/recover-main.d.ts +1 -0
- package/dist/update-recovery/recover-main.js +4 -0
- package/dist/update-recovery/recover-main.js.map +1 -0
- package/dist/update-recovery/recover.d.ts +22 -0
- package/dist/update-recovery/recover.js +124 -0
- package/dist/update-recovery/recover.js.map +1 -0
- package/dist/update-recovery/route.d.ts +53 -0
- package/dist/update-recovery/route.js +262 -0
- package/dist/update-recovery/route.js.map +1 -0
- package/dist/update-recovery/runner.d.ts +58 -0
- package/dist/update-recovery/runner.js +196 -0
- package/dist/update-recovery/runner.js.map +1 -0
- package/dist/update-recovery/service-manager.d.ts +39 -0
- package/dist/update-recovery/service-manager.js +57 -0
- package/dist/update-recovery/service-manager.js.map +1 -0
- package/dist/update-restore.d.ts +44 -0
- package/dist/update-restore.js +355 -0
- package/dist/update-restore.js.map +1 -0
- package/dist/update-retained.d.ts +38 -0
- package/dist/update-retained.js +91 -0
- package/dist/update-retained.js.map +1 -0
- package/dist/update-rollback.d.ts +74 -0
- package/dist/update-rollback.js +221 -0
- package/dist/update-rollback.js.map +1 -0
- package/dist/update-settings.d.ts +36 -0
- package/dist/update-settings.js +122 -0
- package/dist/update-settings.js.map +1 -0
- package/dist/update-snapshot-manifest.d.ts +32 -0
- package/dist/update-snapshot-manifest.js +65 -0
- package/dist/update-snapshot-manifest.js.map +1 -0
- package/dist/update-snapshot-scope.d.ts +67 -0
- package/dist/update-snapshot-scope.js +172 -0
- package/dist/update-snapshot-scope.js.map +1 -0
- package/dist/update-snapshot.d.ts +34 -0
- package/dist/update-snapshot.js +246 -0
- package/dist/update-snapshot.js.map +1 -0
- package/dist/update-writers.d.ts +71 -0
- package/dist/update-writers.js +235 -0
- package/dist/update-writers.js.map +1 -0
- package/dist/web-api.d.ts +3 -0
- package/dist/web-api.js +43 -8
- package/dist/web-api.js.map +1 -1
- package/dist/web-chat-history.d.ts +7 -0
- package/dist/web-chat-history.js +15 -0
- package/dist/web-chat-history.js.map +1 -1
- package/dist/web-preview.d.ts +5 -0
- package/dist/web-preview.js +1 -1
- package/dist/web-preview.js.map +1 -1
- package/dist/web-update.d.ts +6 -0
- package/dist/windows-agents.d.ts +12 -0
- package/dist/windows-agents.js +5 -0
- package/dist/windows-agents.js.map +1 -1
- package/launcher/agend +4 -1
- package/launcher/agend-agent +4 -1
- package/launcher/agend-install.cjs +16 -8
- package/launcher/install-admission.d.cts +8 -0
- package/launcher/npm-allow-scripts.cjs +72 -0
- package/launcher/npm-global-prefix.cjs +81 -0
- package/launcher/postinstall.cjs +9 -8
- package/launcher/runtime-select.cjs +8 -2
- package/package.json +3 -2
- package/scripts/preinstall-guard.cjs +1 -1
package/dist/recover.cjs
ADDED
|
@@ -0,0 +1,2452 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
9
|
+
try {
|
|
10
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
11
|
+
} catch (e) {
|
|
12
|
+
throw mod = 0, e;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var __copyProps = (to, from, except, desc) => {
|
|
16
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
17
|
+
for (let key of __getOwnPropNames(from))
|
|
18
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
19
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
20
|
+
}
|
|
21
|
+
return to;
|
|
22
|
+
};
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
26
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
+
mod
|
|
30
|
+
));
|
|
31
|
+
|
|
32
|
+
// launcher/install-admission.cjs
|
|
33
|
+
var require_install_admission = __commonJS({
|
|
34
|
+
"launcher/install-admission.cjs"(exports2, module2) {
|
|
35
|
+
"use strict";
|
|
36
|
+
var fs = require("fs");
|
|
37
|
+
var path = require("path");
|
|
38
|
+
var childProcess = require("child_process");
|
|
39
|
+
var LOCK = ".agend-install.lock";
|
|
40
|
+
var TOKEN_ENV = "AGEND_INSTALL_TOKEN";
|
|
41
|
+
function globalPrefix(pkgDir) {
|
|
42
|
+
var scope = path.dirname(pkgDir);
|
|
43
|
+
var nodeModules = path.dirname(scope);
|
|
44
|
+
var lib = path.dirname(nodeModules);
|
|
45
|
+
if (path.basename(pkgDir) !== "agend" || path.basename(scope) !== "@songsid" || path.basename(nodeModules) !== "node_modules" || path.basename(lib) !== "lib") return null;
|
|
46
|
+
return path.dirname(lib);
|
|
47
|
+
}
|
|
48
|
+
var PS = ["/bin/ps", "/usr/bin/ps"].filter(function(p) {
|
|
49
|
+
try {
|
|
50
|
+
fs.accessSync(p, fs.constants.X_OK);
|
|
51
|
+
return true;
|
|
52
|
+
} catch (e) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
})[0] || "ps";
|
|
56
|
+
function processStart2(pid) {
|
|
57
|
+
try {
|
|
58
|
+
var env = {};
|
|
59
|
+
Object.keys(process.env).forEach(function(k) {
|
|
60
|
+
env[k] = process.env[k];
|
|
61
|
+
});
|
|
62
|
+
env.LC_ALL = "C";
|
|
63
|
+
env.TZ = "UTC";
|
|
64
|
+
var r = childProcess.spawnSync(PS, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 15e3, env, stdio: ["ignore", "pipe", "ignore"] });
|
|
65
|
+
var text = String(r.stdout || "").trim();
|
|
66
|
+
return r.status === 0 && text ? text : null;
|
|
67
|
+
} catch (e) {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function startTicks2(pid) {
|
|
72
|
+
if (process.platform !== "linux") return null;
|
|
73
|
+
var text;
|
|
74
|
+
try {
|
|
75
|
+
text = fs.readFileSync("/proc/" + pid + "/stat", "utf8");
|
|
76
|
+
} catch (e) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
var fields = text.slice(text.lastIndexOf(")") + 2).split(" ");
|
|
80
|
+
var ticks = fields[19];
|
|
81
|
+
return /^\d+$/.test(ticks || "") ? ticks : null;
|
|
82
|
+
}
|
|
83
|
+
function bootId2() {
|
|
84
|
+
var text;
|
|
85
|
+
try {
|
|
86
|
+
text = fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
|
|
87
|
+
} catch (e) {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
return /^[0-9a-f-]{36}$/.test(text) ? text : null;
|
|
91
|
+
}
|
|
92
|
+
var START_TOLERANCE_MS2 = 2e3;
|
|
93
|
+
function sameStartText2(recorded, seen) {
|
|
94
|
+
if (recorded === seen) return true;
|
|
95
|
+
var a = Date.parse(recorded + " UTC"), b = Date.parse(seen + " UTC");
|
|
96
|
+
return isFinite(a) && isFinite(b) && Math.abs(a - b) <= START_TOLERANCE_MS2;
|
|
97
|
+
}
|
|
98
|
+
function exists2(pid) {
|
|
99
|
+
try {
|
|
100
|
+
process.kill(pid, 0);
|
|
101
|
+
return true;
|
|
102
|
+
} catch (e) {
|
|
103
|
+
return e.code !== "ESRCH";
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function holderState2(lock, deps) {
|
|
107
|
+
var d = deps || {};
|
|
108
|
+
if (!(d.exists || exists2)(lock.pid)) return "stale";
|
|
109
|
+
if (typeof lock.startTicks === "string") {
|
|
110
|
+
var boot = (d.bootId || bootId2)();
|
|
111
|
+
if (boot === null || boot === void 0) return "unknown";
|
|
112
|
+
if (boot !== lock.bootId) return "stale";
|
|
113
|
+
var ticks = (d.startTicks || startTicks2)(lock.pid);
|
|
114
|
+
if (ticks === null || ticks === void 0) return "unknown";
|
|
115
|
+
return ticks === lock.startTicks ? "live" : "stale";
|
|
116
|
+
}
|
|
117
|
+
var seen = (d.processStart || processStart2)(lock.pid);
|
|
118
|
+
if (seen === null || seen === void 0) return "unknown";
|
|
119
|
+
return sameStartText2(lock.processStart, seen) ? "live" : "stale";
|
|
120
|
+
}
|
|
121
|
+
function parse(text) {
|
|
122
|
+
var r;
|
|
123
|
+
try {
|
|
124
|
+
r = JSON.parse(text);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
return r && typeof r === "object" && Number.isSafeInteger(r.pid) && r.pid > 0 && typeof r.processStart === "string" && r.processStart && typeof r.prefix === "string" && typeof r.token === "string" && /^[0-9a-f]{32,}$/.test(r.token) && typeof r.targetSpec === "string" && typeof r.agendHome === "string" && typeof r.createdAt === "string" && (r.startTicks === void 0 && r.bootId === void 0 || typeof r.startTicks === "string" && /^\d+$/.test(r.startTicks) && typeof r.bootId === "string" && /^[0-9a-f-]{36}$/.test(r.bootId)) ? r : null;
|
|
129
|
+
}
|
|
130
|
+
module2.exports = {
|
|
131
|
+
LOCK,
|
|
132
|
+
TOKEN_ENV,
|
|
133
|
+
globalPrefix,
|
|
134
|
+
processStart: processStart2,
|
|
135
|
+
startTicks: startTicks2,
|
|
136
|
+
bootId: bootId2,
|
|
137
|
+
sameStartText: sameStartText2,
|
|
138
|
+
START_TOLERANCE_MS: START_TOLERANCE_MS2,
|
|
139
|
+
exists: exists2,
|
|
140
|
+
holderState: holderState2,
|
|
141
|
+
parse
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// src/update-recovery/recover.ts
|
|
147
|
+
var import_node_child_process3 = require("node:child_process");
|
|
148
|
+
var import_node_crypto7 = require("node:crypto");
|
|
149
|
+
var import_node_path14 = require("node:path");
|
|
150
|
+
var import_install_admission = __toESM(require_install_admission(), 1);
|
|
151
|
+
|
|
152
|
+
// src/update-journal.ts
|
|
153
|
+
var import_node_fs2 = require("node:fs");
|
|
154
|
+
var import_node_path2 = require("node:path");
|
|
155
|
+
|
|
156
|
+
// src/install-lock.ts
|
|
157
|
+
var import_node_fs = require("node:fs");
|
|
158
|
+
var import_node_path = require("node:path");
|
|
159
|
+
var INSTALL_LOCK_FILE = ".agend-install.lock";
|
|
160
|
+
function parseInstallLock(text) {
|
|
161
|
+
let value;
|
|
162
|
+
try {
|
|
163
|
+
value = JSON.parse(text);
|
|
164
|
+
} catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
const r = value;
|
|
168
|
+
return r && Number.isSafeInteger(r.pid) && r.pid > 0 && typeof r.processStart === "string" && r.processStart && typeof r.prefix === "string" && typeof r.token === "string" && /^[0-9a-f]{32,}$/.test(r.token) && typeof r.targetSpec === "string" && typeof r.agendHome === "string" && typeof r.createdAt === "string" && (r.installPrefix === void 0 || typeof r.installPrefix === "string" && r.installPrefix !== "") && (r.startTicks === void 0 && r.bootId === void 0 || typeof r.startTicks === "string" && /^\d+$/.test(r.startTicks) && typeof r.bootId === "string" && /^[0-9a-f-]{36}$/.test(r.bootId)) ? r : null;
|
|
169
|
+
}
|
|
170
|
+
var pidExists = (pid) => {
|
|
171
|
+
try {
|
|
172
|
+
process.kill(pid, 0);
|
|
173
|
+
return true;
|
|
174
|
+
} catch (err) {
|
|
175
|
+
return err.code !== "ESRCH";
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
function holderState(record, deps) {
|
|
179
|
+
if (!(deps.exists ?? pidExists)(record.pid)) return "stale";
|
|
180
|
+
if (record.startTicks !== void 0) {
|
|
181
|
+
const boot = deps.bootId?.() ?? null;
|
|
182
|
+
if (boot === null) return "unknown";
|
|
183
|
+
if (boot !== record.bootId) return "stale";
|
|
184
|
+
const ticks = deps.startTicks?.(record.pid) ?? null;
|
|
185
|
+
if (ticks === null) return "unknown";
|
|
186
|
+
return ticks === record.startTicks ? "live" : "stale";
|
|
187
|
+
}
|
|
188
|
+
const seen = deps.processStart(record.pid);
|
|
189
|
+
if (seen === null) return "unknown";
|
|
190
|
+
return sameStartText(record.processStart, seen) ? "live" : "stale";
|
|
191
|
+
}
|
|
192
|
+
var START_TOLERANCE_MS = 2e3;
|
|
193
|
+
function sameStartText(recorded, seen) {
|
|
194
|
+
if (recorded === seen) return true;
|
|
195
|
+
const a = Date.parse(`${recorded} UTC`), b = Date.parse(`${seen} UTC`);
|
|
196
|
+
return Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= START_TOLERANCE_MS;
|
|
197
|
+
}
|
|
198
|
+
var readOrNull = (path) => {
|
|
199
|
+
try {
|
|
200
|
+
return (0, import_node_fs.readFileSync)(path, "utf8");
|
|
201
|
+
} catch {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
function acquireInstallLock(prefix, target, deps, opts = {}) {
|
|
206
|
+
const file = opts.file ?? INSTALL_LOCK_FILE, name = opts.name ?? "install lock";
|
|
207
|
+
let canonical;
|
|
208
|
+
try {
|
|
209
|
+
canonical = (0, import_node_fs.realpathSync)(prefix);
|
|
210
|
+
} catch {
|
|
211
|
+
return { ok: false, path: (0, import_node_path.join)(prefix, file), reason: `the ${opts.file ? "directory" : "npm prefix"} ${prefix} does not exist` };
|
|
212
|
+
}
|
|
213
|
+
const path = (0, import_node_path.join)(canonical, file);
|
|
214
|
+
const ownStart = deps.processStart(deps.pid);
|
|
215
|
+
if (!ownStart) return { ok: false, path, reason: "this process's own start time cannot be read, so its lock could not be told from a stale one" };
|
|
216
|
+
const ownTicks = deps.startTicks?.(deps.pid) ?? null;
|
|
217
|
+
const ownBoot = deps.bootId?.() ?? null;
|
|
218
|
+
const record = {
|
|
219
|
+
pid: deps.pid,
|
|
220
|
+
processStart: ownStart,
|
|
221
|
+
...ownTicks !== null && ownBoot !== null ? { startTicks: ownTicks, bootId: ownBoot } : {},
|
|
222
|
+
prefix: canonical,
|
|
223
|
+
targetSpec: target.spec,
|
|
224
|
+
agendHome: target.agendHome,
|
|
225
|
+
token: deps.newToken(),
|
|
226
|
+
createdAt: deps.now().toISOString(),
|
|
227
|
+
...target.installPrefix !== void 0 ? { installPrefix: target.installPrefix } : {}
|
|
228
|
+
};
|
|
229
|
+
const serialized = JSON.stringify(record) + "\n";
|
|
230
|
+
const claim = () => {
|
|
231
|
+
try {
|
|
232
|
+
(0, import_node_fs.writeFileSync)(path, serialized, { flag: "wx", mode: 384 });
|
|
233
|
+
return true;
|
|
234
|
+
} catch (err) {
|
|
235
|
+
if (err.code === "EEXIST") return false;
|
|
236
|
+
throw err;
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
const ours = { ok: true, path, token: record.token, release: () => releaseIfOurs(path, serialized, deps) };
|
|
240
|
+
try {
|
|
241
|
+
if (claim()) return ours;
|
|
242
|
+
} catch (err) {
|
|
243
|
+
return { ok: false, path, reason: `the ${name} ${path} could not be created (${err.message})` };
|
|
244
|
+
}
|
|
245
|
+
const seen = readOrNull(path);
|
|
246
|
+
if (seen === null) return { ok: false, path, reason: `another install is starting on ${canonical} (its lock ${path} appeared and went); retry` };
|
|
247
|
+
const holder = parseInstallLock(seen);
|
|
248
|
+
if (!holder) return { ok: false, path, reason: `the ${name} ${path} cannot be read as a lock; if no other \`agend update\` is running, remove it and retry` };
|
|
249
|
+
const state = holderState(holder, deps);
|
|
250
|
+
if (state === "live") {
|
|
251
|
+
return { ok: false, path, reason: `another AgEnD install is running on ${canonical} (pid ${holder.pid}, installing ${holder.targetSpec} for ${holder.agendHome}); wait for it to finish` };
|
|
252
|
+
}
|
|
253
|
+
if (state === "unknown") {
|
|
254
|
+
return { ok: false, path, reason: `whether the install that holds ${path} (pid ${holder.pid}) is still running cannot be told; retry, or remove the lock once no \`agend update\` runs` };
|
|
255
|
+
}
|
|
256
|
+
const marker = `${path}.reclaim`;
|
|
257
|
+
deps.afterStaleJudged?.();
|
|
258
|
+
try {
|
|
259
|
+
(0, import_node_fs.writeFileSync)(marker, serialized, { flag: "wx", mode: 384 });
|
|
260
|
+
} catch (err) {
|
|
261
|
+
if (err.code !== "EEXIST") return { ok: false, path, reason: `the reclaim marker ${marker} could not be created (${err.message})` };
|
|
262
|
+
const other = parseInstallLock(readOrNull(marker) ?? "");
|
|
263
|
+
const otherState = other ? holderState(other, deps) : "unknown";
|
|
264
|
+
return otherState === "live" ? { ok: false, path, reason: `another install is replacing the stale lock on ${canonical}; retry` } : { ok: false, path, reason: `a reclaim marker ${marker} was left behind (pid ${other?.pid ?? "unknown"}); if no \`agend update\` runs, remove it and retry` };
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
if (readOrNull(path) !== seen) return { ok: false, path, reason: `another install is starting on ${canonical}; retry` };
|
|
268
|
+
const aside = `${path}.stale-${deps.pid}-${record.token.slice(0, 8)}`;
|
|
269
|
+
try {
|
|
270
|
+
(0, import_node_fs.renameSync)(path, aside);
|
|
271
|
+
} catch {
|
|
272
|
+
return { ok: false, path, reason: `another install is starting on ${canonical}; retry` };
|
|
273
|
+
}
|
|
274
|
+
deps.afterStaleMoved?.();
|
|
275
|
+
if (readOrNull(aside) !== seen) {
|
|
276
|
+
try {
|
|
277
|
+
(0, import_node_fs.linkSync)(aside, path);
|
|
278
|
+
(0, import_node_fs.unlinkSync)(aside);
|
|
279
|
+
} catch {
|
|
280
|
+
deps.log(` \u26A0 A ${name} changed while it was being replaced; left at ${aside}.`);
|
|
281
|
+
}
|
|
282
|
+
return { ok: false, path, reason: `another install is starting on ${canonical}; retry` };
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
(0, import_node_fs.unlinkSync)(aside);
|
|
286
|
+
} catch {
|
|
287
|
+
}
|
|
288
|
+
deps.log(` Replaced a stale ${name} (pid ${holder.pid} is gone, was installing ${holder.targetSpec}).`);
|
|
289
|
+
try {
|
|
290
|
+
if (claim()) return ours;
|
|
291
|
+
} catch (err) {
|
|
292
|
+
return { ok: false, path, reason: `the ${name} ${path} could not be created (${err.message})` };
|
|
293
|
+
}
|
|
294
|
+
return { ok: false, path, reason: `another install is starting on ${canonical}; retry` };
|
|
295
|
+
} finally {
|
|
296
|
+
releaseIfOurs(marker, serialized, deps);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function releaseIfOurs(path, serialized, deps) {
|
|
300
|
+
if (readOrNull(path) !== serialized) return;
|
|
301
|
+
const aside = `${path}.release-${deps.pid}`;
|
|
302
|
+
try {
|
|
303
|
+
(0, import_node_fs.renameSync)(path, aside);
|
|
304
|
+
} catch {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (readOrNull(aside) === serialized) {
|
|
308
|
+
try {
|
|
309
|
+
(0, import_node_fs.unlinkSync)(aside);
|
|
310
|
+
} catch {
|
|
311
|
+
}
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
(0, import_node_fs.linkSync)(aside, path);
|
|
316
|
+
} catch {
|
|
317
|
+
deps.log(` \u26A0 The install lock changed while being released; left at ${aside}.`);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
(0, import_node_fs.unlinkSync)(aside);
|
|
322
|
+
} catch {
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// src/update-journal.ts
|
|
327
|
+
var TERMINAL = /* @__PURE__ */ new Set(["committed", "rolled-back", "abandoned", "manual-recovery"]);
|
|
328
|
+
var NEXT = {
|
|
329
|
+
opened: ["barrier", "abandoning"],
|
|
330
|
+
barrier: ["stopping", "abandoning"],
|
|
331
|
+
stopping: ["snapshotted", "abandoning"],
|
|
332
|
+
abandoning: ["abandoned"],
|
|
333
|
+
snapshotted: ["installing", "rolling-back"],
|
|
334
|
+
installing: ["trial", "rolling-back"],
|
|
335
|
+
trial: ["proving", "rolling-back"],
|
|
336
|
+
proving: ["committing", "rolling-back"],
|
|
337
|
+
committing: ["committed"],
|
|
338
|
+
"rolling-back": ["rolled-back"],
|
|
339
|
+
abandoned: [],
|
|
340
|
+
committed: [],
|
|
341
|
+
"rolled-back": [],
|
|
342
|
+
"manual-recovery": []
|
|
343
|
+
};
|
|
344
|
+
function canAdvance(from, to) {
|
|
345
|
+
if (TERMINAL.has(from)) return false;
|
|
346
|
+
return to === "manual-recovery" || NEXT[from].includes(to);
|
|
347
|
+
}
|
|
348
|
+
var fsyncDirReal = (dir) => {
|
|
349
|
+
const fd = (0, import_node_fs2.openSync)(dir, "r");
|
|
350
|
+
try {
|
|
351
|
+
(0, import_node_fs2.fsyncSync)(fd);
|
|
352
|
+
} finally {
|
|
353
|
+
(0, import_node_fs2.closeSync)(fd);
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
var defaultJournalIo = {
|
|
357
|
+
now: () => /* @__PURE__ */ new Date(),
|
|
358
|
+
writeSynced: (path, data) => {
|
|
359
|
+
const fd = (0, import_node_fs2.openSync)(path, "wx", 384);
|
|
360
|
+
try {
|
|
361
|
+
(0, import_node_fs2.writeSync)(fd, data);
|
|
362
|
+
(0, import_node_fs2.fsyncSync)(fd);
|
|
363
|
+
} finally {
|
|
364
|
+
(0, import_node_fs2.closeSync)(fd);
|
|
365
|
+
}
|
|
366
|
+
},
|
|
367
|
+
rename: (from, to) => (0, import_node_fs2.renameSync)(from, to),
|
|
368
|
+
link: (from, to) => (0, import_node_fs2.linkSync)(from, to),
|
|
369
|
+
unlink: (path) => (0, import_node_fs2.unlinkSync)(path),
|
|
370
|
+
mkdir: (path) => (0, import_node_fs2.mkdirSync)(path, { mode: 448 }),
|
|
371
|
+
fsyncDir: fsyncDirReal,
|
|
372
|
+
read: (path) => {
|
|
373
|
+
try {
|
|
374
|
+
return (0, import_node_fs2.readFileSync)(path, "utf8");
|
|
375
|
+
} catch (err) {
|
|
376
|
+
if (err.code === "ENOENT") return null;
|
|
377
|
+
throw err;
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
list: (path) => {
|
|
381
|
+
try {
|
|
382
|
+
return (0, import_node_fs2.readdirSync)(path);
|
|
383
|
+
} catch (err) {
|
|
384
|
+
if (err.code === "ENOENT") return [];
|
|
385
|
+
throw err;
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
step: () => {
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
var tmpSeq = 0;
|
|
392
|
+
var tmpOf = (path) => `${path}.tmp-${process.pid}-${Date.now().toString(36)}-${(tmpSeq++).toString(36)}`;
|
|
393
|
+
function writeAtomic(io, path, data) {
|
|
394
|
+
const tmp = tmpOf(path);
|
|
395
|
+
io.writeSynced(tmp, data);
|
|
396
|
+
io.step(`write:${(0, import_node_path2.basename)(tmp)}`);
|
|
397
|
+
io.rename(tmp, path);
|
|
398
|
+
io.step(`rename:${(0, import_node_path2.basename)(path)}`);
|
|
399
|
+
io.fsyncDir((0, import_node_path2.dirname)(path));
|
|
400
|
+
io.step(`fsync-dir:${(0, import_node_path2.basename)((0, import_node_path2.dirname)(path))}`);
|
|
401
|
+
}
|
|
402
|
+
function writeNew(io, path, data) {
|
|
403
|
+
const tmp = tmpOf(path);
|
|
404
|
+
io.writeSynced(tmp, data);
|
|
405
|
+
io.step(`write:${(0, import_node_path2.basename)(tmp)}`);
|
|
406
|
+
try {
|
|
407
|
+
io.link(tmp, path);
|
|
408
|
+
} catch (err) {
|
|
409
|
+
try {
|
|
410
|
+
io.unlink(tmp);
|
|
411
|
+
} catch {
|
|
412
|
+
}
|
|
413
|
+
if (err.code !== "EEXIST") throw err;
|
|
414
|
+
if (io.read(path) !== data) throw new Error(`${path} already exists with other content; the original is kept`);
|
|
415
|
+
io.fsyncDir((0, import_node_path2.dirname)(path));
|
|
416
|
+
io.step(`fsync-dir:${(0, import_node_path2.basename)((0, import_node_path2.dirname)(path))}`);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
io.step(`link:${(0, import_node_path2.basename)(path)}`);
|
|
420
|
+
io.unlink(tmp);
|
|
421
|
+
io.fsyncDir((0, import_node_path2.dirname)(path));
|
|
422
|
+
io.step(`fsync-dir:${(0, import_node_path2.basename)((0, import_node_path2.dirname)(path))}`);
|
|
423
|
+
}
|
|
424
|
+
function renameDurable(io, from, to) {
|
|
425
|
+
io.rename(from, to);
|
|
426
|
+
io.step(`rename:${(0, import_node_path2.basename)(to)}`);
|
|
427
|
+
io.fsyncDir((0, import_node_path2.dirname)(to));
|
|
428
|
+
io.step(`fsync-dir:${(0, import_node_path2.basename)((0, import_node_path2.dirname)(to))}`);
|
|
429
|
+
if ((0, import_node_path2.dirname)(from) !== (0, import_node_path2.dirname)(to)) {
|
|
430
|
+
io.fsyncDir((0, import_node_path2.dirname)(from));
|
|
431
|
+
io.step(`fsync-dir:${(0, import_node_path2.basename)((0, import_node_path2.dirname)(from))}`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
function mkdirDurable(io, base2, path, exclusive = false) {
|
|
435
|
+
const root = base2.replace(/\/+$/, "");
|
|
436
|
+
const rel = path.slice(root.length).split("/").filter(Boolean);
|
|
437
|
+
if (!path.startsWith(root + "/") || rel.length === 0) throw new Error(`${path} is not below ${base2}`);
|
|
438
|
+
let dir = root;
|
|
439
|
+
rel.forEach((part, i) => {
|
|
440
|
+
dir = (0, import_node_path2.join)(dir, part);
|
|
441
|
+
const last = i === rel.length - 1;
|
|
442
|
+
try {
|
|
443
|
+
io.mkdir(dir);
|
|
444
|
+
io.step(`mkdir:${part}`);
|
|
445
|
+
} catch (err) {
|
|
446
|
+
if (err.code !== "EEXIST") throw err;
|
|
447
|
+
if (last && exclusive) throw new Error(`${dir} already exists; an attempt's directory is never reused`);
|
|
448
|
+
}
|
|
449
|
+
io.fsyncDir((0, import_node_path2.dirname)(dir));
|
|
450
|
+
io.step(`fsync-dir:${(0, import_node_path2.basename)((0, import_node_path2.dirname)(dir))}`);
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
var journalDir = (home2) => (0, import_node_path2.join)(home2, ".update-journal");
|
|
454
|
+
var currentPath = (home2) => (0, import_node_path2.join)(journalDir(home2), "current");
|
|
455
|
+
var attemptDir = (home2, id) => (0, import_node_path2.join)(journalDir(home2), "attempts", id);
|
|
456
|
+
var recordPath = (home2, id) => (0, import_node_path2.join)(attemptDir(home2, id), "attempt.json");
|
|
457
|
+
var marksPath = (home2) => (0, import_node_path2.join)(journalDir(home2), "marks.json");
|
|
458
|
+
var ID = /^\d{8}T\d{6}Z-[0-9a-f]{8}$/;
|
|
459
|
+
var isAttemptId = (v) => ID.test(v);
|
|
460
|
+
var STAGES = new Set(Object.keys(NEXT));
|
|
461
|
+
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
462
|
+
var nonEmpty = (v) => typeof v === "string" && v.length > 0;
|
|
463
|
+
var isTime = (v) => nonEmpty(v) && Number.isFinite(Date.parse(v));
|
|
464
|
+
var isPid = (v) => Number.isSafeInteger(v) && v > 0;
|
|
465
|
+
var isArtifact = (v) => isObj(v) && nonEmpty(v.name) && nonEmpty(v.version) && (v.integrity === null || nonEmpty(v.integrity));
|
|
466
|
+
var isStart = (v) => isObj(v) && nonEmpty(v.processStart) && (v.startTicks === void 0 || typeof v.startTicks === "string" && /^\d+$/.test(v.startTicks)) && (v.bootId === void 0 || nonEmpty(v.bootId));
|
|
467
|
+
function parseRecord(text, id) {
|
|
468
|
+
let r;
|
|
469
|
+
try {
|
|
470
|
+
r = JSON.parse(text);
|
|
471
|
+
} catch {
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
if (!isObj(r) || r.schema !== 1 || r.id !== id || !(r.kind === "update" || r.kind === "go-back") || !isTime(r.createdAt)) return null;
|
|
475
|
+
if (!isObj(r.updater) || !isPid(r.updater.pid) || !isStart(r.updater.start) || !isArtifact(r.from) || !isArtifact(r.to)) return null;
|
|
476
|
+
const stage = r.stage;
|
|
477
|
+
if (!STAGES.has(stage) || r.substep !== void 0 && !nonEmpty(r.substep)) return null;
|
|
478
|
+
if (r.goBackOf !== void 0 && !(typeof r.goBackOf === "string" && ID.test(r.goBackOf))) return null;
|
|
479
|
+
if (r.kind === "go-back" && r.goBackOf === void 0) return null;
|
|
480
|
+
const h = r.history;
|
|
481
|
+
if (!Array.isArray(h) || h.length === 0 || h[0]?.stage !== "opened") return null;
|
|
482
|
+
for (const e of h) {
|
|
483
|
+
if (!isObj(e) || !STAGES.has(e.stage) || !isTime(e.at) || e.substep !== void 0 && !nonEmpty(e.substep) || e.note !== void 0 && typeof e.note !== "string") return null;
|
|
484
|
+
}
|
|
485
|
+
if (h[h.length - 1].stage !== stage) return null;
|
|
486
|
+
const terminal = TERMINAL.has(stage);
|
|
487
|
+
if (terminal !== (r.outcome !== void 0)) return null;
|
|
488
|
+
if (terminal) {
|
|
489
|
+
const o = r.outcome;
|
|
490
|
+
if (!isObj(o) || o.kind !== stage || !isTime(o.at) || o.reason !== void 0 && typeof o.reason !== "string") return null;
|
|
491
|
+
}
|
|
492
|
+
return r;
|
|
493
|
+
}
|
|
494
|
+
function readCurrent(home2, io = defaultJournalIo) {
|
|
495
|
+
let text;
|
|
496
|
+
try {
|
|
497
|
+
text = io.read(currentPath(home2));
|
|
498
|
+
} catch (err) {
|
|
499
|
+
return { state: "unknown", reason: `current can't be read (${err.message})`, path: currentPath(home2) };
|
|
500
|
+
}
|
|
501
|
+
if (text === null) return { state: "none" };
|
|
502
|
+
const id = text.trim();
|
|
503
|
+
if (!ID.test(id)) return { state: "unknown", reason: "current names no attempt", path: currentPath(home2) };
|
|
504
|
+
let body;
|
|
505
|
+
try {
|
|
506
|
+
body = io.read(recordPath(home2, id));
|
|
507
|
+
} catch (err) {
|
|
508
|
+
return { state: "unknown", reason: `the attempt record can't be read (${err.message})`, path: recordPath(home2, id) };
|
|
509
|
+
}
|
|
510
|
+
if (body === null) return { state: "unknown", reason: "current names an attempt with no record", path: recordPath(home2, id) };
|
|
511
|
+
const attempt = parseRecord(body, id);
|
|
512
|
+
if (!attempt) return { state: "unknown", reason: "the attempt record isn't valid", path: recordPath(home2, id) };
|
|
513
|
+
if (attempt.stage === "manual-recovery") return { state: "manual", attempt };
|
|
514
|
+
if (TERMINAL.has(attempt.stage)) return { state: "closing", attempt };
|
|
515
|
+
return { state: "open", attempt };
|
|
516
|
+
}
|
|
517
|
+
function finishClosing(home2, attempt, io = defaultJournalIo) {
|
|
518
|
+
if (!TERMINAL.has(attempt.stage) || attempt.stage === "manual-recovery") throw new Error(`attempt ${attempt.id} is not closing`);
|
|
519
|
+
renameDurable(io, currentPath(home2), (0, import_node_path2.join)(attemptDir(home2, attempt.id), "current.closed"));
|
|
520
|
+
io.step("current-cleared");
|
|
521
|
+
}
|
|
522
|
+
function write(home2, attempt, io, step) {
|
|
523
|
+
writeAtomic(io, recordPath(home2, attempt.id), JSON.stringify(attempt, null, 2) + "\n");
|
|
524
|
+
io.step(step);
|
|
525
|
+
}
|
|
526
|
+
function advance(home2, attempt, to, opts = {}, io = defaultJournalIo) {
|
|
527
|
+
if (TERMINAL.has(to)) throw new Error(`a terminal stage (${to}) is written by finish()`);
|
|
528
|
+
if (!canAdvance(attempt.stage, to)) throw new Error(`attempt ${attempt.id}: ${attempt.stage} \u2192 ${to} is not allowed`);
|
|
529
|
+
const at = io.now().toISOString();
|
|
530
|
+
const next = { ...attempt, stage: to, history: [...attempt.history, { stage: to, at, ...opts.substep ? { substep: opts.substep } : {}, ...opts.note ? { note: opts.note } : {} }] };
|
|
531
|
+
if (opts.substep) next.substep = opts.substep;
|
|
532
|
+
else delete next.substep;
|
|
533
|
+
write(home2, next, io, `stage-${to}`);
|
|
534
|
+
return next;
|
|
535
|
+
}
|
|
536
|
+
function substep(home2, attempt, name, io = defaultJournalIo) {
|
|
537
|
+
if (TERMINAL.has(attempt.stage)) throw new Error(`attempt ${attempt.id} is ${attempt.stage}`);
|
|
538
|
+
const next = { ...attempt, substep: name, history: [...attempt.history, { stage: attempt.stage, substep: name, at: io.now().toISOString() }] };
|
|
539
|
+
write(home2, next, io, `substep-${name}`);
|
|
540
|
+
return next;
|
|
541
|
+
}
|
|
542
|
+
function finish(home2, attempt, outcome, io = defaultJournalIo) {
|
|
543
|
+
const to = outcome.kind;
|
|
544
|
+
const allowed = to === "manual-recovery" ? !TERMINAL.has(attempt.stage) : to === "abandoned" && attempt.stage === "abandoning" || to === "rolled-back" && attempt.stage === "rolling-back" || to === "committed" && attempt.stage === "committing";
|
|
545
|
+
if (!allowed) throw new Error(`attempt ${attempt.id}: ${attempt.stage} \u2192 ${to} is not allowed`);
|
|
546
|
+
if (outcome.kind === "rolled-back") appendMark(home2, { version: attempt.to.version, integrity: attempt.to.integrity, attemptId: attempt.id }, io);
|
|
547
|
+
const at = io.now().toISOString();
|
|
548
|
+
const next = {
|
|
549
|
+
...attempt,
|
|
550
|
+
stage: to,
|
|
551
|
+
history: [...attempt.history, { stage: to, at, ...outcome.reason ? { note: outcome.reason } : {} }],
|
|
552
|
+
outcome: { kind: outcome.kind, ...outcome.reason ? { reason: outcome.reason } : {}, at }
|
|
553
|
+
};
|
|
554
|
+
delete next.substep;
|
|
555
|
+
write(home2, next, io, `terminal-${to}`);
|
|
556
|
+
if (to !== "manual-recovery") finishClosing(home2, next, io);
|
|
557
|
+
return next;
|
|
558
|
+
}
|
|
559
|
+
function readMarks(home2, io = defaultJournalIo) {
|
|
560
|
+
let text;
|
|
561
|
+
try {
|
|
562
|
+
text = io.read(marksPath(home2));
|
|
563
|
+
} catch (err) {
|
|
564
|
+
return { ok: false, reason: err.message };
|
|
565
|
+
}
|
|
566
|
+
if (text === null) return { ok: true, marks: [] };
|
|
567
|
+
try {
|
|
568
|
+
const v = JSON.parse(text);
|
|
569
|
+
const valid = (m) => isObj(m) && nonEmpty(m.version) && (m.integrity === null || nonEmpty(m.integrity)) && typeof m.attemptId === "string" && ID.test(m.attemptId) && isTime(m.at);
|
|
570
|
+
if (!Array.isArray(v) || !v.every(valid)) return { ok: false, reason: "marks.json isn't a list of valid marks" };
|
|
571
|
+
return { ok: true, marks: v };
|
|
572
|
+
} catch {
|
|
573
|
+
return { ok: false, reason: "marks.json isn't JSON" };
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
function appendMark(home2, mark, io = defaultJournalIo) {
|
|
577
|
+
const read = readMarks(home2, io);
|
|
578
|
+
if (!read.ok) throw new Error(`marks.json can't be read, so no mark is written over it: ${read.reason}`);
|
|
579
|
+
const landed = read.marks.find((m) => m.attemptId === mark.attemptId);
|
|
580
|
+
if (landed) {
|
|
581
|
+
if (landed.version !== mark.version || landed.integrity !== mark.integrity) throw new Error(`marks.json holds another mark for attempt ${mark.attemptId}`);
|
|
582
|
+
io.fsyncDir(journalDir(home2));
|
|
583
|
+
io.step(`fsync-dir:${(0, import_node_path2.basename)(journalDir(home2))}`);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
mkdirDurable(io, home2, journalDir(home2));
|
|
587
|
+
writeAtomic(io, marksPath(home2), JSON.stringify([...read.marks, { ...mark, at: mark.at ?? io.now().toISOString() }], null, 2) + "\n");
|
|
588
|
+
io.step("mark-written");
|
|
589
|
+
}
|
|
590
|
+
function recoveryPlan(read, updater, ownStart = false) {
|
|
591
|
+
switch (read.state) {
|
|
592
|
+
case "none":
|
|
593
|
+
return { kind: "start" };
|
|
594
|
+
case "unknown":
|
|
595
|
+
return { kind: "refuse", reason: "unknown" };
|
|
596
|
+
case "manual":
|
|
597
|
+
return { kind: "refuse", reason: "manual", attemptId: read.attempt.id, stage: read.attempt.stage };
|
|
598
|
+
case "closing":
|
|
599
|
+
return { kind: "finish-closing", attemptId: read.attempt.id };
|
|
600
|
+
}
|
|
601
|
+
const a = read.attempt;
|
|
602
|
+
if (updater === "live") return ownStart ? { kind: "start" } : { kind: "refuse", reason: "in-progress", attemptId: a.id, stage: a.stage };
|
|
603
|
+
if (updater === "unknown") return { kind: "refuse", reason: "updater-unknown", attemptId: a.id, stage: a.stage };
|
|
604
|
+
const sub = a.substep ? { substep: a.substep } : {};
|
|
605
|
+
switch (a.stage) {
|
|
606
|
+
case "opened":
|
|
607
|
+
case "barrier":
|
|
608
|
+
case "stopping":
|
|
609
|
+
case "abandoning":
|
|
610
|
+
return { kind: "resume-abandoning", attemptId: a.id, ...sub };
|
|
611
|
+
case "snapshotted":
|
|
612
|
+
case "installing":
|
|
613
|
+
case "trial":
|
|
614
|
+
case "proving":
|
|
615
|
+
case "rolling-back":
|
|
616
|
+
return { kind: "resume-rolling-back", attemptId: a.id, ...sub };
|
|
617
|
+
case "committing":
|
|
618
|
+
return { kind: "resume-committing", attemptId: a.id, ...sub };
|
|
619
|
+
default:
|
|
620
|
+
return { kind: "refuse", reason: "unknown" };
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
var generationsOf = (a) => Array.isArray(a.fleets) ? a.fleets : [];
|
|
624
|
+
function planGeneration(home2, attempt, gen, nonce, io = defaultJournalIo) {
|
|
625
|
+
if (!/^[0-9a-f]{32}$/.test(nonce)) throw new Error("a handoff nonce is 32 hex digits");
|
|
626
|
+
if (generationsOf(attempt).some((g) => g.nonce === nonce)) throw new Error("a nonce is never reused");
|
|
627
|
+
const fleets = [...generationsOf(attempt), { gen, nonce, plannedAt: io.now().toISOString() }];
|
|
628
|
+
return substep(home2, { ...attempt, fleets }, "start-planned", io);
|
|
629
|
+
}
|
|
630
|
+
function ackGeneration(home2, attempt, nonce, pid, opts = {}, io = defaultJournalIo) {
|
|
631
|
+
if (!isPid(pid)) throw new Error("a generation's pid is a positive integer");
|
|
632
|
+
const fleets = generationsOf(attempt).map((g) => g.nonce === nonce ? { ...g, pid, consumed: true, ...opts.dead ? { dead: true } : {} } : g);
|
|
633
|
+
if (!fleets.some((g) => g.nonce === nonce)) throw new Error("no generation was planned with that nonce");
|
|
634
|
+
return substep(home2, { ...attempt, fleets }, opts.dead ? "start-dead" : "start-acknowledged", io);
|
|
635
|
+
}
|
|
636
|
+
var startOf = (pid, start) => ({ pid, processStart: start.processStart, ...start.startTicks !== void 0 ? { startTicks: start.startTicks, bootId: start.bootId } : {} });
|
|
637
|
+
function updaterState(attempt, deps) {
|
|
638
|
+
const state = holderState(startOf(attempt.updater.pid, attempt.updater.start), deps);
|
|
639
|
+
return state === "stale" ? "gone" : state;
|
|
640
|
+
}
|
|
641
|
+
var RUNNER_FILE = "runner.json";
|
|
642
|
+
var runnerPath = (home2, id) => (0, import_node_path2.join)(attemptDir(home2, id), RUNNER_FILE);
|
|
643
|
+
function writeRunnerRecord(home2, attemptId, runner, io = defaultJournalIo) {
|
|
644
|
+
if (!isPid(runner.pid) || !isStart(runner.start)) throw new Error("a runner record needs a pid and a start");
|
|
645
|
+
writeAtomic(io, runnerPath(home2, attemptId), JSON.stringify({ pid: runner.pid, start: runner.start }) + "\n");
|
|
646
|
+
}
|
|
647
|
+
function readRunnerRecord(home2, attemptId, io = defaultJournalIo) {
|
|
648
|
+
let text;
|
|
649
|
+
try {
|
|
650
|
+
text = io.read(runnerPath(home2, attemptId));
|
|
651
|
+
} catch {
|
|
652
|
+
return "unreadable";
|
|
653
|
+
}
|
|
654
|
+
if (text === null) return null;
|
|
655
|
+
try {
|
|
656
|
+
const r = JSON.parse(text);
|
|
657
|
+
return isObj(r) && isPid(r.pid) && isStart(r.start) ? { pid: r.pid, start: r.start } : "unreadable";
|
|
658
|
+
} catch {
|
|
659
|
+
return "unreadable";
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
function ownerState(home2, attempt, deps, io = defaultJournalIo) {
|
|
663
|
+
const updater = updaterState(attempt, deps);
|
|
664
|
+
const record = readRunnerRecord(home2, attempt.id, io);
|
|
665
|
+
const runner = record === null ? "gone" : record === "unreadable" ? "unknown" : /* @__PURE__ */ ((s) => s === "stale" ? "gone" : s)(holderState(startOf(record.pid, record.start), deps));
|
|
666
|
+
if (updater === "unknown" || runner === "unknown") return "unknown";
|
|
667
|
+
if (updater === "live" || runner === "live") return "live";
|
|
668
|
+
return "gone";
|
|
669
|
+
}
|
|
670
|
+
function revokeHandoff(home2, attemptId, nonce, updater, liveness, io = defaultJournalIo) {
|
|
671
|
+
if (!/^[0-9a-f]{32}$/.test(nonce)) throw new Error("a handoff nonce is 32 hex digits");
|
|
672
|
+
const path = (0, import_node_path2.join)(attemptDir(home2, attemptId), `handoff-${nonce}.claim`);
|
|
673
|
+
try {
|
|
674
|
+
writeNew(io, path, JSON.stringify({ revokedBy: updater.pid, start: updater.start }) + "\n");
|
|
675
|
+
return "revoked";
|
|
676
|
+
} catch {
|
|
677
|
+
}
|
|
678
|
+
try {
|
|
679
|
+
const claim = JSON.parse(io.read(path) ?? "null");
|
|
680
|
+
if (!isObj(claim) || !isPid(claim.pid) || !isStart(claim.start)) return "claimant-unknown";
|
|
681
|
+
const state = holderState(startOf(claim.pid, claim.start), liveness);
|
|
682
|
+
return state === "stale" ? "claimant-gone" : state === "live" ? "claimed-live" : "claimant-unknown";
|
|
683
|
+
} catch {
|
|
684
|
+
return "claimant-unknown";
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
function voidGeneration(home2, attempt, nonce, io = defaultJournalIo) {
|
|
688
|
+
const fleets = generationsOf(attempt).map((g) => g.nonce === nonce ? { ...g, consumed: true, dead: true } : g);
|
|
689
|
+
return substep(home2, { ...attempt, fleets }, "start-voided", io);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// src/update-recovery/pre-start.ts
|
|
693
|
+
var import_node_path3 = require("node:path");
|
|
694
|
+
var HANDOFF_ENV = "handoff.env";
|
|
695
|
+
var handoffEnvPath = (home2, attemptId) => (0, import_node_path3.join)(attemptDir(home2, attemptId), HANDOFF_ENV);
|
|
696
|
+
var kitDir = (home2, attemptId) => (0, import_node_path3.join)(journalDir(home2), "recovery", attemptId);
|
|
697
|
+
var shellWord = (word) => /^[A-Za-z0-9_./:=@%+,-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
|
|
698
|
+
function operatorCommand(home2, attemptId) {
|
|
699
|
+
const kit = kitDir(home2, attemptId);
|
|
700
|
+
return [(0, import_node_path3.join)(kit, "node"), (0, import_node_path3.join)(kit, "recover.cjs"), "--home", home2, "--attempt", attemptId, "--run"].map(shellWord).join(" ");
|
|
701
|
+
}
|
|
702
|
+
function plannedForStart(attempt) {
|
|
703
|
+
const fleets = Array.isArray(attempt.fleets) ? attempt.fleets : [];
|
|
704
|
+
for (let i = fleets.length - 1; i >= 0; i--) {
|
|
705
|
+
const g = fleets[i];
|
|
706
|
+
if (!g.consumed && !g.dead && g.pid === void 0) return g;
|
|
707
|
+
}
|
|
708
|
+
return null;
|
|
709
|
+
}
|
|
710
|
+
function preStartDecision(home2, read, owner, routeAttempt) {
|
|
711
|
+
switch (read.state) {
|
|
712
|
+
case "none":
|
|
713
|
+
case "closing":
|
|
714
|
+
return { kind: "start" };
|
|
715
|
+
case "unknown":
|
|
716
|
+
return { kind: "refuse", reason: `AgEnD's update journal can't be read (${read.reason}: ${read.path}). This start is refused; run \`agend update --resolve\`.` };
|
|
717
|
+
case "manual":
|
|
718
|
+
return { kind: "refuse", reason: `Update attempt ${read.attempt.id} needs manual recovery. This start is refused; run ${operatorCommand(home2, read.attempt.id)}` };
|
|
719
|
+
}
|
|
720
|
+
const a = read.attempt;
|
|
721
|
+
if (a.id !== routeAttempt) return { kind: "refuse", reason: `AgEnD's update route on this service names attempt ${routeAttempt}, but attempt ${a.id} is open (${a.stage}). This start is refused; run ${operatorCommand(home2, a.id)}` };
|
|
722
|
+
if (owner === "unknown") return { kind: "refuse", reason: `Update attempt ${a.id} (${a.stage}): whether its updater still runs can't be told. This start is refused; if no update is running, run ${operatorCommand(home2, a.id)}` };
|
|
723
|
+
if (owner === "gone") return a.stage === "committing" ? { kind: "start" } : { kind: "start-runner", attemptId: a.id, stage: a.stage };
|
|
724
|
+
const planned = plannedForStart(a);
|
|
725
|
+
if (planned) return { kind: "handoff", attemptId: a.id, nonce: planned.nonce };
|
|
726
|
+
return { kind: "refuse", reason: `AgEnD is updating (attempt ${a.id}, ${a.stage}); this start is refused. The update owns the service until it ends.` };
|
|
727
|
+
}
|
|
728
|
+
function applyHandoffEnv(home2, decision, routeAttempt, io = defaultJournalIo) {
|
|
729
|
+
if (decision.kind === "handoff") {
|
|
730
|
+
if (decision.attemptId !== routeAttempt) throw new Error(`a handoff for attempt ${decision.attemptId} can't go through attempt ${routeAttempt}'s route`);
|
|
731
|
+
const path = handoffEnvPath(home2, decision.attemptId);
|
|
732
|
+
const tmp = `${path}.tmp-${process.pid}`;
|
|
733
|
+
try {
|
|
734
|
+
io.unlink(tmp);
|
|
735
|
+
} catch {
|
|
736
|
+
}
|
|
737
|
+
io.writeSynced(tmp, `AGEND_UPDATE_HANDOFF=${decision.nonce}
|
|
738
|
+
`);
|
|
739
|
+
io.rename(tmp, path);
|
|
740
|
+
io.fsyncDir(attemptDir(home2, decision.attemptId));
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
const absent = (err) => ["ENOENT", "ENOTDIR"].includes(err.code ?? "");
|
|
744
|
+
try {
|
|
745
|
+
io.unlink(handoffEnvPath(home2, routeAttempt));
|
|
746
|
+
} catch (err) {
|
|
747
|
+
if (!absent(err)) throw err;
|
|
748
|
+
}
|
|
749
|
+
try {
|
|
750
|
+
io.fsyncDir(attemptDir(home2, routeAttempt));
|
|
751
|
+
} catch (err) {
|
|
752
|
+
if (!absent(err)) throw err;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// src/update-recovery/runner.ts
|
|
757
|
+
var import_node_path12 = require("node:path");
|
|
758
|
+
|
|
759
|
+
// src/home-update-lock.ts
|
|
760
|
+
var import_node_path4 = require("node:path");
|
|
761
|
+
var import_node_fs3 = require("node:fs");
|
|
762
|
+
var HOME_UPDATE_LOCK_FILE = ".update.lock";
|
|
763
|
+
|
|
764
|
+
// src/install-ownership.ts
|
|
765
|
+
var import_node_fs4 = require("node:fs");
|
|
766
|
+
var import_node_path5 = require("node:path");
|
|
767
|
+
var BIN_NAMES = ["agend", "agend-agent"];
|
|
768
|
+
var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
769
|
+
var nonEmpty2 = (v) => typeof v === "string" && v.length > 0;
|
|
770
|
+
var strOrNull = (v) => v === null || nonEmpty2(v);
|
|
771
|
+
var argvOrNull = (v) => v === null || Array.isArray(v) && v.length > 0 && v.every((x) => typeof x === "string");
|
|
772
|
+
function validOwnership(v) {
|
|
773
|
+
if (!isObj2(v) || !Number.isSafeInteger(v.uid) || v.uid < 0 || !nonEmpty2(v.home) || !nonEmpty2(v.prefix) || !nonEmpty2(v.packagePath)) return false;
|
|
774
|
+
const links = v.binLinks;
|
|
775
|
+
if (!isObj2(links) || !BIN_NAMES.every((name) => nonEmpty2(links[name])) || Object.keys(links).length !== BIN_NAMES.length) return false;
|
|
776
|
+
if (v.service === null) return true;
|
|
777
|
+
const s = v.service;
|
|
778
|
+
return isObj2(s) && (s.kind === "systemd" || s.kind === "launchd") && nonEmpty2(s.unit) && nonEmpty2(s.fragmentPath);
|
|
779
|
+
}
|
|
780
|
+
function validTuple(v) {
|
|
781
|
+
if (!isObj2(v) || !nonEmpty2(v.version) || !strOrNull(v.integrity) || !nonEmpty2(v.entry) || !nonEmpty2(v.interpreter) || !argvOrNull(v.execStart)) return false;
|
|
782
|
+
const bins = v.bins;
|
|
783
|
+
return isObj2(bins) && BIN_NAMES.every((name) => strOrNull(bins[name])) && Object.keys(bins).every((k) => BIN_NAMES.includes(k));
|
|
784
|
+
}
|
|
785
|
+
function validIntent(v) {
|
|
786
|
+
if (!isObj2(v) || !isObj2(v.preimage) || !nonEmpty2(v.preimage.dir) || !/^[0-9a-f]{64}$/.test(String(v.preimage.manifestSha256))) return false;
|
|
787
|
+
const d = v.destination, t = v.target;
|
|
788
|
+
if (!isObj2(d) || !nonEmpty2(d.packagePath) || !Array.isArray(d.binLinks) || !d.binLinks.every(nonEmpty2)) return false;
|
|
789
|
+
if (!isObj2(t) || !nonEmpty2(t.name) || !nonEmpty2(t.version) || !strOrNull(t.integrity)) return false;
|
|
790
|
+
return Array.isArray(v.command) && v.command.length > 0 && v.command.every((x) => typeof x === "string");
|
|
791
|
+
}
|
|
792
|
+
function identityOf(attempt) {
|
|
793
|
+
const expected = attempt.expected;
|
|
794
|
+
if (!validOwnership(attempt.ownership) || !isObj2(expected) || !validTuple(expected.old)) return null;
|
|
795
|
+
if (expected.new !== void 0 && !validTuple(expected.new)) return null;
|
|
796
|
+
if (attempt.intent !== void 0 && !validIntent(attempt.intent)) return null;
|
|
797
|
+
return { ownership: attempt.ownership, expected: { old: expected.old, ...expected.new ? { new: expected.new } : {} }, ...attempt.intent ? { intent: attempt.intent } : {} };
|
|
798
|
+
}
|
|
799
|
+
function stopTarget(attempt, lock, mainPid) {
|
|
800
|
+
const want = attempt.stage === "stopping" ? "old" : attempt.stage === "rolling-back" ? "trial" : null;
|
|
801
|
+
if (!want) return { ok: false, reason: `no fleet is stopped in ${attempt.stage}` };
|
|
802
|
+
if (!lock) return { ok: false, reason: "fleet.lock names no holder" };
|
|
803
|
+
const fleets = Array.isArray(attempt.fleets) ? attempt.fleets : [];
|
|
804
|
+
const gen = fleets.find((g) => g.nonce === lock.nonce);
|
|
805
|
+
if (!gen || gen.pid !== lock.pid) return { ok: false, reason: `fleet.lock's holder (pid ${lock.pid}) is no recorded generation` };
|
|
806
|
+
if (gen.gen !== want) return { ok: false, reason: `fleet.lock's holder is generation ${gen.gen}, not ${want}` };
|
|
807
|
+
const id = identityOf(attempt);
|
|
808
|
+
if (!id) return { ok: false, reason: "the attempt's recorded ownership is missing or malformed" };
|
|
809
|
+
if (id.ownership.service) {
|
|
810
|
+
if (mainPid === null) return { ok: false, reason: `the service ${id.ownership.service.unit}'s MainPID can't be read` };
|
|
811
|
+
if (mainPid !== lock.pid) return { ok: false, reason: `the service's MainPID ${mainPid} matches no recorded generation` };
|
|
812
|
+
} else if (mainPid !== null) return { ok: false, reason: `a detached attempt has no service, yet a MainPID ${mainPid} was given` };
|
|
813
|
+
return { ok: true, generation: gen };
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// src/update-rollback.ts
|
|
817
|
+
var import_node_crypto6 = require("node:crypto");
|
|
818
|
+
|
|
819
|
+
// src/agend-home.ts
|
|
820
|
+
var import_node_module = require("node:module");
|
|
821
|
+
var import_node_worker_threads = require("node:worker_threads");
|
|
822
|
+
|
|
823
|
+
// src/fleet-lock.ts
|
|
824
|
+
var import_node_fs5 = require("node:fs");
|
|
825
|
+
var import_node_child_process = require("node:child_process");
|
|
826
|
+
var import_node_crypto = require("node:crypto");
|
|
827
|
+
var import_node_path6 = require("node:path");
|
|
828
|
+
function processAlive(pid) {
|
|
829
|
+
try {
|
|
830
|
+
process.kill(pid, 0);
|
|
831
|
+
return true;
|
|
832
|
+
} catch {
|
|
833
|
+
return false;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
function parseRecord2(raw) {
|
|
837
|
+
try {
|
|
838
|
+
const value = JSON.parse(raw);
|
|
839
|
+
if (!Number.isSafeInteger(value.pid) || (value.pid ?? 0) <= 1 || typeof value.nonce !== "string") {
|
|
840
|
+
return null;
|
|
841
|
+
}
|
|
842
|
+
if (value.role === "update" && (typeof value.attemptId !== "string" || !value.attemptId)) return null;
|
|
843
|
+
if (value.handoff != null && (typeof value.handoff.nonce !== "string" || !/^[0-9a-f]{32}$/.test(value.handoff.nonce) || !["old", "trial", "rollback"].includes(value.handoff.gen))) return null;
|
|
844
|
+
return value;
|
|
845
|
+
} catch {
|
|
846
|
+
return null;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
var fsyncDir = (dir) => {
|
|
850
|
+
const fd = (0, import_node_fs5.openSync)(dir, "r");
|
|
851
|
+
try {
|
|
852
|
+
(0, import_node_fs5.fsyncSync)(fd);
|
|
853
|
+
} finally {
|
|
854
|
+
(0, import_node_fs5.closeSync)(fd);
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
function setFleetLockHandoff(handle, handoff, revoke) {
|
|
858
|
+
if (handle.record.role !== "update") throw new Error("only an update fence plans a handoff");
|
|
859
|
+
if (handoff && !/^[0-9a-f]{32}$/.test(handoff.nonce)) throw new Error("a handoff nonce is 32 hex digits");
|
|
860
|
+
const planned = handle.record.handoff;
|
|
861
|
+
if (planned) {
|
|
862
|
+
if (!revoke) throw new Error("a planned handoff is replaced only after its nonce is revoked");
|
|
863
|
+
if (!revoke(handle.record.attemptId, planned.nonce)) return null;
|
|
864
|
+
}
|
|
865
|
+
let current;
|
|
866
|
+
try {
|
|
867
|
+
current = (0, import_node_fs5.readFileSync)(handle.path, "utf8");
|
|
868
|
+
} catch {
|
|
869
|
+
return null;
|
|
870
|
+
}
|
|
871
|
+
if (current !== handle.serialized) return null;
|
|
872
|
+
const record = { ...handle.record, handoff };
|
|
873
|
+
const serialized = JSON.stringify(record) + "\n";
|
|
874
|
+
const tmp = `${handle.path}.plan-${record.pid}-${(0, import_node_crypto.randomBytes)(4).toString("hex")}`;
|
|
875
|
+
const fd = (0, import_node_fs5.openSync)(tmp, "wx", 384);
|
|
876
|
+
try {
|
|
877
|
+
(0, import_node_fs5.writeSync)(fd, serialized);
|
|
878
|
+
(0, import_node_fs5.fsyncSync)(fd);
|
|
879
|
+
} finally {
|
|
880
|
+
(0, import_node_fs5.closeSync)(fd);
|
|
881
|
+
}
|
|
882
|
+
(0, import_node_fs5.renameSync)(tmp, handle.path);
|
|
883
|
+
fsyncDir((0, import_node_path6.dirname)(handle.path));
|
|
884
|
+
return { path: handle.path, record, serialized };
|
|
885
|
+
}
|
|
886
|
+
function retakeDeadFleetLock(dataDir, fence, probe = {}) {
|
|
887
|
+
return replaceDeadHolder(dataDir, fence, (owner) => (owner.role ?? "fleet") === "fleet" && owner.nonce === fence.nonce ? null : "fleet.lock doesn't hold that generation's record", probe);
|
|
888
|
+
}
|
|
889
|
+
function adoptUpdateFence(dataDir, fence, probe = {}) {
|
|
890
|
+
const pid = fence.pid ?? process.pid;
|
|
891
|
+
let current;
|
|
892
|
+
try {
|
|
893
|
+
current = (0, import_node_fs5.readFileSync)((0, import_node_path6.join)(dataDir, "fleet.lock"), "utf8");
|
|
894
|
+
} catch (err) {
|
|
895
|
+
return { ok: false, reason: `fleet.lock can't be read (${err.message})` };
|
|
896
|
+
}
|
|
897
|
+
const owner = parseRecord2(current);
|
|
898
|
+
if (owner && owner.role === "update" && owner.attemptId === fence.attemptId && owner.pid === pid) {
|
|
899
|
+
clearCrashedReclaim(dataDir, fence.attemptId, pid, probe);
|
|
900
|
+
return { ok: true, handle: { path: (0, import_node_path6.join)(dataDir, "fleet.lock"), record: owner, serialized: current } };
|
|
901
|
+
}
|
|
902
|
+
return replaceDeadHolder(dataDir, { pid, attemptId: fence.attemptId }, (o) => o.role === "update" && o.attemptId === fence.attemptId ? null : "fleet.lock isn't this attempt's fence", probe);
|
|
903
|
+
}
|
|
904
|
+
var reclaimMarkerPath = (dataDir) => `${(0, import_node_path6.join)(dataDir, "fleet.lock")}.reclaim`;
|
|
905
|
+
function clearCrashedReclaim(dataDir, attemptId, selfPid, probe) {
|
|
906
|
+
const marker = reclaimMarkerPath(dataDir);
|
|
907
|
+
let text;
|
|
908
|
+
try {
|
|
909
|
+
text = (0, import_node_fs5.readFileSync)(marker, "utf8");
|
|
910
|
+
} catch {
|
|
911
|
+
return false;
|
|
912
|
+
}
|
|
913
|
+
const rec = parseRecord2(text);
|
|
914
|
+
if (!rec || rec.role !== "update" || rec.attemptId !== attemptId || rec.pid !== selfPid && (probe.isProcessAlive ?? processAlive)(rec.pid)) return false;
|
|
915
|
+
try {
|
|
916
|
+
(0, import_node_fs5.unlinkSync)(marker);
|
|
917
|
+
fsyncDir(dataDir);
|
|
918
|
+
return true;
|
|
919
|
+
} catch {
|
|
920
|
+
return false;
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function replaceDeadHolder(dataDir, fence, accept, probe) {
|
|
924
|
+
const lockPath = (0, import_node_path6.join)(dataDir, "fleet.lock"), marker = reclaimMarkerPath(dataDir);
|
|
925
|
+
let observed;
|
|
926
|
+
try {
|
|
927
|
+
observed = (0, import_node_fs5.readFileSync)(lockPath, "utf8");
|
|
928
|
+
} catch (err) {
|
|
929
|
+
return { ok: false, reason: `fleet.lock can't be read (${err.message})` };
|
|
930
|
+
}
|
|
931
|
+
const owner = parseRecord2(observed);
|
|
932
|
+
if (!owner) return { ok: false, reason: "fleet.lock can't be read as a record" };
|
|
933
|
+
const why = accept(owner);
|
|
934
|
+
if (why) return { ok: false, reason: why };
|
|
935
|
+
if ((probe.isProcessAlive ?? processAlive)(owner.pid)) return { ok: false, reason: `fleet.lock's holder (pid ${owner.pid}) is still a live process; it is never taken` };
|
|
936
|
+
const pid = fence.pid ?? process.pid;
|
|
937
|
+
const record = { pid, nonce: (0, import_node_crypto.randomBytes)(16).toString("hex"), createdAt: (/* @__PURE__ */ new Date()).toISOString(), role: "update", attemptId: fence.attemptId, handoff: null };
|
|
938
|
+
const serialized = JSON.stringify(record) + "\n";
|
|
939
|
+
const takeMarker = () => (0, import_node_fs5.writeFileSync)(marker, serialized, { flag: "wx", mode: 384 });
|
|
940
|
+
try {
|
|
941
|
+
takeMarker();
|
|
942
|
+
} catch (err) {
|
|
943
|
+
if (err.code !== "EEXIST") return { ok: false, reason: `the reclaim marker can't be created (${err.message})` };
|
|
944
|
+
if (!clearCrashedReclaim(dataDir, fence.attemptId, fence.pid ?? process.pid, probe)) return { ok: false, reason: `a reclaim marker ${marker} is present (another reclaim, or one left by a crash); nothing is taken` };
|
|
945
|
+
try {
|
|
946
|
+
takeMarker();
|
|
947
|
+
} catch (again) {
|
|
948
|
+
return { ok: false, reason: `the reclaim marker can't be taken (${again.message})` };
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
try {
|
|
952
|
+
if ((0, import_node_fs5.readFileSync)(lockPath, "utf8") !== observed) return { ok: false, reason: "fleet.lock changed during the reclaim" };
|
|
953
|
+
const tmp = `${lockPath}.retake-${pid}-${(0, import_node_crypto.randomBytes)(4).toString("hex")}`;
|
|
954
|
+
const fd = (0, import_node_fs5.openSync)(tmp, "wx", 384);
|
|
955
|
+
try {
|
|
956
|
+
(0, import_node_fs5.writeSync)(fd, serialized);
|
|
957
|
+
(0, import_node_fs5.fsyncSync)(fd);
|
|
958
|
+
} finally {
|
|
959
|
+
(0, import_node_fs5.closeSync)(fd);
|
|
960
|
+
}
|
|
961
|
+
(0, import_node_fs5.renameSync)(tmp, lockPath);
|
|
962
|
+
fsyncDir(dataDir);
|
|
963
|
+
return { ok: true, handle: { path: lockPath, record, serialized } };
|
|
964
|
+
} catch (err) {
|
|
965
|
+
return { ok: false, reason: `fleet.lock can't be re-taken (${err.message})` };
|
|
966
|
+
} finally {
|
|
967
|
+
try {
|
|
968
|
+
(0, import_node_fs5.unlinkSync)(marker);
|
|
969
|
+
fsyncDir(dataDir);
|
|
970
|
+
} catch {
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
function readFleetLockRecord(dataDir) {
|
|
975
|
+
try {
|
|
976
|
+
return parseRecord2((0, import_node_fs5.readFileSync)((0, import_node_path6.join)(dataDir, "fleet.lock"), "utf8"));
|
|
977
|
+
} catch {
|
|
978
|
+
return null;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// src/update-restore.ts
|
|
983
|
+
var import_node_crypto3 = require("node:crypto");
|
|
984
|
+
var import_node_fs7 = require("node:fs");
|
|
985
|
+
var import_node_path8 = require("node:path");
|
|
986
|
+
|
|
987
|
+
// src/update-snapshot-scope.ts
|
|
988
|
+
var under = (dir) => (rel) => rel === dir || rel.startsWith(`${dir}/`);
|
|
989
|
+
var exactly = (...names) => (rel) => names.includes(rel);
|
|
990
|
+
var base = (rel) => rel.slice(rel.lastIndexOf("/") + 1);
|
|
991
|
+
var EXCLUDED = [
|
|
992
|
+
{ rule: ".update-journal/", kind: "journal", match: under(".update-journal") },
|
|
993
|
+
{ rule: "update-in-progress.json", kind: "journal", match: exactly("update-in-progress.json") },
|
|
994
|
+
{ rule: "workspaces/", kind: "user-state", match: under("workspaces") },
|
|
995
|
+
{ rule: "credential-profiles/", kind: "user-state", match: under("credential-profiles") },
|
|
996
|
+
{ rule: "cx/", kind: "user-state", match: under("cx") },
|
|
997
|
+
// muse's isolated XDG home per instance (backend/muse.ts): links into the user's ~/.config — the CLI's own config
|
|
998
|
+
// home, the same kind as cx/ and credential-profiles/ (Fable #4523 F3).
|
|
999
|
+
{ rule: "instances/*/muse-xdg/", kind: "user-state", match: (rel) => /^instances\/[^/]+\/muse-xdg(\/|$)/.test(rel) },
|
|
1000
|
+
{ rule: "cache/", kind: "cache", match: under("cache") },
|
|
1001
|
+
{ rule: "cache-codex-rollouts.json, usage-last-good.json", kind: "cache", match: exactly("cache-codex-rollouts.json", "usage-last-good.json") },
|
|
1002
|
+
{ rule: "search.db*", kind: "cache", match: (rel) => !rel.includes("/") && rel.startsWith("search.db") },
|
|
1003
|
+
{ rule: "*.log", kind: "log", match: (rel) => base(rel).endsWith(".log") },
|
|
1004
|
+
{ rule: "profiles/", kind: "log", match: under("profiles") },
|
|
1005
|
+
{ rule: "tmux/, operator/", kind: "runtime", match: (rel) => under("tmux")(rel) || under("operator")(rel) },
|
|
1006
|
+
{ rule: "*.sock", kind: "runtime", match: (rel) => base(rel).endsWith(".sock") },
|
|
1007
|
+
{ rule: "fleet.pid, fleet.lock (+ its reclaim/handoff/tmp files)", kind: "runtime", match: (rel) => rel === "fleet.pid" || rel === "fleet.lock" || rel.startsWith("fleet.lock.") },
|
|
1008
|
+
{ rule: ".update.lock, .service.lock (+ reclaim markers)", kind: "runtime", match: (rel) => /^\.(update|service)\.lock(\.reclaim)?$/.test(rel) },
|
|
1009
|
+
{ rule: "tunnel.lease, web.token, view.token", kind: "runtime", match: exactly("tunnel.lease", "web.token", "view.token") },
|
|
1010
|
+
{ rule: ".state-lease.sqlite (+ -journal)", kind: "lease", match: exactly(".state-lease.sqlite", ".state-lease.sqlite-journal") }
|
|
1011
|
+
];
|
|
1012
|
+
function classify(rel) {
|
|
1013
|
+
if (rel === "" || rel.startsWith("/") || rel.split("/").some((p) => p === "" || p === "." || p === "..")) throw new Error(`not a relative path in the home: ${JSON.stringify(rel)}`);
|
|
1014
|
+
for (const r of EXCLUDED) if (r.match(rel)) return { included: false, kind: r.kind, rule: r.rule };
|
|
1015
|
+
return { included: true };
|
|
1016
|
+
}
|
|
1017
|
+
var home = (path, phase, by, extra = {}) => ({ path, where: "home", phase, by, ...extra });
|
|
1018
|
+
var outside = (path, phase, by, restoredBy) => ({ path, where: "outside", phase, by, ...restoredBy ? { restoredBy } : {} });
|
|
1019
|
+
var WRITER_INVENTORY = [
|
|
1020
|
+
// ── Fleet startup and migrations (pre-commit: the trial fleet starts before commit) ──
|
|
1021
|
+
home("fleet.yaml", "pre-commit", "config load and migrations (fleet-yaml-patch, cli)"),
|
|
1022
|
+
home("fleet.pid", "pre-commit", "fleet start"),
|
|
1023
|
+
home("fleet.lock", "pre-commit", "fleet start (fleet-lock)"),
|
|
1024
|
+
home("fleet.lock.reclaim", "pre-commit", "fleet-lock's reclaim marker (the update's owned re-take of a dead holder)"),
|
|
1025
|
+
home("fleet.log", "pre-commit", "fleet logger"),
|
|
1026
|
+
home("fleet-fatal.log", "pre-commit", "fleet fatal handler"),
|
|
1027
|
+
home("daemon.log", "pre-commit", "daemon logger"),
|
|
1028
|
+
home("update.log", "pre-commit", "agend update"),
|
|
1029
|
+
home("update-in-progress.json", "pre-commit", "agend update (marker)"),
|
|
1030
|
+
home("events.db", "pre-commit", "event log (opened at start)"),
|
|
1031
|
+
home("scheduler.db", "pre-commit", "scheduler (opened at start; CLI under the state lease)"),
|
|
1032
|
+
home("delivery-outbox.db", "pre-commit", "delivery outbox (opened at start)"),
|
|
1033
|
+
home("profiles.db", "pre-commit", "web profiles (opened at start)"),
|
|
1034
|
+
home("reply-buttons.db", "pre-commit", "reply buttons (opened at start)"),
|
|
1035
|
+
home("instances", "pre-commit", "instance state at start (instances/<name>/\u2026)"),
|
|
1036
|
+
home("tmux", "pre-commit", "private tmux server"),
|
|
1037
|
+
home("tmux-migration.json", "pre-commit", "tmux migration"),
|
|
1038
|
+
home("operator", "pre-commit", "operator socket"),
|
|
1039
|
+
home("web.token", "pre-commit", "web server start"),
|
|
1040
|
+
home("view.token", "pre-commit", "web server start"),
|
|
1041
|
+
home("tunnel.lease", "pre-commit", "tunnel at start"),
|
|
1042
|
+
home("cli-env", "pre-commit", "CLI environment files at start"),
|
|
1043
|
+
home("hub-member", "pre-commit", "Hub member state at start"),
|
|
1044
|
+
home("hub-member-invalidate.pending", "pre-commit", "Hub member invalidation"),
|
|
1045
|
+
home("kiro-v3", "pre-commit", "kiro engine at start"),
|
|
1046
|
+
home("kiro-engine-ledger.json", "pre-commit", "kiro engine at start"),
|
|
1047
|
+
home("kiro-identity", "pre-commit", "kiro engine identity"),
|
|
1048
|
+
home(".update-journal", "pre-commit", "the update transaction"),
|
|
1049
|
+
home("host-monitoring.sqlite", "pre-commit", "host monitoring (a SQLite database opened at fleet start; \xA75.3 treats it as one)"),
|
|
1050
|
+
home("rollback.json", "pre-commit", "tmux migration rollback (tmux-rollback)"),
|
|
1051
|
+
home("kiro-classic-archives", "pre-commit", "kiro classic migration (kiro-classic-archive, kiro-migration-verify)"),
|
|
1052
|
+
home("kiro-reconciliations", "pre-commit", "kiro reconcile store"),
|
|
1053
|
+
home("search.db", "pre-commit", "search index (startSearchIndex at fleet start); another schema \u2192 rebuilt (search-store meta.schema)", { olderBuildRebuilds: true }),
|
|
1054
|
+
home("cache-codex-rollouts.json", "pre-commit", "cache service's codex rollout metadata; unknown entries are skipped (cache-service)", { olderBuildRebuilds: true }),
|
|
1055
|
+
home("usage-last-good.json", "pre-commit", "usage last-good rows; another version or shape is ignored (usage-api loadLastGood)", { olderBuildRebuilds: true }),
|
|
1056
|
+
// ── Ordinary operation (post-commit) ──
|
|
1057
|
+
home("workspaces", "post-commit", "agent launch (the agents' working directories)"),
|
|
1058
|
+
home("credential-profiles", "post-commit", "agent launch (the CLIs' homes, each profile's .claude.json)"),
|
|
1059
|
+
home("cx", "post-commit", "codex backend at agent launch"),
|
|
1060
|
+
home("instances/*/muse-xdg", "post-commit", "muse backend at agent launch (its isolated XDG home: links into ~/.config)"),
|
|
1061
|
+
home("cache", "post-commit", "caches"),
|
|
1062
|
+
home("usage-quota-history.jsonl", "post-commit", "usage"),
|
|
1063
|
+
home("quota-notices.json", "post-commit", "usage notices"),
|
|
1064
|
+
home("profiles", "post-commit", "CPU profiles"),
|
|
1065
|
+
home("access", "post-commit", "channel access lists"),
|
|
1066
|
+
home("inbox", "post-commit", "attachments inbox"),
|
|
1067
|
+
home("avatars", "post-commit", "web avatars"),
|
|
1068
|
+
home("cards", "post-commit", "web cards"),
|
|
1069
|
+
home("archived-topics.json", "post-commit", "topic archive"),
|
|
1070
|
+
home("backend-signin-pending.json", "post-commit", "backend sign-in"),
|
|
1071
|
+
home("bin", "post-commit", "cloudflared install"),
|
|
1072
|
+
home(".env", "post-commit", "quickstart settings"),
|
|
1073
|
+
home("classicBot.yaml", "post-commit", "ClassicBot"),
|
|
1074
|
+
home("credential-vault", "post-commit", "credential vault"),
|
|
1075
|
+
home("delivery-audit", "post-commit", "delivery audit"),
|
|
1076
|
+
home("forged-envelope-reports.json", "post-commit", "envelope reports"),
|
|
1077
|
+
home("hub-assistant", "post-commit", "Hub room assistant"),
|
|
1078
|
+
home("hub-classic-private.json", "post-commit", "Hub ClassicBot sharing"),
|
|
1079
|
+
home("hub-contact-windows.json", "post-commit", "Hub contact windows"),
|
|
1080
|
+
home("pending-owner-notices.json", "post-commit", "owner notices"),
|
|
1081
|
+
home("skipped-skills.json", "post-commit", "skill sync"),
|
|
1082
|
+
home("web-app-icon", "post-commit", "web settings"),
|
|
1083
|
+
home("web-authority.json", "post-commit", "web sign-in"),
|
|
1084
|
+
home("web-authorizations.json", "post-commit", "web sign-in"),
|
|
1085
|
+
home("web-devices.json", "post-commit", "web sign-in"),
|
|
1086
|
+
home("web-host-authorized", "post-commit", "web host"),
|
|
1087
|
+
home("web-mods", "post-commit", "web mods"),
|
|
1088
|
+
home("web-mods.json", "post-commit", "web mods"),
|
|
1089
|
+
home("web-office-skins", "post-commit", "web office"),
|
|
1090
|
+
home("web-offices.json", "post-commit", "web office"),
|
|
1091
|
+
home("web-owner-css", "post-commit", "web theme"),
|
|
1092
|
+
home("web-pins.json", "post-commit", "web pins"),
|
|
1093
|
+
home("web-sessions.json", "post-commit", "web sessions"),
|
|
1094
|
+
home("web-themes", "post-commit", "web themes"),
|
|
1095
|
+
home("web-themes.json", "post-commit", "web themes"),
|
|
1096
|
+
home("needs-you-message.json", "post-commit", "Needs-you hub"),
|
|
1097
|
+
home("agy-statusline.sh", "post-commit", "antigravity backend at agent launch"),
|
|
1098
|
+
home("shared", "post-commit", "web office packs (web-office-pack-read; its stateDir is the home)"),
|
|
1099
|
+
home("signin-launch", "post-commit", "web sign-in links \u2014 via web-signin-link's join over the home it is passed (cli.ts passes DATA_DIR)"),
|
|
1100
|
+
// ── Outside the home ──
|
|
1101
|
+
outside(".claude.json", "post-commit", "claude-code backend at agent launch (trust, onboarding); $CLAUDE_CONFIG_DIR/.claude.json when set"),
|
|
1102
|
+
outside(".claude", "post-commit", "claude-code backend and usage at agent launch"),
|
|
1103
|
+
outside(".codex", "post-commit", "codex backend at agent launch"),
|
|
1104
|
+
outside(".gemini", "post-commit", "gemini profiles at agent launch"),
|
|
1105
|
+
outside(".grok", "post-commit", "grok backend at agent launch"),
|
|
1106
|
+
outside(".kiro", "post-commit", "kiro backend at agent launch"),
|
|
1107
|
+
outside(".local", "post-commit", "backend CLIs' data at agent launch"),
|
|
1108
|
+
outside("AppData", "post-commit", "Windows pane stdio"),
|
|
1109
|
+
outside(".agend", "pre-commit", "the default AgEnD home itself (paths.ts) \u2014 the home, not outside it"),
|
|
1110
|
+
outside(".config", "pre-commit", "the systemd user unit (service-installer)", "unit-preimage"),
|
|
1111
|
+
outside("Library", "pre-commit", "the launchd agent plist (service-installer)", "unit-preimage"),
|
|
1112
|
+
outside(".npm-global", "pre-commit", "the npm prefix (the install itself)", "package-preimage"),
|
|
1113
|
+
outside(".nvm", "pre-commit", "nvm's Node prefix (the install itself)", "package-preimage")
|
|
1114
|
+
];
|
|
1115
|
+
|
|
1116
|
+
// src/update-snapshot-manifest.ts
|
|
1117
|
+
var import_node_crypto2 = require("node:crypto");
|
|
1118
|
+
var import_node_fs6 = require("node:fs");
|
|
1119
|
+
var import_node_path7 = require("node:path");
|
|
1120
|
+
var SNAPSHOT_DIR = "snapshot";
|
|
1121
|
+
var SNAPSHOT_MANIFEST = "snapshot.json";
|
|
1122
|
+
var sha256File = (path) => (0, import_node_crypto2.createHash)("sha256").update((0, import_node_fs6.readFileSync)(path)).digest("hex");
|
|
1123
|
+
function readManifest(attemptDir2) {
|
|
1124
|
+
try {
|
|
1125
|
+
const m = JSON.parse((0, import_node_fs6.readFileSync)((0, import_node_path7.join)(attemptDir2, SNAPSHOT_MANIFEST), "utf8"));
|
|
1126
|
+
return m && m.schema === 1 && Array.isArray(m.entries) && Array.isArray(m.databases) ? m : null;
|
|
1127
|
+
} catch {
|
|
1128
|
+
return null;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
function verifySnapshot(attemptDir2, manifest) {
|
|
1132
|
+
const out = (0, import_node_path7.join)(attemptDir2, SNAPSHOT_DIR);
|
|
1133
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1134
|
+
const visit = (rel) => {
|
|
1135
|
+
for (const name of (0, import_node_fs6.readdirSync)(rel ? (0, import_node_path7.join)(out, rel) : out).sort()) {
|
|
1136
|
+
const r = rel ? `${rel}/${name}` : name;
|
|
1137
|
+
const st = (0, import_node_fs6.lstatSync)((0, import_node_path7.join)(out, r));
|
|
1138
|
+
if (st.isSymbolicLink()) seen.set(r, { rel: r, type: "link", mode: 0, target: (0, import_node_fs6.readlinkSync)((0, import_node_path7.join)(out, r)) });
|
|
1139
|
+
else if (st.isDirectory()) {
|
|
1140
|
+
seen.set(r, { rel: r, type: "dir", mode: st.mode & 4095 });
|
|
1141
|
+
visit(r);
|
|
1142
|
+
} else if (st.isFile()) seen.set(r, { rel: r, type: "file", mode: st.mode & 4095, size: st.size, sha256: sha256File((0, import_node_path7.join)(out, r)) });
|
|
1143
|
+
else seen.set(r, { rel: r, type: "file", mode: -1 });
|
|
1144
|
+
}
|
|
1145
|
+
};
|
|
1146
|
+
try {
|
|
1147
|
+
visit("");
|
|
1148
|
+
} catch (err) {
|
|
1149
|
+
return { ok: false, reason: `the snapshot can't be read (${err.message})` };
|
|
1150
|
+
}
|
|
1151
|
+
if (seen.size !== manifest.entries.length) return { ok: false, reason: `the snapshot holds ${seen.size} entries, its manifest ${manifest.entries.length}` };
|
|
1152
|
+
for (const e of manifest.entries) {
|
|
1153
|
+
const s = seen.get(e.rel);
|
|
1154
|
+
if (!s) return { ok: false, reason: `${e.rel} is missing from the snapshot` };
|
|
1155
|
+
if (s.type !== e.type) return { ok: false, reason: `${e.rel} is a ${s.type}, not a ${e.type}` };
|
|
1156
|
+
if (e.type === "link" && s.target !== e.target) return { ok: false, reason: `${e.rel} points elsewhere` };
|
|
1157
|
+
if (e.type === "file" && (s.sha256 !== e.sha256 || s.size !== e.size || s.mode !== e.mode)) return { ok: false, reason: `${e.rel} differs from its manifest` };
|
|
1158
|
+
if (e.type === "dir" && s.mode !== e.mode) return { ok: false, reason: `${e.rel}'s mode differs from its manifest` };
|
|
1159
|
+
}
|
|
1160
|
+
return { ok: true };
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
// src/update-restore.ts
|
|
1164
|
+
var RESTORE_LOG = "restore.log";
|
|
1165
|
+
var REPLACED_DIR = "replaced";
|
|
1166
|
+
var TMP_SUFFIX = ".restore-tmp";
|
|
1167
|
+
var defaultRestoreIo = { step: () => {
|
|
1168
|
+
} };
|
|
1169
|
+
var Manual = class extends Error {
|
|
1170
|
+
};
|
|
1171
|
+
var Retryable = class extends Error {
|
|
1172
|
+
};
|
|
1173
|
+
var fsyncPath = (p) => {
|
|
1174
|
+
const fd = (0, import_node_fs7.openSync)(p, "r");
|
|
1175
|
+
try {
|
|
1176
|
+
(0, import_node_fs7.fsyncSync)(fd);
|
|
1177
|
+
} finally {
|
|
1178
|
+
(0, import_node_fs7.closeSync)(fd);
|
|
1179
|
+
}
|
|
1180
|
+
};
|
|
1181
|
+
var sha256File2 = (p) => (0, import_node_crypto3.createHash)("sha256").update((0, import_node_fs7.readFileSync)(p)).digest("hex");
|
|
1182
|
+
var parentRel = (rel) => rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
|
|
1183
|
+
var under2 = (rel, u) => rel === u || rel.startsWith(`${u}/`);
|
|
1184
|
+
function identOf(path) {
|
|
1185
|
+
try {
|
|
1186
|
+
const st = (0, import_node_fs7.lstatSync)(path);
|
|
1187
|
+
return { type: st.isSymbolicLink() ? "link" : st.isDirectory() ? "dir" : "file", dev: st.dev, ino: st.ino, size: st.size, mtimeMs: st.mtimeMs };
|
|
1188
|
+
} catch {
|
|
1189
|
+
return null;
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
var sameIdent = (a, b) => !!a && !!b && a.type === b.type && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs;
|
|
1193
|
+
function currentScope(home2) {
|
|
1194
|
+
const entries = /* @__PURE__ */ new Map(), containers = /* @__PURE__ */ new Set([""]);
|
|
1195
|
+
const visit = (rel) => {
|
|
1196
|
+
let excludedBelow = false;
|
|
1197
|
+
for (const name of (0, import_node_fs7.readdirSync)(rel ? (0, import_node_path8.join)(home2, rel) : home2).sort()) {
|
|
1198
|
+
const r = rel ? `${rel}/${name}` : name;
|
|
1199
|
+
if (r.endsWith(TMP_SUFFIX) && classify(r.slice(0, -TMP_SUFFIX.length)).included) continue;
|
|
1200
|
+
if (!classify(r).included) {
|
|
1201
|
+
excludedBelow = true;
|
|
1202
|
+
continue;
|
|
1203
|
+
}
|
|
1204
|
+
const st = (0, import_node_fs7.lstatSync)((0, import_node_path8.join)(home2, r));
|
|
1205
|
+
if (st.isSymbolicLink()) entries.set(r, { rel: r, type: "link", mode: 0, target: (0, import_node_fs7.readlinkSync)((0, import_node_path8.join)(home2, r)) });
|
|
1206
|
+
else if (st.isDirectory()) {
|
|
1207
|
+
entries.set(r, { rel: r, type: "dir", mode: st.mode & 4095 });
|
|
1208
|
+
if (visit(r)) {
|
|
1209
|
+
containers.add(r);
|
|
1210
|
+
excludedBelow = true;
|
|
1211
|
+
}
|
|
1212
|
+
} else entries.set(r, { rel: r, type: "file", mode: st.mode & 4095, size: st.size });
|
|
1213
|
+
}
|
|
1214
|
+
return excludedBelow;
|
|
1215
|
+
};
|
|
1216
|
+
visit("");
|
|
1217
|
+
return { entries, containers };
|
|
1218
|
+
}
|
|
1219
|
+
function unitsOf(rels, containers) {
|
|
1220
|
+
return [...rels].filter((r) => containers.has(parentRel(r)) && !containers.has(r));
|
|
1221
|
+
}
|
|
1222
|
+
function matchesManifest(home2, u, manifest) {
|
|
1223
|
+
const want = manifest.entries.filter((e) => under2(e.rel, u));
|
|
1224
|
+
const seen = [];
|
|
1225
|
+
const add = (r) => {
|
|
1226
|
+
let st;
|
|
1227
|
+
try {
|
|
1228
|
+
st = (0, import_node_fs7.lstatSync)((0, import_node_path8.join)(home2, r));
|
|
1229
|
+
} catch {
|
|
1230
|
+
return false;
|
|
1231
|
+
}
|
|
1232
|
+
if (st.isSymbolicLink()) seen.push({ rel: r, type: "link", mode: 0, target: (0, import_node_fs7.readlinkSync)((0, import_node_path8.join)(home2, r)) });
|
|
1233
|
+
else if (st.isDirectory()) {
|
|
1234
|
+
seen.push({ rel: r, type: "dir", mode: st.mode & 4095 });
|
|
1235
|
+
for (const n of (0, import_node_fs7.readdirSync)((0, import_node_path8.join)(home2, r))) if (!add(`${r}/${n}`)) return false;
|
|
1236
|
+
} else seen.push({ rel: r, type: "file", mode: st.mode & 4095, size: st.size, sha256: sha256File2((0, import_node_path8.join)(home2, r)) });
|
|
1237
|
+
return true;
|
|
1238
|
+
};
|
|
1239
|
+
if (!add(u) || seen.length !== want.length) return false;
|
|
1240
|
+
const byRel = new Map(seen.map((e) => [e.rel, e]));
|
|
1241
|
+
return want.every((e) => {
|
|
1242
|
+
const s = byRel.get(e.rel);
|
|
1243
|
+
if (!s || s.type !== e.type) return false;
|
|
1244
|
+
if (e.type === "link") return s.target === e.target;
|
|
1245
|
+
if (e.type === "dir") return s.mode === e.mode;
|
|
1246
|
+
return s.sha256 === e.sha256 && s.size === e.size && s.mode === e.mode;
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
1249
|
+
function build(snapshot, u, dst, manifest) {
|
|
1250
|
+
const entries = manifest.entries.filter((e) => under2(e.rel, u)).sort((a, b) => a.rel.length - b.rel.length || a.rel.localeCompare(b.rel));
|
|
1251
|
+
const dirs = [];
|
|
1252
|
+
for (const e of entries) {
|
|
1253
|
+
const to = e.rel === u ? dst : (0, import_node_path8.join)(dst, e.rel.slice(u.length + 1));
|
|
1254
|
+
if (e.type === "dir") {
|
|
1255
|
+
(0, import_node_fs7.mkdirSync)(to, { mode: 448 });
|
|
1256
|
+
dirs.push(to);
|
|
1257
|
+
continue;
|
|
1258
|
+
}
|
|
1259
|
+
if (e.type === "link") {
|
|
1260
|
+
(0, import_node_fs7.symlinkSync)(e.target, to);
|
|
1261
|
+
continue;
|
|
1262
|
+
}
|
|
1263
|
+
const from = (0, import_node_path8.join)(snapshot, e.rel);
|
|
1264
|
+
(0, import_node_fs7.copyFileSync)(from, to, import_node_fs7.constants.COPYFILE_EXCL | import_node_fs7.constants.COPYFILE_FICLONE);
|
|
1265
|
+
(0, import_node_fs7.chmodSync)(to, e.mode);
|
|
1266
|
+
const st = (0, import_node_fs7.lstatSync)(from);
|
|
1267
|
+
(0, import_node_fs7.utimesSync)(to, st.atime, st.mtime);
|
|
1268
|
+
fsyncPath(to);
|
|
1269
|
+
}
|
|
1270
|
+
for (const e of entries) if (e.type === "dir") (0, import_node_fs7.chmodSync)(e.rel === u ? dst : (0, import_node_path8.join)(dst, e.rel.slice(u.length + 1)), e.mode);
|
|
1271
|
+
for (const d of dirs.sort((a, b) => b.length - a.length)) fsyncPath(d);
|
|
1272
|
+
}
|
|
1273
|
+
function restoreHome(home2, attemptDir2, deps) {
|
|
1274
|
+
const io = deps.io ?? defaultRestoreIo;
|
|
1275
|
+
const snapshot = (0, import_node_path8.join)(attemptDir2, SNAPSHOT_DIR), replaced = (0, import_node_path8.join)(attemptDir2, REPLACED_DIR), logPath = (0, import_node_path8.join)(attemptDir2, RESTORE_LOG);
|
|
1276
|
+
const manifest = readManifest(attemptDir2);
|
|
1277
|
+
if (!manifest) return { ok: false, manual: true, reason: "the snapshot's manifest can't be read" };
|
|
1278
|
+
const intact = verifySnapshot(attemptDir2, manifest);
|
|
1279
|
+
if (!intact.ok) return { ok: false, manual: true, reason: `the snapshot doesn't verify: ${intact.reason}` };
|
|
1280
|
+
const manifestSha256 = (0, import_node_crypto3.createHash)("sha256").update((0, import_node_fs7.readFileSync)((0, import_node_path8.join)(attemptDir2, SNAPSHOT_MANIFEST))).digest("hex");
|
|
1281
|
+
try {
|
|
1282
|
+
let header, logged;
|
|
1283
|
+
let text = null;
|
|
1284
|
+
try {
|
|
1285
|
+
text = (0, import_node_fs7.readFileSync)(logPath, "utf8");
|
|
1286
|
+
} catch (err) {
|
|
1287
|
+
if (err.code !== "ENOENT") throw err;
|
|
1288
|
+
}
|
|
1289
|
+
if (text === null) {
|
|
1290
|
+
const now = currentScope(home2);
|
|
1291
|
+
const manifestRels = new Set(manifest.entries.map((e) => e.rel));
|
|
1292
|
+
const currentUnits = unitsOf(now.entries.keys(), now.containers);
|
|
1293
|
+
const manifestUnits = unitsOf(manifestRels, now.containers);
|
|
1294
|
+
const all = [.../* @__PURE__ */ new Set([...currentUnits, ...manifestUnits])].sort();
|
|
1295
|
+
const units = all.map((rel) => {
|
|
1296
|
+
const inCurrent = currentUnits.includes(rel), inManifest = manifestUnits.includes(rel);
|
|
1297
|
+
const current = inCurrent ? identOf((0, import_node_path8.join)(home2, rel)) ?? void 0 : void 0;
|
|
1298
|
+
return { rel, kind: inCurrent && inManifest ? "both" : inCurrent ? "new-only" : "manifest-only", ...current ? { current } : {} };
|
|
1299
|
+
});
|
|
1300
|
+
header = { schema: 1, manifestSha256, units, containers: [...now.containers].filter((c) => c !== "").sort() };
|
|
1301
|
+
const tmp = `${logPath}.tmp-${process.pid}`;
|
|
1302
|
+
const fd = (0, import_node_fs7.openSync)(tmp, "wx", 384);
|
|
1303
|
+
try {
|
|
1304
|
+
(0, import_node_fs7.writeSync)(fd, JSON.stringify(header) + "\n");
|
|
1305
|
+
(0, import_node_fs7.fsyncSync)(fd);
|
|
1306
|
+
} finally {
|
|
1307
|
+
(0, import_node_fs7.closeSync)(fd);
|
|
1308
|
+
}
|
|
1309
|
+
(0, import_node_fs7.renameSync)(tmp, logPath);
|
|
1310
|
+
fsyncPath(attemptDir2);
|
|
1311
|
+
io.step("header");
|
|
1312
|
+
logged = [];
|
|
1313
|
+
} else {
|
|
1314
|
+
const end = text.lastIndexOf("\n") + 1;
|
|
1315
|
+
if (end < text.length) {
|
|
1316
|
+
(0, import_node_fs7.truncateSync)(logPath, Buffer.byteLength(text.slice(0, end)));
|
|
1317
|
+
fsyncPath(logPath);
|
|
1318
|
+
io.step("truncate-torn");
|
|
1319
|
+
text = text.slice(0, end);
|
|
1320
|
+
}
|
|
1321
|
+
const lines = text.split("\n").filter(Boolean);
|
|
1322
|
+
if (lines.length === 0) throw new Manual("restore.log has no header");
|
|
1323
|
+
try {
|
|
1324
|
+
header = JSON.parse(lines[0]);
|
|
1325
|
+
} catch {
|
|
1326
|
+
throw new Manual("restore.log's header can't be read");
|
|
1327
|
+
}
|
|
1328
|
+
if (header.schema !== 1 || header.manifestSha256 !== manifestSha256) throw new Manual("restore.log's header doesn't match this snapshot");
|
|
1329
|
+
logged = [];
|
|
1330
|
+
for (const l of lines.slice(1)) {
|
|
1331
|
+
try {
|
|
1332
|
+
logged.push(JSON.parse(l));
|
|
1333
|
+
} catch {
|
|
1334
|
+
throw new Manual("restore.log has an unreadable line");
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
const log = (line) => {
|
|
1339
|
+
const fd = (0, import_node_fs7.openSync)(logPath, "a");
|
|
1340
|
+
try {
|
|
1341
|
+
(0, import_node_fs7.writeSync)(fd, JSON.stringify(line) + "\n");
|
|
1342
|
+
(0, import_node_fs7.fsyncSync)(fd);
|
|
1343
|
+
} finally {
|
|
1344
|
+
(0, import_node_fs7.closeSync)(fd);
|
|
1345
|
+
}
|
|
1346
|
+
logged.push(line);
|
|
1347
|
+
io.step("step" in line && "u" in line ? `log:${line.step}:${line.u}` : `log:${line.step}`);
|
|
1348
|
+
};
|
|
1349
|
+
const has = (u, step) => logged.some((l) => "u" in l && l.u === u && l.step === step);
|
|
1350
|
+
const aside = (u) => {
|
|
1351
|
+
const to = (0, import_node_path8.join)(replaced, u);
|
|
1352
|
+
(0, import_node_fs7.mkdirSync)((0, import_node_path8.dirname)(to), { recursive: true, mode: 448 });
|
|
1353
|
+
(0, import_node_fs7.renameSync)((0, import_node_path8.join)(home2, u), to);
|
|
1354
|
+
io.step(`rename-aside:${u}`);
|
|
1355
|
+
fsyncPath((0, import_node_path8.dirname)((0, import_node_path8.join)(home2, u)));
|
|
1356
|
+
fsyncPath((0, import_node_path8.dirname)(to));
|
|
1357
|
+
io.step(`fsync-aside:${u}`);
|
|
1358
|
+
log({ u, step: "aside" });
|
|
1359
|
+
};
|
|
1360
|
+
const restore = (u) => {
|
|
1361
|
+
const tmp = (0, import_node_path8.join)(home2, u + TMP_SUFFIX);
|
|
1362
|
+
(0, import_node_fs7.rmSync)(tmp, { recursive: true, force: true });
|
|
1363
|
+
build(snapshot, u, tmp, manifest);
|
|
1364
|
+
io.step(`built:${u}`);
|
|
1365
|
+
(0, import_node_fs7.renameSync)(tmp, (0, import_node_path8.join)(home2, u));
|
|
1366
|
+
io.step(`rename-restore:${u}`);
|
|
1367
|
+
fsyncPath((0, import_node_path8.dirname)((0, import_node_path8.join)(home2, u)));
|
|
1368
|
+
io.step(`fsync-restore:${u}`);
|
|
1369
|
+
log({ u, step: "restored" });
|
|
1370
|
+
};
|
|
1371
|
+
for (const unit of header.units) {
|
|
1372
|
+
const u = unit.rel, at = (0, import_node_path8.join)(home2, u), moved = (0, import_node_path8.join)(replaced, u);
|
|
1373
|
+
const complete = has(u, "restored") || unit.kind === "new-only" && has(u, "aside");
|
|
1374
|
+
if (complete) continue;
|
|
1375
|
+
const here = identOf(at), there = identOf(moved);
|
|
1376
|
+
if (unit.kind === "new-only") {
|
|
1377
|
+
if (!here && sameIdent(there, unit.current)) {
|
|
1378
|
+
log({ u, step: "aside" });
|
|
1379
|
+
continue;
|
|
1380
|
+
}
|
|
1381
|
+
if (here && !there) {
|
|
1382
|
+
aside(u);
|
|
1383
|
+
continue;
|
|
1384
|
+
}
|
|
1385
|
+
throw new Manual(`${u} (new since the snapshot) is in a state the restore doesn't cover`);
|
|
1386
|
+
}
|
|
1387
|
+
if (unit.kind === "both" && !has(u, "aside")) {
|
|
1388
|
+
if (!here && sameIdent(there, unit.current)) log({ u, step: "aside" });
|
|
1389
|
+
else if (sameIdent(here, unit.current) && !there) aside(u);
|
|
1390
|
+
else throw new Manual(`${u} is in a state the restore doesn't cover (present: ${!!here}, set aside: ${!!there})`);
|
|
1391
|
+
}
|
|
1392
|
+
if (identOf(at)) {
|
|
1393
|
+
if (matchesManifest(home2, u, manifest)) {
|
|
1394
|
+
log({ u, step: "restored" });
|
|
1395
|
+
continue;
|
|
1396
|
+
}
|
|
1397
|
+
throw new Manual(`${u} is present and matches neither the snapshot nor the plan`);
|
|
1398
|
+
}
|
|
1399
|
+
restore(u);
|
|
1400
|
+
}
|
|
1401
|
+
if (!logged.some((l) => l.step === "containers")) {
|
|
1402
|
+
const modes = new Map(manifest.entries.filter((e) => e.type === "dir").map((e) => [e.rel, e.mode]));
|
|
1403
|
+
for (const c of header.containers) {
|
|
1404
|
+
if (!identOf((0, import_node_path8.join)(home2, c))) (0, import_node_fs7.mkdirSync)((0, import_node_path8.join)(home2, c), { recursive: true, mode: 448 });
|
|
1405
|
+
const mode = modes.get(c);
|
|
1406
|
+
if (mode !== void 0) (0, import_node_fs7.chmodSync)((0, import_node_path8.join)(home2, c), mode);
|
|
1407
|
+
}
|
|
1408
|
+
fsyncPath(home2);
|
|
1409
|
+
log({ step: "containers" });
|
|
1410
|
+
}
|
|
1411
|
+
if (!logged.some((l) => l.step === "verified")) {
|
|
1412
|
+
const now = currentScope(home2).entries;
|
|
1413
|
+
const want = new Map(manifest.entries.map((e) => [e.rel, e]));
|
|
1414
|
+
const newContainers = new Set(header.containers.filter((c) => !want.has(c)));
|
|
1415
|
+
for (const rel of now.keys()) {
|
|
1416
|
+
if (want.has(rel) || newContainers.has(rel)) continue;
|
|
1417
|
+
throw new Manual(`after the restore, ${rel} is in the home but not in the snapshot`);
|
|
1418
|
+
}
|
|
1419
|
+
for (const e of manifest.entries) if (!now.has(e.rel)) throw new Manual(`after the restore, ${e.rel} is missing`);
|
|
1420
|
+
for (const u of header.units) if (want.has(u.rel) && !matchesManifest(home2, u.rel, manifest)) throw new Manual(`after the restore, ${u.rel} doesn't match the snapshot`);
|
|
1421
|
+
const writers = deps.proveWritersGone();
|
|
1422
|
+
if (!writers.ok) throw new Retryable(`a writer appeared during the restore: ${writers.reason}`);
|
|
1423
|
+
log({ step: "verified" });
|
|
1424
|
+
}
|
|
1425
|
+
return { ok: true };
|
|
1426
|
+
} catch (err) {
|
|
1427
|
+
if (err instanceof Manual) return { ok: false, manual: true, reason: err.message };
|
|
1428
|
+
if (err instanceof Retryable) return { ok: false, manual: false, reason: err.message };
|
|
1429
|
+
throw err;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
// src/update-package-restore.ts
|
|
1434
|
+
var import_node_crypto4 = require("node:crypto");
|
|
1435
|
+
var import_node_fs9 = require("node:fs");
|
|
1436
|
+
var import_node_path10 = require("node:path");
|
|
1437
|
+
|
|
1438
|
+
// src/update-recovery/route.ts
|
|
1439
|
+
var import_node_fs8 = require("node:fs");
|
|
1440
|
+
var import_node_path9 = require("node:path");
|
|
1441
|
+
var DROP_IN_NAME = "agend-update-recovery.conf";
|
|
1442
|
+
var WRAPPER_ARG0 = "agend-update-recovery";
|
|
1443
|
+
var UNIT_PREIMAGE = "unit.preimage";
|
|
1444
|
+
var NONCE_CASE = Array.from({ length: 32 }, () => "[0-9a-f]").join("");
|
|
1445
|
+
var WRAPPER_SCRIPT = [
|
|
1446
|
+
`"$1" "$2" --home "$3" --attempt "$4" --pre-start || exit $?`,
|
|
1447
|
+
`f="$3/.update-journal/attempts/$4/handoff.env"`,
|
|
1448
|
+
`if [ -f "$f" ]; then`,
|
|
1449
|
+
` IFS= read -r line < "$f" || true`,
|
|
1450
|
+
` case "$line" in`,
|
|
1451
|
+
` AGEND_UPDATE_HANDOFF=${NONCE_CASE}) AGEND_UPDATE_HANDOFF=\${line#AGEND_UPDATE_HANDOFF=}; export AGEND_UPDATE_HANDOFF ;;`,
|
|
1452
|
+
` esac`,
|
|
1453
|
+
`fi`,
|
|
1454
|
+
`shift 4`,
|
|
1455
|
+
`exec "$@"`
|
|
1456
|
+
].join("\n");
|
|
1457
|
+
var dropInPath = (service) => (0, import_node_path9.join)((0, import_node_path9.dirname)(service.fragmentPath), `${service.unit}.d`, DROP_IN_NAME);
|
|
1458
|
+
var unitPreimagePath = (home2, attemptId) => (0, import_node_path9.join)(attemptDir(home2, attemptId), UNIT_PREIMAGE);
|
|
1459
|
+
var unitSafe = (path) => /^\/[A-Za-z0-9_./@+:,-]*$/.test(path);
|
|
1460
|
+
function writeDurable(path, data, io, mode = 384) {
|
|
1461
|
+
const tmp = `${path}.tmp-${process.pid}-${Date.now().toString(36)}`;
|
|
1462
|
+
const fileMode = mode === "keep" ? (0, import_node_fs8.statSync)(path).mode & 4095 : mode;
|
|
1463
|
+
const fd = (0, import_node_fs8.openSync)(tmp, "wx", fileMode);
|
|
1464
|
+
try {
|
|
1465
|
+
(0, import_node_fs8.writeSync)(fd, typeof data === "string" ? Buffer.from(data) : data);
|
|
1466
|
+
(0, import_node_fs8.fchmodSync)(fd, fileMode);
|
|
1467
|
+
(0, import_node_fs8.fsyncSync)(fd);
|
|
1468
|
+
} finally {
|
|
1469
|
+
(0, import_node_fs8.closeSync)(fd);
|
|
1470
|
+
}
|
|
1471
|
+
(0, import_node_fs8.renameSync)(tmp, path);
|
|
1472
|
+
io.fsyncDir((0, import_node_path9.dirname)(path));
|
|
1473
|
+
}
|
|
1474
|
+
function dropInText(home2, attemptId) {
|
|
1475
|
+
const kit = kitDir(home2, attemptId);
|
|
1476
|
+
return [
|
|
1477
|
+
"# AgEnD update recovery (M-3770): every start of this service first asks the update journal.",
|
|
1478
|
+
"[Service]",
|
|
1479
|
+
`ExecStartPre=${(0, import_node_path9.join)(kit, "node")} ${(0, import_node_path9.join)(kit, "recover.cjs")} --home ${home2} --attempt ${attemptId} --pre-start`,
|
|
1480
|
+
`EnvironmentFile=-${handoffEnvPath(home2, attemptId)}`,
|
|
1481
|
+
""
|
|
1482
|
+
].join("\n");
|
|
1483
|
+
}
|
|
1484
|
+
var xmlEscape = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1485
|
+
var PROGRAM_ARGS = /(<key>ProgramArguments<\/key>\s*<array>)([\s\S]*?)(\s*<\/array>)/;
|
|
1486
|
+
function wrapPlist(xml, home2, attemptId, originalArgs) {
|
|
1487
|
+
if (/<key>Program<\/key>/.test(xml) || (xml.match(/<key>ProgramArguments<\/key>/g) ?? []).length !== 1) return null;
|
|
1488
|
+
const kit = kitDir(home2, attemptId);
|
|
1489
|
+
const words = ["/bin/sh", "-c", WRAPPER_SCRIPT, WRAPPER_ARG0, (0, import_node_path9.join)(kit, "node"), (0, import_node_path9.join)(kit, "recover.cjs"), home2, attemptId, ...originalArgs];
|
|
1490
|
+
return xml.replace(PROGRAM_ARGS, (_all, open, _body, close) => `${open}
|
|
1491
|
+
${words.map((w) => ` <string>${xmlEscape(w)}</string>`).join("\n")}${close}`);
|
|
1492
|
+
}
|
|
1493
|
+
function wrappedFromPreimage(home2, attemptId, preimage, plistArgs) {
|
|
1494
|
+
const original = plistArgs(preimage);
|
|
1495
|
+
if (!original || original.length === 0) return { ok: false, reason: "the job's original arguments can't be read" };
|
|
1496
|
+
const xml = wrapPlist(preimage, home2, attemptId, original);
|
|
1497
|
+
return xml ? { ok: true, xml } : { ok: false, reason: "it has no single ProgramArguments array to wrap" };
|
|
1498
|
+
}
|
|
1499
|
+
function writeRecoveryRoute(home2, attempt, deps, io = defaultJournalIo) {
|
|
1500
|
+
const service = identityOf(attempt)?.ownership.service;
|
|
1501
|
+
if (!service) return { ok: false, reason: "the attempt records no service to route through" };
|
|
1502
|
+
let bytes;
|
|
1503
|
+
try {
|
|
1504
|
+
bytes = (0, import_node_fs8.readFileSync)(service.fragmentPath);
|
|
1505
|
+
} catch (err) {
|
|
1506
|
+
return { ok: false, reason: `the service definition ${service.fragmentPath} can't be read (${err.message})` };
|
|
1507
|
+
}
|
|
1508
|
+
const pre = unitPreimagePath(home2, attempt.id);
|
|
1509
|
+
let kept = null;
|
|
1510
|
+
try {
|
|
1511
|
+
kept = (0, import_node_fs8.readFileSync)(pre);
|
|
1512
|
+
} catch (err) {
|
|
1513
|
+
if (err.code !== "ENOENT") return { ok: false, reason: `${pre} can't be read (${err.message})` };
|
|
1514
|
+
}
|
|
1515
|
+
if (kept === null) {
|
|
1516
|
+
try {
|
|
1517
|
+
mkdirDurable(io, home2, attemptDir(home2, attempt.id));
|
|
1518
|
+
writeDurable(pre, bytes, io);
|
|
1519
|
+
} catch (err) {
|
|
1520
|
+
return { ok: false, reason: `the unit's preimage can't be kept (${err.message})` };
|
|
1521
|
+
}
|
|
1522
|
+
} else if (service.kind === "systemd" && !kept.equals(bytes)) {
|
|
1523
|
+
return { ok: false, reason: `the unit ${service.fragmentPath} changed since its preimage was kept` };
|
|
1524
|
+
}
|
|
1525
|
+
if (service.kind === "systemd") {
|
|
1526
|
+
const kit = kitDir(home2, attempt.id);
|
|
1527
|
+
for (const p of [home2, kit, handoffEnvPath(home2, attempt.id)]) if (!unitSafe(p)) return { ok: false, reason: `${p} can't be written into a unit file as one plain word` };
|
|
1528
|
+
const path = dropInPath(service);
|
|
1529
|
+
try {
|
|
1530
|
+
mkdirDurable(io, (0, import_node_path9.dirname)((0, import_node_path9.dirname)(path)), (0, import_node_path9.dirname)(path));
|
|
1531
|
+
writeDurable(path, dropInText(home2, attempt.id), io, 420);
|
|
1532
|
+
} catch (err) {
|
|
1533
|
+
return { ok: false, reason: `the drop-in ${path} can't be written (${err.message})` };
|
|
1534
|
+
}
|
|
1535
|
+
return { ok: true, path };
|
|
1536
|
+
}
|
|
1537
|
+
const wrapped = wrappedFromPreimage(home2, attempt.id, (kept ?? bytes).toString("utf8"), deps.plistArgs);
|
|
1538
|
+
if (!wrapped.ok) return { ok: false, reason: `${service.fragmentPath}: ${wrapped.reason}` };
|
|
1539
|
+
const current = bytes.toString("utf8");
|
|
1540
|
+
if (kept !== null && current !== kept.toString("utf8") && current !== wrapped.xml) {
|
|
1541
|
+
return { ok: false, reason: `${service.fragmentPath} changed since its preimage was kept (it is neither the preimage nor this route's wrapper)` };
|
|
1542
|
+
}
|
|
1543
|
+
if (current === wrapped.xml) return { ok: true, path: service.fragmentPath };
|
|
1544
|
+
try {
|
|
1545
|
+
writeDurable(service.fragmentPath, wrapped.xml, io, "keep");
|
|
1546
|
+
} catch (err) {
|
|
1547
|
+
return { ok: false, reason: `${service.fragmentPath} can't be written (${err.message})` };
|
|
1548
|
+
}
|
|
1549
|
+
return { ok: true, path: service.fragmentPath };
|
|
1550
|
+
}
|
|
1551
|
+
function removeRecoveryRoute(home2, attempt, deps, io = defaultJournalIo) {
|
|
1552
|
+
const service = identityOf(attempt)?.ownership.service;
|
|
1553
|
+
if (!service) return { ok: false, reason: "the attempt records no service" };
|
|
1554
|
+
if (service.kind === "systemd") {
|
|
1555
|
+
const path = dropInPath(service);
|
|
1556
|
+
try {
|
|
1557
|
+
(0, import_node_fs8.unlinkSync)(path);
|
|
1558
|
+
} catch (err) {
|
|
1559
|
+
if (err.code !== "ENOENT") return { ok: false, reason: `${path} can't be removed (${err.message})` };
|
|
1560
|
+
}
|
|
1561
|
+
try {
|
|
1562
|
+
io.fsyncDir((0, import_node_path9.dirname)(path));
|
|
1563
|
+
} catch (err) {
|
|
1564
|
+
if (err.code !== "ENOENT") return { ok: false, reason: `${(0, import_node_path9.dirname)(path)} can't be synced (${err.message})` };
|
|
1565
|
+
}
|
|
1566
|
+
return { ok: true, path };
|
|
1567
|
+
}
|
|
1568
|
+
let kept, current;
|
|
1569
|
+
try {
|
|
1570
|
+
kept = (0, import_node_fs8.readFileSync)(unitPreimagePath(home2, attempt.id));
|
|
1571
|
+
} catch (err) {
|
|
1572
|
+
return { ok: false, reason: `the unit's preimage can't be read (${err.message}); the wrapper stays` };
|
|
1573
|
+
}
|
|
1574
|
+
try {
|
|
1575
|
+
current = (0, import_node_fs8.readFileSync)(service.fragmentPath, "utf8");
|
|
1576
|
+
} catch (err) {
|
|
1577
|
+
return { ok: false, reason: `${service.fragmentPath} can't be read (${err.message}); the wrapper stays` };
|
|
1578
|
+
}
|
|
1579
|
+
if (current === kept.toString("utf8")) return { ok: true, path: service.fragmentPath };
|
|
1580
|
+
const wrapped = wrappedFromPreimage(home2, attempt.id, kept.toString("utf8"), deps.plistArgs);
|
|
1581
|
+
if (!wrapped.ok || current !== wrapped.xml) return { ok: false, reason: `${service.fragmentPath} isn't this route's wrapper any more; it is left as it is` };
|
|
1582
|
+
try {
|
|
1583
|
+
writeDurable(service.fragmentPath, kept, io, "keep");
|
|
1584
|
+
} catch (err) {
|
|
1585
|
+
return { ok: false, reason: `${service.fragmentPath} can't be written back (${err.message})` };
|
|
1586
|
+
}
|
|
1587
|
+
return { ok: true, path: service.fragmentPath };
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// src/update-package-restore.ts
|
|
1591
|
+
var ATTEMPT_PREIMAGE_PREFIX = "attempt-";
|
|
1592
|
+
var PREIMAGE_MANIFEST = "preimage.json";
|
|
1593
|
+
var attemptPreimageDir = (prefix, attemptId) => (0, import_node_path10.join)(prefix, ".agend-rollback", `${ATTEMPT_PREIMAGE_PREFIX}${attemptId}`);
|
|
1594
|
+
var fsyncPath2 = (p) => {
|
|
1595
|
+
const fd = (0, import_node_fs9.openSync)(p, "r");
|
|
1596
|
+
try {
|
|
1597
|
+
(0, import_node_fs9.fsyncSync)(fd);
|
|
1598
|
+
} finally {
|
|
1599
|
+
(0, import_node_fs9.closeSync)(fd);
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
var sha256 = (b) => (0, import_node_crypto4.createHash)("sha256").update(b).digest("hex");
|
|
1603
|
+
function treeOf(root) {
|
|
1604
|
+
const out = [];
|
|
1605
|
+
const visit = (rel) => {
|
|
1606
|
+
for (const name of (0, import_node_fs9.readdirSync)(rel ? (0, import_node_path10.join)(root, rel) : root).sort()) {
|
|
1607
|
+
const r = rel ? `${rel}/${name}` : name, st = (0, import_node_fs9.lstatSync)((0, import_node_path10.join)(root, r));
|
|
1608
|
+
if (st.isSymbolicLink()) out.push({ rel: r, type: "link", mode: 0, target: (0, import_node_fs9.readlinkSync)((0, import_node_path10.join)(root, r)) });
|
|
1609
|
+
else if (st.isDirectory()) {
|
|
1610
|
+
out.push({ rel: r, type: "dir", mode: st.mode & 4095 });
|
|
1611
|
+
visit(r);
|
|
1612
|
+
} else out.push({ rel: r, type: "file", mode: st.mode & 4095, sha256: sha256((0, import_node_fs9.readFileSync)((0, import_node_path10.join)(root, r))) });
|
|
1613
|
+
}
|
|
1614
|
+
};
|
|
1615
|
+
visit("");
|
|
1616
|
+
return out;
|
|
1617
|
+
}
|
|
1618
|
+
function treeMatches(root, entries) {
|
|
1619
|
+
if (!(0, import_node_fs9.existsSync)(root)) return false;
|
|
1620
|
+
let now;
|
|
1621
|
+
try {
|
|
1622
|
+
now = treeOf(root);
|
|
1623
|
+
} catch {
|
|
1624
|
+
return false;
|
|
1625
|
+
}
|
|
1626
|
+
return JSON.stringify(now) === JSON.stringify(entries);
|
|
1627
|
+
}
|
|
1628
|
+
function fsyncTree(root) {
|
|
1629
|
+
const dirs = [root];
|
|
1630
|
+
for (const e of treeOf(root)) {
|
|
1631
|
+
if (e.type === "dir") dirs.push((0, import_node_path10.join)(root, e.rel));
|
|
1632
|
+
else if (e.type === "file") fsyncPath2((0, import_node_path10.join)(root, e.rel));
|
|
1633
|
+
}
|
|
1634
|
+
for (const d of dirs.sort((a, b) => b.length - a.length)) fsyncPath2(d);
|
|
1635
|
+
}
|
|
1636
|
+
function readAttemptPreimage(dir, manifestSha256) {
|
|
1637
|
+
let text;
|
|
1638
|
+
try {
|
|
1639
|
+
text = (0, import_node_fs9.readFileSync)((0, import_node_path10.join)(dir, PREIMAGE_MANIFEST), "utf8");
|
|
1640
|
+
} catch (err) {
|
|
1641
|
+
return { ok: false, reason: `the preimage's manifest can't be read (${err.message})` };
|
|
1642
|
+
}
|
|
1643
|
+
if (sha256(text) !== manifestSha256) return { ok: false, reason: "the preimage's manifest isn't the one the attempt recorded" };
|
|
1644
|
+
const manifest = JSON.parse(text);
|
|
1645
|
+
if (!treeMatches((0, import_node_path10.join)(dir, "agend"), manifest.entries)) return { ok: false, reason: "the preimage's tree doesn't match its manifest" };
|
|
1646
|
+
return { ok: true, manifest };
|
|
1647
|
+
}
|
|
1648
|
+
var Manual2 = class extends Error {
|
|
1649
|
+
};
|
|
1650
|
+
function restorePackage(ownership, attemptId, manifestSha256, steps) {
|
|
1651
|
+
const dir = attemptPreimageDir(ownership.prefix, attemptId);
|
|
1652
|
+
const pre = readAttemptPreimage(dir, manifestSha256);
|
|
1653
|
+
if (!pre.ok) return { ok: false, manual: true, reason: pre.reason };
|
|
1654
|
+
const { manifest } = pre;
|
|
1655
|
+
const pkg = ownership.packagePath, scope = (0, import_node_path10.dirname)(pkg), staged = (0, import_node_path10.join)(scope, `.agend-restore-${attemptId}`), replaced = (0, import_node_path10.join)(dir, "replaced-package");
|
|
1656
|
+
try {
|
|
1657
|
+
if (pkg !== manifest.packagePath) throw new Manual2(`the preimage was taken for ${manifest.packagePath}, not ${pkg}`);
|
|
1658
|
+
if (!steps.done("pkg-aside")) {
|
|
1659
|
+
const here = (0, import_node_fs9.existsSync)(pkg) || isLink(pkg), there = (0, import_node_fs9.existsSync)(replaced) || isLink(replaced);
|
|
1660
|
+
if (here && !there) {
|
|
1661
|
+
(0, import_node_fs9.renameSync)(pkg, replaced);
|
|
1662
|
+
fsyncPath2(scope);
|
|
1663
|
+
fsyncPath2(dir);
|
|
1664
|
+
} else if (here && there) throw new Manual2(`${pkg} and ${replaced} both exist`);
|
|
1665
|
+
steps.record("pkg-aside");
|
|
1666
|
+
}
|
|
1667
|
+
if (!steps.done("pkg-staged")) {
|
|
1668
|
+
(0, import_node_fs9.rmSync)(staged, { recursive: true, force: true });
|
|
1669
|
+
(0, import_node_fs9.cpSync)((0, import_node_path10.join)(dir, "agend"), staged, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true });
|
|
1670
|
+
fsyncTree(staged);
|
|
1671
|
+
fsyncPath2(scope);
|
|
1672
|
+
steps.record("pkg-staged");
|
|
1673
|
+
}
|
|
1674
|
+
if (!steps.done("pkg-placed")) {
|
|
1675
|
+
if (treeMatches(pkg, manifest.entries) && !(0, import_node_fs9.existsSync)(staged)) {
|
|
1676
|
+
} else if ((0, import_node_fs9.existsSync)(staged) && !(0, import_node_fs9.existsSync)(pkg) && !isLink(pkg)) {
|
|
1677
|
+
(0, import_node_fs9.renameSync)(staged, pkg);
|
|
1678
|
+
fsyncPath2(scope);
|
|
1679
|
+
} else throw new Manual2(`${pkg} can't be placed: ${(0, import_node_fs9.existsSync)(pkg) ? "something else is there" : "the staged tree is missing"}`);
|
|
1680
|
+
steps.record("pkg-placed");
|
|
1681
|
+
}
|
|
1682
|
+
if (!steps.done("bins")) {
|
|
1683
|
+
for (const before of Object.values(manifest.bins)) {
|
|
1684
|
+
const { link } = before;
|
|
1685
|
+
const st = (0, import_node_fs9.lstatSync)(link, { throwIfNoEntry: false });
|
|
1686
|
+
if (before.kind === "file") {
|
|
1687
|
+
if (!st || !st.isFile() || sha256((0, import_node_fs9.readFileSync)(link)) !== before.sha256) throw new Manual2(`${link} was a file before the install, and isn't that file now`);
|
|
1688
|
+
continue;
|
|
1689
|
+
}
|
|
1690
|
+
if (before.kind === "absent") {
|
|
1691
|
+
if (st) {
|
|
1692
|
+
if (st.isSymbolicLink()) (0, import_node_fs9.unlinkSync)(link);
|
|
1693
|
+
else throw new Manual2(`${link} wasn't there before, and isn't a link now`);
|
|
1694
|
+
}
|
|
1695
|
+
continue;
|
|
1696
|
+
}
|
|
1697
|
+
if (st?.isSymbolicLink() && (0, import_node_fs9.readlinkSync)(link) === before.target) continue;
|
|
1698
|
+
if (st && !st.isSymbolicLink()) throw new Manual2(`${link} is a file now, not the link it was`);
|
|
1699
|
+
const tmp = `${link}.restore-tmp`;
|
|
1700
|
+
(0, import_node_fs9.rmSync)(tmp, { force: true });
|
|
1701
|
+
(0, import_node_fs9.symlinkSync)(before.target, tmp);
|
|
1702
|
+
(0, import_node_fs9.renameSync)(tmp, link);
|
|
1703
|
+
}
|
|
1704
|
+
for (const d of new Set(Object.values(manifest.bins).map((b) => (0, import_node_path10.dirname)(b.link)))) fsyncPath2(d);
|
|
1705
|
+
steps.record("bins");
|
|
1706
|
+
}
|
|
1707
|
+
return { ok: true };
|
|
1708
|
+
} catch (err) {
|
|
1709
|
+
if (err instanceof Manual2) return { ok: false, manual: true, reason: err.message };
|
|
1710
|
+
throw err;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
function isLink(p) {
|
|
1714
|
+
try {
|
|
1715
|
+
return (0, import_node_fs9.lstatSync)(p).isSymbolicLink();
|
|
1716
|
+
} catch {
|
|
1717
|
+
return false;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
function restoreUnit(home2, attempt, opts, steps) {
|
|
1721
|
+
const service = identityOf(attempt)?.ownership.service;
|
|
1722
|
+
if (!service) return { ok: false, manual: true, reason: "the attempt records no service" };
|
|
1723
|
+
let preimage;
|
|
1724
|
+
try {
|
|
1725
|
+
preimage = (0, import_node_fs9.readFileSync)(unitPreimagePath(home2, attempt.id));
|
|
1726
|
+
} catch (err) {
|
|
1727
|
+
return { ok: false, manual: true, reason: `the unit's preimage can't be read (${err.message})` };
|
|
1728
|
+
}
|
|
1729
|
+
let want = preimage;
|
|
1730
|
+
if (service.kind === "launchd" && opts.keepRoute) {
|
|
1731
|
+
const original = opts.plistArgs(preimage.toString("utf8"));
|
|
1732
|
+
const wrapped = original ? wrapPlist(preimage.toString("utf8"), home2, attempt.id, original) : null;
|
|
1733
|
+
if (!wrapped) return { ok: false, manual: true, reason: "the job's original arguments can't be wrapped" };
|
|
1734
|
+
want = Buffer.from(wrapped);
|
|
1735
|
+
}
|
|
1736
|
+
try {
|
|
1737
|
+
if (!steps.done("unit-written")) {
|
|
1738
|
+
const tmp = `${service.fragmentPath}.restore-tmp`;
|
|
1739
|
+
(0, import_node_fs9.rmSync)(tmp, { force: true });
|
|
1740
|
+
let mode = 420;
|
|
1741
|
+
try {
|
|
1742
|
+
mode = (0, import_node_fs9.lstatSync)(service.fragmentPath).mode & 4095;
|
|
1743
|
+
} catch {
|
|
1744
|
+
}
|
|
1745
|
+
const fd = (0, import_node_fs9.openSync)(tmp, "wx", mode);
|
|
1746
|
+
try {
|
|
1747
|
+
(0, import_node_fs9.writeSync)(fd, want);
|
|
1748
|
+
(0, import_node_fs9.fsyncSync)(fd);
|
|
1749
|
+
} finally {
|
|
1750
|
+
(0, import_node_fs9.closeSync)(fd);
|
|
1751
|
+
}
|
|
1752
|
+
(0, import_node_fs9.renameSync)(tmp, service.fragmentPath);
|
|
1753
|
+
fsyncPath2((0, import_node_path10.dirname)(service.fragmentPath));
|
|
1754
|
+
steps.record("unit-written");
|
|
1755
|
+
}
|
|
1756
|
+
if (opts.keepRoute && service.kind === "systemd" && !steps.done("unit-route-kept")) {
|
|
1757
|
+
const path = dropInPath(service), want2 = dropInText(home2, attempt.id);
|
|
1758
|
+
let now = null;
|
|
1759
|
+
try {
|
|
1760
|
+
now = (0, import_node_fs9.readFileSync)(path, "utf8");
|
|
1761
|
+
} catch (err) {
|
|
1762
|
+
if (err.code !== "ENOENT") throw err;
|
|
1763
|
+
}
|
|
1764
|
+
if (now !== null && now !== want2) throw new Manual2(`${path} isn't this attempt's drop-in any more`);
|
|
1765
|
+
if (now === null) {
|
|
1766
|
+
(0, import_node_fs9.mkdirSync)((0, import_node_path10.dirname)(path), { recursive: true, mode: 493 });
|
|
1767
|
+
const tmp = `${path}.restore-tmp`;
|
|
1768
|
+
(0, import_node_fs9.rmSync)(tmp, { force: true });
|
|
1769
|
+
const fd = (0, import_node_fs9.openSync)(tmp, "wx", 420);
|
|
1770
|
+
try {
|
|
1771
|
+
(0, import_node_fs9.writeSync)(fd, want2);
|
|
1772
|
+
(0, import_node_fs9.fsyncSync)(fd);
|
|
1773
|
+
} finally {
|
|
1774
|
+
(0, import_node_fs9.closeSync)(fd);
|
|
1775
|
+
}
|
|
1776
|
+
(0, import_node_fs9.renameSync)(tmp, path);
|
|
1777
|
+
fsyncPath2((0, import_node_path10.dirname)(path));
|
|
1778
|
+
fsyncPath2((0, import_node_path10.dirname)((0, import_node_path10.dirname)(path)));
|
|
1779
|
+
}
|
|
1780
|
+
steps.record("unit-route-kept");
|
|
1781
|
+
}
|
|
1782
|
+
if (!opts.keepRoute && service.kind === "systemd" && !steps.done("unit-route-removed")) {
|
|
1783
|
+
const removed = removeRecoveryRoute(home2, attempt, { plistArgs: opts.plistArgs });
|
|
1784
|
+
if (!removed.ok) throw new Manual2(removed.reason);
|
|
1785
|
+
steps.record("unit-route-removed");
|
|
1786
|
+
}
|
|
1787
|
+
if (!steps.done("unit-reloaded")) {
|
|
1788
|
+
if (!opts.reload()) return { ok: false, manual: false, reason: `the service manager couldn't reload ${(0, import_node_path10.basename)(service.fragmentPath)}; retry` };
|
|
1789
|
+
steps.record("unit-reloaded");
|
|
1790
|
+
}
|
|
1791
|
+
return { ok: true };
|
|
1792
|
+
} catch (err) {
|
|
1793
|
+
if (err instanceof Manual2) return { ok: false, manual: true, reason: err.message };
|
|
1794
|
+
throw err;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
// src/update-recovery/kit.ts
|
|
1799
|
+
var import_node_crypto5 = require("node:crypto");
|
|
1800
|
+
var import_node_fs10 = require("node:fs");
|
|
1801
|
+
var import_node_child_process2 = require("node:child_process");
|
|
1802
|
+
var import_node_path11 = require("node:path");
|
|
1803
|
+
var KIT_FILE = "kit.json";
|
|
1804
|
+
var sha2562 = (data) => (0, import_node_crypto5.createHash)("sha256").update(data).digest("hex");
|
|
1805
|
+
function verifyRecoveryKit(home2, attemptId) {
|
|
1806
|
+
const dir = kitDir(home2, attemptId);
|
|
1807
|
+
let manifest;
|
|
1808
|
+
try {
|
|
1809
|
+
manifest = JSON.parse((0, import_node_fs10.readFileSync)((0, import_node_path11.join)(dir, KIT_FILE), "utf8"));
|
|
1810
|
+
} catch (err) {
|
|
1811
|
+
return { ok: false, reason: `the kit's manifest can't be read (${err.message})` };
|
|
1812
|
+
}
|
|
1813
|
+
if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) return { ok: false, reason: "the kit's manifest isn't an object" };
|
|
1814
|
+
if (manifest.schema !== 1 || manifest.attemptId !== attemptId || manifest.home !== home2) return { ok: false, reason: "the kit's manifest names another attempt or home" };
|
|
1815
|
+
for (const [file, want] of [["node", manifest.node?.sha256], ["recover.cjs", manifest.recover?.sha256]]) {
|
|
1816
|
+
let got;
|
|
1817
|
+
try {
|
|
1818
|
+
got = sha2562((0, import_node_fs10.readFileSync)((0, import_node_path11.join)(dir, file)));
|
|
1819
|
+
} catch (err) {
|
|
1820
|
+
return { ok: false, reason: `the kit's ${file} can't be read (${err.message})` };
|
|
1821
|
+
}
|
|
1822
|
+
if (got !== want) return { ok: false, reason: `the kit's ${file} doesn't match its manifest` };
|
|
1823
|
+
}
|
|
1824
|
+
return { ok: true, dir, manifest };
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
// src/update-rollback.ts
|
|
1828
|
+
var import_node_fs11 = require("node:fs");
|
|
1829
|
+
var ROLLBACK_FROM = /* @__PURE__ */ new Set(["snapshotted", "installing", "trial", "proving"]);
|
|
1830
|
+
var generationsOf2 = (a) => Array.isArray(a.fleets) ? a.fleets : [];
|
|
1831
|
+
var didSubstep = (a, name) => a.history.some((h) => h.stage === "rolling-back" && h.substep === name);
|
|
1832
|
+
function ensureFence(home2, attempt, d) {
|
|
1833
|
+
let a = attempt;
|
|
1834
|
+
for (let round = 0; round < 3; round++) {
|
|
1835
|
+
const rec = readFleetLockRecord(home2);
|
|
1836
|
+
if (!rec) return { ok: false, reason: `fleet.lock is missing or unreadable in ${a.stage}`, attempt: a };
|
|
1837
|
+
if (rec.role === "update") {
|
|
1838
|
+
if (rec.attemptId !== a.id) return { ok: false, reason: `fleet.lock fences another attempt (${rec.attemptId})`, attempt: a };
|
|
1839
|
+
const adopted = adoptUpdateFence(home2, { pid: d.self.pid, attemptId: a.id }, { isProcessAlive: d.isProcessAlive });
|
|
1840
|
+
if (adopted.ok) return { ok: true, handle: adopted.handle, attempt: a };
|
|
1841
|
+
if (/changed during/.test(adopted.reason)) continue;
|
|
1842
|
+
return { ok: false, reason: adopted.reason, attempt: a };
|
|
1843
|
+
}
|
|
1844
|
+
let gen = generationsOf2(a).find((g) => g.nonce === rec.nonce);
|
|
1845
|
+
if (!gen) return { ok: false, reason: `fleet.lock's holder (pid ${rec.pid}) is no recorded generation`, attempt: a };
|
|
1846
|
+
if (!gen.consumed && !gen.dead) {
|
|
1847
|
+
a = ackGeneration(home2, a, gen.nonce, rec.pid, {}, d.io);
|
|
1848
|
+
gen = generationsOf2(a).find((g) => g.nonce === rec.nonce);
|
|
1849
|
+
}
|
|
1850
|
+
if (d.isProcessAlive(rec.pid)) {
|
|
1851
|
+
const target = stopTarget(a, { pid: rec.pid, nonce: rec.nonce }, d.manager.mainPid());
|
|
1852
|
+
if (!target.ok) return { ok: false, reason: target.reason, attempt: a };
|
|
1853
|
+
if (!d.manager.stop()) return { ok: false, reason: `the ${gen.gen} fleet (pid ${rec.pid}) didn't stop`, attempt: a };
|
|
1854
|
+
if (d.isProcessAlive(rec.pid)) return { ok: false, reason: `the ${gen.gen} fleet (pid ${rec.pid}) is still running after the stop`, attempt: a };
|
|
1855
|
+
}
|
|
1856
|
+
if (!gen.dead || gen.pid !== rec.pid) a = ackGeneration(home2, a, gen.nonce, rec.pid, { dead: true }, d.io);
|
|
1857
|
+
const retaken = retakeDeadFleetLock(home2, { pid: d.self.pid, attemptId: a.id, nonce: rec.nonce }, { isProcessAlive: d.isProcessAlive });
|
|
1858
|
+
if (retaken.ok) return { ok: true, handle: retaken.handle, attempt: a };
|
|
1859
|
+
if (!/changed during/.test(retaken.reason)) return { ok: false, reason: retaken.reason, attempt: a };
|
|
1860
|
+
}
|
|
1861
|
+
return { ok: false, reason: `fleet.lock kept changing in ${a.stage}`, attempt: a };
|
|
1862
|
+
}
|
|
1863
|
+
function startGeneration(home2, attempt, gen, fence, d) {
|
|
1864
|
+
const io = d.io ?? defaultJournalIo;
|
|
1865
|
+
let a = attempt;
|
|
1866
|
+
const fail = (reason, manual = true) => ({ ok: false, manual, reason, attempt: a });
|
|
1867
|
+
const id = identityOf(a);
|
|
1868
|
+
if (!id) return fail("the attempt's recorded ownership is missing or malformed");
|
|
1869
|
+
if (generationsOf2(a).some((g) => g.gen === gen && g.consumed && !g.dead)) return { ok: true, attempt: a };
|
|
1870
|
+
let handle = fence;
|
|
1871
|
+
const planned = generationsOf2(a).find((g) => !g.consumed && !g.dead);
|
|
1872
|
+
if (planned) {
|
|
1873
|
+
const taken = readFleetLockRecord(home2);
|
|
1874
|
+
if (taken?.role === "fleet" && taken.nonce === planned.nonce) {
|
|
1875
|
+
if (planned.gen !== gen) return fail(`the ${planned.gen} generation took fleet.lock over; the ${gen} generation can't start`);
|
|
1876
|
+
return { ok: true, attempt: ackGeneration(home2, a, planned.nonce, taken.pid, {}, io) };
|
|
1877
|
+
}
|
|
1878
|
+
const revoked = revokeHandoff(home2, a.id, planned.nonce, d.self, d.liveness, io);
|
|
1879
|
+
if (revoked === "claimed-live" || revoked === "claimant-unknown") return fail(`the ${planned.gen} generation's claim is held (${revoked})`);
|
|
1880
|
+
if (!handle) return fail(`fleet.lock holds no fence to hand the ${gen} generation over from`);
|
|
1881
|
+
if (handle.record.handoff) {
|
|
1882
|
+
const cleared = setFleetLockHandoff(handle, null, () => true);
|
|
1883
|
+
if (!cleared) return fail("fleet.lock changed while the old handoff was cleared");
|
|
1884
|
+
handle = cleared;
|
|
1885
|
+
}
|
|
1886
|
+
a = voidGeneration(home2, a, planned.nonce, io);
|
|
1887
|
+
}
|
|
1888
|
+
if (!handle) return fail(`no fence to hand the ${gen} generation over from`);
|
|
1889
|
+
const nonce = d.newNonce?.() ?? (0, import_node_crypto6.randomBytes)(16).toString("hex");
|
|
1890
|
+
a = planGeneration(home2, a, gen, nonce, io);
|
|
1891
|
+
if (id.ownership.service) {
|
|
1892
|
+
const kit = verifyRecoveryKit(home2, a.id);
|
|
1893
|
+
if (!kit.ok) return fail(`the ${gen} generation can't start through the recovery route: ${kit.reason}`);
|
|
1894
|
+
}
|
|
1895
|
+
const handed = setFleetLockHandoff(handle, { nonce, gen }, (attemptId, n) => {
|
|
1896
|
+
const r = revokeHandoff(home2, attemptId, n, d.self, d.liveness, io);
|
|
1897
|
+
return r === "revoked" || r === "claimant-gone";
|
|
1898
|
+
});
|
|
1899
|
+
if (!handed) return fail("fleet.lock isn't this attempt's fence any more");
|
|
1900
|
+
if (!d.manager.start({ nonce, gen })) return fail(`the service didn't start for the ${gen} generation; retry`, false);
|
|
1901
|
+
const pid = d.waitTakeover(nonce);
|
|
1902
|
+
if (pid === null) return fail(`the ${gen} generation didn't take fleet.lock over in time; retry`, false);
|
|
1903
|
+
return { ok: true, attempt: ackGeneration(home2, a, nonce, pid, {}, io) };
|
|
1904
|
+
}
|
|
1905
|
+
function rollBack(home2, attempt, d) {
|
|
1906
|
+
const io = d.io ?? defaultJournalIo;
|
|
1907
|
+
let a = attempt;
|
|
1908
|
+
const fail = (reason, manual = true) => ({ ok: false, manual, reason, attempt: a });
|
|
1909
|
+
const id = identityOf(a);
|
|
1910
|
+
if (!id) return fail("the attempt's recorded ownership is missing or malformed");
|
|
1911
|
+
if (a.stage !== "rolling-back") {
|
|
1912
|
+
if (!ROLLBACK_FROM.has(a.stage)) return fail(`attempt ${a.id} can't roll back from ${a.stage}`);
|
|
1913
|
+
a = advance(home2, a, "rolling-back", { note: "the update didn't prove itself" }, io);
|
|
1914
|
+
}
|
|
1915
|
+
const holder = readFleetLockRecord(home2);
|
|
1916
|
+
const rollbackHolds = holder?.role === "fleet" && generationsOf2(a).some((g) => g.gen === "rollback" && g.nonce === holder.nonce);
|
|
1917
|
+
let fenceHandle = null;
|
|
1918
|
+
if (!rollbackHolds) {
|
|
1919
|
+
const fence = ensureFence(home2, a, d);
|
|
1920
|
+
a = fence.attempt;
|
|
1921
|
+
if (!fence.ok) return fail(fence.reason);
|
|
1922
|
+
fenceHandle = fence.handle;
|
|
1923
|
+
}
|
|
1924
|
+
const steps = { done: (n) => didSubstep(a, n), record: (n) => {
|
|
1925
|
+
a = substep(home2, a, n, io);
|
|
1926
|
+
} };
|
|
1927
|
+
if (!steps.done("home-restored")) {
|
|
1928
|
+
const r = restoreHome(home2, attemptDir(home2, a.id), { proveWritersGone: d.proveWritersGone });
|
|
1929
|
+
if (!r.ok) return fail(r.reason, r.manual);
|
|
1930
|
+
steps.record("home-restored");
|
|
1931
|
+
}
|
|
1932
|
+
const intent = a.intent;
|
|
1933
|
+
if (intent?.preimage?.manifestSha256 && !steps.done("bins")) {
|
|
1934
|
+
const r = restorePackage(id.ownership, a.id, intent.preimage.manifestSha256, steps);
|
|
1935
|
+
if (!r.ok) return fail(r.reason, r.manual);
|
|
1936
|
+
}
|
|
1937
|
+
if (id.ownership.service && !(0, import_node_fs11.existsSync)(unitPreimagePath(home2, a.id))) {
|
|
1938
|
+
const kit = verifyRecoveryKit(home2, a.id);
|
|
1939
|
+
if (!kit.ok) return fail(`the recovery route can't be made: ${kit.reason}`);
|
|
1940
|
+
const route = writeRecoveryRoute(home2, a, { plistArgs: d.plistArgs }, io);
|
|
1941
|
+
if (!route.ok) return fail(route.reason);
|
|
1942
|
+
}
|
|
1943
|
+
if (id.ownership.service && !steps.done("unit-reloaded")) {
|
|
1944
|
+
const r = restoreUnit(home2, a, { keepRoute: true, plistArgs: d.plistArgs, reload: d.manager.reload }, steps);
|
|
1945
|
+
if (!r.ok) return fail(r.reason, r.manual);
|
|
1946
|
+
}
|
|
1947
|
+
const started = startGeneration(home2, a, "rollback", fenceHandle, d);
|
|
1948
|
+
a = started.attempt;
|
|
1949
|
+
if (!started.ok) return fail(started.reason, started.manual);
|
|
1950
|
+
if (id.ownership.service && !steps.done("route-removed")) {
|
|
1951
|
+
const removed = removeRecoveryRoute(home2, a, { plistArgs: d.plistArgs }, io);
|
|
1952
|
+
if (!removed.ok) return fail(removed.reason);
|
|
1953
|
+
if (!d.manager.reload()) return fail("the service manager couldn't reload after the route was taken off; retry", false);
|
|
1954
|
+
steps.record("route-removed");
|
|
1955
|
+
}
|
|
1956
|
+
a = finish(home2, a, { kind: "rolled-back", reason: "rolled back to the previous version" }, io);
|
|
1957
|
+
return { ok: true, attempt: a };
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
// src/plist-args.ts
|
|
1961
|
+
var xmlUnescape = (text) => text.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|(lt|gt|quot|apos|amp));/g, (whole, dec, hex, name) => {
|
|
1962
|
+
if (dec !== void 0 || hex !== void 0) {
|
|
1963
|
+
const code = dec !== void 0 ? Number.parseInt(dec, 10) : Number.parseInt(hex, 16);
|
|
1964
|
+
return code <= 1114111 ? String.fromCodePoint(code) : whole;
|
|
1965
|
+
}
|
|
1966
|
+
return { lt: "<", gt: ">", quot: '"', apos: "'", amp: "&" }[name];
|
|
1967
|
+
});
|
|
1968
|
+
function plistProgramArguments(xml) {
|
|
1969
|
+
const args = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(xml);
|
|
1970
|
+
if (!args) return null;
|
|
1971
|
+
const argv = [...args[1].matchAll(/<string>([\s\S]*?)<\/string>/g)].map((m) => xmlUnescape(m[1]));
|
|
1972
|
+
return argv.length ? argv : null;
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
// src/update-recovery/runner.ts
|
|
1976
|
+
var SERVICE_LOCK_FILE = ".service.lock";
|
|
1977
|
+
var startOf2 = (pid, d) => {
|
|
1978
|
+
const processStart2 = d.lock.processStart(pid);
|
|
1979
|
+
if (!processStart2) return null;
|
|
1980
|
+
const ticks = d.lock.startTicks?.(pid) ?? null, boot = d.lock.bootId?.() ?? null;
|
|
1981
|
+
return { processStart: processStart2, ...ticks !== null && boot !== null ? { startTicks: ticks, bootId: boot } : {} };
|
|
1982
|
+
};
|
|
1983
|
+
function evidence(home2, attemptId, d) {
|
|
1984
|
+
const read = readCurrent(home2, d.io);
|
|
1985
|
+
if (read.state === "none") return { ok: false, done: true, words: "No AgEnD update attempt is open; there is nothing to recover." };
|
|
1986
|
+
if (read.state === "unknown") return { ok: false, done: false, words: `the update journal can't be read (${read.reason}: ${read.path}). Run \`agend update --resolve\`.` };
|
|
1987
|
+
if (read.attempt.id !== attemptId) return { ok: false, done: false, words: `the journal's attempt is ${read.attempt.id}, not this kit's.` };
|
|
1988
|
+
if (read.state === "manual") return { ok: false, done: false, words: "it needs manual recovery. Run `agend update --resolve`." };
|
|
1989
|
+
if (read.state === "open") {
|
|
1990
|
+
const updater = updaterState(read.attempt, d.liveness);
|
|
1991
|
+
if (updater === "live") return { ok: false, done: false, words: "its updater is still running; the update owns it until it ends." };
|
|
1992
|
+
if (updater === "unknown") return { ok: false, done: false, words: "whether its updater still runs can't be told; nothing is taken over." };
|
|
1993
|
+
}
|
|
1994
|
+
const runner = readRunnerRecord(home2, attemptId, d.io);
|
|
1995
|
+
if (runner === "unreadable") return { ok: false, done: false, words: "its recovery runner's record can't be read." };
|
|
1996
|
+
if (runner !== null && runner.pid !== d.pid) {
|
|
1997
|
+
const s = holderState({ pid: runner.pid, ...runner.start }, d.liveness);
|
|
1998
|
+
if (s !== "stale") return { ok: false, done: false, words: s === "live" ? `another recovery runner (pid ${runner.pid}) is acting for it.` : `whether its recovery runner (pid ${runner.pid}) still runs can't be told.` };
|
|
1999
|
+
}
|
|
2000
|
+
const prefix = identityOf(read.attempt)?.ownership.prefix;
|
|
2001
|
+
if (!prefix) return { ok: false, done: false, words: "its recorded ownership (the npm prefix) is missing or malformed, so the prefix lock can't be taken." };
|
|
2002
|
+
return { ok: true, read, prefix };
|
|
2003
|
+
}
|
|
2004
|
+
function runRecovery(home2, attemptId, d) {
|
|
2005
|
+
const refuse = (why) => {
|
|
2006
|
+
d.err(`AgEnD's update recovery for attempt ${attemptId} is refused: ${why}`);
|
|
2007
|
+
return 1;
|
|
2008
|
+
};
|
|
2009
|
+
const first = evidence(home2, attemptId, d);
|
|
2010
|
+
if (!first.ok) {
|
|
2011
|
+
if (first.done) {
|
|
2012
|
+
d.out(first.words);
|
|
2013
|
+
return 0;
|
|
2014
|
+
}
|
|
2015
|
+
return refuse(first.words);
|
|
2016
|
+
}
|
|
2017
|
+
const held = [];
|
|
2018
|
+
const releaseAll = () => {
|
|
2019
|
+
for (const l of held.reverse()) if (l.ok) l.release();
|
|
2020
|
+
};
|
|
2021
|
+
const lockDeps = { ...d.lock, pid: d.pid };
|
|
2022
|
+
const locks = [
|
|
2023
|
+
[home2, `recover:${attemptId}`, { file: HOME_UPDATE_LOCK_FILE, name: "home update lock" }],
|
|
2024
|
+
[first.prefix, `recover:${attemptId}`, {}],
|
|
2025
|
+
[home2, `attempt:${attemptId}`, { file: SERVICE_LOCK_FILE, name: "service lock" }]
|
|
2026
|
+
];
|
|
2027
|
+
for (const [dir, spec, opts] of locks) {
|
|
2028
|
+
const taken = acquireInstallLock(dir, { spec, agendHome: home2 }, lockDeps, opts);
|
|
2029
|
+
if (!taken.ok) {
|
|
2030
|
+
releaseAll();
|
|
2031
|
+
return refuse(taken.reason);
|
|
2032
|
+
}
|
|
2033
|
+
held.push(taken);
|
|
2034
|
+
}
|
|
2035
|
+
try {
|
|
2036
|
+
const now = evidence(home2, attemptId, d);
|
|
2037
|
+
if (!now.ok) {
|
|
2038
|
+
if (now.done) {
|
|
2039
|
+
d.out(`The attempt was closed meanwhile. ${now.words}`);
|
|
2040
|
+
return 0;
|
|
2041
|
+
}
|
|
2042
|
+
return refuse(`${now.words} (found again under the locks)`);
|
|
2043
|
+
}
|
|
2044
|
+
if (now.prefix !== first.prefix) return refuse(`its recorded npm prefix changed while the locks were taken (${first.prefix} \u2192 ${now.prefix}).`);
|
|
2045
|
+
const start = startOf2(d.pid, d);
|
|
2046
|
+
if (!start) return refuse("this process's own start time can't be read, so it can't record itself.");
|
|
2047
|
+
writeRunnerRecord(home2, attemptId, { pid: d.pid, start }, d.io);
|
|
2048
|
+
const read = now.read;
|
|
2049
|
+
const plan = recoveryPlan(read, "gone");
|
|
2050
|
+
switch (plan.kind) {
|
|
2051
|
+
case "finish-closing":
|
|
2052
|
+
finishClosing(home2, read.attempt, d.io);
|
|
2053
|
+
d.out(`AgEnD update attempt ${attemptId} (${read.attempt.stage}) is closed.`);
|
|
2054
|
+
return 0;
|
|
2055
|
+
case "start":
|
|
2056
|
+
return 0;
|
|
2057
|
+
case "refuse":
|
|
2058
|
+
return refuse(plan.reason === "manual" ? "it needs manual recovery. Run `agend update --resolve`." : `the journal reads ${plan.reason}.`);
|
|
2059
|
+
case "resume-rolling-back": {
|
|
2060
|
+
const service = identityOf(read.attempt)?.ownership.service ?? null;
|
|
2061
|
+
if (!d.hands) return refuse("this kit can't drive a rollback (no service manager given).");
|
|
2062
|
+
if (!service) return refuse("the attempt records no service to roll back through; start the previous version yourself, then run `agend update --resolve`.");
|
|
2063
|
+
const manager = d.hands.manager(service);
|
|
2064
|
+
if (!manager.waitSettled()) return refuse("the service's refused start hasn't settled; run the recovery again.");
|
|
2065
|
+
const self = { pid: d.pid, start };
|
|
2066
|
+
const res = rollBack(home2, read.attempt, {
|
|
2067
|
+
self,
|
|
2068
|
+
liveness: d.liveness,
|
|
2069
|
+
isProcessAlive: (pid) => (d.liveness.exists ?? (() => true))(pid),
|
|
2070
|
+
proveWritersGone: () => d.hands.proveWritersGone({ updater: read.attempt.updater, runner: self, helpers: [] }),
|
|
2071
|
+
plistArgs: plistProgramArguments,
|
|
2072
|
+
manager,
|
|
2073
|
+
waitTakeover: (nonce) => d.hands.waitTakeover(nonce),
|
|
2074
|
+
io: d.io
|
|
2075
|
+
});
|
|
2076
|
+
if (res.ok) {
|
|
2077
|
+
d.out(`AgEnD update attempt ${attemptId} is rolled back; the previous version runs again.`);
|
|
2078
|
+
return 0;
|
|
2079
|
+
}
|
|
2080
|
+
return refuse(`${res.reason}${res.manual ? " Run `agend update --resolve`." : " Run the recovery again."}`);
|
|
2081
|
+
}
|
|
2082
|
+
case "resume-committing":
|
|
2083
|
+
return refuse(`it is committing ${read.attempt.to.version}, which only the new version's own fleet start finishes, never this recovery kit. Nothing was changed; if the fleet's start can't finish it, run \`agend update --resolve\`.`);
|
|
2084
|
+
default:
|
|
2085
|
+
return refuse(`it needs ${plan.kind.replace("resume-", "resuming ")} from ${read.attempt.stage}${plan.substep ? ` (${plan.substep})` : ""}, which this recovery kit can't do yet. Nothing was changed.`);
|
|
2086
|
+
}
|
|
2087
|
+
} finally {
|
|
2088
|
+
releaseAll();
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
function runnerLaunchCommand(home2, attempt, uid) {
|
|
2092
|
+
const service = identityOf(attempt)?.ownership.service;
|
|
2093
|
+
if (!service) return null;
|
|
2094
|
+
const kit = kitDir(home2, attempt.id);
|
|
2095
|
+
const runner = [(0, import_node_path12.join)(kit, "node"), (0, import_node_path12.join)(kit, "recover.cjs"), "--home", home2, "--attempt", attempt.id, "--run"];
|
|
2096
|
+
if (service.kind === "systemd") {
|
|
2097
|
+
return { command: "systemd-run", args: [...uid !== 0 ? ["--user"] : [], `--unit=agend-update-recovery-${attempt.id}`, "--collect", "--property=KillMode=process", ...runner] };
|
|
2098
|
+
}
|
|
2099
|
+
return { command: "launchctl", args: ["submit", "-l", `com.agend.update-recovery.${attempt.id}`, "--", ...runner] };
|
|
2100
|
+
}
|
|
2101
|
+
function launchRunner(home2, attempt, d, waitMs = 1e4) {
|
|
2102
|
+
const cmd = runnerLaunchCommand(home2, attempt, d.uid());
|
|
2103
|
+
const manual = `run ${operatorCommand(home2, attempt.id)}`;
|
|
2104
|
+
if (!cmd) return { started: false, reason: `the attempt has no recorded service to start a runner beside; ${manual}` };
|
|
2105
|
+
const status = d.run(cmd.command, cmd.args);
|
|
2106
|
+
if (status !== 0) return { started: false, reason: `${cmd.command} couldn't start the recovery runner (${status === null ? "not run" : `exit ${status}`}); ${manual}` };
|
|
2107
|
+
const until = d.now() + waitMs;
|
|
2108
|
+
for (; ; ) {
|
|
2109
|
+
const r = readRunnerRecord(home2, attempt.id, d.io);
|
|
2110
|
+
if (r !== null && r !== "unreadable" && holderState({ pid: r.pid, ...r.start }, d.liveness) === "live") return { started: true, pid: r.pid };
|
|
2111
|
+
if (d.now() >= until) return { started: false, reason: `the recovery runner didn't answer within ${Math.round(waitMs / 1e3)} s; ${manual}` };
|
|
2112
|
+
d.sleep(200);
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
// src/update-recovery/service-manager.ts
|
|
2117
|
+
var SETTLE_MS = 3e4;
|
|
2118
|
+
var POLL_MS = 250;
|
|
2119
|
+
function serviceManager(service, d) {
|
|
2120
|
+
const poll = (ok, timeoutMs) => {
|
|
2121
|
+
const until = d.now() + timeoutMs;
|
|
2122
|
+
for (; ; ) {
|
|
2123
|
+
if (ok()) return true;
|
|
2124
|
+
if (d.now() >= until) return false;
|
|
2125
|
+
d.sleep(POLL_MS);
|
|
2126
|
+
}
|
|
2127
|
+
};
|
|
2128
|
+
if (service.kind === "systemd") {
|
|
2129
|
+
const sc = (...args) => d.run("systemctl", [...d.uid !== 0 ? ["--user"] : [], ...args]);
|
|
2130
|
+
const state = () => sc("is-active", service.unit).stdout.trim();
|
|
2131
|
+
return {
|
|
2132
|
+
mainPid: () => {
|
|
2133
|
+
const r = sc("show", "-p", "MainPID", "--value", service.unit);
|
|
2134
|
+
const pid = Number(r.stdout.trim());
|
|
2135
|
+
return r.status === 0 && Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
2136
|
+
},
|
|
2137
|
+
stop: () => sc("stop", service.unit).status === 0 && poll(() => ["inactive", "failed"].includes(state()), SETTLE_MS),
|
|
2138
|
+
reload: () => sc("daemon-reload").status === 0,
|
|
2139
|
+
start: () => {
|
|
2140
|
+
sc("reset-failed", service.unit);
|
|
2141
|
+
return sc("start", "--no-block", service.unit).status === 0;
|
|
2142
|
+
},
|
|
2143
|
+
waitSettled: (timeoutMs = SETTLE_MS) => poll(() => !["activating", "deactivating", "reloading"].includes(state()), timeoutMs)
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
const target = `gui/${d.uid}/${service.unit}`;
|
|
2147
|
+
const printed = () => d.run("launchctl", ["print", target]);
|
|
2148
|
+
const pidOf = (text) => {
|
|
2149
|
+
const m = /^\s*pid = (\d+)\s*$/m.exec(text);
|
|
2150
|
+
return m ? Number(m[1]) : null;
|
|
2151
|
+
};
|
|
2152
|
+
return {
|
|
2153
|
+
mainPid: () => {
|
|
2154
|
+
const r = printed();
|
|
2155
|
+
return r.status === 0 ? pidOf(r.stdout) : null;
|
|
2156
|
+
},
|
|
2157
|
+
stop: () => {
|
|
2158
|
+
const r = d.run("launchctl", ["bootout", target]);
|
|
2159
|
+
if (r.status !== 0 && printed().status === 0) return false;
|
|
2160
|
+
return poll(() => printed().status !== 0, SETTLE_MS);
|
|
2161
|
+
},
|
|
2162
|
+
reload: () => true,
|
|
2163
|
+
start: () => {
|
|
2164
|
+
const loaded = printed();
|
|
2165
|
+
if (loaded.status === 0) {
|
|
2166
|
+
if (pidOf(loaded.stdout) !== null) return false;
|
|
2167
|
+
const out = d.run("launchctl", ["bootout", target]);
|
|
2168
|
+
if (out.status !== 0 && printed().status === 0) return false;
|
|
2169
|
+
if (!poll(() => printed().status !== 0, SETTLE_MS)) return false;
|
|
2170
|
+
}
|
|
2171
|
+
if (d.run("launchctl", ["bootstrap", `gui/${d.uid}`, service.fragmentPath]).status !== 0) return false;
|
|
2172
|
+
return d.run("launchctl", ["kickstart", target]).status === 0;
|
|
2173
|
+
},
|
|
2174
|
+
waitSettled: (timeoutMs = SETTLE_MS) => poll(() => {
|
|
2175
|
+
const r = printed();
|
|
2176
|
+
return r.status !== 0 || !/^\s*state = (spawn scheduled|xpcproxy)\s*$/m.test(r.stdout);
|
|
2177
|
+
}, timeoutMs)
|
|
2178
|
+
};
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
// src/update-writers.ts
|
|
2182
|
+
var import_node_fs12 = require("node:fs");
|
|
2183
|
+
var import_node_path13 = require("node:path");
|
|
2184
|
+
var isUnder = (path, root) => path === root || path.startsWith(root + import_node_path13.sep);
|
|
2185
|
+
function capsExceed(targetStatus, readerStatus) {
|
|
2186
|
+
const caps = (text) => BigInt(`0x${/^CapPrm:\s+([0-9a-f]+)/m.exec(text)?.[1] ?? "0"}`);
|
|
2187
|
+
return (caps(targetStatus) & ~caps(readerStatus)) !== 0n;
|
|
2188
|
+
}
|
|
2189
|
+
var UNREADABLE_RETRIES = 5;
|
|
2190
|
+
var UNREADABLE_BACKOFF_MS = 20;
|
|
2191
|
+
function proveWritersGone(home2, exempt, d) {
|
|
2192
|
+
if (d.platform !== "linux") return { ok: false, incomplete: true, reason: `no writers scan exists on ${d.platform} yet` };
|
|
2193
|
+
let root;
|
|
2194
|
+
try {
|
|
2195
|
+
root = (0, import_node_fs12.realpathSync)(home2);
|
|
2196
|
+
} catch (err) {
|
|
2197
|
+
return { ok: false, incomplete: true, reason: `the home can't be resolved (${err.message})` };
|
|
2198
|
+
}
|
|
2199
|
+
const pids = d.listPids();
|
|
2200
|
+
if (!pids) return { ok: false, incomplete: true, reason: "the process list can't be read" };
|
|
2201
|
+
const isExact = (pid, who) => !!who && who.pid === pid && d.sameProcess(pid, who.start);
|
|
2202
|
+
const owners = [exempt.updater, ...exempt.runner ? [exempt.runner] : []];
|
|
2203
|
+
const isHelper = (pid) => {
|
|
2204
|
+
const helper = exempt.helpers.find((h) => h.pid === pid);
|
|
2205
|
+
if (!helper || !d.sameProcess(pid, helper.start)) return false;
|
|
2206
|
+
let cur = pid;
|
|
2207
|
+
for (let hops = 0; hops < 64 && typeof cur === "number" && cur > 1; hops++) {
|
|
2208
|
+
const parent = d.ppidOf(cur);
|
|
2209
|
+
if (typeof parent !== "number") return false;
|
|
2210
|
+
if (owners.some((o) => isExact(parent, o))) return true;
|
|
2211
|
+
const step = exempt.helpers.find((h) => h.pid === parent);
|
|
2212
|
+
if (!step || !d.sameProcess(parent, step.start)) return false;
|
|
2213
|
+
cur = parent;
|
|
2214
|
+
}
|
|
2215
|
+
return false;
|
|
2216
|
+
};
|
|
2217
|
+
const writers = [];
|
|
2218
|
+
const uninspectable = [];
|
|
2219
|
+
const look = (pid) => {
|
|
2220
|
+
const uid = d.uidOf(pid);
|
|
2221
|
+
if (uid === "gone") return { kind: "skip" };
|
|
2222
|
+
if (uid === null) return { kind: "unreadable", what: "owner" };
|
|
2223
|
+
if (uid !== d.uid) return { kind: "skip" };
|
|
2224
|
+
if (owners.some((o) => isExact(pid, o)) || isHelper(pid)) return { kind: "skip" };
|
|
2225
|
+
const sealed = d.sealed(pid);
|
|
2226
|
+
if (sealed) return { kind: "uninspectable", why: sealed };
|
|
2227
|
+
const env = d.agendHomeOf(pid), cwd = d.cwdOf(pid), files = d.filesOf(pid);
|
|
2228
|
+
if (env === "gone" || cwd === "gone" || files === "gone") return { kind: "skip" };
|
|
2229
|
+
if (env === null || cwd === null || files === null) return { kind: "unreadable", what: env === null ? "environment" : cwd === null ? "working directory" : "open files" };
|
|
2230
|
+
return { kind: "read", env, cwd, files };
|
|
2231
|
+
};
|
|
2232
|
+
for (const pid of pids) {
|
|
2233
|
+
let r = look(pid);
|
|
2234
|
+
let seen = r.kind === "unreadable" ? d.startOf(pid) : null;
|
|
2235
|
+
for (let tries = 0, renewals = 0; r.kind === "unreadable" && tries < UNREADABLE_RETRIES; tries++) {
|
|
2236
|
+
d.sleep(UNREADABLE_BACKOFF_MS);
|
|
2237
|
+
const start = d.startOf(pid);
|
|
2238
|
+
if (start && seen && !d.sameProcess(pid, seen) && renewals < 3) {
|
|
2239
|
+
seen = start;
|
|
2240
|
+
tries = -1;
|
|
2241
|
+
renewals++;
|
|
2242
|
+
} else if (!seen) seen = start;
|
|
2243
|
+
r = look(pid);
|
|
2244
|
+
}
|
|
2245
|
+
if (r.kind === "skip") continue;
|
|
2246
|
+
if (r.kind === "uninspectable") {
|
|
2247
|
+
uninspectable.push({ pid, name: d.nameOf?.(pid) ?? null, why: r.why });
|
|
2248
|
+
continue;
|
|
2249
|
+
}
|
|
2250
|
+
if (r.kind === "unreadable") {
|
|
2251
|
+
const name = d.nameOf?.(pid);
|
|
2252
|
+
return { ok: false, incomplete: true, reason: `pid ${pid}${name ? ` (${name})` : ""}, this user's, stays unreadable (its ${r.what}) through ${UNREADABLE_RETRIES} re-reads` };
|
|
2253
|
+
}
|
|
2254
|
+
const { env, cwd, files } = r;
|
|
2255
|
+
const real = (p) => {
|
|
2256
|
+
try {
|
|
2257
|
+
return (0, import_node_fs12.realpathSync)(p);
|
|
2258
|
+
} catch {
|
|
2259
|
+
return p;
|
|
2260
|
+
}
|
|
2261
|
+
};
|
|
2262
|
+
if (env !== void 0 && real(env) === root) {
|
|
2263
|
+
writers.push({ pid, why: `its AGEND_HOME is this home` });
|
|
2264
|
+
continue;
|
|
2265
|
+
}
|
|
2266
|
+
if (isUnder(real(cwd), root)) {
|
|
2267
|
+
writers.push({ pid, why: `its working directory is under the home (${cwd})` });
|
|
2268
|
+
continue;
|
|
2269
|
+
}
|
|
2270
|
+
const scoped = files.find((f) => {
|
|
2271
|
+
if (!isUnder(f, root) || f === root) return false;
|
|
2272
|
+
const rel = f.slice(root.length + 1).split(import_node_path13.sep).join("/");
|
|
2273
|
+
try {
|
|
2274
|
+
return classify(rel).included;
|
|
2275
|
+
} catch {
|
|
2276
|
+
return false;
|
|
2277
|
+
}
|
|
2278
|
+
});
|
|
2279
|
+
if (scoped) writers.push({ pid, why: `it has ${scoped} open or mapped` });
|
|
2280
|
+
}
|
|
2281
|
+
return writers.length ? { ok: false, incomplete: false, writers, reason: writers.map((w) => `pid ${w.pid}: ${w.why}`).join("; ") } : { ok: true, ...uninspectable.length ? { uninspectable } : {} };
|
|
2282
|
+
}
|
|
2283
|
+
function procWritersDeps(sameProcess, startOf3) {
|
|
2284
|
+
const gone = (err) => ["ENOENT", "ESRCH"].includes(err.code ?? "");
|
|
2285
|
+
const read = (fn) => {
|
|
2286
|
+
try {
|
|
2287
|
+
return fn();
|
|
2288
|
+
} catch (err) {
|
|
2289
|
+
return gone(err) ? "gone" : null;
|
|
2290
|
+
}
|
|
2291
|
+
};
|
|
2292
|
+
return {
|
|
2293
|
+
listPids: () => {
|
|
2294
|
+
try {
|
|
2295
|
+
return (0, import_node_fs12.readdirSync)("/proc").filter((n) => /^\d+$/.test(n)).map(Number);
|
|
2296
|
+
} catch {
|
|
2297
|
+
return null;
|
|
2298
|
+
}
|
|
2299
|
+
},
|
|
2300
|
+
uidOf: (pid) => read(() => (0, import_node_fs12.statSync)(`/proc/${pid}`).uid),
|
|
2301
|
+
agendHomeOf: (pid) => read(() => {
|
|
2302
|
+
const env = (0, import_node_fs12.readFileSync)(`/proc/${pid}/environ`, "latin1").split("\0").find((e) => e.startsWith("AGEND_HOME="));
|
|
2303
|
+
return env === void 0 ? void 0 : env.slice("AGEND_HOME=".length);
|
|
2304
|
+
}),
|
|
2305
|
+
cwdOf: (pid) => read(() => (0, import_node_fs12.readlinkSync)(`/proc/${pid}/cwd`)),
|
|
2306
|
+
filesOf: (pid) => read(() => {
|
|
2307
|
+
const out = [];
|
|
2308
|
+
for (const fd of (0, import_node_fs12.readdirSync)(`/proc/${pid}/fd`)) {
|
|
2309
|
+
try {
|
|
2310
|
+
const t = (0, import_node_fs12.readlinkSync)((0, import_node_path13.join)(`/proc/${pid}/fd`, fd));
|
|
2311
|
+
if (t.startsWith("/")) out.push(t.replace(/ \(deleted\)$/, ""));
|
|
2312
|
+
} catch (err) {
|
|
2313
|
+
if (!gone(err)) throw err;
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
for (const line of (0, import_node_fs12.readFileSync)(`/proc/${pid}/maps`, "utf8").split("\n")) {
|
|
2317
|
+
const at = line.indexOf("/");
|
|
2318
|
+
if (at >= 0) out.push(line.slice(at).replace(/ \(deleted\)$/, ""));
|
|
2319
|
+
}
|
|
2320
|
+
return out;
|
|
2321
|
+
}),
|
|
2322
|
+
ppidOf: (pid) => read(() => {
|
|
2323
|
+
const stat = (0, import_node_fs12.readFileSync)(`/proc/${pid}/stat`, "utf8");
|
|
2324
|
+
return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
|
|
2325
|
+
}),
|
|
2326
|
+
startOf: (pid) => {
|
|
2327
|
+
const t = startOf3(pid);
|
|
2328
|
+
return t ? { processStart: t } : null;
|
|
2329
|
+
},
|
|
2330
|
+
sleep: (ms) => {
|
|
2331
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
2332
|
+
},
|
|
2333
|
+
sealed: (pid) => {
|
|
2334
|
+
try {
|
|
2335
|
+
const status = (0, import_node_fs12.readFileSync)(`/proc/${pid}/status`, "utf8");
|
|
2336
|
+
const real = /^Uid:\s+(\d+)/m.exec(status)?.[1];
|
|
2337
|
+
if (real === void 0 || Number(real) === 0) return false;
|
|
2338
|
+
if ((0, import_node_fs12.statSync)(`/proc/${pid}/fd`).uid === 0) return "non-dumpable";
|
|
2339
|
+
return capsExceed(status, (0, import_node_fs12.readFileSync)("/proc/self/status", "utf8")) ? "privileged" : false;
|
|
2340
|
+
} catch {
|
|
2341
|
+
return false;
|
|
2342
|
+
}
|
|
2343
|
+
},
|
|
2344
|
+
nameOf: (pid) => {
|
|
2345
|
+
try {
|
|
2346
|
+
return /^Name:\s+(.*)$/m.exec((0, import_node_fs12.readFileSync)(`/proc/${pid}/status`, "utf8"))?.[1] ?? null;
|
|
2347
|
+
} catch {
|
|
2348
|
+
return null;
|
|
2349
|
+
}
|
|
2350
|
+
},
|
|
2351
|
+
sameProcess,
|
|
2352
|
+
uid: typeof process.getuid === "function" ? process.getuid() : -1,
|
|
2353
|
+
platform: process.platform
|
|
2354
|
+
};
|
|
2355
|
+
}
|
|
2356
|
+
|
|
2357
|
+
// src/update-recovery/recover.ts
|
|
2358
|
+
var sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
2359
|
+
function realHands(home2, takeoverMs = 6e4) {
|
|
2360
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
2361
|
+
const run = (command, args) => {
|
|
2362
|
+
const r = (0, import_node_child_process3.spawnSync)(command, args, { encoding: "utf8", timeout: 3e4 });
|
|
2363
|
+
return { status: r.error ? null : r.status, stdout: r.stdout ?? "" };
|
|
2364
|
+
};
|
|
2365
|
+
return {
|
|
2366
|
+
manager: (service) => serviceManager(service, { run, uid, sleep: sleepSync, now: () => performance.now() }),
|
|
2367
|
+
waitTakeover: (nonce) => {
|
|
2368
|
+
const until = performance.now() + takeoverMs;
|
|
2369
|
+
for (; ; ) {
|
|
2370
|
+
const rec = readFleetLockRecord(home2);
|
|
2371
|
+
if (rec?.role === "fleet" && rec.nonce === nonce) return rec.pid;
|
|
2372
|
+
if (performance.now() >= until) return null;
|
|
2373
|
+
sleepSync(250);
|
|
2374
|
+
}
|
|
2375
|
+
},
|
|
2376
|
+
proveWritersGone: (exempt) => {
|
|
2377
|
+
const res = proveWritersGone(home2, exempt, procWritersDeps((pid, s) => (0, import_install_admission.processStart)(pid) === s.processStart, (pid) => (0, import_install_admission.processStart)(pid)));
|
|
2378
|
+
return res.ok ? { ok: true } : { ok: false, reason: res.reason };
|
|
2379
|
+
}
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
var defaultRecoverDeps = () => ({
|
|
2383
|
+
liveness: { processStart: import_install_admission.processStart, startTicks: import_install_admission.startTicks, bootId: import_install_admission.bootId, exists: import_install_admission.exists },
|
|
2384
|
+
io: defaultJournalIo,
|
|
2385
|
+
err: (line) => process.stderr.write(line + "\n"),
|
|
2386
|
+
out: (line) => process.stdout.write(line + "\n"),
|
|
2387
|
+
runner: {
|
|
2388
|
+
pid: process.pid,
|
|
2389
|
+
lock: { processStart: import_install_admission.processStart, startTicks: import_install_admission.startTicks, bootId: import_install_admission.bootId, exists: import_install_admission.exists, newToken: () => (0, import_node_crypto7.randomBytes)(16).toString("hex"), now: () => /* @__PURE__ */ new Date(), log: () => {
|
|
2390
|
+
} }
|
|
2391
|
+
},
|
|
2392
|
+
launch: {
|
|
2393
|
+
run: (command, args) => {
|
|
2394
|
+
const r = (0, import_node_child_process3.spawnSync)(command, args, { stdio: "ignore", timeout: 15e3 });
|
|
2395
|
+
return r.error ? null : r.status;
|
|
2396
|
+
},
|
|
2397
|
+
sleep: sleepSync,
|
|
2398
|
+
now: () => Date.now(),
|
|
2399
|
+
uid: () => typeof process.getuid === "function" ? process.getuid() : 0
|
|
2400
|
+
}
|
|
2401
|
+
});
|
|
2402
|
+
function parseArgs(argv) {
|
|
2403
|
+
let home2 = null, attempt = null, mode = null;
|
|
2404
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2405
|
+
const a = argv[i];
|
|
2406
|
+
if (a === "--home" && argv[i + 1] && home2 === null) home2 = argv[++i];
|
|
2407
|
+
else if (a === "--attempt" && argv[i + 1] && attempt === null) attempt = argv[++i];
|
|
2408
|
+
else if (a === "--pre-start" && !mode) mode = "pre-start";
|
|
2409
|
+
else if (a === "--run" && !mode) mode = "run";
|
|
2410
|
+
else return null;
|
|
2411
|
+
}
|
|
2412
|
+
return home2 && attempt && mode && (0, import_node_path14.isAbsolute)(home2) && isAttemptId(attempt) ? { home: home2, attempt, mode } : null;
|
|
2413
|
+
}
|
|
2414
|
+
function main(argv, deps = defaultRecoverDeps()) {
|
|
2415
|
+
const args = parseArgs(argv);
|
|
2416
|
+
if (!args) {
|
|
2417
|
+
deps.err("usage: recover.cjs --home <absolute home> --attempt <attempt id> (--pre-start | --run)");
|
|
2418
|
+
return 2;
|
|
2419
|
+
}
|
|
2420
|
+
const { home: home2, attempt } = args;
|
|
2421
|
+
if (args.mode === "run") {
|
|
2422
|
+
return runRecovery(home2, attempt, { ...deps.runner, hands: deps.runner.hands ?? realHands(home2), liveness: deps.liveness, io: deps.io, err: deps.err, out: deps.out });
|
|
2423
|
+
}
|
|
2424
|
+
const read = readCurrent(home2, deps.io);
|
|
2425
|
+
const owner = read.state === "open" ? ownerState(home2, read.attempt, deps.liveness, deps.io) : "gone";
|
|
2426
|
+
const decision = preStartDecision(home2, read, owner, attempt);
|
|
2427
|
+
try {
|
|
2428
|
+
applyHandoffEnv(home2, decision, attempt, deps.io);
|
|
2429
|
+
} catch (err) {
|
|
2430
|
+
deps.err(`AgEnD's update pre-start check couldn't write the handoff (${err.message}). This start is refused.`);
|
|
2431
|
+
return 1;
|
|
2432
|
+
}
|
|
2433
|
+
switch (decision.kind) {
|
|
2434
|
+
case "start":
|
|
2435
|
+
return 0;
|
|
2436
|
+
case "handoff":
|
|
2437
|
+
deps.out(`AgEnD update attempt ${decision.attemptId}: this start takes the planned handoff.`);
|
|
2438
|
+
return 0;
|
|
2439
|
+
case "refuse":
|
|
2440
|
+
deps.err(decision.reason);
|
|
2441
|
+
return 1;
|
|
2442
|
+
case "start-runner": {
|
|
2443
|
+
if (read.state !== "open") return 1;
|
|
2444
|
+
const launched = launchRunner(home2, read.attempt, { ...deps.launch, liveness: deps.liveness, io: deps.io });
|
|
2445
|
+
deps.err(launched.started ? `Update attempt ${decision.attemptId} (${decision.stage}) was interrupted: its updater is gone. The recovery runner (pid ${launched.pid}) took over; this start is refused.` : `Update attempt ${decision.attemptId} (${decision.stage}) was interrupted: its updater is gone. This start is refused; ${launched.reason}`);
|
|
2446
|
+
return 1;
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
// src/update-recovery/recover-main.ts
|
|
2452
|
+
process.exitCode = main(process.argv.slice(2));
|