repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat(the-system): open documents for editing

904249b951bb9d36ffec3b7dcdc9148107533c5c

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (5)

CHANGELOG.md

Modified
11 11 - Seed `/system init` core files with concise SYSTEM, MISSION, and RULES role guidance while preserving existing core content on rerun
12 12 - Fix `/system init` so rerunning in an initialized project reuses the existing prefix instead of asking again
13 13 - Fix exact `/system` subcommands such as `doctor` and `book` so autocomplete does not consume Enter
14 +- Add `/system edit <path|id|slug>` to open System documents in VISUAL, EDITOR, or a platform editor
14 15 - Fix The System document prompt and governance to require plural artifact directories and block unknown `.system` paths such as `.system/spec`
15 16 - Fix `/system view` and `/system book` HTML output so rendered pages include document bodies and open in the browser
16 17 - Fix rich System doc rendering so heading anchors are document-scoped and iframe embeds use browser-loadable file URLs

extensions/the-system/README.md

Modified
8 8 - `/system init [PROJECT-PREFIX]` initializes or upgrades `.system` after confirmation.
9 9 - `/system doctor` runs read-only validation.
10 10 - `/system view <path|id|slug>` renders one document to temporary HTML.
11 +- `/system edit <path|id|slug>` opens one document in `VISUAL`, `EDITOR`, or a platform editor.
11 12 - `/system book` renders the full dossier to temporary HTML.
12 13 - `/system research|spec|spec-verify|phase|plan|issue|exec [instructions]` injects stage prompts.

extensions/the-system/__tests__/the-system.test.ts

Modified
1 1 import assert from "node:assert/strict";
2 2 import {
3 + chmodSync,
3 4 mkdirSync,
4 5 mkdtempSync,
5 6 readFileSync,
10 11 import path from "node:path";
11 12 import { afterEach, describe, it } from "vitest";
12 13 import registerTheSystem from "../index.ts";
14 +import { editorCandidates, parseEditorCommand } from "../open-editor.ts";
13 15 import { createSystemCommand } from "../system-command.ts";
15 17 const roots: string[] = [];
116 118 command.getArgumentCompletions?.("sp")?.map((item) => item.value),
117 119 ["spec", "spec-verify"],
121 + assert.deepEqual(
122 + command.getArgumentCompletions?.("ed")?.map((item) => item.value),
123 + ["edit"],
124 + );
119 125 assert.equal(command.getArgumentCompletions?.("doctor"), null);
120 126 const notices: string[] = [];
121 127 await command.handler("", {
237 243 await command.handler("view PX-SPEC-SPEC0001", ctx);
238 244 await command.handler("book", ctx);
239 245 await command.handler("view PX-SPEC-SPEC0001 extra", ctx);
246 + await command.handler("edit PX-SPEC-SPEC0001 extra", ctx);
240 247 assert.match(notices[0] ?? "", /OK/);
241 248 assert.match(notices[1] ?? "", /System view written:/);
242 249 assert.match(notices[1] ?? "", /Open: file:\/\//);
243 250 assert.match(notices[2] ?? "", /System book written:/);
244 251 assert.match(notices[3] ?? "", /Usage: \/system view/);
252 + assert.match(notices[4] ?? "", /Usage: \/system edit/);
245 253 const view = readFileSync(pathFromNotice(notices[1] ?? ""), "utf8");
246 254 const docs = readFileSync(pathFromNotice(notices[2] ?? ""), "utf8");
247 255 assert.match(view, /class="system-article"/);
306 314 assert.match(docs, /spec/);
307 315 assert.match(docs, /class="system-article"/);
318 + it("opens documents in VISUAL, EDITOR, or a platform editor", async () => {
319 + const project = temp();
320 + validSystem(project);
321 + const editor = path.join(project, "editor.cjs");
322 + const log = path.join(project, "editor.log");
323 + writeFileSync(
324 + editor,
325 + `const { writeFileSync } = require("node:fs"); writeFileSync(process.argv[2], process.argv.slice(3).join("\\n"));`,
326 + "utf8",
327 + );
328 + chmodSync(editor, 0o755);
329 + const previousVisual = process.env.VISUAL;
330 + const previousEditor = process.env.EDITOR;
331 + process.env.VISUAL = `${process.execPath} ${JSON.stringify(editor)} ${JSON.stringify(log)}`;
332 + delete process.env.EDITOR;
333 + try {
334 + const command = createSystemCommand({ sendUserMessage() {} } as never);
335 + const notices: string[] = [];
336 + await command.handler("edit contract", {
337 + cwd: project,
338 + waitForIdle: async () => {},
339 + ui: { notify: (message: string) => notices.push(message) },
340 + } as never);
341 + assert.match(notices[0] ?? "", /System document opened:/);
342 + assert.equal(
343 + readFileSync(log, "utf8"),
344 + path.join(project, ".system/specs/PX-SPEC-SPEC0001-contract/index.md"),
345 + );
346 + } finally {
347 + if (previousVisual === undefined) delete process.env.VISUAL;
348 + else process.env.VISUAL = previousVisual;
349 + if (previousEditor === undefined) delete process.env.EDITOR;
350 + else process.env.EDITOR = previousEditor;
352 + });
353 +});
355 +describe("editor opening", () => {
356 + it("parses quoted editor commands and falls back cross-platform", () => {
357 + assert.deepEqual(parseEditorCommand('code --wait "two words"'), {
358 + command: "code",
359 + args: ["--wait", "two words"],
360 + });
361 + assert.deepEqual(
362 + editorCandidates("file.md", { VISUAL: "v", EDITOR: "e" }, "linux").slice(
363 + 0,
364 + 2,
365 + ),
367 + { command: "v", args: ["file.md"], wait: true },
368 + { command: "e", args: ["file.md"], wait: true },
369 + ],
370 + );
371 + assert.deepEqual(editorCandidates("file.md", {}, "win32").at(0), {
372 + command: "notepad.exe",
373 + args: ["file.md"],
374 + wait: false,
375 + });
376 + });
311 379 function pathFromNotice(notice: string): string {

extensions/the-system/open-editor.ts

Added
new file mode 100644
1 +import { spawn } from "node:child_process";
3 +export type EditorOpenResult =
4 + | { ok: true; file: string; command: string }
5 + | { ok: false; file: string; error: string };
7 +export interface EditorCandidate {
8 + command: string;
9 + args: string[];
10 + wait: boolean;
13 +export async function openEditableFile(
14 + file: string,
15 + env: NodeJS.ProcessEnv = process.env,
16 + platform: NodeJS.Platform = process.platform,
17 +): Promise<EditorOpenResult> {
18 + for (const candidate of editorCandidates(file, env, platform)) {
19 + const ok = await trySpawn(candidate);
20 + if (ok) return { ok: true, file, command: candidate.command };
21 + }
22 + return { ok: false, file, error: "No editor opener found" };
25 +export function editorCandidates(
26 + file: string,
27 + env: NodeJS.ProcessEnv = process.env,
28 + platform: NodeJS.Platform = process.platform,
29 +): EditorCandidate[] {
30 + const configured = [env.VISUAL, env.EDITOR]
31 + .map((item) => parseEditorCommand(item ?? ""))
32 + .filter((item): item is { command: string; args: string[] } =>
33 + Boolean(item),
34 + )
35 + .map((item) => ({ ...item, args: [...item.args, file], wait: true }));
36 + return [...configured, ...platformCandidates(file, platform)];
39 +export function parseEditorCommand(
40 + input: string,
41 +): { command: string; args: string[] } | undefined {
42 + const parts = splitCommandLine(input.trim());
43 + const command = parts[0];
44 + if (!command) return undefined;
45 + return { command, args: parts.slice(1) };
48 +function platformCandidates(
49 + file: string,
50 + platform: NodeJS.Platform,
51 +): EditorCandidate[] {
52 + if (process.env.TERMUX_VERSION)
53 + return [{ command: "termux-open", args: [file], wait: false }];
54 + if (platform === "darwin")
55 + return [{ command: "open", args: ["-t", file], wait: false }];
56 + if (platform === "win32")
57 + return [{ command: "notepad.exe", args: [file], wait: false }];
58 + return [
59 + { command: "xdg-open", args: [file], wait: false },
60 + { command: "gio", args: ["open", file], wait: false },
61 + { command: "wslview", args: [file], wait: false },
62 + { command: "vi", args: [file], wait: true },
63 + ];
66 +function trySpawn(candidate: EditorCandidate): Promise<boolean> {
67 + return new Promise((resolve) => {
68 + const child = spawn(candidate.command, candidate.args, {
69 + detached: !candidate.wait,
70 + stdio: candidate.wait ? "inherit" : "ignore",
71 + windowsHide: !candidate.wait,
72 + });
73 + let settled = false;
74 + const done = (ok: boolean) => {
75 + if (settled) return;
76 + settled = true;
77 + resolve(ok);
78 + };
79 + child.once("error", () => done(false));
80 + if (candidate.wait) child.once("close", (code) => done(code === 0));
81 + else
82 + child.once("spawn", () => {
83 + child.unref();
84 + done(true);
85 + });
86 + });
89 +function splitCommandLine(input: string): string[] {
90 + const parts: string[] = [];
91 + let current = "";
92 + let quote: "'" | '"' | undefined;
93 + let escaping = false;
95 + for (const char of input) {
96 + if (escaping) {
97 + current += char;
98 + escaping = false;
99 + continue;
101 + if (char === "\\" && quote !== "'") {
102 + escaping = true;
103 + continue;
105 + if ((char === "'" || char === '"') && !quote) {
106 + quote = char;
107 + continue;
109 + if (char === quote) {
110 + quote = undefined;
111 + continue;
113 + if (/\s/.test(char) && !quote) {
114 + if (current) parts.push(current);
115 + current = "";
116 + continue;
118 + current += char;
120 + if (escaping) current += "\\";
121 + if (current) parts.push(current);
122 + return parts;

extensions/the-system/system-command.ts

Modified
1 1 import { randomBytes } from "node:crypto";
2 -import { readFileSync } from "node:fs";
2 +import { lstatSync, readFileSync } from "node:fs";
3 3 import path from "node:path";
4 4 import type {
5 5 ExtensionAPI,
19 19 } from "./documents.ts";
20 20 import { applyInitialization, inspectInitialization } from "./init.ts";
21 21 import { openHtmlFile } from "./open-browser.ts";
22 +import { openEditableFile } from "./open-editor.ts";
22 23 import { systemPromptFor } from "./system-prompts.ts";
23 24 import {
24 25 renderSystemBookSite,
34 35 "issue",
35 36 "exec",
37 -const NON_LIFECYCLE = new Set(["init", "doctor", "view", "book"]);
38 +const NON_LIFECYCLE = new Set(["init", "doctor", "view", "book", "edit"]);
38 39 const SUBCOMMANDS = [
39 40 "init",
40 41 "doctor",
41 42 "view",
42 43 "book",
44 + "edit",
43 45 "research",
44 46 "spec",
45 47 "spec-verify",
82 84 ctx.ui.notify(await openNotice("System view", output), "info");
83 85 return;
87 + if (parsed.subcommand === "edit") {
88 + const selectors = parsed.rest.trim().split(/\s+/).filter(Boolean);
89 + if (selectors.length !== 1) {
90 + ctx.ui.notify("Usage: /system edit <path|id|slug>", "error");
91 + return;
92 + }
93 + const output = await editSystemDocument(
94 + ctx.cwd,
95 + selectors[0] as string,
96 + );
97 + ctx.ui.notify(output, output.includes("opened:") ? "info" : "error");
98 + return;
99 + }
85 100 if (parsed.subcommand === "book") {
86 101 if (parsed.rest.trim()) {
87 102 ctx.ui.notify("Usage: /system book", "error");
128 143 "init [PROJECT-PREFIX]",
129 144 "doctor",
130 145 "view <path|id|slug>",
146 + "edit <path|id|slug>",
131 147 "book",
132 148 "research [instructions]",
133 149 "spec [instructions]",
231 247 return renderSystemBookSite(projectIndex(cwd)).file;
250 +async function editSystemDocument(
251 + cwd: string,
252 + selector: string,
253 +): Promise<string> {
254 + const index = projectIndex(cwd);
255 + const file = editableSystemPath(index.root, index.documents, selector);
256 + const opened = await openEditableFile(file);
257 + if (opened.ok)
258 + return `System document opened: ${file}\nEditor: ${opened.command}`;
259 + return `System document not opened: ${file}\nEditor: ${opened.error}`;
262 +function editableSystemPath(
263 + root: string,
264 + documents: ReturnType<typeof projectIndex>["documents"],
265 + selector: string,
266 +): string {
267 + const normalized = selector.split(path.sep).join("/");
268 + if (normalized.includes("/") || normalized.endsWith(".md")) {
269 + const target = path.resolve(root, selector);
270 + const relative = path.relative(root, target).split(path.sep).join("/");
271 + if (
272 + relative.startsWith("../") ||
273 + relative === ".." ||
274 + !relative.startsWith(".system/")
276 + throw new Error(`System edit path must be inside .system: ${selector}`);
277 + const stats = lstatSync(target, { throwIfNoEntry: false });
278 + if (!stats?.isFile() || stats.isSymbolicLink())
279 + throw new Error(`No editable System file: ${selector}`);
280 + return target;
282 + return path.join(root, resolveDocument(root, documents, selector).path);
234 285 function resolveDocument(
235 286 root: string,
236 287 documents: ReturnType<typeof projectIndex>["documents"],