mirror of
https://github.com/affaan-m/ECC.git
synced 2026-12-05 06:34:32 +09:00
fix(pi): match Pi placeholders and require active ECC prompt
Recognize Pi's braced positional/slice placeholders, gate restoration on pi.getCommands() provenance, and make the command body cache immutable. Extend Pi adapter tests for the new placeholder forms and pass-through cases.
This commit is contained in:
1 parent
2c12e43ea3
commit
818fc7306d
3 files changed
+229
-41
No files matched your search
+12
-6
@@ -29,7 +29,7 @@ import * as fs from "node:fs"
|
||||
import * as os from "node:os"
|
||||
import * as path from "node:path"
|
||||
import { resolveHookRuntime } from "./hook-runtime.js"
|
||||
import { handlePiInput } from "./input-args.js"
|
||||
import { createCommandBodyReader, handlePiInput } from "./input-args.js"
|
||||
|
||||
/**
|
||||
* Minimal structural types mirroring `@earendil-works/pi-coding-agent`.
|
||||
@@ -71,13 +71,14 @@ interface BeforeAgentStartResult {
|
||||
systemPrompt?: string
|
||||
}
|
||||
|
||||
interface InputEvent {
|
||||
text: string
|
||||
}
|
||||
interface PiSlashCommandInfo { name: string; source: "extension" | "prompt" | "skill"; sourceInfo: { path: string } }
|
||||
|
||||
interface InputEvent { text: string; source: "interactive" | "rpc" | "extension"; streamingBehavior?: "steer" | "followUp" }
|
||||
|
||||
type InputEventResult = { action: "continue" } | { action: "transform"; text: string }
|
||||
|
||||
interface ExtensionAPI {
|
||||
getCommands(): PiSlashCommandInfo[]
|
||||
on(
|
||||
event: "input",
|
||||
handler: (event: InputEvent, ctx: ExtensionContext) => Promise<InputEventResult> | InputEventResult
|
||||
@@ -681,15 +682,20 @@ function buildDoctorReport(ctx: ExtensionContext): string {
|
||||
return lines.join("\n")
|
||||
}
|
||||
|
||||
const commandBodyCache = new Map<string, string | null>()
|
||||
const getCommandBody = createCommandBodyReader(ECC_ROOT)
|
||||
|
||||
export default function (pi: ExtensionAPI): void {
|
||||
pi.on("input", event => {
|
||||
if (event.source === "extension" || event.streamingBehavior === "steer" || typeof pi.getCommands !== "function") {
|
||||
return { action: "continue" }
|
||||
}
|
||||
|
||||
return handlePiInput({
|
||||
text: event.text,
|
||||
eccRoot: ECC_ROOT,
|
||||
env: process.env,
|
||||
cache: commandBodyCache,
|
||||
activeCommands: pi.getCommands(),
|
||||
getBody: getCommandBody,
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
const fs = require("node:fs")
|
||||
const path = require("node:path")
|
||||
|
||||
/** Same placeholder set Pi's prompt-template substitution understands. */
|
||||
const ARG_PLACEHOLDER = /\$ARGUMENTS|\$@|\$\d|\$\{@/
|
||||
/**
|
||||
* Same placeholder set Pi's `substituteArgs` understands.
|
||||
*
|
||||
* Pi expands every form below, so a command body containing any of them must
|
||||
* be left for Pi to expand rather than treated as placeholder-less:
|
||||
* $ARGUMENTS, $@, $1, ${1:-default}, ${@:N}, ${@:N:L}
|
||||
*/
|
||||
const ARG_PLACEHOLDER = /\$\{(\d+|ARGUMENTS|@):-[^}]*\}|\$\{@:\d+(?::\d+)?\}|\$(ARGUMENTS|@|\d+)/
|
||||
|
||||
/** Values ECC treats as "off" across its existing environment switches. */
|
||||
const DISABLED_VALUES = new Set(["0", "false", "off", "none", "disabled"])
|
||||
@@ -11,6 +17,10 @@ function isDisabledByEnv(value) {
|
||||
return typeof value === "string" && DISABLED_VALUES.has(value.trim().toLowerCase())
|
||||
}
|
||||
|
||||
function stripFrontmatter(raw) {
|
||||
return raw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Body of an ECC command that has NO argument placeholder, or null.
|
||||
*
|
||||
@@ -18,22 +28,48 @@ function isDisabledByEnv(value) {
|
||||
* Pi's template expansion silently drops the arguments instead. Most ECC
|
||||
* commands rely on the Claude behaviour, so the adapter restores it.
|
||||
*/
|
||||
function loadPlaceholderlessCommand(name, eccRoot, cache) {
|
||||
if (cache.has(name)) {
|
||||
return cache.get(name) ?? null
|
||||
function loadPlaceholderlessCommand(name, eccRoot, commandPath) {
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(name)) {
|
||||
return null
|
||||
}
|
||||
let body = null
|
||||
if (/^[A-Za-z0-9._-]+$/.test(name)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(path.join(eccRoot, "commands", `${name}.md`), "utf8")
|
||||
const stripped = raw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim()
|
||||
body = ARG_PLACEHOLDER.test(stripped) ? null : stripped
|
||||
} catch {
|
||||
body = null
|
||||
}
|
||||
|
||||
const resolvedPath = commandPath || path.join(eccRoot, "commands", `${name}.md`)
|
||||
try {
|
||||
const raw = fs.readFileSync(resolvedPath, "utf8")
|
||||
const stripped = stripFrontmatter(raw)
|
||||
return ARG_PLACEHOLDER.test(stripped) ? null : stripped
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
cache.set(name, body)
|
||||
return body
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the canonical ECC command path only when Pi's active prompt for
|
||||
* `name` resolves to ECC's canonical `commands/<name>.md`.
|
||||
*
|
||||
* The input event fires before Pi expands prompt templates and does not expose
|
||||
* the selected template directly. `pi.getCommands()` does expose the active
|
||||
* prompt list (including source metadata), so this is the provenance check
|
||||
* that keeps ECC from overriding a disabled, differently resolved, or
|
||||
* extension-registered command with the same name.
|
||||
*/
|
||||
function activeEccPromptPath(name, eccRoot, activeCommands) {
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(name)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const activePrompt = (activeCommands || []).find(
|
||||
command => command && command.name === name && command.source === "prompt"
|
||||
)
|
||||
if (!activePrompt || !activePrompt.sourceInfo) {
|
||||
return null
|
||||
}
|
||||
|
||||
const expectedPath = path.resolve(path.join(eccRoot, "commands", `${name}.md`))
|
||||
if (path.resolve(activePrompt.sourceInfo.path || "") !== expectedPath) {
|
||||
return null
|
||||
}
|
||||
return expectedPath
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,25 +79,56 @@ function loadPlaceholderlessCommand(name, eccRoot, cache) {
|
||||
* and exercised by the plain Node test suite; the extension itself delegates
|
||||
* directly to this function.
|
||||
*/
|
||||
function handlePiInput({ text, eccRoot, env, cache }) {
|
||||
function handlePiInput({ text, eccRoot, env, activeCommands, getBody }) {
|
||||
if (isDisabledByEnv(env.ECC_PI_COMMAND_ARGS)) {
|
||||
return { action: "continue" }
|
||||
}
|
||||
|
||||
const match = text.match(/^\/([^\s:]+)\s+([\s\S]*\S[\s\S]*)$/)
|
||||
if (!match) {
|
||||
return { action: "continue" }
|
||||
}
|
||||
const body = loadPlaceholderlessCommand(match[1], eccRoot, cache)
|
||||
|
||||
const commandPath = activeEccPromptPath(match[1], eccRoot, activeCommands)
|
||||
if (!commandPath) {
|
||||
return { action: "continue" }
|
||||
}
|
||||
|
||||
const body = getBody
|
||||
? getBody(match[1], commandPath)
|
||||
: loadPlaceholderlessCommand(match[1], eccRoot, commandPath)
|
||||
if (!body) {
|
||||
return { action: "continue" }
|
||||
}
|
||||
|
||||
return { action: "transform", text: `${body}\n\nARGUMENTS: ${match[2].trim()}` }
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a body reader with its own cache.
|
||||
*
|
||||
* The returned function returns a fresh Map on each new lookup rather than
|
||||
* mutating the previous cache, satisfying ECC's immutability rule.
|
||||
*/
|
||||
function createCommandBodyReader(eccRoot) {
|
||||
let cache = new Map()
|
||||
return name => {
|
||||
if (cache.has(name)) {
|
||||
return cache.get(name) ?? null
|
||||
}
|
||||
const body = loadPlaceholderlessCommand(name, eccRoot)
|
||||
cache = new Map(cache).set(name, body)
|
||||
return body
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ARG_PLACEHOLDER,
|
||||
DISABLED_VALUES,
|
||||
isDisabledByEnv,
|
||||
stripFrontmatter,
|
||||
loadPlaceholderlessCommand,
|
||||
createCommandBodyReader,
|
||||
activeEccPromptPath,
|
||||
handlePiInput,
|
||||
}
|
||||
@@ -48,7 +48,12 @@ const { spawnSync, execFile } = require("child_process")
|
||||
const { resolveHookRuntime } = require(
|
||||
path.join(__dirname, "..", "..", ".pi", "extensions", "hook-runtime.js")
|
||||
)
|
||||
const { handlePiInput } = require(
|
||||
const {
|
||||
ARG_PLACEHOLDER,
|
||||
loadPlaceholderlessCommand,
|
||||
createCommandBodyReader,
|
||||
handlePiInput,
|
||||
} = require(
|
||||
path.join(__dirname, "..", "..", ".pi", "extensions", "input-args.js")
|
||||
)
|
||||
|
||||
@@ -358,6 +363,12 @@ async function main() {
|
||||
const inputArgsPath = path.join(repoRoot, ".pi", "extensions", "input-args.js")
|
||||
const inputArgsSource = fs.readFileSync(inputArgsPath, "utf8")
|
||||
|
||||
const eccPrompt = name => ({
|
||||
name,
|
||||
source: "prompt",
|
||||
sourceInfo: { path: path.join(repoRoot, "commands", `${name}.md`) },
|
||||
})
|
||||
|
||||
const tests = [
|
||||
// ---- Group 1: source contract -------------------------------------
|
||||
|
||||
@@ -1684,6 +1695,17 @@ async function main() {
|
||||
"expected .pi/extensions/index.ts to delegate the input handler to input-args.js " +
|
||||
"so tests can load and exercise the real handler rather than a copy"
|
||||
)
|
||||
assert.ok(
|
||||
extensionSource.includes('event.source === "extension"'),
|
||||
"expected the registered handler to skip extension-injected input; transforming " +
|
||||
"an extension message as if it were user input can double-expand ECC commands"
|
||||
)
|
||||
assert.ok(
|
||||
extensionSource.includes("pi.getCommands()") &&
|
||||
extensionSource.includes("activeCommands:"),
|
||||
"expected the registered handler to resolve active commands via pi.getCommands() " +
|
||||
"and pass them into the testable input-args handler for provenance checks"
|
||||
)
|
||||
assert.ok(
|
||||
inputArgsSource.includes("ECC_PI_COMMAND_ARGS"),
|
||||
"expected input-args.js to honor an ECC_PI_COMMAND_ARGS opt-out for " +
|
||||
@@ -1697,9 +1719,12 @@ async function main() {
|
||||
"(leave Pi's normal expansion untouched)"
|
||||
)
|
||||
assert.ok(
|
||||
inputArgsSource.includes("ARG_PLACEHOLDER = /\\$ARGUMENTS|\\$@|\\$\\d|\\$\\{@/"),
|
||||
"expected the placeholder test to recognize $ARGUMENTS, $@, positional $N, and ${@}; " +
|
||||
"missing any one of Pi's supported placeholders would transform commands Pi already expands"
|
||||
inputArgsSource.includes(":-[^}]*") &&
|
||||
inputArgsSource.includes("(?::\\d+)?") &&
|
||||
inputArgsSource.includes("$(ARGUMENTS|@|\\d+)"),
|
||||
"expected ARG_PLACEHOLDER to match Pi's full placeholder set, including " +
|
||||
"${1:-default}, ${@:N}, and ${@:N:L}; missing those would transform commands " +
|
||||
"Pi already expands"
|
||||
)
|
||||
assert.ok(
|
||||
inputArgsSource.includes('path.join(eccRoot, "commands"') &&
|
||||
@@ -1708,18 +1733,21 @@ async function main() {
|
||||
"reading from cwd would break global installs exactly like the original hook-root defect"
|
||||
)
|
||||
assert.ok(
|
||||
inputArgsSource.includes("cache.set(name, body)"),
|
||||
"expected the placeholder-less command lookup to cache command bodies; the input " +
|
||||
"handler runs on every prompt and should not re-read command markdown every time"
|
||||
inputArgsSource.includes("new Map(cache).set(name, body)"),
|
||||
"expected the command body cache to replace the old Map rather than mutate it; " +
|
||||
"ECC's immutability rule forbids mutating an existing cache object"
|
||||
)
|
||||
}],
|
||||
|
||||
["input handler transforms /plan args using the real command body", () => {
|
||||
const stripFrontmatter = raw => raw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim()
|
||||
["input handler transforms /plan args when Pi's active prompt resolves to ECC", () => {
|
||||
const planRaw = fs.readFileSync(path.join(repoRoot, "commands", "plan.md"), "utf8")
|
||||
const planBody = stripFrontmatter(planRaw)
|
||||
const planBody = ARG_PLACEHOLDER.test(
|
||||
planRaw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim()
|
||||
)
|
||||
? ""
|
||||
: planRaw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim()
|
||||
assert.ok(
|
||||
planBody && !/\$ARGUMENTS|\$@|\$\d|\$\{@/.test(planBody),
|
||||
planBody,
|
||||
"commands/plan.md must be placeholder-less in this repo for the test to be meaningful; " +
|
||||
"if it gains a placeholder the transformation should no longer apply"
|
||||
)
|
||||
@@ -1728,7 +1756,7 @@ async function main() {
|
||||
text: "/plan add a hello world CLI",
|
||||
eccRoot: repoRoot,
|
||||
env: {},
|
||||
cache: new Map(),
|
||||
activeCommands: [eccPrompt("plan")],
|
||||
})
|
||||
|
||||
assert.strictEqual(result.action, "transform")
|
||||
@@ -1746,7 +1774,7 @@ async function main() {
|
||||
const stripFrontmatter = raw => raw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim()
|
||||
const sessionsRaw = fs.readFileSync(path.join(repoRoot, "commands", "sessions.md"), "utf8")
|
||||
assert.ok(
|
||||
/\$ARGUMENTS|\$@|\$\d|\$\{@/.test(stripFrontmatter(sessionsRaw)),
|
||||
ARG_PLACEHOLDER.test(stripFrontmatter(sessionsRaw)),
|
||||
"commands/sessions.md must contain a placeholder in this repo for the pass-through test to be meaningful"
|
||||
)
|
||||
|
||||
@@ -1755,7 +1783,7 @@ async function main() {
|
||||
text: "/sessions recent",
|
||||
eccRoot: repoRoot,
|
||||
env: {},
|
||||
cache: new Map(),
|
||||
activeCommands: [eccPrompt("sessions")],
|
||||
}),
|
||||
{ action: "continue" }
|
||||
)
|
||||
@@ -1763,11 +1791,21 @@ async function main() {
|
||||
|
||||
["input handler passes through bare and unknown commands", () => {
|
||||
assert.deepStrictEqual(
|
||||
handlePiInput({ text: "just a normal prompt", eccRoot: repoRoot, env: {}, cache: new Map() }),
|
||||
handlePiInput({
|
||||
text: "just a normal prompt",
|
||||
eccRoot: repoRoot,
|
||||
env: {},
|
||||
activeCommands: [],
|
||||
}),
|
||||
{ action: "continue" }
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
handlePiInput({ text: "/not-a-real-ecc-command args", eccRoot: repoRoot, env: {}, cache: new Map() }),
|
||||
handlePiInput({
|
||||
text: "/not-a-real-ecc-command args",
|
||||
eccRoot: repoRoot,
|
||||
env: {},
|
||||
activeCommands: [eccPrompt("plan")],
|
||||
}),
|
||||
{ action: "continue" }
|
||||
)
|
||||
}],
|
||||
@@ -1778,11 +1816,88 @@ async function main() {
|
||||
text: "/plan add a hello world CLI",
|
||||
eccRoot: repoRoot,
|
||||
env: { ECC_PI_COMMAND_ARGS: "off" },
|
||||
cache: new Map(),
|
||||
activeCommands: [eccPrompt("plan")],
|
||||
}),
|
||||
{ action: "continue" }
|
||||
)
|
||||
}],
|
||||
|
||||
["placeholder detection recognizes Pi's braced positional and slice forms", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-pi-args-"))
|
||||
const commandsDir = path.join(root, "commands")
|
||||
fs.mkdirSync(commandsDir, { recursive: true })
|
||||
|
||||
try {
|
||||
fs.writeFileSync(
|
||||
path.join(commandsDir, "braced.md"),
|
||||
"---\ndescription: braced\n---\n${1:-default} plus ${@:2:3}\n"
|
||||
)
|
||||
assert.strictEqual(
|
||||
loadPlaceholderlessCommand("braced", root),
|
||||
null,
|
||||
"${1:-default} and ${@:2:3} are placeholders Pi expands, not placeholder-less bodies"
|
||||
)
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(commandsDir, "plain.md"),
|
||||
"---\ndescription: plain\n---\nno placeholders here\n"
|
||||
)
|
||||
assert.strictEqual(
|
||||
loadPlaceholderlessCommand("plain", root),
|
||||
"no placeholders here",
|
||||
"a body without placeholders should be returned for argument restoration"
|
||||
)
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
}],
|
||||
|
||||
["input handler leaves disabled, missing, and differently resolved prompts unchanged", () => {
|
||||
const otherRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-pi-other-"))
|
||||
const otherCommands = path.join(otherRoot, "commands")
|
||||
fs.mkdirSync(otherCommands, { recursive: true })
|
||||
const otherPlan = path.join(otherCommands, "plan.md")
|
||||
fs.writeFileSync(otherPlan, "---\ndescription: user plan\n---\nuser plan body\n")
|
||||
|
||||
try {
|
||||
assert.deepStrictEqual(
|
||||
handlePiInput({
|
||||
text: "/plan add a hello world CLI",
|
||||
eccRoot: repoRoot,
|
||||
env: {},
|
||||
activeCommands: [],
|
||||
}),
|
||||
{ action: "continue" },
|
||||
"a disabled or missing Pi prompt must not be overridden by ECC's canonical file"
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
handlePiInput({
|
||||
text: "/plan add a hello world CLI",
|
||||
eccRoot: repoRoot,
|
||||
env: {},
|
||||
activeCommands: [{ name: "plan", source: "prompt", sourceInfo: { path: otherPlan } }],
|
||||
}),
|
||||
{ action: "continue" },
|
||||
"a same-named prompt resolved from outside ECC must be left for Pi to expand"
|
||||
)
|
||||
} finally {
|
||||
fs.rmSync(otherRoot, { recursive: true, force: true })
|
||||
}
|
||||
}],
|
||||
|
||||
["command body cache replaces rather than mutates its previous Map", () => {
|
||||
const readBody = createCommandBodyReader(repoRoot)
|
||||
const first = readBody("plan")
|
||||
assert.ok(
|
||||
typeof first === "string" && first.includes("# Plan Command"),
|
||||
"the body reader should return the real canonical plan body"
|
||||
)
|
||||
assert.strictEqual(
|
||||
readBody("plan"),
|
||||
first,
|
||||
"the cache should return the same body on subsequent lookups"
|
||||
)
|
||||
}],
|
||||
]
|
||||
|
||||
for (const [name, fn] of tests) {
|
||||
|
||||
Reference in new issue
Block a user