@bastani/atomic 0.9.15 → 0.9.16-alpha.2

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.
Files changed (151) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +10 -0
  3. package/dist/builtin/intercom/README.md +8 -8
  4. package/dist/builtin/intercom/contact-supervisor-tool.ts +68 -32
  5. package/dist/builtin/intercom/index-heavy.ts +1 -0
  6. package/dist/builtin/intercom/index.ts +21 -15
  7. package/dist/builtin/intercom/intercom-tool.ts +66 -10
  8. package/dist/builtin/intercom/package.json +1 -1
  9. package/dist/builtin/intercom/parent-ask-handoff.ts +72 -0
  10. package/dist/builtin/mcp/package.json +1 -1
  11. package/dist/builtin/subagents/CHANGELOG.md +26 -0
  12. package/dist/builtin/subagents/README.md +37 -114
  13. package/dist/builtin/subagents/agents/worker.md +2 -2
  14. package/dist/builtin/subagents/package.json +1 -5
  15. package/dist/builtin/subagents/skills/subagent/SKILL.md +26 -103
  16. package/dist/builtin/subagents/src/extension/index.ts +5 -30
  17. package/dist/builtin/subagents/src/extension/notification-content.ts +1 -1
  18. package/dist/builtin/subagents/src/extension/schemas.ts +2 -14
  19. package/dist/builtin/subagents/src/extension/tool-description.ts +1 -4
  20. package/dist/builtin/subagents/src/extension/tool-rendering.ts +53 -0
  21. package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +1 -54
  22. package/dist/builtin/subagents/src/intercom/result-intercom.ts +4 -4
  23. package/dist/builtin/subagents/src/runs/foreground/execution-parent-ask-handoff.ts +78 -0
  24. package/dist/builtin/subagents/src/runs/foreground/inprocess-run-sync.ts +7 -5
  25. package/dist/builtin/subagents/src/runs/foreground/notify.ts +5 -6
  26. package/dist/builtin/subagents/src/runs/foreground/parent-ask-output.ts +48 -0
  27. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-burst-display.ts +46 -0
  28. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-burst.ts +403 -0
  29. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +48 -9
  30. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-input.ts +3 -1
  31. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-live-update.ts +11 -0
  32. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +164 -93
  33. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +36 -29
  34. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parent-ask-projection.ts +11 -0
  35. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +42 -17
  36. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +3 -121
  37. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +7 -2
  38. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +30 -257
  39. package/dist/builtin/subagents/src/runs/inprocess/control-status.ts +0 -34
  40. package/dist/builtin/subagents/src/runs/inprocess/index.ts +0 -12
  41. package/dist/builtin/subagents/src/runs/inprocess/prompt-behavior.ts +1 -1
  42. package/dist/builtin/subagents/src/runs/inprocess/runner.ts +2 -141
  43. package/dist/builtin/subagents/src/runs/shared/parallel-utils.ts +8 -0
  44. package/dist/builtin/subagents/src/shared/status-format.ts +3 -3
  45. package/dist/builtin/subagents/src/shared/types-config.ts +41 -0
  46. package/dist/builtin/subagents/src/shared/types-foreground-state.ts +7 -15
  47. package/dist/builtin/subagents/src/shared/types-results.ts +3 -1
  48. package/dist/builtin/subagents/src/shared/types-runtime.ts +1 -11
  49. package/dist/builtin/subagents/src/slash/slash-commands.ts +4 -468
  50. package/dist/builtin/subagents/src/tui/render-progress.ts +2 -2
  51. package/dist/builtin/subagents/src/tui/render-result-compact.ts +2 -2
  52. package/dist/builtin/subagents/src/tui/render-result.ts +38 -14
  53. package/dist/builtin/subagents/src/tui/render-status-progress.ts +1 -1
  54. package/dist/builtin/web-access/package.json +1 -1
  55. package/dist/builtin/workflows/CHANGELOG.md +16 -0
  56. package/dist/builtin/workflows/README.md +1 -1
  57. package/dist/builtin/workflows/package.json +1 -1
  58. package/dist/builtin/workflows/skills/bro/LICENSE.txt +21 -0
  59. package/dist/builtin/workflows/skills/bro/SKILL.md +14 -0
  60. package/dist/builtin/workflows/skills/how/LICENSE.txt +21 -0
  61. package/dist/builtin/workflows/skills/how/SKILL.md +162 -0
  62. package/dist/builtin/workflows/skills/how/references/critic-prompt.md +59 -0
  63. package/dist/builtin/workflows/skills/how/references/critique-rubric.md +58 -0
  64. package/dist/builtin/workflows/skills/how/references/explainer-prompt.md +55 -0
  65. package/dist/builtin/workflows/skills/how/references/explorer-prompt.md +52 -0
  66. package/dist/builtin/workflows/skills/teach/LICENSE.txt +21 -0
  67. package/dist/builtin/workflows/skills/teach/SKILL.md +28 -0
  68. package/dist/builtin/workflows/skills/unslop/LICENSE.txt +21 -0
  69. package/dist/builtin/workflows/skills/unslop/SKILL.md +87 -0
  70. package/dist/builtin/workflows/skills/why/LICENSE.txt +21 -0
  71. package/dist/builtin/workflows/skills/why/SKILL.md +267 -0
  72. package/dist/builtin/workflows/skills/why/references/epistemics.md +144 -0
  73. package/dist/builtin/workflows/skills/why/references/investigator-prompt.md +103 -0
  74. package/dist/builtin/workflows/skills/why/references/source-playbook.md +17 -0
  75. package/dist/builtin/workflows/skills/why/references/sources/code-archaeology.md +88 -0
  76. package/dist/builtin/workflows/skills/why/references/sources/databricks.md +70 -0
  77. package/dist/builtin/workflows/skills/why/references/sources/datadog.md +99 -0
  78. package/dist/builtin/workflows/skills/why/references/sources/incident-postmortem.md +15 -0
  79. package/dist/builtin/workflows/skills/why/references/sources/linear.md +48 -0
  80. package/dist/builtin/workflows/skills/why/references/sources/notion.md +55 -0
  81. package/dist/builtin/workflows/skills/why/references/sources/sentry.md +100 -0
  82. package/dist/builtin/workflows/skills/why/references/sources/slack.md +54 -0
  83. package/dist/builtin/workflows/skills/why/references/synthesizer-prompt.md +135 -0
  84. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts +548 -39
  85. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres.ts +529 -65
  86. package/dist/builtin/workflows/src/durable/dbos-lifecycle.ts +30 -8
  87. package/dist/builtin/workflows/src/durable/dbos-local-postgres.ts +36 -3
  88. package/dist/builtin/workflows/src/durable/local-command.ts +68 -10
  89. package/dist/builtin/workflows/src/extension/companions.ts +1 -1
  90. package/dist/builtin/workflows/src/extension/dispatcher.ts +7 -1
  91. package/dist/builtin/workflows/src/extension/extension-factory.ts +2 -2
  92. package/dist/builtin/workflows/src/extension/index.bundle.mjs +1094 -298
  93. package/dist/builtin/workflows/src/extension/public-types.ts +2 -2
  94. package/dist/builtin/workflows/src/extension/render-result.ts +16 -2
  95. package/dist/builtin/workflows/src/extension/runtime.ts +8 -1
  96. package/dist/builtin/workflows/src/extension/workflow-request-abort.ts +15 -0
  97. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +4 -3
  98. package/dist/builtin/workflows/src/extension/workflow-tool-registration.ts +107 -13
  99. package/dist/builtin/workflows/src/extension/workflow-tool.ts +22 -12
  100. package/dist/builtin/workflows/src/tui/widget.ts +25 -6
  101. package/dist/core/agent-session-auto-compaction.js +10 -10
  102. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  103. package/dist/core/agent-session-events.d.ts.map +1 -1
  104. package/dist/core/agent-session-events.js +11 -13
  105. package/dist/core/agent-session-events.js.map +1 -1
  106. package/dist/core/agent-session-methods.d.ts +1 -1
  107. package/dist/core/agent-session-methods.d.ts.map +1 -1
  108. package/dist/core/agent-session-methods.js.map +1 -1
  109. package/dist/core/agent-session-models.d.ts.map +1 -1
  110. package/dist/core/agent-session-models.js +5 -7
  111. package/dist/core/agent-session-models.js.map +1 -1
  112. package/dist/core/agent-session-prompt.js +4 -4
  113. package/dist/core/agent-session-prompt.js.map +1 -1
  114. package/dist/core/agent-session-retry.d.ts +4 -4
  115. package/dist/core/agent-session-retry.d.ts.map +1 -1
  116. package/dist/core/agent-session-retry.js +8 -34
  117. package/dist/core/agent-session-retry.js.map +1 -1
  118. package/dist/core/agent-session-tool-hooks.js +4 -4
  119. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  120. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  121. package/dist/core/atomic-guide-command.js +3 -10
  122. package/dist/core/atomic-guide-command.js.map +1 -1
  123. package/dist/core/event-bus.d.ts.map +1 -1
  124. package/dist/core/event-bus.js +19 -3
  125. package/dist/core/event-bus.js.map +1 -1
  126. package/dist/core/slash-commands.d.ts.map +1 -1
  127. package/dist/core/slash-commands.js +0 -3
  128. package/dist/core/slash-commands.js.map +1 -1
  129. package/dist/core/system-prompt.d.ts.map +1 -1
  130. package/dist/core/system-prompt.js +0 -12
  131. package/dist/core/system-prompt.js.map +1 -1
  132. package/dist/modes/interactive-engine/remote-command-catalog.d.ts +1 -1
  133. package/dist/modes/interactive-engine/remote-command-catalog.js +1 -1
  134. package/dist/modes/interactive-engine/remote-command-catalog.js.map +1 -1
  135. package/docs/intercom.md +29 -27
  136. package/docs/settings.md +2 -2
  137. package/docs/subagents.md +18 -15
  138. package/docs/usage.md +0 -9
  139. package/docs/workflows.md +27 -10
  140. package/npm-shrinkwrap.json +32 -32
  141. package/package.json +3 -3
  142. package/dist/builtin/subagents/prompts/gather-context-and-clarify.md +0 -27
  143. package/dist/builtin/subagents/prompts/parallel-cleanup.md +0 -61
  144. package/dist/builtin/subagents/prompts/parallel-context-build.md +0 -43
  145. package/dist/builtin/subagents/prompts/parallel-handoff-plan.md +0 -47
  146. package/dist/builtin/subagents/prompts/parallel-research.md +0 -34
  147. package/dist/builtin/subagents/prompts/parallel-review.md +0 -47
  148. package/dist/builtin/subagents/prompts/review-loop.md +0 -39
  149. package/dist/builtin/subagents/src/extension/doctor.ts +0 -188
  150. package/dist/builtin/subagents/src/runs/inprocess/attempt-handles.ts +0 -104
  151. /package/dist/builtin/subagents/src/runs/foreground/{subagent-executor-resume.ts → subagent-executor-cwd.ts} +0 -0
@@ -8,21 +8,36 @@
8
8
  * directory (`/root` is mode 0700 and untraversable by that account), and run
9
9
  * every Postgres command with dropped privileges.
10
10
  *
11
- * Privilege dropping is strategy-probed at runtime: Node honors the child
12
- * process `uid`/`gid` spawn options, but Bun currently ignores them, so we
13
- * verify the drop actually happens (`id -u` must report the owner) and fall
14
- * back to `setpriv`, `runuser`, or `su` wrappers when it does not.
11
+ * Privilege dropping is strategy-probed at runtime because subprocess
12
+ * implementations can differ in how completely they apply `uid`/`gid` spawn
13
+ * options. Every candidate must prove the target uid, primary gid, and safe
14
+ * supplementary groups before it can run any owner command. Incomplete
15
+ * candidates fall back to `setpriv`, `runuser`, or `su`.
15
16
  *
16
17
  * The embedded binaries themselves may also live under an untraversable
17
- * prefix (for example a root-owned `~/.nvm` global install), so the caller can
18
- * probe them as the unprivileged owner and fall back to a one-time copy into
19
- * the cluster base directory.
18
+ * probe them as the unprivileged owner and fall back to a recoverable staged
19
+ * copy in the cluster base directory.
20
20
  */
21
21
 
22
- import { cpSync, existsSync } from "node:fs";
22
+ import { createHash, type Hash } from "node:crypto";
23
+ import type { Stats } from "node:fs";
24
+ import {
25
+ chmod,
26
+ chown,
27
+ cp,
28
+ lstat,
29
+ mkdir,
30
+ open,
31
+ readdir,
32
+ readlink,
33
+ realpath,
34
+ rename,
35
+ rm,
36
+ writeFile,
37
+ } from "node:fs/promises";
23
38
  import { homedir } from "node:os";
24
- import { dirname, join } from "node:path";
25
- import { type LocalCommandResult, runLocalCommand } from "./local-command.js";
39
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
40
+ import { type LocalCommandOptions, type LocalCommandResult, runLocalCommand } from "./local-command.js";
26
41
 
27
42
  export interface EmbeddedPostgresOwner {
28
43
  readonly uid: number;
@@ -42,12 +57,13 @@ export interface EmbeddedPostgresRunContext {
42
57
  export interface EmbeddedPostgresBinaryPaths {
43
58
  readonly pg_ctl: string;
44
59
  readonly initdb: string;
60
+ readonly postgres: string;
45
61
  }
46
62
 
47
63
  export type LocalCommandRunner = (
48
64
  command: string,
49
65
  args: readonly string[],
50
- options?: { readonly uid?: number; readonly gid?: number },
66
+ options?: LocalCommandOptions,
51
67
  ) => Promise<LocalCommandResult>;
52
68
 
53
69
  /** Root-safe cluster location: system path, traversable by system accounts. */
@@ -87,40 +103,107 @@ export async function resolveEmbeddedRunContext(
87
103
 
88
104
  /**
89
105
  * Return a runner that verifiably executes commands as the owner, or
90
- * `undefined` when no drop mechanism works. Each strategy is validated by
91
- * running `id -u` through it and requiring the owner's uid on stdout — the
92
- * spawn `uid`/`gid` options in particular are silently ignored by Bun.
106
+ * `undefined` when no drop mechanism works. Each candidate proves its complete
107
+ * effective identity through its own runner before it can be selected.
93
108
  */
94
109
  export async function resolvePrivilegeDrop(
95
110
  runner: LocalCommandRunner,
96
111
  owner: EmbeddedPostgresOwner,
97
112
  ): Promise<LocalCommandRunner | undefined> {
98
113
  const strategies: readonly LocalCommandRunner[] = [
99
- (command, args) => runner(command, args, { uid: owner.uid, gid: owner.gid }),
100
- (command, args) =>
101
- runner("setpriv", [`--reuid=${owner.uid}`, `--regid=${owner.gid}`, "--clear-groups", "--", command, ...args]),
102
- (command, args) => runner("runuser", ["-u", owner.name, "--", command, ...args]),
103
- (command, args) => runner("su", ["-s", "/bin/sh", "-c", shellCommand(command, args), owner.name]),
114
+ (command, args, options) => runner(command, args, { ...options, uid: owner.uid, gid: owner.gid }),
115
+ (command, args, options) =>
116
+ runner(
117
+ "setpriv",
118
+ [`--reuid=${owner.uid}`, `--regid=${owner.gid}`, "--clear-groups", "--", command, ...args],
119
+ options,
120
+ ),
121
+ (command, args, options) => runner("runuser", ["-u", owner.name, "--", command, ...args], options),
122
+ (command, args, options) =>
123
+ runner("su", ["-s", "/bin/sh", "-c", shellCommand(command, args), owner.name], options),
104
124
  ];
105
125
  for (const strategy of strategies) {
106
- const probe = await strategy("id", ["-u"]).catch(() => undefined);
107
- if (probe !== undefined && probe.exitCode === 0 && probe.stdout.trim() === String(owner.uid)) {
108
- return strategy;
109
- }
126
+ if (await provesOwnerIdentity(strategy, owner)) return strategy;
110
127
  }
111
128
  return undefined;
112
129
  }
113
130
 
131
+ async function provesOwnerIdentity(strategy: LocalCommandRunner, owner: EmbeddedPostgresOwner): Promise<boolean> {
132
+ try {
133
+ const uid = parseIdentityNumber(await strategy("id", ["-u"]));
134
+ if (uid !== owner.uid) return false;
135
+ const gid = parseIdentityNumber(await strategy("id", ["-g"]));
136
+ if (gid !== owner.gid) return false;
137
+ const groups = parseIdentityGroups(await strategy("id", ["-G"]));
138
+ return groups?.has(owner.gid) === true && (owner.uid === 0 || !groups.has(0));
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ function parseIdentityNumber(result: LocalCommandResult): number | undefined {
145
+ if (result.exitCode !== 0 || result.stdoutTruncated === true) return undefined;
146
+ const match = /^(0|[1-9]\d*)\r?\n?$/.exec(result.stdout);
147
+ if (match === null) return undefined;
148
+ const value = Number(match[1]);
149
+ return Number.isSafeInteger(value) ? value : undefined;
150
+ }
151
+
152
+ function parseIdentityGroups(result: LocalCommandResult): ReadonlySet<number> | undefined {
153
+ if (
154
+ result.exitCode !== 0 ||
155
+ result.stdoutTruncated === true ||
156
+ !/^(0|[1-9]\d*)(?:[ \t]+(0|[1-9]\d*))*\r?\n?$/.test(result.stdout)
157
+ ) {
158
+ return undefined;
159
+ }
160
+ const values = result.stdout
161
+ .trimEnd()
162
+ .split(/[ \t]+/)
163
+ .map(Number);
164
+ if (values.some((value) => !Number.isSafeInteger(value))) return undefined;
165
+ const groups = new Set(values);
166
+ return groups.size === values.length ? groups : undefined;
167
+ }
168
+
169
+ export interface RuntimePublicationLease {
170
+ /** Unique setup-lock owner token persisted beside unpublished stage work. */
171
+ readonly ownerToken: string;
172
+ /** Refresh ownership now; false means stale takeover displaced this publisher. */
173
+ readonly refresh: () => boolean;
174
+ }
175
+
176
+ export interface RuntimePreparationOptions {
177
+ readonly publicationLease?: RuntimePublicationLease;
178
+ /** Test seam immediately after the first exact source snapshot. */
179
+ readonly afterInitialSourceSnapshot?: () => void | Promise<void>;
180
+ /** Test seam at the sealed validation/publication boundary. */
181
+ readonly beforePublish?: (stagedRuntime: string) => void | Promise<void>;
182
+ /** Test seam immediately after the atomic publication rename. */
183
+ readonly afterPublish?: (publishedRuntime: string) => void | Promise<void>;
184
+ /** Test seam after published content/source validation but before final lease selection. */
185
+ readonly afterPublishValidation?: (publishedRuntime: string) => void | Promise<void>;
186
+ /** Test seam for deterministic event-loop cooperation without real delays. */
187
+ readonly yieldToEventLoop?: () => Promise<void>;
188
+ }
189
+
190
+ const STAGE_OWNER_FILE = ".atomic-stage-owner";
191
+ const STAGE_PAYLOAD_DIR = "runtime";
192
+ const TRAVERSAL_OPERATIONS_PER_YIELD = 16;
193
+ const HASH_CHUNK_BYTES = 64 * 1024;
194
+
114
195
  /**
115
196
  * Ensure the embedded binaries are executable by the drop-privilege owner.
116
197
  * Probes `initdb --version` as the owner; on failure (typically an
117
- * untraversable ancestor such as `/root`) copies the package's `native` tree
118
- * into the cluster base directory once and reuses it afterwards.
198
+ * untraversable ancestor such as `/root`) uses an immutable copied package
199
+ * generation. Each generation is tied to the exact source-tree content and
200
+ * raw symlink text, so a stale or corrupt prior copy is never selected.
119
201
  */
120
202
  export async function prepareBinariesForOwner(
121
203
  binaries: EmbeddedPostgresBinaryPaths,
122
204
  context: EmbeddedPostgresRunContext,
123
205
  runner: LocalCommandRunner = runLocalCommand,
206
+ options: RuntimePreparationOptions = {},
124
207
  ): Promise<EmbeddedPostgresBinaryPaths> {
125
208
  const owner = context.owner;
126
209
  if (owner === undefined) return binaries;
@@ -129,23 +212,451 @@ export async function prepareBinariesForOwner(
129
212
  if (probe !== undefined && probe.exitCode === 0) return binaries;
130
213
 
131
214
  // `<packageRoot>/native/bin/initdb` → copy the whole `native` tree so the
132
- // binaries keep their relative `../lib` runtime library references.
133
- const nativeDir = dirname(dirname(binaries.initdb));
134
- const copiedNativeDir = join(context.baseDir, "pg-runtime", "native");
135
- const copied: EmbeddedPostgresBinaryPaths = {
215
+ // binaries keep their relative `../lib` runtime library references. Do not
216
+ // resolve or rewrite the configured caller paths or any relative link text.
217
+ const sourceNativeDir = dirname(dirname(binaries.initdb));
218
+ const copiedRuntimeDir = join(context.baseDir, "pg-runtime");
219
+ const publisher = publisherIdentity();
220
+ const progress = runtimeProgress(options);
221
+ const sourceSnapshot = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
222
+ await options.afterInitialSourceSnapshot?.();
223
+ const copiedNativeDir = await findOrCreateRuntimeGeneration(
224
+ sourceNativeDir,
225
+ sourceSnapshot,
226
+ copiedRuntimeDir,
227
+ publisher,
228
+ runner,
229
+ progress,
230
+ options,
231
+ );
232
+ return {
136
233
  pg_ctl: join(copiedNativeDir, "bin", "pg_ctl"),
137
234
  initdb: join(copiedNativeDir, "bin", "initdb"),
235
+ postgres: join(copiedNativeDir, "bin", "postgres"),
138
236
  };
139
- if (!existsSync(copied.initdb)) {
140
- cpSync(nativeDir, copiedNativeDir, { recursive: true });
237
+ }
238
+
239
+ /**
240
+ * Reap only stages whose setup owner was both displaced and proven dead.
241
+ * A stale heartbeat alone is not abandonment: a live process can have been
242
+ * scheduler-starved, and deleting its stage would race in-flight copy/hash I/O.
243
+ * Legacy untagged stages remain finite migration evidence and are not guessed at.
244
+ */
245
+ export async function cleanupAbandonedRuntimeStages(
246
+ baseDir: string,
247
+ abandonedOwnerTokens: ReadonlySet<string> = new Set(),
248
+ ): Promise<void> {
249
+ if (abandonedOwnerTokens.size === 0) return;
250
+ const copiedRuntimeDir = join(baseDir, "pg-runtime");
251
+ let entries: string[];
252
+ try {
253
+ entries = await readdir(copiedRuntimeDir);
254
+ } catch (error) {
255
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
256
+ if (code === "ENOENT") return;
257
+ throw error;
141
258
  }
142
- const chown = await runner("chown", ["-R", `${owner.uid}:${owner.gid}`, join(context.baseDir, "pg-runtime")]);
143
- if (chown.exitCode !== 0) {
259
+ for (const entry of entries) {
260
+ if (!entry.startsWith(".native-staged-")) continue;
261
+ const stage = join(copiedRuntimeDir, entry);
262
+ let ownerToken: string;
263
+ try {
264
+ ownerToken = await readSmallFile(join(stage, STAGE_OWNER_FILE));
265
+ } catch {
266
+ continue;
267
+ }
268
+ if (abandonedOwnerTokens.has(ownerToken)) await rm(stage, { recursive: true, force: true });
269
+ }
270
+ }
271
+
272
+ interface PublisherIdentity {
273
+ readonly uid: number;
274
+ readonly gid: number;
275
+ }
276
+
277
+ interface SourceRuntimeSnapshot {
278
+ readonly sourceIdentity: string;
279
+ readonly sealedIdentity: string;
280
+ }
281
+
282
+ type RuntimeProgress = () => Promise<void>;
283
+
284
+ /**
285
+ * One exact source identity owns one deterministic path. If that path is
286
+ * externally corrupted it is retained (it may be executing) and setup fails
287
+ * closed; repeated calls neither append repair generations nor scan legacy
288
+ * unique generations, selected `native`, or `.native-retired-*` evidence.
289
+ */
290
+ async function findOrCreateRuntimeGeneration(
291
+ sourceNativeDir: string,
292
+ sourceSnapshot: SourceRuntimeSnapshot,
293
+ copiedRuntimeDir: string,
294
+ publisher: PublisherIdentity,
295
+ runner: LocalCommandRunner,
296
+ progress: RuntimeProgress,
297
+ options: RuntimePreparationOptions,
298
+ ): Promise<string> {
299
+ await mkdir(copiedRuntimeDir, { recursive: true, mode: 0o755 });
300
+ const runtimeStat = await lstat(copiedRuntimeDir);
301
+ if (!runtimeStat.isDirectory() || runtimeStat.isSymbolicLink()) {
302
+ throw new Error(`Embedded Postgres runtime parent must be a real directory: ${copiedRuntimeDir}`);
303
+ }
304
+ await chown(copiedRuntimeDir, publisher.uid, publisher.gid);
305
+ await chmod(copiedRuntimeDir, 0o755);
306
+ const generationNativeDir = join(copiedRuntimeDir, `native-${sourceSnapshot.sourceIdentity}`);
307
+ const existing = await lstatOrUndefined(generationNativeDir);
308
+ if (existing !== undefined) {
309
+ try {
310
+ if ((await snapshotSealedRuntime(generationNativeDir, progress)) !== sourceSnapshot.sealedIdentity) {
311
+ throw new Error("sealed identity mismatch");
312
+ }
313
+ await assertSourceSnapshotUnchanged(
314
+ sourceNativeDir,
315
+ sourceSnapshot,
316
+ publisher,
317
+ progress,
318
+ "Embedded Postgres source package changed while selecting an existing generation.",
319
+ );
320
+ return generationNativeDir;
321
+ } catch (error) {
322
+ if (error instanceof SourceRuntimeChangedError) throw error;
323
+ const detail = error instanceof Error ? error.message : String(error);
324
+ throw new Error(
325
+ `Embedded Postgres runtime generation is corrupt and cannot be replaced while it may be in use (${generationNativeDir}): ${detail}`,
326
+ );
327
+ }
328
+ }
329
+
330
+ const stageOwner = options.publicationLease?.ownerToken ?? `unmanaged-${process.pid}-${crypto.randomUUID()}`;
331
+ const stagedRoot = join(copiedRuntimeDir, `.native-staged-${process.pid}-${crypto.randomUUID()}`);
332
+ const stagedNativeDir = join(stagedRoot, STAGE_PAYLOAD_DIR);
333
+ await mkdir(stagedRoot, { mode: 0o700 });
334
+ await writeFile(join(stagedRoot, STAGE_OWNER_FILE), stageOwner, { mode: 0o600, flag: "wx" });
335
+ try {
336
+ await progress();
337
+ await cp(sourceNativeDir, stagedNativeDir, { recursive: true, verbatimSymlinks: true });
338
+ const copiedSnapshot = await snapshotSourceRuntime(stagedNativeDir, publisher, progress);
339
+ if (copiedSnapshot.sourceIdentity !== sourceSnapshot.sourceIdentity) {
340
+ throw new Error("Copied embedded Postgres runtime did not match its source package.");
341
+ }
342
+ await sealRuntimeForPublisher(stagedNativeDir, publisher, runner, progress);
343
+ if ((await snapshotSealedRuntime(stagedNativeDir, progress)) !== sourceSnapshot.sealedIdentity) {
344
+ throw new Error("Sealed embedded Postgres runtime did not match its source package.");
345
+ }
346
+ await options.beforePublish?.(stagedNativeDir);
347
+ if ((await snapshotSealedRuntime(stagedNativeDir, progress)) !== sourceSnapshot.sealedIdentity) {
348
+ throw new Error("Embedded Postgres runtime changed after sealed validation and before publication.");
349
+ }
350
+ await assertSourceSnapshotUnchanged(
351
+ sourceNativeDir,
352
+ sourceSnapshot,
353
+ publisher,
354
+ progress,
355
+ "Embedded Postgres source package changed while preparing a generation.",
356
+ );
357
+ assertPublicationLease(options, "Embedded Postgres runtime publication lost its setup lease.");
358
+ await progress();
359
+ // The stage is publisher-owned and has no write bit for any uid before
360
+ // this single same-parent rename. The Postgres uid therefore has no
361
+ // validation-to-publication mutation window. Root mutation is caught by
362
+ // validation through the deterministic path after the rename.
363
+ await rename(stagedNativeDir, generationNativeDir);
364
+ await options.afterPublish?.(generationNativeDir);
365
+ if ((await snapshotSealedRuntime(generationNativeDir, progress)) !== sourceSnapshot.sealedIdentity) {
366
+ throw new Error("Embedded Postgres published runtime changed during publication.");
367
+ }
368
+ await assertSourceSnapshotUnchanged(
369
+ sourceNativeDir,
370
+ sourceSnapshot,
371
+ publisher,
372
+ progress,
373
+ "Embedded Postgres source package changed during publication.",
374
+ );
375
+ await options.afterPublishValidation?.(generationNativeDir);
376
+ assertPublicationLease(options, "Embedded Postgres runtime lost its setup lease after publication.");
377
+ return generationNativeDir;
378
+ } finally {
379
+ await makeUnpublishedStageRemovable(stagedNativeDir).catch(() => {});
380
+ await rm(stagedRoot, { recursive: true, force: true });
381
+ }
382
+ }
383
+
384
+ class SourceRuntimeChangedError extends Error {}
385
+
386
+ async function assertSourceSnapshotUnchanged(
387
+ sourceNativeDir: string,
388
+ expected: SourceRuntimeSnapshot,
389
+ publisher: PublisherIdentity,
390
+ progress: RuntimeProgress,
391
+ message: string,
392
+ ): Promise<void> {
393
+ const current = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
394
+ if (current.sourceIdentity !== expected.sourceIdentity || current.sealedIdentity !== expected.sealedIdentity) {
395
+ throw new SourceRuntimeChangedError(message);
396
+ }
397
+ }
398
+
399
+ function assertPublicationLease(options: RuntimePreparationOptions, message: string): void {
400
+ if (options.publicationLease !== undefined && !options.publicationLease.refresh()) throw new Error(message);
401
+ }
402
+ function runtimeProgress(options: RuntimePreparationOptions): RuntimeProgress {
403
+ let operations = 0;
404
+ const yieldToEventLoop = options.yieldToEventLoop ?? (() => new Promise<void>((resolve) => setImmediate(resolve)));
405
+ return async () => {
406
+ if (operations % TRAVERSAL_OPERATIONS_PER_YIELD === 0) {
407
+ if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
408
+ throw new Error("Embedded Postgres runtime publication lost its setup lease.");
409
+ }
410
+ if (operations > 0) {
411
+ await yieldToEventLoop();
412
+ if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
413
+ throw new Error("Embedded Postgres runtime publication lost its setup lease.");
414
+ }
415
+ }
416
+ }
417
+ operations += 1;
418
+ };
419
+ }
420
+
421
+ /** Hash source bytes/raw link text/modes and its exact sealed projection. */
422
+ async function snapshotSourceRuntime(
423
+ root: string,
424
+ publisher: PublisherIdentity,
425
+ progress: RuntimeProgress,
426
+ ): Promise<SourceRuntimeSnapshot> {
427
+ const rootStat = await lstat(root);
428
+ assertRuntimeRoot(root, rootStat);
429
+ const rootRealPath = await realpath(root);
430
+ const sourceHash = createHash("sha256");
431
+ const sealedHash = createHash("sha256");
432
+ await hashSourceEntry(sourceHash, sealedHash, root, ".", rootRealPath, publisher, progress);
433
+ return { sourceIdentity: sourceHash.digest("hex"), sealedIdentity: sealedHash.digest("hex") };
434
+ }
435
+
436
+ async function hashSourceEntry(
437
+ sourceHash: Hash,
438
+ sealedHash: Hash,
439
+ path: string,
440
+ relativePath: string,
441
+ rootRealPath: string,
442
+ publisher: PublisherIdentity,
443
+ progress: RuntimeProgress,
444
+ ): Promise<void> {
445
+ await progress();
446
+ const stat = await lstat(path);
447
+ if (stat.isSymbolicLink()) {
448
+ const target = await validatedLinkTarget(path, relativePath, rootRealPath);
449
+ hashField(sourceHash, "link", relativePath, target);
450
+ hashField(sealedHash, "link", relativePath, String(publisher.uid), String(publisher.gid), target);
451
+ return;
452
+ }
453
+ if (stat.isDirectory()) {
454
+ hashField(sourceHash, "directory", relativePath, String(stat.mode & 0o777));
455
+ hashField(
456
+ sealedHash,
457
+ "directory",
458
+ relativePath,
459
+ String(sealedDirectoryMode(relativePath === ".")),
460
+ String(publisher.uid),
461
+ String(publisher.gid),
462
+ );
463
+ for (const entry of (await readdir(path)).sort()) {
464
+ await hashSourceEntry(
465
+ sourceHash,
466
+ sealedHash,
467
+ join(path, entry),
468
+ relativePath === "." ? entry : join(relativePath, entry),
469
+ rootRealPath,
470
+ publisher,
471
+ progress,
472
+ );
473
+ }
474
+ return;
475
+ }
476
+ if (stat.isFile()) {
477
+ hashField(sourceHash, "file", relativePath, String(stat.mode & 0o777), String(stat.size));
478
+ hashField(
479
+ sealedHash,
480
+ "file",
481
+ relativePath,
482
+ String(sealedFileMode(stat.mode)),
483
+ String(publisher.uid),
484
+ String(publisher.gid),
485
+ String(stat.size),
486
+ );
487
+ await hashFileInto([sourceHash, sealedHash], path, progress);
488
+ return;
489
+ }
490
+ throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
491
+ }
492
+
493
+ async function snapshotSealedRuntime(root: string, progress: RuntimeProgress): Promise<string> {
494
+ const rootStat = await lstat(root);
495
+ assertRuntimeRoot(root, rootStat);
496
+ const rootRealPath = await realpath(root);
497
+ const hash = createHash("sha256");
498
+ await hashSealedEntry(hash, root, ".", rootRealPath, progress);
499
+ return hash.digest("hex");
500
+ }
501
+
502
+ async function hashSealedEntry(
503
+ hash: Hash,
504
+ path: string,
505
+ relativePath: string,
506
+ rootRealPath: string,
507
+ progress: RuntimeProgress,
508
+ ): Promise<void> {
509
+ await progress();
510
+ const stat = await lstat(path);
511
+ if (stat.isSymbolicLink()) {
512
+ const target = await validatedLinkTarget(path, relativePath, rootRealPath);
513
+ hashField(hash, "link", relativePath, String(stat.uid), String(stat.gid), target);
514
+ return;
515
+ }
516
+ if (stat.isDirectory()) {
517
+ hashField(hash, "directory", relativePath, String(stat.mode & 0o777), String(stat.uid), String(stat.gid));
518
+ for (const entry of (await readdir(path)).sort()) {
519
+ await hashSealedEntry(
520
+ hash,
521
+ join(path, entry),
522
+ relativePath === "." ? entry : join(relativePath, entry),
523
+ rootRealPath,
524
+ progress,
525
+ );
526
+ }
527
+ return;
528
+ }
529
+ if (stat.isFile()) {
530
+ hashField(
531
+ hash,
532
+ "file",
533
+ relativePath,
534
+ String(stat.mode & 0o777),
535
+ String(stat.uid),
536
+ String(stat.gid),
537
+ String(stat.size),
538
+ );
539
+ await hashFileInto([hash], path, progress);
540
+ return;
541
+ }
542
+ throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
543
+ }
544
+
545
+ async function validatedLinkTarget(path: string, relativePath: string, rootRealPath: string): Promise<string> {
546
+ const target = await readlink(path);
547
+ if (isAbsolute(target)) throw new Error(`Embedded Postgres runtime contains an absolute link: ${relativePath}`);
548
+ const resolvedTarget = await realpath(path);
549
+ const targetFromRoot = relative(rootRealPath, resolvedTarget);
550
+ if (targetFromRoot === ".." || targetFromRoot.startsWith(`..${sep}`) || isAbsolute(targetFromRoot)) {
551
+ throw new Error(`Embedded Postgres runtime link escapes its tree: ${relativePath}`);
552
+ }
553
+ return target;
554
+ }
555
+
556
+ async function hashFileInto(hashes: readonly Hash[], path: string, progress: RuntimeProgress): Promise<void> {
557
+ const handle = await open(path, "r");
558
+ const buffer = Buffer.allocUnsafe(HASH_CHUNK_BYTES);
559
+ try {
560
+ for (;;) {
561
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
562
+ if (bytesRead === 0) return;
563
+ const chunk = buffer.subarray(0, bytesRead);
564
+ for (const hash of hashes) hash.update(chunk);
565
+ await progress();
566
+ }
567
+ } finally {
568
+ await handle.close();
569
+ }
570
+ }
571
+
572
+ async function sealRuntimeForPublisher(
573
+ runtimeDir: string,
574
+ publisher: PublisherIdentity,
575
+ runner: LocalCommandRunner,
576
+ progress: RuntimeProgress,
577
+ ): Promise<void> {
578
+ const result = await runner("chown", ["-R", `${publisher.uid}:${publisher.gid}`, runtimeDir]);
579
+ if (result.exitCode !== 0) {
144
580
  throw new Error(
145
- `Could not hand the copied embedded Postgres runtime to ${owner.name}: ${chown.stderr.trim() || chown.stdout.trim() || `exit ${chown.exitCode}`}`,
581
+ `Could not seal the copied embedded Postgres runtime: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`}`,
146
582
  );
147
583
  }
148
- return copied;
584
+ await sealRuntimeModes(runtimeDir, progress, true);
585
+ }
586
+
587
+ async function sealRuntimeModes(path: string, progress: RuntimeProgress, isRoot = false): Promise<void> {
588
+ await progress();
589
+ const stat = await lstat(path);
590
+ if (stat.isSymbolicLink()) return;
591
+ if (stat.isDirectory()) {
592
+ await chmod(path, 0o700);
593
+ for (const entry of await readdir(path)) await sealRuntimeModes(join(path, entry), progress);
594
+ await chmod(path, sealedDirectoryMode(isRoot));
595
+ return;
596
+ }
597
+ if (stat.isFile()) {
598
+ await chmod(path, sealedFileMode(stat.mode));
599
+ return;
600
+ }
601
+ throw new Error(`Embedded Postgres runtime contains an unsupported entry while sealing: ${path}`);
602
+ }
603
+
604
+ async function makeUnpublishedStageRemovable(path: string): Promise<void> {
605
+ const stat = await lstatOrUndefined(path);
606
+ if (stat === undefined || stat.isSymbolicLink()) return;
607
+ if (stat.isDirectory()) {
608
+ await chmod(path, 0o700);
609
+ for (const entry of await readdir(path)) await makeUnpublishedStageRemovable(join(path, entry));
610
+ } else if (stat.isFile()) {
611
+ await chmod(path, 0o600);
612
+ }
613
+ }
614
+
615
+ function sealedDirectoryMode(isRoot: boolean): number {
616
+ // Node maps Windows chmod/stat to one shared read-only attribute; it cannot
617
+ // preserve POSIX execute bits or distinct owner/group/other permissions.
618
+ if (process.platform === "win32") return 0o444;
619
+ return isRoot ? 0o755 : 0o555;
620
+ }
621
+
622
+ function sealedFileMode(mode: number): number {
623
+ if (process.platform === "win32") return 0o444;
624
+ return (mode & 0o111) === 0 ? 0o444 : 0o555;
625
+ }
626
+
627
+ function publisherIdentity(): PublisherIdentity {
628
+ return { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };
629
+ }
630
+
631
+ function assertRuntimeRoot(root: string, stat: Stats): void {
632
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
633
+ throw new Error(`Embedded Postgres runtime must be a real directory: ${root}`);
634
+ }
635
+ }
636
+
637
+ async function lstatOrUndefined(path: string): Promise<Stats | undefined> {
638
+ try {
639
+ return await lstat(path);
640
+ } catch (error) {
641
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
642
+ if (code === "ENOENT") return undefined;
643
+ throw error;
644
+ }
645
+ }
646
+
647
+ async function readSmallFile(path: string): Promise<string> {
648
+ const handle = await open(path, "r");
649
+ try {
650
+ const stat = await handle.stat();
651
+ if (stat.size > 4096) throw new Error(`Unexpectedly large runtime stage owner marker: ${path}`);
652
+ return (await handle.readFile("utf8")).trim();
653
+ } finally {
654
+ await handle.close();
655
+ }
656
+ }
657
+
658
+ function hashField(hash: Hash, ...values: readonly string[]): void {
659
+ for (const value of values) hash.update(`${Buffer.byteLength(value)}:${value}`);
149
660
  }
150
661
 
151
662
  async function lookupOwner(runner: LocalCommandRunner, name: string): Promise<EmbeddedPostgresOwner | undefined> {
@@ -157,10 +668,8 @@ async function lookupOwner(runner: LocalCommandRunner, name: string): Promise<Em
157
668
 
158
669
  async function lookupId(runner: LocalCommandRunner, args: readonly string[]): Promise<number | undefined> {
159
670
  try {
160
- const result = await runner("id", args);
161
- if (result.exitCode !== 0) return undefined;
162
- const value = Number.parseInt(result.stdout.trim(), 10);
163
- return Number.isInteger(value) && value > 0 ? value : undefined;
671
+ const value = parseIdentityNumber(await runner("id", args));
672
+ return value !== undefined && value > 0 ? value : undefined;
164
673
  } catch {
165
674
  return undefined;
166
675
  }