repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(pi): add constrained security review workflow

199f7ab8ec887e667a21ddd0c344fc3147f02f5c

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (11)

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/current.json

Added
new file mode 100644
1 +{
2 + "schemaVersion": 1,
3 + "name": "security-review-writer",
4 + "revision": "d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6",
5 + "description": "Registers one constrained tool for security-scan workers to atomically create or overwrite UTF-8 text only within the current project's ai-workspace/security-reviews directory.",
6 + "topic": "Constrained persistence of security-scan review artifacts within a project-local review root.",
7 + "publishedAt": "2026-08-27T11:01:03.148Z"
8 +}

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/.ultra-validation.json

Added
new file mode 100644
1 +{
2 + "schemaVersion": 1,
3 + "validatorContractVersion": 1,
4 + "sourceHash": "d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6",
5 + "validatedAt": "2026-08-27T11:01:03.043Z",
6 + "platform": "win32",
7 + "testedPlatforms": [
8 + "win32"
9 + ],
10 + "nodeVersion": "v26.7.0",
11 + "warningTargetMs": 5000,
12 + "gates": [
13 + "manifest",
14 + "readme",
15 + "package",
16 + "debug-template",
17 + "artifacts",
18 + "executables",
19 + "tests",
20 + "benchmark",
21 + "real-loader",
22 + "load-timing",
23 + "hash"
24 + ]

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/README.md

Added
new file mode 100644
1 +# security-review-writer
3 +## Purpose
5 +This extension gives security-scan worker agents one constrained persistence tool for review artifacts.
6 +It atomically creates or overwrites UTF-8 text beneath the current project's `ai-workspace/security-reviews` directory.
8 +## Scope
10 +The `security_review_writer` tool accepts a review-root-relative path or an absolute path already beneath the review root.
11 +It rejects outside paths, traversal segments, symbolic-link components, symbolic-link targets, directories, non-regular files, and parents that resolve outside the canonical review root.
12 +It creates missing real parent directories and commits complete content with an atomic same-directory rename.
13 +It activates during `session_start` in TUI, RPC, JSON, and headless print modes without startup filesystem or subprocess probes.
15 +## Non-goals
17 +- This extension is not a general-purpose file writer.
18 +- This extension does not read review artifacts.
19 +- This extension does not perform or interpret security scans.
20 +- This extension does not override Pi's built-in `write` tool.
21 +- This extension does not write outside `ai-workspace/security-reviews`.
23 +## Alternatives considered
25 +No validated catalog candidate matched the constrained security-review artifact writer topic.
26 +Repeating path checks in worker prompts was rejected because prompts cannot provide an enforceable filesystem boundary.
27 +Overriding built-in `write` was rejected because the workflow intentionally omits that built-in and requires a separately named constrained tool.
29 +## Decision rationale
31 +A single purpose-built tool gives security-scan workers a stable least-authority write surface while preserving Pi's built-in tool namespace.
32 +Native Node filesystem APIs provide portable UTF-8 encoding, exclusive temporary-file creation, canonical path checks, abort propagation, and atomic rename without runtime dependencies or shell probes.
34 +## Usage
36 +Load `security-review-writer` through the Ultra step's `dynamicExtensions` field.
37 +Omit built-in `write` from the worker's selected tools and call `security_review_writer` with `{ "path": "worker-id/review.md", "text": "..." }`.
38 +Relative paths are resolved beneath `ai-workspace/security-reviews`, while absolute paths must already be lexically contained by that root.
39 +On success the tool returns the root-relative path, UTF-8 byte count, and whether it replaced an existing regular file.
40 +Typed failures include an error code and an actionable hint, and abort signals are rethrown unchanged.
42 +## Architecture
44 +`index.ts` synchronously registers exactly one tool and activates it from `session_start` without blocking startup.
45 +`core.ts` owns path resolution, canonical containment, directory and target inspection, symlink rejection, UTF-8 temporary-file persistence, durability sync, and atomic rename.
46 +The temporary file is created in the verified target directory with exclusive mode and is removed after failures or aborts before commit.
47 +`debug.ts` remains scaffold-identical, while `index.ts` emits bounded events that exclude review text and redact requested paths to shape metadata on failure.
48 +Compact rendering reports create or overwrite status, and expanded rendering adds the relative path, byte count, and atomic commit detail.
50 +## Test matrix
52 +| Capability | Exact `node:test` case name | Coverage |
53 +| --- | --- | --- |
54 +| `security-review-write-atomic` | `security-review-write-atomic` | Relative create, contained absolute overwrite, UTF-8 content, and temporary-file cleanup. |
55 +| `security-review-path-containment` | `security-review-path-containment` | Absolute outside path, slash and backslash traversal, and directory target rejection. |
56 +| `security-review-symlink-defense` | `security-review-symlink-defense` | Escaping linked parent, direct linked target, outside-file preservation, and platform-supported link forms. |
58 +## Promotion notes
60 +The stable catalog name is `security-review-writer` and the registered tool name is `security_review_writer`.
61 +Keep this package private until a human deliberately promotes it.
62 +Future revisions must preserve or tighten the 10 ms path-resolution hot-path budgets and retain the no-override contract.

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/benchmark.ts

Added
new file mode 100644
1 +import { performance } from "node:perf_hooks";
2 +import { resolve } from "node:path";
3 +import { resolveTargetPath } from "./core.ts";
5 +const root = resolve(process.cwd(), "ai-workspace", "security-reviews");
6 +const started = performance.now();
7 +for (let index = 0; index < 250; index++) resolveTargetPath(root, root, `worker-${index}/review.md`);
8 +const hotPathMs = performance.now() - started;
9 +console.log(JSON.stringify({ hotPathMs }));

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/core.ts

Added
new file mode 100644
1 +import { randomUUID } from "node:crypto";
2 +import { lstat, mkdir, open, realpath, rename, stat, unlink } from "node:fs/promises";
3 +import { isAbsolute, join, relative, resolve, sep } from "node:path";
5 +const REVIEW_ROOT_PARTS = ["ai-workspace", "security-reviews"] as const;
6 +const TEMP_PREFIX = ".security-review-writer-";
8 +export type ReviewWriteErrorCode =
9 + | "INVALID_PATH"
10 + | "OUTSIDE_ROOT"
11 + | "SYMLINK_ESCAPE"
12 + | "TARGET_IS_DIRECTORY"
13 + | "TARGET_NOT_FILE"
14 + | "IO_FAILURE";
16 +export class ReviewWriteError extends Error {
17 + readonly code: ReviewWriteErrorCode;
18 + readonly hint: string;
19 + readonly cause?: unknown;
21 + constructor(code: ReviewWriteErrorCode, message: string, hint: string, cause?: unknown) {
22 + super(`[${code}] ${message} Hint: ${hint}`);
23 + this.name = "ReviewWriteError";
24 + this.code = code;
25 + this.hint = hint;
26 + this.cause = cause;
27 + }
30 +export type ReviewWriteResult = {
31 + ok: true;
32 + relativePath: string;
33 + bytes: number;
34 + replaced: boolean;
35 +};
37 +function fail(code: ReviewWriteErrorCode, message: string, hint: string): never {
38 + throw new ReviewWriteError(code, message, hint);
41 +function isFsError(error: unknown, code: string): boolean {
42 + return typeof error === "object" && error !== null && "code" in error && error.code === code;
45 +function isAbortError(error: unknown): boolean {
46 + return error instanceof Error && error.name === "AbortError";
49 +function atOrWithin(root: string, candidate: string): boolean {
50 + const suffix = relative(root, candidate);
51 + return suffix === "" || (suffix !== ".." && !suffix.startsWith(`..${sep}`) && !isAbsolute(suffix));
54 +function strictlyWithin(root: string, candidate: string): boolean {
55 + return candidate !== root && atOrWithin(root, candidate);
58 +function traversalRequested(path: string): boolean {
59 + return path.replaceAll("\\", "/").split("/").includes("..");
62 +function pathSuffixWithin(root: string, candidate: string): string | undefined {
63 + const suffix = relative(root, candidate);
64 + if (suffix === "" || suffix === ".." || suffix.startsWith(`..${sep}`) || isAbsolute(suffix)) return undefined;
65 + return suffix;
68 +export function resolveTargetPath(
69 + configuredRoot: string,
70 + canonicalRoot: string,
71 + requestedPath: string,
72 +): string {
73 + if (requestedPath.length === 0 || requestedPath.includes("\0")) {
74 + fail("INVALID_PATH", "The target path is empty or contains a NUL byte.", "Provide a non-empty review file path.");
75 + }
76 + if (traversalRequested(requestedPath)) {
77 + fail("INVALID_PATH", "Traversal segments are not allowed in review paths.", "Remove every '..' path segment.");
78 + }
80 + if (!isAbsolute(requestedPath)) {
81 + const target = resolve(canonicalRoot, requestedPath);
82 + if (!strictlyWithin(canonicalRoot, target)) {
83 + fail("OUTSIDE_ROOT", "The relative target does not name a file beneath the review root.", "Use a root-relative review file path.");
84 + }
85 + return target;
86 + }
88 + const absoluteTarget = resolve(requestedPath);
89 + for (const acceptedRoot of [canonicalRoot, configuredRoot]) {
90 + const suffix = pathSuffixWithin(acceptedRoot, absoluteTarget);
91 + if (suffix !== undefined) return resolve(canonicalRoot, suffix);
92 + }
93 + fail("OUTSIDE_ROOT", "The absolute target is outside ai-workspace/security-reviews.", "Choose an absolute path beneath the current project's review root.");
96 +async function inspectDirectory(path: string, root: string): Promise<void> {
97 + const info = await lstat(path);
98 + if (info.isSymbolicLink()) {
99 + fail("SYMLINK_ESCAPE", "A review directory component is a symbolic link.", "Replace the link with a real directory beneath the review root.");
101 + if (!info.isDirectory()) {
102 + fail("INVALID_PATH", "A review path parent is not a directory.", "Choose a target whose parent components are directories.");
104 + const canonical = await realpath(path);
105 + if (!atOrWithin(root, canonical)) {
106 + fail("SYMLINK_ESCAPE", "An existing review parent resolves outside the review root.", "Use only real directories contained by ai-workspace/security-reviews.");
110 +async function createAndInspectDirectory(path: string, root: string): Promise<void> {
111 + try {
112 + await mkdir(path);
113 + } catch (error) {
114 + if (!isFsError(error, "EEXIST")) throw error;
116 + await inspectDirectory(path, root);
119 +async function ensureReviewRoot(cwd: string): Promise<{ configuredRoot: string; canonicalRoot: string }> {
120 + const projectRoot = await realpath(cwd);
121 + const projectInfo = await stat(projectRoot);
122 + if (!projectInfo.isDirectory()) {
123 + fail("INVALID_PATH", "The current project path is not a directory.", "Start Pi from a project directory.");
126 + let current = projectRoot;
127 + for (const part of REVIEW_ROOT_PARTS) {
128 + current = join(current, part);
129 + await createAndInspectDirectory(current, projectRoot);
131 + const canonicalRoot = await realpath(current);
132 + if (!strictlyWithin(projectRoot, canonicalRoot)) {
133 + fail("SYMLINK_ESCAPE", "The review root resolves outside the current project.", "Use a real project-local ai-workspace/security-reviews directory.");
135 + return {
136 + configuredRoot: resolve(cwd, ...REVIEW_ROOT_PARTS),
137 + canonicalRoot,
138 + };
141 +async function ensureTargetParent(root: string, target: string): Promise<string> {
142 + const suffix = relative(root, target);
143 + const parts = suffix.split(sep);
144 + parts.pop();
145 + let current = root;
146 + for (const part of parts) {
147 + current = join(current, part);
148 + await createAndInspectDirectory(current, root);
150 + const canonicalParent = await realpath(current);
151 + if (!atOrWithin(root, canonicalParent)) {
152 + fail("SYMLINK_ESCAPE", "The target's existing parent resolves outside the review root.", "Use only real directories beneath the review root.");
154 + return current;
157 +async function inspectTarget(target: string): Promise<boolean> {
158 + try {
159 + const info = await lstat(target);
160 + if (info.isSymbolicLink()) {
161 + fail("SYMLINK_ESCAPE", "The target is a symbolic link.", "Write to a real file beneath the review root instead.");
163 + if (info.isDirectory()) {
164 + fail("TARGET_IS_DIRECTORY", "The target is a directory.", "Provide a review file path, not a directory path.");
166 + if (!info.isFile()) {
167 + fail("TARGET_NOT_FILE", "The target is not a regular file.", "Provide a new path or an existing regular file.");
169 + return true;
170 + } catch (error) {
171 + if (isFsError(error, "ENOENT")) return false;
172 + throw error;
176 +export async function writeSecurityReview(args: {
177 + cwd: string;
178 + path: string;
179 + text: string;
180 + signal?: AbortSignal;
181 +}): Promise<ReviewWriteResult> {
182 + let temporaryPath: string | undefined;
183 + let handle: Awaited<ReturnType<typeof open>> | undefined;
184 + try {
185 + args.signal?.throwIfAborted();
186 + const { configuredRoot, canonicalRoot } = await ensureReviewRoot(args.cwd);
187 + const target = resolveTargetPath(configuredRoot, canonicalRoot, args.path);
188 + const parent = await ensureTargetParent(canonicalRoot, target);
189 + const replaced = await inspectTarget(target);
190 + args.signal?.throwIfAborted();
192 + temporaryPath = join(parent, `${TEMP_PREFIX}${randomUUID()}.tmp`);
193 + handle = await open(temporaryPath, "wx", 0o600);
194 + await handle.writeFile(args.text, { encoding: "utf8" });
195 + await handle.sync();
196 + await handle.close();
197 + handle = undefined;
199 + args.signal?.throwIfAborted();
200 + await inspectDirectory(parent, canonicalRoot);
201 + await inspectTarget(target);
202 + await rename(temporaryPath, target);
203 + temporaryPath = undefined;
205 + return {
206 + ok: true,
207 + relativePath: relative(canonicalRoot, target),
208 + bytes: Buffer.byteLength(args.text, "utf8"),
209 + replaced,
210 + };
211 + } catch (error) {
212 + if (handle !== undefined) await handle.close().catch(() => undefined);
213 + if (temporaryPath !== undefined) await unlink(temporaryPath).catch(() => undefined);
214 + if (error instanceof ReviewWriteError || isAbortError(error) || args.signal?.aborted) throw error;
215 + throw new ReviewWriteError(
216 + "IO_FAILURE",
217 + "The review file could not be written atomically.",
218 + "Check project permissions and retry with a regular file path beneath the review root.",
219 + error,
220 + );

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/debug.ts

Added
new file mode 100644
1 +import { appendFile, mkdir, open, stat } from "node:fs/promises";
2 +import { homedir } from "node:os";
3 +import { basename, dirname, join } from "node:path";
4 +import { fileURLToPath } from "node:url";
5 +import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7 +const LOG_LIMIT_BYTES = 1024 * 1024;
8 +const MARKER_RESERVE_BYTES = 512;
9 +const VALUE_LIMIT = 12_000;
11 +function cacheRoot(): string {
12 + if (process.platform === "win32")
13 + return process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local");
14 + if (process.platform === "darwin")
15 + return join(homedir(), "Library", "Caches");
16 + return process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache");
19 +function bounded(value: unknown): unknown {
20 + let encoded: string;
21 + try {
22 + encoded = JSON.stringify(value);
23 + } catch {
24 + encoded = String(value);
25 + }
26 + return encoded.length <= VALUE_LIMIT
27 + ? value
28 + : { truncated: true, preview: encoded.slice(0, VALUE_LIMIT) };
31 +export function dynamicExtensionRevision(moduleUrl: string): string {
32 + return basename(dirname(fileURLToPath(moduleUrl)));
35 +export function dynamicExtensionLogPath(
36 + sessionId: string,
37 + extensionName: string,
38 +): string {
39 + return join(
40 + cacheRoot(),
41 + "pi",
42 + "ultra",
43 + "dynamic-extensions",
44 + "logs",
45 + sessionId,
46 + `${extensionName}.jsonl`,
47 + );
50 +async function hasTruncationMarker(path: string, size: number): Promise<boolean> {
51 + if (size === 0) return false;
52 + const handle = await open(path, "r");
53 + try {
54 + const length = Math.min(size, 1024);
55 + const bytes = Buffer.alloc(length);
56 + await handle.read(bytes, 0, length, size - length);
57 + return bytes.toString("utf8").includes('"event":"log_truncated"');
58 + } finally {
59 + await handle.close();
60 + }
63 +export async function logDynamicExtensionEvent(args: {
64 + name: string;
65 + revision: string;
66 + ctx: ExtensionContext;
67 + event: string;
68 + durationMs?: number;
69 + context?: unknown;
70 +}): Promise<void> {
71 + const sessionId = args.ctx.sessionManager.getSessionId();
72 + const path = dynamicExtensionLogPath(sessionId, args.name);
73 + await mkdir(dirname(path), { recursive: true });
74 + const size = await stat(path).then((value) => value.size, () => 0);
75 + if (size >= LOG_LIMIT_BYTES) return;
76 + const record = {
77 + timestamp: new Date().toISOString(),
78 + extension: { name: args.name, revision: args.revision },
79 + childSessionId: sessionId,
80 + event: args.event,
81 + ...(args.durationMs === undefined ? {} : { durationMs: args.durationMs }),
82 + ...(args.context === undefined ? {} : { context: bounded(args.context) }),
83 + };
84 + const line = `${JSON.stringify(record)}\n`;
85 + if (
86 + size < LOG_LIMIT_BYTES - MARKER_RESERVE_BYTES &&
87 + size + Buffer.byteLength(line) <= LOG_LIMIT_BYTES - MARKER_RESERVE_BYTES
88 + ) {
89 + await appendFile(path, line, "utf8");
90 + return;
91 + }
92 + if (await hasTruncationMarker(path, size)) return;
93 + const marker = {
94 + timestamp: new Date().toISOString(),
95 + extension: { name: args.name, revision: args.revision },
96 + childSessionId: sessionId,
97 + event: "log_truncated",
98 + context: { limitBytes: LOG_LIMIT_BYTES },
99 + };
100 + await appendFile(path, `${JSON.stringify(marker)}\n`, "utf8");

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/index.test.ts

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { mkdtemp, mkdir, readFile, readdir, symlink, writeFile } from "node:fs/promises";
3 +import { tmpdir } from "node:os";
4 +import { join, resolve } from "node:path";
5 +import test from "node:test";
6 +import { ReviewWriteError, writeSecurityReview } from "./core.ts";
8 +async function project(): Promise<string> {
9 + return mkdtemp(join(tmpdir(), "security-review-writer-"));
12 +async function rejectsWithCode(operation: Promise<unknown>, code: string): Promise<void> {
13 + await assert.rejects(operation, (error: unknown) => error instanceof ReviewWriteError && error.code === code);
16 +test("security-review-write-atomic", async () => {
17 + const cwd = await project();
18 + const relativePath = join("worker-1", "review.md");
19 + const target = join(cwd, "ai-workspace", "security-reviews", relativePath);
21 + const created = await writeSecurityReview({ cwd, path: relativePath, text: "first ä" });
22 + assert.equal(created.replaced, false);
23 + assert.equal(await readFile(target, "utf8"), "first ä");
25 + const overwritten = await writeSecurityReview({ cwd, path: resolve(target), text: "second ✓" });
26 + assert.equal(overwritten.replaced, true);
27 + assert.equal(await readFile(target, "utf8"), "second ✓");
28 + assert.deepEqual((await readdir(join(cwd, "ai-workspace", "security-reviews", "worker-1"))).sort(), ["review.md"]);
29 +});
31 +test("security-review-path-containment", async () => {
32 + const cwd = await project();
33 + const outside = join(cwd, "outside.md");
34 + await rejectsWithCode(writeSecurityReview({ cwd, path: outside, text: "no" }), "OUTSIDE_ROOT");
35 + await rejectsWithCode(writeSecurityReview({ cwd, path: join("..", "escape.md"), text: "no" }), "INVALID_PATH");
36 + await rejectsWithCode(writeSecurityReview({ cwd, path: "..\\escape.md", text: "no" }), "INVALID_PATH");
38 + const directory = join(cwd, "ai-workspace", "security-reviews", "directory-target");
39 + await mkdir(directory, { recursive: true });
40 + await rejectsWithCode(writeSecurityReview({ cwd, path: "directory-target", text: "no" }), "TARGET_IS_DIRECTORY");
41 +});
43 +test("security-review-symlink-defense", async () => {
44 + const cwd = await project();
45 + await writeSecurityReview({ cwd, path: "seed.md", text: "seed" });
46 + const root = join(cwd, "ai-workspace", "security-reviews");
47 + const outside = await mkdtemp(join(tmpdir(), "security-review-outside-"));
48 + const linkedParent = join(root, "linked-parent");
49 + await symlink(outside, linkedParent, process.platform === "win32" ? "junction" : "dir");
51 + await rejectsWithCode(writeSecurityReview({ cwd, path: join("linked-parent", "escaped.md"), text: "no" }), "SYMLINK_ESCAPE");
52 + await rejectsWithCode(writeSecurityReview({ cwd, path: "linked-parent", text: "no" }), "SYMLINK_ESCAPE");
53 + await assert.rejects(readFile(join(outside, "escaped.md"), "utf8"), { code: "ENOENT" });
55 + if (process.platform !== "win32") {
56 + const outsideFile = join(outside, "outside.md");
57 + await writeFile(outsideFile, "unchanged", "utf8");
58 + await symlink(outsideFile, join(root, "linked-file.md"), "file");
59 + await rejectsWithCode(writeSecurityReview({ cwd, path: "linked-file.md", text: "no" }), "SYMLINK_ESCAPE");
60 + assert.equal(await readFile(outsideFile, "utf8"), "unchanged");
61 + }
62 +});

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/index.ts

Added
new file mode 100644
1 +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2 +import type { ReviewWriteResult } from "./core.ts";
4 +const EXTENSION_NAME = "security-review-writer";
5 +const TOOL_NAME = "security_review_writer";
7 +type PlainTextComponent = {
8 + setText(value: string): void;
9 + render(width: number): string[];
10 + invalidate(): void;
11 +};
13 +function plainText(initial: string): PlainTextComponent {
14 + let value = initial;
15 + return {
16 + setText(next) {
17 + value = next;
18 + },
19 + render(width) {
20 + return value.split("\n").map((line) => line.slice(0, Math.max(0, width)));
21 + },
22 + invalidate() {},
23 + };
26 +function component(previous: unknown): PlainTextComponent {
27 + return previous !== null && typeof previous === "object" && "setText" in previous
28 + ? previous as PlainTextComponent
29 + : plainText("");
32 +function redactedPathShape(path: string): { kind: "absolute" | "relative"; length: number } {
33 + return { kind: /^([A-Za-z]:[\\/]|[\\/])/.test(path) ? "absolute" : "relative", length: path.length };
36 +function errorCode(error: unknown): string {
37 + return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
38 + ? error.code
39 + : "UNEXPECTED";
42 +async function emit(ctx: ExtensionContext, event: string, durationMs: number, context: unknown): Promise<void> {
43 + const { dynamicExtensionRevision, logDynamicExtensionEvent } = await import("./debug.ts");
44 + await logDynamicExtensionEvent({
45 + name: EXTENSION_NAME,
46 + revision: dynamicExtensionRevision(import.meta.url),
47 + ctx,
48 + event,
49 + durationMs,
50 + context,
51 + }).catch(() => undefined);
54 +export default function dynamicExtension(pi: ExtensionAPI) {
55 + pi.registerTool({
56 + name: TOOL_NAME,
57 + label: "Security Review Writer",
58 + description: "Atomically create or overwrite one UTF-8 text file beneath the current project's ai-workspace/security-reviews directory. Relative paths are review-root-relative; absolute paths must already be beneath that root.",
59 + parameters: {
60 + type: "object",
61 + properties: {
62 + path: { type: "string", description: "Review-root-relative or contained absolute target file path." },
63 + text: { type: "string", description: "Complete UTF-8 text content to write atomically." },
64 + },
65 + required: ["path", "text"],
66 + additionalProperties: false,
67 + },
68 + async execute(_id, params, signal, _onUpdate, ctx) {
69 + const started = performance.now();
70 + try {
71 + const { writeSecurityReview } = await import("./core.ts");
72 + const result = await writeSecurityReview({ cwd: ctx.cwd, path: params.path, text: params.text, signal });
73 + await emit(ctx, "write_complete", performance.now() - started, {
74 + relativePath: result.relativePath,
75 + bytes: result.bytes,
76 + replaced: result.replaced,
77 + });
78 + return {
79 + content: [{
80 + type: "text" as const,
81 + text: `${result.replaced ? "Overwrote" : "Created"} ${result.relativePath} atomically (${result.bytes} UTF-8 bytes).`,
82 + }],
83 + details: result,
84 + };
85 + } catch (error) {
86 + if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) throw error;
87 + await emit(ctx, "write_failed", performance.now() - started, {
88 + path: redactedPathShape(params.path),
89 + code: errorCode(error),
90 + });
91 + throw error;
92 + }
93 + },
94 + renderCall(args, _theme, context) {
95 + const text = component(context.lastComponent);
96 + text.setText(`${TOOL_NAME} ${args.path}`);
97 + return text;
98 + },
99 + renderResult(result, { expanded, isPartial }, _theme, context) {
100 + const text = component(context.lastComponent);
101 + if (isPartial) {
102 + text.setText("Writing review…");
103 + return text;
105 + const details = result.details as ReviewWriteResult | undefined;
106 + if (details?.ok) {
107 + let rendered = details.replaced ? "✓ Review overwritten" : "✓ Review created";
108 + if (expanded) rendered += `\n${details.relativePath} · ${details.bytes} UTF-8 bytes · atomic rename`;
109 + text.setText(rendered);
110 + return text;
112 + text.setText("Review write failed");
113 + return text;
114 + },
115 + });
117 + pi.on("session_start", () => {
118 + const active = pi.getActiveTools();
119 + if (!active.includes(TOOL_NAME)) pi.setActiveTools([...active, TOOL_NAME]);
120 + });

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/manifest.json

Added
new file mode 100644
1 +{
2 + "schemaVersion": 1,
3 + "name": "security-review-writer",
4 + "description": "Registers one constrained tool for security-scan workers to atomically create or overwrite UTF-8 text only within the current project's ai-workspace/security-reviews directory.",
5 + "topic": "Constrained persistence of security-scan review artifacts within a project-local review root.",
6 + "scope": "Resolve absolute and relative review paths against the current project, enforce containment beneath ai-workspace/security-reviews, reject traversal, outside paths, symlink escapes, directories, and existing parents resolving outside the root, then atomically write UTF-8 text without overriding Pi's built-in write tool.",
7 + "nonGoals": [
8 + "General-purpose file writing or reading.",
9 + "Security scanning, review generation, or report interpretation.",
10 + "Writing outside ai-workspace/security-reviews.",
11 + "Overriding Pi built-in tools, including write.",
12 + "Managing permissions, encryption, credentials, or remote storage."
13 + ],
14 + "tags": [
15 + "security-review",
16 + "atomic-write",
17 + "path-containment",
18 + "worker-agent"
19 + ],
20 + "capabilities": [
21 + "security-review-write-atomic",
22 + "security-review-path-containment",
23 + "security-review-symlink-defense"
24 + ],
25 + "requiredExecutables": [],
26 + "optionalExecutables": [],
27 + "overrides": [],
28 + "benchmarkBudgets": {
29 + "darwin": {
30 + "hotPathMs": 10
31 + },
32 + "linux": {
33 + "hotPathMs": 10
34 + },
35 + "win32": {
36 + "hotPathMs": 10
37 + }
38 + }

pi/agent/ultra/dynamic-extensions/catalog/security-review-writer/d0e991293c4407629bb3b19989f7e51429c04cdbe44d170cfd26c5f19bf2fcc6/package.json

Added
new file mode 100644
1 +{
2 + "name": "@ultra-dynamic/security-review-writer",
3 + "private": true,
4 + "type": "module",
5 + "main": "index.ts",
6 + "peerDependencies": {
7 + "@earendil-works/pi-coding-agent": "*"
8 + }
9 +}

pi/agent/workflows/security-scan-workers.json

Added
new file mode 100644
1 +{
2 + "name": "security-scan-workers",
3 + "description": "Run isolated security-scan worker tasks with a path-gated review writer.",
4 + "args": {
5 + "hint": "JSON object containing a tasks array"
6 + },
7 + "schemas": {
8 + "WorkerResult": {
9 + "type": "object",
10 + "properties": {
11 + "taskId": {
12 + "type": "string"
13 + },
14 + "outputPath": {
15 + "type": "string"
16 + },
17 + "ok": {
18 + "type": "boolean"
19 + },
20 + "count": {
21 + "type": "integer",
22 + "minimum": 0
23 + },
24 + "result": {
25 + "type": "string"
26 + }
27 + },
28 + "required": [
29 + "taskId",
30 + "outputPath",
31 + "ok",
32 + "count",
33 + "result"
34 + ]
35 + }
36 + },
37 + "phases": [
38 + {
39 + "id": "work",
40 + "kind": "fanout",
41 + "over": "{args.tasks}",
42 + "concurrency": 4,
43 + "writeIsolation": "Every task descriptor owns one unique outputPath beneath ai-workspace/security-reviews; callers must never submit duplicate output paths in one run.",
44 + "step": {
45 + "summary": "Run security task {item}",
46 + "prompt": "Execute this security-scan task: {item}. Read the agentTemplate named in the descriptor and follow its security analysis, scope, evidence, severity, and document-format instructions. The descriptor and this prompt override the template's harness-specific tool and final-response instructions. Use lowercase Pi tools. Use security_review_writer instead of Write, and write only the descriptor's outputPath. Do not modify source code, config, findings outside outputPath, or any other file. Read only the stated scope plus imported shared controls needed to verify a claim. After writing, read outputPath back and verify it. Then submit structured output matching WorkerResult: echo taskId and outputPath, set ok, set count to the number of findings, reviews, or scenarios produced as appropriate, and summarize the result tersely. Never return the report body through structured output.",
47 + "tools": [
48 + "read",
49 + "grep",
50 + "find",
51 + "ls"
52 + ],
53 + "dynamicExtensions": [
54 + "security-review-writer"
55 + ],
56 + "model": "big",
57 + "thinkingLevel": "high",
58 + "schema": "WorkerResult"
59 + }
60 + }
61 + ],
62 + "return": "{work.results}"