@bakers-build/core 0.6.1-next.1 → 0.6.1-next.3

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.
@@ -0,0 +1,19 @@
1
+ /** Git metadata a sandboxed agent run may write, and what inside it stays read-only. */
2
+ export interface GitSandboxPaths {
3
+ write: string[];
4
+ protect: string[];
5
+ }
6
+ /**
7
+ * The Git paths to grant a sandboxed run in `workspacePath`. A linked worktree
8
+ * gets its own git dir and the shared objects, refs and reflogs, never the
9
+ * shared dir itself, so its config, hooks and lock files stay unwritable.
10
+ * Only existing paths are named: a sandbox mounts over a missing protected
11
+ * path by creating an empty placeholder in the real repository.
12
+ */
13
+ export declare function gitSandboxPaths(workspacePath: string): GitSandboxPaths;
14
+ /**
15
+ * `allow_write` without entries that are, or lie inside, a `.git` directory:
16
+ * granting one whole makes the sandbox protect metadata inside it, which it
17
+ * materialises as placeholders. Git metadata comes from `gitSandboxPaths`.
18
+ */
19
+ export declare function withoutGitDirs(paths: readonly string[], warn?: (message: string) => void): string[];
@@ -0,0 +1,58 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join, sep } from 'node:path';
4
+ /** Code an unsandboxed Git command later runs, or a redirect it follows to such code. */
5
+ const PROTECTED = [
6
+ 'config',
7
+ 'config.worktree',
8
+ 'hooks',
9
+ 'commondir',
10
+ 'gitdir',
11
+ 'modules',
12
+ 'worktrees',
13
+ ];
14
+ /** What a commit, fetch or push from a linked worktree writes in the shared Git dir. */
15
+ const SHARED_WRITES = ['objects', 'refs', 'logs'];
16
+ function revParse(workspacePath, option) {
17
+ const git = spawnSync('git', ['-C', workspacePath, 'rev-parse', '--path-format=absolute', option], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' } });
18
+ if (git.error)
19
+ throw git.error;
20
+ if (git.status !== 0) {
21
+ if (git.stderr.includes('not a git repository'))
22
+ return null;
23
+ throw new Error(`Cannot resolve workspace Git directories: ${git.stderr.trim()}`);
24
+ }
25
+ return git.stdout.replace(/\r?\n$/, '');
26
+ }
27
+ /**
28
+ * The Git paths to grant a sandboxed run in `workspacePath`. A linked worktree
29
+ * gets its own git dir and the shared objects, refs and reflogs, never the
30
+ * shared dir itself, so its config, hooks and lock files stay unwritable.
31
+ * Only existing paths are named: a sandbox mounts over a missing protected
32
+ * path by creating an empty placeholder in the real repository.
33
+ */
34
+ export function gitSandboxPaths(workspacePath) {
35
+ const gitDir = revParse(workspacePath, '--git-dir');
36
+ if (gitDir === null)
37
+ return { write: [], protect: [] };
38
+ const common = revParse(workspacePath, '--git-common-dir') ?? gitDir;
39
+ const shared = common === gitDir ? [] : SHARED_WRITES.map((name) => join(common, name));
40
+ return {
41
+ write: [gitDir, ...shared.filter((path) => existsSync(path))],
42
+ protect: PROTECTED.map((name) => join(gitDir, name)).filter((path) => existsSync(path)),
43
+ };
44
+ }
45
+ /**
46
+ * `allow_write` without entries that are, or lie inside, a `.git` directory:
47
+ * granting one whole makes the sandbox protect metadata inside it, which it
48
+ * materialises as placeholders. Git metadata comes from `gitSandboxPaths`.
49
+ */
50
+ export function withoutGitDirs(paths, warn = console.warn) {
51
+ return paths.filter((path) => {
52
+ const inGit = path.split(sep).includes('.git');
53
+ if (inGit) {
54
+ warn(`sandbox.allow_write: ignoring ${path}; Git metadata is granted automatically`);
55
+ }
56
+ return !inGit;
57
+ });
58
+ }
@@ -75,3 +75,25 @@ export declare function signalVerifiedProcess(input: SignalVerifiedInput): Signa
75
75
  * guessing. Start is unaffected everywhere.
76
76
  */
77
77
  export declare function defaultProcProbe(): ProcProbe;
78
+ /** What `killRunProcesses` needs from the platform, injected for tests. */
79
+ export interface RunProcessProbe {
80
+ readonly supported: boolean;
81
+ /** Every running pid. */
82
+ pids(): number[];
83
+ /** A process's environment entries, or `undefined` when gone or unreadable. */
84
+ environOf(pid: number): string[] | undefined;
85
+ uidOf(pid: number): number | undefined;
86
+ send(pid: number, signal: NodeJS.Signals): void;
87
+ }
88
+ export declare function defaultRunProcessProbe(): RunProcessProbe;
89
+ /**
90
+ * Ends every process of this OS user that carries `BB_RUN_UUID=<runUuid>`:
91
+ * the run's agent, its sandbox and background commands that outlive the
92
+ * PTY. SIGTERM first, SIGKILL for survivors after `graceMs`. Best-effort.
93
+ * shortcut: a process that clears its environment is not found; track
94
+ * process groups or cgroups if that ever matters.
95
+ */
96
+ export declare function killRunProcesses(runUuid: string, probe?: RunProcessProbe, graceMs?: number): Promise<{
97
+ supported: boolean;
98
+ pids: number[];
99
+ }>;
@@ -1,4 +1,4 @@
1
- import { readFileSync, statSync } from 'node:fs';
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
2
  /**
3
3
  * Substrings a live bakers-conductor foreground process's command line must all
4
4
  * contain (see `cmdStartBody`'s `fgCmd`: `bakers oven … start --foreground
@@ -154,3 +154,59 @@ export function defaultProcProbe() {
154
154
  },
155
155
  };
156
156
  }
157
+ export function defaultRunProcessProbe() {
158
+ const base = defaultProcProbe();
159
+ return {
160
+ supported: base.supported,
161
+ pids() {
162
+ if (!base.supported)
163
+ return [];
164
+ return readdirSync('/proc')
165
+ .filter((name) => /^\d+$/.test(name))
166
+ .map(Number);
167
+ },
168
+ environOf(pid) {
169
+ try {
170
+ return readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
171
+ }
172
+ catch {
173
+ return undefined;
174
+ }
175
+ },
176
+ uidOf: (pid) => base.uidOf(pid),
177
+ send: (pid, signal) => base.send(pid, signal),
178
+ };
179
+ }
180
+ /**
181
+ * Ends every process of this OS user that carries `BB_RUN_UUID=<runUuid>`:
182
+ * the run's agent, its sandbox and background commands that outlive the
183
+ * PTY. SIGTERM first, SIGKILL for survivors after `graceMs`. Best-effort.
184
+ * shortcut: a process that clears its environment is not found; track
185
+ * process groups or cgroups if that ever matters.
186
+ */
187
+ export async function killRunProcesses(runUuid, probe = defaultRunProcessProbe(), graceMs = 2000) {
188
+ if (!probe.supported || runUuid === '') {
189
+ return { supported: probe.supported, pids: [] };
190
+ }
191
+ const marker = `BB_RUN_UUID=${runUuid}`;
192
+ const uid = process.getuid?.();
193
+ const ofRun = (pid) => probe.environOf(pid)?.includes(marker) === true;
194
+ const pids = probe
195
+ .pids()
196
+ .filter((pid) => pid !== process.pid && probe.uidOf(pid) === uid && ofRun(pid));
197
+ const signal = (signal) => (pid) => {
198
+ try {
199
+ probe.send(pid, signal);
200
+ }
201
+ catch {
202
+ // Gone already.
203
+ }
204
+ };
205
+ if (pids.length === 0)
206
+ return { supported: true, pids };
207
+ pids.forEach(signal('SIGTERM'));
208
+ if (graceMs > 0)
209
+ await new Promise((r) => setTimeout(r, graceMs));
210
+ pids.filter(ofRun).forEach(signal('SIGKILL'));
211
+ return { supported: true, pids };
212
+ }
@@ -16,9 +16,10 @@ export { BB_PACKAGE, checkForUpdate, declineUpdate, defaultUpdateCachePath, fetc
16
16
  export { discoverBbWorkspaces, loadReadyBbConnection, resolveWorkspaceSelector, type WorkspaceChoice, type WorkspaceRecoveryOptions, workspaceSearchCommand, } from './cli/workspace-recovery.js';
17
17
  export { configHomeOf, defaultRootGitExec, deriveCheckoutRoot, type RootGitExec, } from './core/checkout-root.js';
18
18
  export { CommandRunner, ExecError, exec, setDefaultCommandRunner, } from './core/exec.js';
19
+ export { type GitSandboxPaths, gitSandboxPaths, withoutGitDirs, } from './core/git-sandbox.js';
19
20
  export { type ConductorLiveness, type ConductorLivenessInput, deriveConductorLiveness, toUnixSeconds, } from './core/liveness.js';
20
21
  export { type ConductorLogger, createLogger } from './core/logger.js';
21
- export { defaultProcProbe, type ProcProbe, type SignalFailureReason, type SignalOutcome, type SignalVerifiedInput, signalVerifiedProcess, type VerifyOutcome, type VerifyProcessInput, verifyConductorProcess, } from './core/proc.js';
22
+ export { defaultProcProbe, defaultRunProcessProbe, killRunProcesses, type ProcProbe, type RunProcessProbe, type SignalFailureReason, type SignalOutcome, type SignalVerifiedInput, signalVerifiedProcess, type VerifyOutcome, type VerifyProcessInput, verifyConductorProcess, } from './core/proc.js';
22
23
  export { shellQuote } from './core/shell.js';
23
24
  export { DEFAULT_SLUG_MAX_LENGTH, slugify } from './core/slug.js';
24
25
  export { AddonUnresolvedError, discoverAddons, loadAddonPreset, type ResolvedConductorSlots, resolveConductorSlots, } from './plugins/discover-addons.js';
package/dist/src/index.js CHANGED
@@ -18,9 +18,10 @@ export { BB_PACKAGE, checkForUpdate, declineUpdate, defaultUpdateCachePath, fetc
18
18
  export { discoverBbWorkspaces, loadReadyBbConnection, resolveWorkspaceSelector, workspaceSearchCommand, } from './cli/workspace-recovery.js';
19
19
  export { configHomeOf, defaultRootGitExec, deriveCheckoutRoot, } from './core/checkout-root.js';
20
20
  export { CommandRunner, ExecError, exec, setDefaultCommandRunner, } from './core/exec.js';
21
+ export { gitSandboxPaths, withoutGitDirs, } from './core/git-sandbox.js';
21
22
  export { deriveConductorLiveness, toUnixSeconds, } from './core/liveness.js';
22
23
  export { createLogger } from './core/logger.js';
23
- export { defaultProcProbe, signalVerifiedProcess, verifyConductorProcess, } from './core/proc.js';
24
+ export { defaultProcProbe, defaultRunProcessProbe, killRunProcesses, signalVerifiedProcess, verifyConductorProcess, } from './core/proc.js';
24
25
  export { shellQuote } from './core/shell.js';
25
26
  export { DEFAULT_SLUG_MAX_LENGTH, slugify } from './core/slug.js';
26
27
  // BB-215: the Storybook-style preset contract + the shared addon discovery.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/core",
3
- "version": "0.6.1-next.1",
3
+ "version": "0.6.1-next.3",
4
4
  "description": "bakers.build surface-agnostic kernel: host contract, split-config helpers, addon preset/discovery machinery, shared primitives.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,7 +38,7 @@
38
38
  "yaml": "^2.7.0"
39
39
  },
40
40
  "bakersBuild": {
41
- "commit": "a92b86267d70b1d4bc469e62ef3c6964807c7dd0",
41
+ "commit": "1531a0bb0d34ccf6b54a051fcb8b016902c31f0f",
42
42
  "channel": "next"
43
43
  }
44
44
  }