@pugi/cli 0.1.0-beta.93 → 0.1.0-beta.95

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 (35) hide show
  1. package/dist/commands/retro.js +210 -0
  2. package/dist/core/diagnostics/probes/sandbox.js +65 -33
  3. package/dist/core/engine/native-pugi.js +184 -10
  4. package/dist/core/engine/tool-bridge.js +35 -0
  5. package/dist/core/engine/verification-patterns.js +9 -9
  6. package/dist/core/mcp/orchestrator-config.js +192 -0
  7. package/dist/core/mcp/orchestrator-tools.js +147 -3
  8. package/dist/core/pugi-gitignore.js +52 -0
  9. package/dist/core/repl/engine-bridge.js +199 -0
  10. package/dist/core/repl/session.js +395 -6
  11. package/dist/core/repl/tool-route.js +382 -0
  12. package/dist/core/retro/git-collector.js +251 -0
  13. package/dist/core/retro/health-card.js +25 -0
  14. package/dist/core/retro/metrics.js +342 -0
  15. package/dist/core/retro/narrative.js +249 -0
  16. package/dist/core/retro/plane-collector.js +274 -0
  17. package/dist/core/retro/pr-issue-link.js +65 -0
  18. package/dist/core/retro/types.js +16 -0
  19. package/dist/core/sandboxing/adapter.js +29 -0
  20. package/dist/core/sandboxing/index.js +49 -0
  21. package/dist/core/sandboxing/none.js +19 -0
  22. package/dist/core/sandboxing/seatbelt.js +183 -0
  23. package/dist/core/session.js +27 -0
  24. package/dist/core/settings.js +22 -0
  25. package/dist/runtime/cli.js +167 -33
  26. package/dist/runtime/commands/mcp.js +64 -8
  27. package/dist/runtime/deprecation-warning.js +69 -0
  28. package/dist/runtime/headless.js +8 -3
  29. package/dist/runtime/stream-renderer.js +195 -0
  30. package/dist/runtime/version.js +1 -1
  31. package/dist/tui/agent-tree.js +11 -0
  32. package/dist/tui/ask-user-question-chips.js +1 -1
  33. package/dist/tui/multi-file-diff-approval.js +3 -3
  34. package/dist/tui/repl-render.js +42 -0
  35. package/package.json +2 -2
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Plane REST client for `pugi retro`.
3
+ *
4
+ * Read-only by default — lists closed + created issues, cycles, and
5
+ * modules in the configured project. `postRetroToPlane` is the only
6
+ * mutating surface and is gated by --post-plane.
7
+ *
8
+ * Config is read from `.pugi/settings.json` + env (precedence: env
9
+ * overrides settings). The REST shape mirrors the admin-api's
10
+ * PlaneService: `X-API-Key: <token>` header, `redirect: 'manual'` so
11
+ * a malicious 3xx never carries the token to an attacker-chosen host.
12
+ */
13
+ import { existsSync, readFileSync } from 'node:fs';
14
+ import { join } from 'node:path';
15
+ const SETTINGS_REL = '.pugi/settings.json';
16
+ const DEFAULT_BASE_URL = 'https://plane.pugi.io';
17
+ const DEFAULT_WORKSPACE = 'pugi-customers';
18
+ /** Marker embedded into every retro post so we can detect a prior
19
+ * post for the same date+seq and short-circuit to idempotent. */
20
+ export function buildRetroMarker(dateLabel, sequence) {
21
+ return `pugi-retro-id: ${dateLabel}-${sequence}`;
22
+ }
23
+ export function resolvePlaneConfig(root, env = process.env) {
24
+ const settings = readSettings(root);
25
+ const baseUrl = (env.PLANE_BASE_URL ?? settings.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
26
+ const apiKey = env.PLANE_API_KEY ?? settings.apiKey ?? '';
27
+ const workspaceSlug = env.PLANE_WORKSPACE_SLUG ?? settings.workspaceSlug ?? DEFAULT_WORKSPACE;
28
+ const projectId = env.PLANE_PROJECT_ID ?? settings.projectId ?? '';
29
+ if (!apiKey) {
30
+ return { ok: false, reason: 'PLANE_API_KEY not configured' };
31
+ }
32
+ if (!projectId) {
33
+ return { ok: false, reason: 'PLANE_PROJECT_ID not configured' };
34
+ }
35
+ return {
36
+ ok: true,
37
+ config: { baseUrl, apiKey, workspaceSlug, projectId },
38
+ };
39
+ }
40
+ function readSettings(root) {
41
+ const path = join(root, SETTINGS_REL);
42
+ if (!existsSync(path))
43
+ return {};
44
+ try {
45
+ const body = JSON.parse(readFileSync(path, 'utf8'));
46
+ const plane = body.plane;
47
+ if (!plane || typeof plane !== 'object')
48
+ return {};
49
+ const slice = plane;
50
+ const baseUrl = typeof slice.baseUrl === 'string' ? slice.baseUrl : undefined;
51
+ const apiKey = typeof slice.apiKey === 'string' ? slice.apiKey : undefined;
52
+ const workspaceSlug = typeof slice.workspaceSlug === 'string' ? slice.workspaceSlug : undefined;
53
+ const projectId = typeof slice.projectId === 'string' ? slice.projectId : undefined;
54
+ return { baseUrl, apiKey, workspaceSlug, projectId };
55
+ }
56
+ catch {
57
+ return {};
58
+ }
59
+ }
60
+ async function planeRequest(config, path, init, fetchImpl) {
61
+ const url = `${config.baseUrl}/api/v1${path.startsWith('/') ? path : `/${path}`}`;
62
+ const headers = {
63
+ 'X-API-Key': config.apiKey,
64
+ Accept: 'application/json',
65
+ };
66
+ if (init.body !== undefined) {
67
+ headers['Content-Type'] = 'application/json';
68
+ }
69
+ const merged = {
70
+ ...init,
71
+ headers: { ...headers, ...init.headers },
72
+ // Mirror admin-api PlaneService — never auto-follow redirects so a
73
+ // compromised upstream cannot redirect us with the API key in tow.
74
+ redirect: 'manual',
75
+ };
76
+ const res = await fetchImpl(url, merged);
77
+ if (res.status >= 300 && res.status < 400) {
78
+ throw new Error(`plane_unexpected_redirect_${res.status}`);
79
+ }
80
+ if (!res.ok) {
81
+ // P1 (triple-review 2026-06-04, ): never echo upstream body.
82
+ // It may contain the API key if the operator misconfigured the URL
83
+ // with a query-string token, or any future Plane request-id header
84
+ // that surfaces the bearer. Generic shape only.
85
+ throw new Error(`plane_upstream_${res.status}`);
86
+ }
87
+ if (res.status === 204) {
88
+ // P3 → P1 (triple-review 2026-06-04 round 2): 204 has two meanings.
89
+ // On GET = empty collection → return []. On POST/PATCH = no body
90
+ // returned, but `postRetroToPlane` requires the created resource id
91
+ // back, so casting `[]` to a single `RawPlaneIssue` and reading
92
+ // `.id` would silently produce `''` and break idempotency. Throw
93
+ // when 204 lands on a mutation method instead.
94
+ const method = (init.method ?? 'GET').toUpperCase();
95
+ if (method !== 'GET' && method !== 'HEAD') {
96
+ throw new Error(`plane_unexpected_204_on_${method.toLowerCase()}`);
97
+ }
98
+ return [];
99
+ }
100
+ return (await res.json());
101
+ }
102
+ async function listIssues(config, query, fetchImpl) {
103
+ const out = [];
104
+ let path = `/workspaces/${config.workspaceSlug}/projects/${config.projectId}/issues/${query}`;
105
+ while (path) {
106
+ const page = await planeRequest(config, path, { method: 'GET' }, fetchImpl);
107
+ if (Array.isArray(page)) {
108
+ out.push(...page);
109
+ path = undefined;
110
+ }
111
+ else {
112
+ out.push(...(page.results ?? []));
113
+ // We do not support cross-host pagination here (admin-api does); for
114
+ // retros, the first page is sufficient at our typical issue counts.
115
+ path = undefined;
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+ function toIssueRef(raw, statesById) {
121
+ const stateId = raw.state_id ?? raw.state;
122
+ const state = stateId ? statesById.get(stateId) : undefined;
123
+ return {
124
+ id: raw.id ?? '',
125
+ sequenceId: typeof raw.sequence_id === 'number' ? raw.sequence_id : 0,
126
+ name: raw.name ?? '',
127
+ stateId,
128
+ stateName: state?.name,
129
+ stateGroup: state?.group,
130
+ createdAt: raw.created_at,
131
+ completedAt: raw.completed_at ?? undefined,
132
+ };
133
+ }
134
+ async function listStates(config, fetchImpl) {
135
+ const path = `/workspaces/${config.workspaceSlug}/projects/${config.projectId}/states/`;
136
+ const page = await planeRequest(config, path, { method: 'GET' }, fetchImpl);
137
+ if (Array.isArray(page))
138
+ return page;
139
+ return page.results ?? [];
140
+ }
141
+ async function listCycles(config, fetchImpl) {
142
+ const path = `/workspaces/${config.workspaceSlug}/projects/${config.projectId}/cycles/`;
143
+ const page = await planeRequest(config, path, { method: 'GET' }, fetchImpl);
144
+ if (Array.isArray(page))
145
+ return page;
146
+ return page.results ?? [];
147
+ }
148
+ async function listModules(config, fetchImpl) {
149
+ const path = `/workspaces/${config.workspaceSlug}/projects/${config.projectId}/modules/`;
150
+ const page = await planeRequest(config, path, { method: 'GET' }, fetchImpl);
151
+ if (Array.isArray(page))
152
+ return page;
153
+ return page.results ?? [];
154
+ }
155
+ function pickActiveCycle(cycles, now) {
156
+ const nowMs = now.getTime();
157
+ let chosen;
158
+ for (const c of cycles) {
159
+ if (!c.start_date || !c.end_date)
160
+ continue;
161
+ const start = Date.parse(c.start_date);
162
+ const end = Date.parse(c.end_date);
163
+ if (!Number.isFinite(start) || !Number.isFinite(end))
164
+ continue;
165
+ if (start <= nowMs && nowMs <= end) {
166
+ chosen = c;
167
+ break;
168
+ }
169
+ }
170
+ if (!chosen)
171
+ return undefined;
172
+ const total = chosen.total_issues ?? 0;
173
+ const completed = chosen.completed_issues ?? 0;
174
+ const progressPercent = total === 0 ? 0 : Math.round((completed / total) * 100);
175
+ return {
176
+ id: chosen.id ?? '',
177
+ name: chosen.name ?? '',
178
+ startDate: chosen.start_date,
179
+ endDate: chosen.end_date,
180
+ progressPercent,
181
+ };
182
+ }
183
+ export async function collectPlaneSlice(options) {
184
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
185
+ const sinceIso = options.since.toISOString();
186
+ const states = await listStates(options.config, fetchImpl);
187
+ const statesById = new Map();
188
+ for (const s of states)
189
+ if (s.id)
190
+ statesById.set(s.id, s);
191
+ const [closedRaw, createdRaw, cyclesRaw, modulesRaw] = await Promise.all([
192
+ listIssues(options.config, `?state__group=completed&completed_at__gte=${encodeURIComponent(sinceIso)}`, fetchImpl),
193
+ listIssues(options.config, `?created_at__gte=${encodeURIComponent(sinceIso)}`, fetchImpl),
194
+ listCycles(options.config, fetchImpl),
195
+ listModules(options.config, fetchImpl),
196
+ ]);
197
+ const closedIssues = closedRaw.map((r) => toIssueRef(r, statesById));
198
+ const createdIssues = createdRaw.map((r) => toIssueRef(r, statesById));
199
+ const modules = modulesRaw.map((m) => ({
200
+ id: m.id ?? '',
201
+ name: m.name ?? '',
202
+ issueCount: m.total_issues ?? 0,
203
+ }));
204
+ const activeCycle = pickActiveCycle(cyclesRaw, new Date());
205
+ return {
206
+ closedIssues,
207
+ createdIssues,
208
+ activeCycle,
209
+ modules,
210
+ oversizedModules: [],
211
+ prToIssueLinks: [],
212
+ sprintVelocity: {
213
+ closedCount: closedIssues.length,
214
+ createdCount: createdIssues.length,
215
+ netDelta: closedIssues.length - createdIssues.length,
216
+ },
217
+ };
218
+ }
219
+ /** Pick a state in the `backlog` group so the post lands in the right
220
+ * column. Falls back to the first available state if no backlog state
221
+ * is found (Plane lets operators rename groups, but `group=backlog`
222
+ * is the canonical default).
223
+ */
224
+ async function pickBacklogStateId(config, fetchImpl) {
225
+ const states = await listStates(config, fetchImpl);
226
+ const backlog = states.find((s) => s.group === 'backlog');
227
+ if (backlog?.id)
228
+ return backlog.id;
229
+ const first = states[0];
230
+ return first?.id;
231
+ }
232
+ export async function postRetroToPlane(options) {
233
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
234
+ const marker = buildRetroMarker(options.dateLabel, options.sequence);
235
+ const issueName = `Retro ${options.dateLabel} (seq ${options.sequence})`;
236
+ // Idempotency probe: list recent issues, look for the marker in
237
+ // description_html or the canonical issue name.
238
+ const recent = await listIssues(options.config, `?name__icontains=${encodeURIComponent(`Retro ${options.dateLabel}`)}`, fetchImpl);
239
+ for (const raw of recent) {
240
+ const haystack = `${raw.name ?? ''}\n${raw.description_html ?? ''}`;
241
+ if (haystack.includes(marker)) {
242
+ return {
243
+ url: buildIssueUrl(options.config, raw.id ?? ''),
244
+ issueId: raw.id ?? '',
245
+ alreadyExists: true,
246
+ };
247
+ }
248
+ }
249
+ const stateId = await pickBacklogStateId(options.config, fetchImpl);
250
+ const descriptionHtml = `<!-- ${marker} -->\n<pre>${escapeHtml(options.markdown)}</pre>`;
251
+ const body = {
252
+ name: issueName,
253
+ description_html: descriptionHtml,
254
+ priority: 'none',
255
+ };
256
+ if (stateId)
257
+ body.state = stateId;
258
+ const created = await planeRequest(options.config, `/workspaces/${options.config.workspaceSlug}/projects/${options.config.projectId}/issues/`, { method: 'POST', body: JSON.stringify(body) }, fetchImpl);
259
+ return {
260
+ url: buildIssueUrl(options.config, created.id ?? ''),
261
+ issueId: created.id ?? '',
262
+ alreadyExists: false,
263
+ };
264
+ }
265
+ function buildIssueUrl(config, issueId) {
266
+ return `${config.baseUrl}/${config.workspaceSlug}/projects/${config.projectId}/issues/${issueId}`;
267
+ }
268
+ function escapeHtml(s) {
269
+ return s
270
+ .replace(/&/g, '&amp;')
271
+ .replace(/</g, '&lt;')
272
+ .replace(/>/g, '&gt;');
273
+ }
274
+ //# sourceMappingURL=plane-collector.js.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * PR-to-issue link extractor for `pugi retro`.
3
+ *
4
+ * Walks the harvested commits and matches `[A-Z]+-\d+` markers in
5
+ * subject + body — same shape as the existing admin-api state-sync
6
+ * cron uses for `PUGI-N` matches. Enrichment joins the matched ref
7
+ * against the Plane issue collection (when --plane is on) so the
8
+ * narrative can show "PR ↔ issue" pairs.
9
+ */
10
+ const ISSUE_REF_RE = /\b([A-Z][A-Z0-9]*-\d+)\b/g;
11
+ /** Extract every `<PREFIX>-<NUM>` token from a haystack. Order is
12
+ * preserved (first occurrence wins); duplicates collapse.
13
+ */
14
+ export function extractIssueRefs(haystack) {
15
+ const out = [];
16
+ const seen = new Set();
17
+ ISSUE_REF_RE.lastIndex = 0;
18
+ let m;
19
+ while ((m = ISSUE_REF_RE.exec(haystack)) !== null) {
20
+ const ref = m[1];
21
+ if (!ref)
22
+ continue;
23
+ if (seen.has(ref))
24
+ continue;
25
+ seen.add(ref);
26
+ out.push(ref);
27
+ }
28
+ return out;
29
+ }
30
+ /** Build PR-to-issue links from a commit list. When `issues` is
31
+ * empty the links carry `planeIssue: undefined`; this lets the
32
+ * renderer surface the refs even without Plane enrichment.
33
+ */
34
+ export function enrichLinks(commits, issues) {
35
+ // Build a quick lookup from sequenceId + project-prefix to PlaneIssueRef.
36
+ // We don't know the project's identifier here, so we match by the
37
+ // numeric tail of `<PREFIX>-<seq>` against `issue.sequenceId`.
38
+ const bySequence = new Map();
39
+ for (const issue of issues) {
40
+ bySequence.set(issue.sequenceId, issue);
41
+ }
42
+ const links = [];
43
+ const seen = new Set();
44
+ for (const commit of commits) {
45
+ const haystack = `${commit.subject}\n${commit.body}`;
46
+ const refs = extractIssueRefs(haystack);
47
+ for (const ref of refs) {
48
+ const dedupeKey = `${commit.sha}:${ref}`;
49
+ if (seen.has(dedupeKey))
50
+ continue;
51
+ seen.add(dedupeKey);
52
+ const tailMatch = /-(\d+)$/.exec(ref);
53
+ const seq = tailMatch ? Number.parseInt(tailMatch[1] ?? '0', 10) : NaN;
54
+ const planeIssue = Number.isFinite(seq) ? bySequence.get(seq) : undefined;
55
+ links.push({
56
+ prSha: commit.sha,
57
+ prSubject: commit.subject,
58
+ issueRef: ref,
59
+ planeIssue,
60
+ });
61
+ }
62
+ }
63
+ return links;
64
+ }
65
+ //# sourceMappingURL=pr-issue-link.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Shared types for `pugi retro` — engineering retrospective command.
3
+ *
4
+ * The retro pipeline runs in three stages:
5
+ * 1. Git collection (git-collector.ts) → RawCommit[]
6
+ * 2. Metric aggregation (metrics.ts) → RetroMetrics
7
+ * 3. Render + persist (narrative.ts) → markdown + JSON snapshot
8
+ *
9
+ * Optional Plane enrichment (plane-collector.ts) populates a PlaneSlice
10
+ * which the renderer joins onto the markdown if --plane was passed.
11
+ *
12
+ * All timestamps are ISO 8601 strings. Numeric fields default to 0
13
+ * (never undefined) so the renderer never branches on absence.
14
+ */
15
+ export {};
16
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Bash sandbox adapter interface (Trust Sprint item 6).
3
+ *
4
+ * Adapter pattern so the bash tool stays unchanged: a runner wraps the
5
+ * spawn invocation with an OS-level sandbox primitive. Today's variants:
6
+ *
7
+ * - none — passthrough (existing behaviour).
8
+ * - macOS-seatbelt — /usr/bin/sandbox-exec with a workspace-scoped
9
+ * write allowlist, read-anywhere, network-allow
10
+ * profile.
11
+ * - docker — Linux fallback. Throws at boot (deferred to a
12
+ * follow-up PR; schema accepts the keyword so
13
+ * operators can see it documented).
14
+ *
15
+ * The CLI bash tool itself is owned by a parallel agent (PUGI-VERIFY-
16
+ * GATE). We intentionally do NOT modify `tools/bash.ts` here. Instead
17
+ * the sandbox sits as an indirection layer between higher-level
18
+ * callers (`runtime/cli.ts`, `core/bash-runner.ts` if introduced
19
+ * later) and the existing bash entry-point.
20
+ *
21
+ * Future: replace this with native landlock bindings on Linux and
22
+ * job-object on Windows. The interface is stable, the adapters
23
+ * change.
24
+ */
25
+ export {};
26
+ // The `makeAdapter` resolver lives in `./index.ts` so it can import
27
+ // the concrete adapters via ESM without circular references. This
28
+ // file stays pure interfaces.
29
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Sandbox adapter resolver (Trust Sprint item 6).
3
+ *
4
+ * Single re-export surface so consumers (`pugi doctor`, future bash
5
+ * runner indirection, MCP serve diagnostics) can do:
6
+ *
7
+ * import { makeAdapter, type SandboxMode } from '.../sandboxing';
8
+ *
9
+ * The concrete adapters live in sibling files; this index wires the
10
+ * lookup table without forcing a circular import between the
11
+ * interface (`adapter.ts`) and the implementations.
12
+ */
13
+ import { NoneSandboxAdapter } from './none.js';
14
+ import { SeatbeltSandboxAdapter } from './seatbelt.js';
15
+ export { NoneSandboxAdapter } from './none.js';
16
+ export { SeatbeltSandboxAdapter } from './seatbelt.js';
17
+ /**
18
+ * Resolve a sandbox adapter from a configured mode. Throws for
19
+ * `docker` (documented but not shipped in this PR) and for unknown
20
+ * modes (defends against forward-rolled settings.json files).
21
+ */
22
+ export function makeAdapter(mode) {
23
+ switch (mode) {
24
+ case 'none':
25
+ return new NoneSandboxAdapter();
26
+ case 'macOS-seatbelt':
27
+ return new SeatbeltSandboxAdapter();
28
+ case 'docker':
29
+ throw new Error('bash sandbox: docker mode is documented but not yet implemented. ' +
30
+ 'Use bash.sandbox = "none" or "macOS-seatbelt" until the docker adapter ships.');
31
+ default: {
32
+ const exhaustive = mode;
33
+ throw new Error(`bash sandbox: unknown mode "${String(exhaustive)}"`);
34
+ }
35
+ }
36
+ }
37
+ /**
38
+ * Convenience: probe the configured mode without spawning anything.
39
+ * Used by `pugi doctor` so the sandbox probe can report the same
40
+ * armed state the bash runner would see.
41
+ */
42
+ export function probeSandbox(opts) {
43
+ const adapter = makeAdapter(opts.mode);
44
+ return adapter.probe({
45
+ workspaceRoot: opts.workspaceRoot,
46
+ ...(opts.extraWritePaths ? { extraWritePaths: opts.extraWritePaths } : {}),
47
+ });
48
+ }
49
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,19 @@
1
+ export class NoneSandboxAdapter {
2
+ mode = 'none';
3
+ probe(_opts) {
4
+ return {
5
+ mode: 'none',
6
+ armed: false,
7
+ reason: "policy 'none' selected — bash dispatches run unsandboxed (classifier + permission FSM still apply).",
8
+ details: ['mode: none (passthrough)', 'enforcement: bash classifier + permission FSM only'],
9
+ };
10
+ }
11
+ wrap(cmd, _opts) {
12
+ return {
13
+ command: cmd.command,
14
+ args: cmd.args,
15
+ description: 'sandbox: none (passthrough)',
16
+ };
17
+ }
18
+ }
19
+ //# sourceMappingURL=none.js.map
@@ -0,0 +1,183 @@
1
+ /**
2
+ * macOS Seatbelt sandbox adapter (Trust Sprint item 6).
3
+ *
4
+ * Wraps bash command execution with `/usr/bin/sandbox-exec` and a
5
+ * dynamically-generated profile. Policy posture:
6
+ *
7
+ * - Reads ANYWHERE (so `node_modules` lookups, system headers,
8
+ * package indices etc all keep working).
9
+ * - Writes ALLOWED under: workspaceRoot, ~/.pugi/, and any
10
+ * additional paths the caller explicitly passes (typical: /tmp,
11
+ * plus the resolved pnpm cache dir if it lives outside ~/.pugi).
12
+ * - Process execution ALLOWED (we need to spawn child binaries to
13
+ * run pnpm / git / etc).
14
+ * - Network egress ALLOWED (npm install, git fetch, web fetch).
15
+ *
16
+ * Profile is rendered to a tmp file per `wrap()` call. The temp file
17
+ * lives in OS tmpdir with mode 0o600. We do NOT cache the profile
18
+ * because workspaceRoot or extraWritePaths can vary per call (e.g.
19
+ * REPL working-directory changes); the file write is cheap.
20
+ *
21
+ * Cancel-cleanup: profile temp files are written with the process
22
+ * pid + random suffix so concurrent calls don't collide. We leave
23
+ * cleanup to the kernel's tmp reaper rather than tracking handles
24
+ * inside the adapter — adding ref-counting would couple the sandbox
25
+ * lifecycle to the bash runner and `pugi mcp serve`, both of which
26
+ * are owned by other agents.
27
+ *
28
+ * Security note: sandbox-exec's profile language is best-effort. It
29
+ * is not a kernel-enforced jail. The intent here is to catch
30
+ * accidental writes outside the workspace (e.g. a renamed test that
31
+ * accidentally writes to $HOME), not to harden against a determined
32
+ * attacker who controls the spawned binary.
33
+ */
34
+ import { execFileSync } from 'node:child_process';
35
+ import { mkdtempSync, writeFileSync } from 'node:fs';
36
+ import { tmpdir } from 'node:os';
37
+ import { isAbsolute, join } from 'node:path';
38
+ const SANDBOX_EXEC_PATH = '/usr/bin/sandbox-exec';
39
+ export class SeatbeltSandboxAdapter {
40
+ mode = 'macOS-seatbelt';
41
+ probe(opts) {
42
+ if (process.platform !== 'darwin') {
43
+ return {
44
+ mode: 'macOS-seatbelt',
45
+ armed: false,
46
+ reason: `macOS-seatbelt unavailable on ${process.platform} — choose 'none' or 'docker'.`,
47
+ details: [`platform: ${process.platform}`, `expected: darwin`],
48
+ };
49
+ }
50
+ if (!sandboxExecBinaryAvailable()) {
51
+ return {
52
+ mode: 'macOS-seatbelt',
53
+ armed: false,
54
+ reason: `sandbox-exec not callable at ${SANDBOX_EXEC_PATH}.`,
55
+ details: [
56
+ `binary: ${SANDBOX_EXEC_PATH}`,
57
+ 'remediation: verify Apple has not deprecated the binary on this macOS major.',
58
+ ],
59
+ };
60
+ }
61
+ return {
62
+ mode: 'macOS-seatbelt',
63
+ armed: true,
64
+ details: [
65
+ 'platform: darwin',
66
+ `binary: ${SANDBOX_EXEC_PATH}`,
67
+ `workspaceRoot: ${opts.workspaceRoot}`,
68
+ `extraWritePaths: ${(opts.extraWritePaths ?? []).join(', ') || '<none>'}`,
69
+ ],
70
+ };
71
+ }
72
+ wrap(cmd, opts) {
73
+ const armed = this.probe(opts);
74
+ if (!armed.armed) {
75
+ throw new Error(`SeatbeltSandboxAdapter.wrap: ${armed.reason}`);
76
+ }
77
+ if (!isAbsolute(opts.workspaceRoot)) {
78
+ throw new Error(`SeatbeltSandboxAdapter.wrap: workspaceRoot must be absolute, got "${opts.workspaceRoot}"`);
79
+ }
80
+ for (const p of opts.extraWritePaths ?? []) {
81
+ if (!isAbsolute(p)) {
82
+ throw new Error(`SeatbeltSandboxAdapter.wrap: extraWritePaths entry must be absolute, got "${p}"`);
83
+ }
84
+ }
85
+ const profilePath = writeProfileFile(opts);
86
+ return {
87
+ command: SANDBOX_EXEC_PATH,
88
+ args: ['-f', profilePath, cmd.command, ...cmd.args],
89
+ description: `sandbox: macOS-seatbelt (profile=${profilePath})`,
90
+ };
91
+ }
92
+ /**
93
+ * Render the Seatbelt profile (TCL/Lisp-ish) for the given write
94
+ * allowlist. Exposed for unit tests; the live wrap path uses
95
+ * `writeProfileFile` internally.
96
+ */
97
+ renderProfile(opts) {
98
+ return renderProfile(opts);
99
+ }
100
+ }
101
+ function sandboxExecBinaryAvailable() {
102
+ try {
103
+ // `sandbox-exec` exits non-zero with a usage banner on `-h`. We
104
+ // capture the banner via stderr and accept any rapid exit as
105
+ // evidence the binary is callable.
106
+ execFileSync(SANDBOX_EXEC_PATH, ['-h'], {
107
+ stdio: ['ignore', 'ignore', 'pipe'],
108
+ timeout: 3000,
109
+ });
110
+ return true;
111
+ }
112
+ catch (err) {
113
+ const e = err;
114
+ // ENOENT means the binary itself is missing. A non-zero exit code
115
+ // (sandbox-exec usage banner) is success for our purposes.
116
+ if (e?.code === 'ENOENT')
117
+ return false;
118
+ return true;
119
+ }
120
+ }
121
+ function writeProfileFile(opts) {
122
+ const profile = renderProfile(opts);
123
+ const dir = mkdtempSync(join(tmpdir(), 'pugi-seatbelt-'));
124
+ const path = join(dir, 'profile.sb');
125
+ writeFileSync(path, profile, { mode: 0o600 });
126
+ return path;
127
+ }
128
+ /**
129
+ * Generate the Seatbelt profile. Keep the language tight:
130
+ *
131
+ * - (version 1) — required header.
132
+ * - (deny default) — start from no permissions.
133
+ * - (allow process*) — allow spawning child processes.
134
+ * - (allow file-read*) — reads unrestricted.
135
+ * - (allow file-write* (subpath "...")) — writes scoped.
136
+ * - (allow network*) — egress unrestricted.
137
+ * - (allow signal) + sysctl-read for normal node operation.
138
+ */
139
+ function renderProfile(opts) {
140
+ const writePaths = [opts.workspaceRoot, ...(opts.extraWritePaths ?? [])];
141
+ const writeRules = writePaths
142
+ .map((p) => ` (subpath ${quoteForSeatbelt(p)})`)
143
+ .join('\n');
144
+ // Devices required for normal stdout/stderr piping. /dev/null is
145
+ // table stakes; pts/* keeps interactive PTY-based tools (pagers,
146
+ // editors) working when an operator runs them under the sandbox.
147
+ const devicePaths = ['/dev/null', '/dev/dtracehelper', '/dev/tty', '/dev/stdout', '/dev/stderr'];
148
+ const deviceRules = devicePaths
149
+ .map((p) => ` (literal ${quoteForSeatbelt(p)})`)
150
+ .join('\n');
151
+ return [
152
+ '(version 1)',
153
+ '(deny default)',
154
+ '(allow process-exec)',
155
+ '(allow process-fork)',
156
+ '(allow signal (target self))',
157
+ '(allow sysctl-read)',
158
+ '(allow file-read*)',
159
+ '(allow file-write*',
160
+ writeRules,
161
+ ')',
162
+ '(allow file-write*',
163
+ deviceRules,
164
+ ')',
165
+ '(allow network*)',
166
+ '(allow mach-lookup)',
167
+ '(allow ipc-posix-shm)',
168
+ '',
169
+ ].join('\n');
170
+ }
171
+ /**
172
+ * Seatbelt profile string literals use TCL-style double-quoted
173
+ * strings. We need to escape `"` and `\` but the profile language
174
+ * does not accept arbitrary control chars; reject any input that
175
+ * contains them so we never silently emit a malformed profile.
176
+ */
177
+ function quoteForSeatbelt(value) {
178
+ if (/[\x00-\x1f"\\]/.test(value)) {
179
+ throw new Error(`SeatbeltSandboxAdapter: refusing to render profile with non-printable or quote chars in "${value}"`);
180
+ }
181
+ return `"${value}"`;
182
+ }
183
+ //# sourceMappingURL=seatbelt.js.map
@@ -16,8 +16,35 @@ export function openSession(root) {
16
16
  pugiDir,
17
17
  eventsPath,
18
18
  enabled,
19
+ verificationLedger: [],
19
20
  };
20
21
  }
22
+ /**
23
+ * PUGI-VERIFY-GATE — append a verification ledger entry. Mutates
24
+ * `session.verificationLedger` in place AND mirrors the entry to
25
+ * the JSONL audit log when the session is enabled. Pure helper
26
+ * (no I/O on disabled sessions); safe to call from sync code
27
+ * paths.
28
+ *
29
+ * The bash tool dispatcher calls this after every shell exec whose
30
+ * head matches a `VERIFICATION_PATTERNS` entry.
31
+ */
32
+ export function recordVerificationCall(session, entry) {
33
+ session.verificationLedger.push(entry);
34
+ if (!session.enabled)
35
+ return;
36
+ appendEvent({
37
+ id: randomUUID(),
38
+ sessionId: session.id,
39
+ timestamp: now(),
40
+ type: 'verification',
41
+ name: 'call_recorded',
42
+ tool: entry.tool,
43
+ command: entry.command,
44
+ exitCode: entry.exitCode,
45
+ tailStderrLen: entry.tailStderr.length,
46
+ }, session.eventsPath);
47
+ }
21
48
  /**
22
49
  * MVP — fire the `SessionStart` lifecycle event for all hooks
23
50
  * declared in `~/.pugi/hooks-mvp.json`. Single-call surface; the REPL