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)
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";
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"],
122 + command.
getArgumentCompletions?.(
"ed")?.
map((item)
=> item.
value),
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");
325 + `const { writeFileSync } = require("node:fs"); writeFileSync(process.argv[2], process.argv.slice(3).join("\\n"));`,
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;
334 + const command
= createSystemCommand({
sendUserMessage() {} }
as never);
335 + const notices
: string[]
= [];
336 + await command.
handler(
"edit contract", {
338 + waitForIdle:
async ()
=> {},
339 + ui: {
notify: (message
: string)
=> notices.
push(message) },
341 + assert.
match(notices[
0]
?? "",
/System document opened:/);
343 + readFileSync(log,
"utf8"),
344 + path.
join(project,
".system/specs/PX-SPEC-SPEC0001-contract/index.md"),
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;
355 +describe(
"editor opening", ()
=> {
356 + it(
"parses quoted editor commands and falls back cross-platform", ()
=> {
357 + assert.
deepEqual(
parseEditorCommand(
'code --wait "two words"'), {
359 + args: [
"--wait",
"two words"],
362 + editorCandidates(
"file.md", { VISUAL:
"v", EDITOR:
"e" },
"linux").
slice(
367 + { command:
"v", args: [
"file.md"], wait:
true },
368 + { command:
"e", args: [
"file.md"], wait:
true },
371 + assert.
deepEqual(
editorCandidates(
"file.md", {},
"win32").
at(
0), {
372 + command:
"notepad.exe",
311 379 function pathFromNotice(notice
: string)
: string {
extensions/the-system/open-editor.ts
Addednew 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 {
13 +export async function openEditableFile(
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 };
22 + return { ok:
false, file, error:
"No editor opener found" };
25 +export function editorCandidates(
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[] }
=> 35 + .
map((item)
=> ({
...item, args: [
...item.args, file], wait:
true }));
36 + return [
...configured,
...platformCandidates(file, platform)];
39 +export function parseEditorCommand(
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(
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 }];
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 },
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,
73 + let settled
= false;
74 + const done = (ok
: boolean)
=> {
75 + if (settled)
return;
79 + child.
once(
"error", ()
=> done(
false));
80 + if (candidate.wait) child.
once(
"close", (code)
=> done(code
=== 0));
82 + child.
once(
"spawn", ()
=> {
89 +function splitCommandLine(input
: string)
: string[] {
90 + const parts
: string[]
= [];
92 + let quote
: "'" | '"' | undefined;
93 + let escaping
= false;
95 + for (
const char
of input) {
101 + if (char
=== "\\" && quote
!== "'") {
105 + if ((char
=== "'" || char
=== '"')
&& !quote) {
109 + if (char
=== quote) {
113 + if (
/\s/.
test(char)
&& !quote) {
114 + if (current) parts.
push(current);
120 + if (escaping) current
+= "\\";
121 + if (current) parts.
push(current);
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";
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";
24 25 renderSystemBookSite,
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
= [
82 84 ctx.ui.
notify(
await openNotice(
"System view", output),
"info");
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");
93 + const output
= await editSystemDocument(
95 + selectors[
0]
as string,
97 + ctx.ui.
notify(output, output.
includes(
"opened:")
? "info" : "error");
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]",
130 145 "view <path|id|slug>",
146 + "edit <path|id|slug>",
132 148 "research [instructions]",
133 149 "spec [instructions]",
231 247 return renderSystemBookSite(
projectIndex(cwd)).file;
250 +async function editSystemDocument(
253 +)
: Promise<
string> {
254 + const index
= projectIndex(cwd);
255 + const file
= editableSystemPath(index.root, index.documents, selector);
256 + const opened
= await openEditableFile(file);
258 + return `System document opened: ${file}\nEditor: ${opened.command}`;
259 + return `System document not opened: ${file}\nEditor: ${opened.error}`;
262 +function editableSystemPath(
264 + documents
: ReturnType<
typeof projectIndex>[
"documents"],
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(
"/");
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}`);
282 + return path.
join(
root,
resolveDocument(
root, documents, selector).path);
234 285 function resolveDocument(
236 287 documents
: ReturnType<
typeof projectIndex>[
"documents"],