mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Port upstream skill scripts into v2.4.1: deterministic workflow steps run as Node scripts beside each SKILL.md (specs, pathfinder, feedback payload, commit message, review scope, agent files, handoff path) with tests, the prompt limit rises to 20,000 chars, upstream review fixes are folded in (linked agent files never overwrite AGENTS.md, review stops with no base, paste-safe commit commands, Pathfinder number high-water mark and dry runs), and web console workspace folders are remembered per project and spec, with Finalize forgetting an archived spec's list
AI Assisted
This commit is contained in:
1 parent
c0ea70e838
commit
6a66440095
243 files changed
+23698
-1607
No files matched your search
@@ -22,6 +22,14 @@ Analyze this codebase and create `AGENTS.md` to guide future AI coding agents (C
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before exploring the codebase: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Every confirmation — the restructure offer, the AI-agent file-sync prompt — goes through it, and the finished AGENTS.md lands on the page as a doc marked `saved` (the file is already on disk — no download offered). Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then Content. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console.md → Finishing).
|
||||
|
||||
## Scripts
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-init/scripts/` globally). Run from the project root; each prints one JSON object, and on a non-zero exit `next` says what to do.
|
||||
|
||||
- `node "<S>/agents-md.mjs" inspect`: does AGENTS.md exist, its line count against 500, `structure` (`progressive` or `single-file`), sections, `.agents-docs/` files, broken links, orphans. Run it first.
|
||||
- `node "<S>/agents-md.mjs" filename "<Section Name>"`: a section's detail file name, its `Details:` link line and its two header lines.
|
||||
- `node "<S>/agent-files.mjs" detect` / `apply <id> ... [--dry-run]`: AI Agent File Sync (below).
|
||||
|
||||
## Content
|
||||
|
||||
1. **Commands**: Build, lint, test, run single test, and other common development tasks
|
||||
@@ -31,8 +39,8 @@ The FIRST thing you do, before anything else in this file — before exploring t
|
||||
|
||||
## Rules
|
||||
|
||||
- If `AGENTS.md` exists: suggest improvements instead of creating new
|
||||
- If only `CLAUDE.md` exists: migrate its content to the new `AGENTS.md`
|
||||
- If `AGENTS.md` exists (`inspect` → `exists`): suggest improvements instead of creating new
|
||||
- If only `CLAUDE.md` exists (`inspect` → `otherFiles`): migrate its content to the new `AGENTS.md`
|
||||
- Include relevant content from: `README.md`, `PROJECT.md`, `.cursorrules`, `.cursor/rules/`, `GEMINI.md`, `.github/copilot-instructions.md`
|
||||
- Omit: obvious instructions, generic dev practices, easily discoverable file structures, made-up sections
|
||||
- Keep under 500 lines with focused, actionable, scoped rules
|
||||
@@ -51,13 +59,8 @@ This file provides guidance to AI coding agents working with code in this reposi
|
||||
|
||||
Generate AGENTS.md as an **index file** — each section gets a 2-3 line summary with a markdown link to a detail file. Full content goes in `.agents-docs/` directory files.
|
||||
|
||||
- **Index format** — each section in AGENTS.md: heading, brief summary, then `Details: [Section Name](./.agents-docs/AGENTS-<section-name>.md)`
|
||||
- **Detail files** — named `AGENTS-<section-name>.md` using kebab-case from the section header (e.g., "Development Commands" → `AGENTS-development-commands.md`)
|
||||
- **Detail file header** — each file starts with:
|
||||
```
|
||||
# <Section Name>
|
||||
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
|
||||
```
|
||||
- **Index format** — each section in AGENTS.md: heading, brief summary, then its `Details:` link line
|
||||
- **Detail files** — `agents-md.mjs filename "<Section Name>"` gives the file (`AGENTS-<kebab-case>.md`, e.g. "Development Commands" → `.agents-docs/AGENTS-development-commands.md`), the `Details:` link and the two header lines (`# <Section Name>` plus the "Part of AGENTS.md" breadcrumb) to start it with
|
||||
|
||||
### Always Inline
|
||||
|
||||
@@ -90,9 +93,8 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
|
||||
### Directory Setup
|
||||
|
||||
- Create `.agents-docs/` directory in the project root
|
||||
- Each file: `AGENTS-<section-name>.md` where `<section-name>` is kebab-case of the section header
|
||||
- Each file starts with `# <Section Name>` followed by breadcrumb: `> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.`
|
||||
- Create `.agents-docs/` directory in the project root, one file per split section, named and headed as `filename` prints
|
||||
- After writing, rerun `inspect`: `problems` must be empty (no broken link, no orphan, no missing breadcrumb, nothing always-inline split out)
|
||||
|
||||
### Grouping Heuristics
|
||||
|
||||
@@ -102,24 +104,13 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
|
||||
### Existing AGENTS.md Without `.agents-docs/`
|
||||
|
||||
If AGENTS.md exists but `.agents-docs/` does not, offer to restructure: "Your AGENTS.md uses a single-file format. Want to restructure it for progressive discovery? This splits detailed sections into `.agents-docs/` files and converts AGENTS.md to a lightweight index." Only restructure if the user confirms — never auto-restructure.
|
||||
If `inspect` reports `structure: "single-file"`, offer to restructure: "Your AGENTS.md uses a single-file format. Want to restructure it for progressive discovery? This splits detailed sections into `.agents-docs/` files and converts AGENTS.md to a lightweight index." Only restructure if the user confirms — never auto-restructure.
|
||||
|
||||
---
|
||||
|
||||
## AI Agent File Sync
|
||||
|
||||
After creating `AGENTS.md`, check for these files and offer to replace with references:
|
||||
|
||||
| File | Title | Path |
|
||||
|------|-------|------|
|
||||
| `CLAUDE.md` | CLAUDE.md | `./AGENTS.md` |
|
||||
| `GEMINI.md` | GEMINI.md | `./AGENTS.md` |
|
||||
| `.cursorrules` | .cursorrules | `./AGENTS.md` |
|
||||
| `.github/copilot-instructions.md` | Copilot Instructions | `../AGENTS.md` |
|
||||
| `.cursor/rules/*.md` | Project Rules | `../../AGENTS.md` |
|
||||
| `.windsurf/rules/*.md` | Project Rules | `../../AGENTS.md` |
|
||||
|
||||
For `.cursor/rules/` and `.windsurf/rules/`: delete existing `.md` files, create single `reference.md`.
|
||||
After creating `AGENTS.md`, run `agent-files.mjs detect`. It finds `CLAUDE.md`, `GEMINI.md`, `.cursorrules`, `.github/copilot-instructions.md`, and the `.cursor/rules/` and `.windsurf/rules/` folders, with each one's line count and `custom` (more than 10 lines). Leave out entries with `alreadyPointer: true` (already the AGENTS.md pointer) and `linkedToAgents: true` (a symlink or hard link: they are AGENTS.md); nothing left: skip this step silently.
|
||||
|
||||
### Confirmation Prompt
|
||||
|
||||
@@ -133,45 +124,11 @@ If files found, show:
|
||||
╰┬─┬╯
|
||||
|
||||
I found these AI agent configuration files:
|
||||
- [list files found]
|
||||
- [each `found` id, with its line count]
|
||||
|
||||
Update them to reference AGENTS.md? (Yes / Select / No)
|
||||
```
|
||||
|
||||
Only modify confirmed files.
|
||||
Relay every `warnings` line (custom content that would be replaced). A rules folder is one entry: replacing it deletes its `.md` files (and `.mdc` for Cursor) and leaves one `reference.md`.
|
||||
|
||||
### CLAUDE.md Template
|
||||
|
||||
CLAUDE.md gets a special template because Claude Code auto-loads it — the `CRITICAL — MANDATORY FIRST STEP` directive ensures AGENTS.md is always read:
|
||||
|
||||
```markdown
|
||||
# CLAUDE.md
|
||||
|
||||
**CRITICAL — MANDATORY FIRST STEP: You MUST read [AGENTS.md](./AGENTS.md) before responding to ANY user message, including simple questions. Do NOT skip this step regardless of how trivial the request appears. No exceptions.**
|
||||
|
||||
See AGENTS.md for complete project documentation including:
|
||||
- Development commands and setup
|
||||
- Architecture overview
|
||||
- Environment variables
|
||||
- Testing patterns
|
||||
- Deployment guides
|
||||
- Keeping this file current / Failure log
|
||||
- Section details in .agents-docs/
|
||||
|
||||
This file exists for Claude Code auto-loading. All AI coding agents should reference AGENTS.md.
|
||||
```
|
||||
|
||||
### Reference Template (all other files)
|
||||
|
||||
```markdown
|
||||
# [Title]
|
||||
|
||||
See [AGENTS.md]([Path]) for complete project documentation including:
|
||||
- Development commands and setup
|
||||
- Architecture overview
|
||||
- Environment variables
|
||||
- Testing patterns
|
||||
- Deployment guides
|
||||
- Keeping this file current / Failure log
|
||||
- Section details in .agents-docs/
|
||||
```
|
||||
Only modify confirmed files: `agent-files.mjs apply <id> ...` with the ids the user confirmed (`--all` for Yes). It writes the pointer templates itself: `CLAUDE.md` gets the `CRITICAL — MANDATORY FIRST STEP` directive that makes Claude Code read AGENTS.md first (it auto-loads CLAUDE.md); every other file gets the "See AGENTS.md for complete project documentation including:" pointer with the same bullet list and the right relative path. Rerunning is harmless (`unchanged`).
|
||||
@@ -556,8 +556,15 @@ enforces it, so never tell someone to keep asking past it.
|
||||
The person can add folders beside the one the session started in (a shared
|
||||
library, a design folder), from the footer's folder label. Together they are
|
||||
the session's **workspace**: context for every skill run in this console
|
||||
session, each folder addressed by a short `@name`. It outlives dashboard hops;
|
||||
a new console session starts with the original folder alone.
|
||||
session, each folder addressed by a short `@name`. It outlives dashboard hops,
|
||||
and it is remembered: every change is saved to `workspaces.json` beside
|
||||
`looks.json` (never into the project), keyed by the folder the session runs
|
||||
in and then by spec. A session with a spec opens on that spec's list, one with
|
||||
none on the project's; a spec with nothing saved starts as a copy of the
|
||||
project's list. The dashboard's picker swaps the list as the selection moves,
|
||||
and a `specDir` you post mid-run takes the current list with it. There is
|
||||
nothing for you to load: `open` prints the list, and a switch of spec on a
|
||||
resume reaches you as ordinary workspace changes on your next `wait`.
|
||||
|
||||
### What you are told
|
||||
|
||||
@@ -767,7 +774,7 @@ that is what the person is there to download. The finish carries no
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
that is never coming.
|
||||
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
||||
and `pathfinder-research` (id = the question's file slug) as each research
|
||||
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
|
||||
subagent reports back, or when you resolve a `research` question yourself
|
||||
(Posting an update → Session meter). Other questions score through their
|
||||
answers, so there is nothing to post for them.
|
||||
@@ -820,7 +827,7 @@ know:
|
||||
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
||||
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
die,
|
||||
ensureDir,
|
||||
fileStamp,
|
||||
forgetWorkspace,
|
||||
handOff,
|
||||
handleFile,
|
||||
healthOk,
|
||||
@@ -65,6 +66,7 @@ import {
|
||||
readLedger,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
remoteWarning,
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
@@ -73,6 +75,7 @@ import {
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
sleepSync,
|
||||
specKey,
|
||||
staleScratch,
|
||||
staleSessions,
|
||||
sweepUploads,
|
||||
@@ -317,7 +320,7 @@ async function cmdOpen() {
|
||||
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
||||
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
||||
} catch {}
|
||||
const workspace = workspaceOnOpen(dir, worktree);
|
||||
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
|
||||
|
||||
// Month-old sessions and scratch files: listed before the print so the
|
||||
// agent can see what went, removed after it so the page waits for nothing.
|
||||
@@ -403,10 +406,11 @@ async function cmdOpen() {
|
||||
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
||||
* match: the agent now has the whole list, so no change up to here is owed.
|
||||
* Read-only on workspace.json, which only the server writes; on a fresh
|
||||
* session the server has not made it yet, so the original folder stands in.
|
||||
* session the server has not made it yet, so what was remembered for this
|
||||
* folder and spec stands in, the same list the server is about to make.
|
||||
*/
|
||||
function workspaceOnOpen(dir, worktree) {
|
||||
const ws = readWorkspace(dir) || initialWorkspace(worktree);
|
||||
function workspaceOnOpen(dir, worktree, specDir) {
|
||||
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
|
||||
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
||||
try {
|
||||
writeWorkspaceCursor(dir, ws.version || 0);
|
||||
@@ -946,6 +950,18 @@ function realNearest(p) {
|
||||
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- forget */
|
||||
|
||||
// Drop the folder list remembered for one spec (Finalize, once the spec is
|
||||
// archived). The project's own list and every other spec's are untouched.
|
||||
function cmdForget() {
|
||||
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
|
||||
let spec = specKey(args.spec);
|
||||
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
|
||||
const worktree = repoRoots().worktree;
|
||||
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- help */
|
||||
|
||||
function cmdHelp() {
|
||||
@@ -961,7 +977,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
first post. --file is optional, and --title defaults to the
|
||||
project's folder name. Also prints workspace: { folders: [{ name,
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name.
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
@@ -988,6 +1005,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
||||
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
||||
missing. Paste link as it is.
|
||||
forget --spec specs/<idea>
|
||||
Drop the workspace folders remembered for that spec, in this
|
||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
||||
status [--session <sid>] [--all]
|
||||
One session, or every session belonging to this project.
|
||||
stop --session <sid> | --all
|
||||
@@ -1206,6 +1227,7 @@ const COMMANDS = {
|
||||
wait: cmdWait,
|
||||
chat: cmdChat,
|
||||
keep: cmdKeep,
|
||||
forget: cmdForget,
|
||||
status: cmdStatus,
|
||||
stop: cmdStop,
|
||||
help: cmdHelp,
|
||||
|
||||
@@ -178,8 +178,8 @@ function lockStale(lock) {
|
||||
// Run fn while holding the session's state lock, and release it however fn
|
||||
// ends. fn must not call process.exit(): the release would never run, and the
|
||||
// next writer would wait out the stale age.
|
||||
export function withStateLock(dir, fn) {
|
||||
const lock = path.join(dir, STATE_LOCK_FILE);
|
||||
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
||||
const lock = path.join(dir, lockName);
|
||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||
let fd = null;
|
||||
for (let attempt = 0; fd === null; attempt++) {
|
||||
@@ -188,7 +188,7 @@ export function withStateLock(dir, fn) {
|
||||
} catch (err) {
|
||||
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
||||
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
||||
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
|
||||
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
|
||||
if (err.code === "EEXIST" && lockStale(lock)) {
|
||||
try {
|
||||
fs.rmSync(lock, { force: true });
|
||||
@@ -487,8 +487,9 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks and the pointer to this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
|
||||
// looks, the folders remembered per project and spec, and the pointer to
|
||||
// this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -1619,17 +1620,125 @@ export function readWorkspace(dir) {
|
||||
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
||||
}
|
||||
|
||||
// A fresh workspace: just the original folder, named after itself.
|
||||
export function initialWorkspace(worktree) {
|
||||
// A fresh workspace: the original folder, named after itself, plus whatever
|
||||
// was remembered for this folder and spec (rememberedWorkspace() below).
|
||||
export function initialWorkspace(worktree, remembered = null) {
|
||||
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
|
||||
if (remembered && remembered.original) {
|
||||
if (remembered.original.name) original.name = remembered.original.name;
|
||||
if (remembered.original.description) original.description = remembered.original.description;
|
||||
}
|
||||
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
|
||||
id: "f" + (i + 1),
|
||||
path: f.path,
|
||||
name: f.name,
|
||||
description: f.description || "",
|
||||
...(f.nested ? { nested: true } : {}),
|
||||
}));
|
||||
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ remembered workspaces */
|
||||
|
||||
// The folder list outlives the console session: one file for the person,
|
||||
// beside looks.json, keyed by the folder a session runs in and then by spec.
|
||||
// Never under specs/: the paths are this machine's, and the server never
|
||||
// writes into a project.
|
||||
//
|
||||
// { "projects": { "<folded worktree>": {
|
||||
// "path": "<worktree>",
|
||||
// "project": { original, folders, at }, // no spec picked
|
||||
// "specs": { "specs/<name>": { original, folders, at } } } } }
|
||||
//
|
||||
// `original` holds the first folder's name and description only (its path is
|
||||
// always the session's own); `folders` the added ones as { path, name,
|
||||
// description, nested? }. Two writers, the server on every change and
|
||||
// `console.mjs forget`, each a read-modify-write of one key.
|
||||
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
|
||||
|
||||
const foldKey = (p) => {
|
||||
const resolved = path.resolve(String(p || ""));
|
||||
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
|
||||
};
|
||||
|
||||
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
|
||||
export function specKey(specDir) {
|
||||
return String(specDir || "")
|
||||
.trim()
|
||||
.replace(/\\/g, "/")
|
||||
.replace(/^\.\//, "")
|
||||
.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function readStore() {
|
||||
const saved = readJson(WORKSPACES_FILE, null);
|
||||
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* What was remembered for this folder and spec: `{ entry, from }`, where
|
||||
* `from` is "spec" when the spec has its own list, "project" when it falls
|
||||
* back to the project's (a spec's list starts as a copy of it), and null
|
||||
* when nothing was ever saved.
|
||||
*/
|
||||
export function rememberedWorkspace(worktree, specDir) {
|
||||
const project = readStore().projects[foldKey(worktree)];
|
||||
if (!project) return { entry: null, from: null };
|
||||
const spec = specKey(specDir);
|
||||
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
|
||||
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
|
||||
}
|
||||
|
||||
// The workspace's folders as the store keeps them.
|
||||
export function rememberable(ws) {
|
||||
const folders = (ws && ws.folders) || [];
|
||||
const first = folders.find((f) => f.original) || {};
|
||||
return {
|
||||
version: 0,
|
||||
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
|
||||
missing: [],
|
||||
changes: [],
|
||||
remote: "",
|
||||
original: { name: first.name || "", description: first.description || "" },
|
||||
folders: folders
|
||||
.filter((f) => !f.original)
|
||||
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
|
||||
at: nowIso(),
|
||||
};
|
||||
}
|
||||
|
||||
// Every server and `console.mjs forget` writes the one file, so each
|
||||
// read-modify-write holds this lock beside it.
|
||||
const WORKSPACES_LOCK = "workspaces.json.lock";
|
||||
|
||||
// Save the list for this folder and spec ("" for the project's own).
|
||||
export function rememberWorkspace(worktree, specDir, ws) {
|
||||
ensureDir(path.dirname(WORKSPACES_FILE));
|
||||
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
|
||||
}
|
||||
|
||||
function saveRemembered(worktree, specDir, ws) {
|
||||
const store = readStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store.projects[key] || { path: path.resolve(worktree) };
|
||||
const spec = specKey(specDir);
|
||||
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
|
||||
else project.project = rememberable(ws);
|
||||
store.projects[key] = project;
|
||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
||||
}
|
||||
|
||||
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
|
||||
export function forgetWorkspace(worktree, specDir) {
|
||||
const spec = specKey(specDir);
|
||||
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
|
||||
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
|
||||
}
|
||||
|
||||
function dropRemembered(worktree, spec) {
|
||||
const store = readStore();
|
||||
const project = store.projects[foldKey(worktree)];
|
||||
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
|
||||
delete project.specs[spec];
|
||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function writeWorkspace(dir, ws) {
|
||||
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
||||
|
||||
@@ -2505,6 +2505,9 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
actions stay put. */
|
||||
.modal.workspace { max-width: 680px; }
|
||||
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||
.workspace .modal-blurb { margin-bottom: 6px; }
|
||||
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
|
||||
|
||||
.workspace-list {
|
||||
list-style: none; margin: 0; padding: 0;
|
||||
display: grid; gap: 12px;
|
||||
|
||||
@@ -2542,6 +2542,7 @@ function renderDashboard(main) {
|
||||
const specs = specList();
|
||||
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
||||
wrap.appendChild(hideUnavailableToggle());
|
||||
if (!local.launching && !launchScoping) syncWorkspaceScope();
|
||||
|
||||
// "Unavailable" is the scan's verdict for the selected spec, not the
|
||||
// momentary greying while a launch is in flight or the server is away, so
|
||||
@@ -2963,6 +2964,11 @@ async function launchSkill(entry) {
|
||||
// cards that take no spec (utilities, setup) launch untargeted even while
|
||||
// a spec is selected.
|
||||
if (target) action.spec = target.dir;
|
||||
// The skill opens on the folders remembered for what it was launched for.
|
||||
// Held until the launch is in flight: the swap's own frame re-renders the
|
||||
// dashboard, which would otherwise sync back to the picker's spec.
|
||||
launchScoping = true;
|
||||
await syncWorkspaceScope(target ? target.dir : "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
@@ -2973,6 +2979,7 @@ async function launchSkill(entry) {
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
launchScoping = false;
|
||||
pendingResult = true;
|
||||
banner("Your last pick is still being picked up. One moment.", "info");
|
||||
return;
|
||||
@@ -2980,10 +2987,12 @@ async function launchSkill(entry) {
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
sound("startSkill");
|
||||
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
||||
launchScoping = false;
|
||||
pendingResult = true;
|
||||
save();
|
||||
render();
|
||||
} catch {
|
||||
launchScoping = false;
|
||||
banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
@@ -5854,6 +5863,32 @@ async function postJson(url, body) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The workspace follows the dashboard's picker: the folders remembered for
|
||||
the selected spec, or the project's own under "Start from scratch". The
|
||||
server swaps the list and remembers every change after it. */
|
||||
let scopeAsked = null;
|
||||
// True from a launch's scope sync until its send has gone (or failed).
|
||||
let launchScoping = false;
|
||||
async function syncWorkspaceScope(spec) {
|
||||
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
|
||||
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
|
||||
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
|
||||
scopeAsked = want;
|
||||
const { status, body } = await postJson("/workspace/scope", { spec: want });
|
||||
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
|
||||
scopeAsked = null;
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
}
|
||||
|
||||
// The dialog's "Remembered for" line: whose list this is.
|
||||
function workspaceScopeText() {
|
||||
const scope = (wsFrame && wsFrame.scope) || "";
|
||||
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
|
||||
const spec = specList().find((s) => s.dir === scope);
|
||||
const name = spec ? spec.name : scope.split("/").pop();
|
||||
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
|
||||
}
|
||||
|
||||
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
||||
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
||||
// The folder whose Remove is waiting on its inline confirm, by id.
|
||||
@@ -5893,6 +5928,7 @@ function renderWorkspace() {
|
||||
}
|
||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
|
||||
$("workspace-scope").textContent = workspaceScopeText();
|
||||
}
|
||||
|
||||
function workspaceRow(f) {
|
||||
|
||||
@@ -833,10 +833,28 @@
|
||||
Click the folder name in the middle of the bottom bar. It shows your
|
||||
folder's name and branch, such as <strong>shop · main</strong>, and
|
||||
<strong>shop + 2 folders · main</strong> once you have added some.
|
||||
The workspace lasts for this console session only: it carries across
|
||||
steps you start from the dashboard, and a new console session starts
|
||||
with just the folder you started in.
|
||||
It carries across steps you start from the dashboard.
|
||||
</p>
|
||||
<h4>Remembered for next time</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Every change is saved as you make it, so the next console session in
|
||||
this folder starts with the same folders.
|
||||
</li>
|
||||
<li>
|
||||
Each spec keeps its own list. The first time you pick a spec on the
|
||||
dashboard it starts as a copy of the project's list (the one shown
|
||||
under <strong>Start from scratch</strong>), and after that the two
|
||||
are separate. Picking a spec loads its list; the line under the
|
||||
dialog's title says whose list you are looking at.
|
||||
</li>
|
||||
<li>
|
||||
The lists live in <code>workspaces.json</code> in your own
|
||||
Plan2Code settings folder, beside your look and feel, never in the
|
||||
project. Finalize offers to forget a spec's list when it archives the
|
||||
spec.
|
||||
</li>
|
||||
</ul>
|
||||
<h4>Adding a folder</h4>
|
||||
<ul>
|
||||
<li>
|
||||
@@ -1363,9 +1381,10 @@
|
||||
<h4>What it counts</h4>
|
||||
<p>
|
||||
Each step you run here adds points: a plan or a set of documents
|
||||
weighs more than a single answered question, and a built phase more
|
||||
still, by how many tasks it completed: a big phase adds more than a
|
||||
small one. Every two questions you answer add a point too, so a long
|
||||
weighs more than a quick task, and a built phase more still, by how
|
||||
many tasks it completed: a big phase adds more than a small one.
|
||||
Every two questions you answer within one step add a point too
|
||||
(rounded down, so a single answer adds nothing), so a long
|
||||
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
|
||||
points, with what it added. It is a rule of thumb, not a
|
||||
reading of Plan2Code's real memory: long sessions tend to make it
|
||||
@@ -2003,6 +2022,7 @@
|
||||
The folders the agent uses as context this session. It reads the extra ones for
|
||||
reference and only changes them if you ask.
|
||||
</p>
|
||||
<p class="workspace-scope" id="workspace-scope"></p>
|
||||
<ul class="workspace-list" id="workspace-list"></ul>
|
||||
<div class="workspace-add">
|
||||
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
|
||||
|
||||
@@ -45,7 +45,10 @@ import {
|
||||
readLedger,
|
||||
readOverview,
|
||||
readWorkspace,
|
||||
rememberWorkspace,
|
||||
rememberedWorkspace,
|
||||
remoteWarning,
|
||||
specKey,
|
||||
typedCount,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
@@ -326,7 +329,9 @@ function workspaceNow() {
|
||||
return ws;
|
||||
}
|
||||
const root = sessionWorktree();
|
||||
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
|
||||
const scope = specKey(stateNow?.specDir);
|
||||
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
|
||||
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
|
||||
// There but unreadable for now (a scanner's lock): never written over, and
|
||||
// never cached, so the next call reads it again.
|
||||
if (stamp) return workspaceSeen.ws || fresh;
|
||||
@@ -347,13 +352,87 @@ function saveWorkspace(ws) {
|
||||
|
||||
// One change: a new version, an entry in the change log the agent is handed,
|
||||
// the file, and every open page.
|
||||
function bumpWorkspace(ws, change) {
|
||||
function bumpWorkspace(ws, change, { remember = true } = {}) {
|
||||
ws.version = (ws.version || 0) + 1;
|
||||
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
|
||||
saveWorkspace(ws);
|
||||
// Remembered for the next console session too. A folder gone missing or
|
||||
// found again is not a change of mind, so it is not saved.
|
||||
if (remember) rememberNow(ws);
|
||||
pushState();
|
||||
}
|
||||
|
||||
function rememberNow(ws) {
|
||||
const root = sessionWorktree();
|
||||
if (!root) return;
|
||||
try {
|
||||
rememberWorkspace(root, ws.scope || "", ws);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Point the workspace at another spec ("" for the project's own list) and
|
||||
* swap in what was remembered there, logging each difference as a change so
|
||||
* the agent's cursor stays truthful. A spec with nothing saved starts from
|
||||
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
|
||||
* list it has and saves it as the spec's (`seed: "current"`, a spec created
|
||||
* mid-run). Folders keep their ids when their path stays.
|
||||
*/
|
||||
function setScope(ws, spec, seed = "project") {
|
||||
const root = sessionWorktree();
|
||||
const next = specKey(spec);
|
||||
if (!root || (ws.scope || "") === next) return false;
|
||||
const found = rememberedWorkspace(root, next);
|
||||
ws.scope = next;
|
||||
if (next && found.from !== "spec" && seed === "current") {
|
||||
saveWorkspace(ws);
|
||||
rememberNow(ws);
|
||||
pushState();
|
||||
return true;
|
||||
}
|
||||
const want = initialWorkspace(root, found.entry).folders;
|
||||
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
|
||||
const kept = new Set();
|
||||
const folders = [];
|
||||
const changes = [];
|
||||
for (const w of want) {
|
||||
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
|
||||
if (!have) {
|
||||
folders.push({ ...w, id: "pending" });
|
||||
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
|
||||
continue;
|
||||
}
|
||||
kept.add(have);
|
||||
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
|
||||
if ((have.description || "") !== (w.description || "")) {
|
||||
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
|
||||
}
|
||||
folders.push({ ...have, name: w.name, description: w.description || "" });
|
||||
}
|
||||
for (const f of ws.folders) {
|
||||
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
|
||||
}
|
||||
ws.folders = folders.filter((f) => f.id !== "pending");
|
||||
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
|
||||
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
|
||||
if (!changes.length) {
|
||||
saveWorkspace(ws);
|
||||
pushState();
|
||||
}
|
||||
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
|
||||
checkFolders(ws);
|
||||
return true;
|
||||
}
|
||||
|
||||
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
|
||||
// learns its spec late) takes the workspace with it.
|
||||
function followSpecDir(state) {
|
||||
const spec = specKey(state && state.specDir);
|
||||
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
|
||||
const ws = workspaceNow();
|
||||
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
|
||||
}
|
||||
|
||||
function isFolder(p) {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory();
|
||||
@@ -370,10 +449,10 @@ function checkFolders(ws) {
|
||||
const marked = ws.missing.includes(f.id);
|
||||
if (!there && !marked) {
|
||||
ws.missing = [...ws.missing, f.id];
|
||||
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
|
||||
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
|
||||
} else if (there && marked) {
|
||||
ws.missing = ws.missing.filter((id) => id !== f.id);
|
||||
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
|
||||
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -402,8 +481,8 @@ function folderIssues(entries) {
|
||||
}
|
||||
|
||||
function workspaceView() {
|
||||
const { folders, missing, remote } = workspaceNow();
|
||||
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
|
||||
const { folders, missing, remote, scope } = workspaceNow();
|
||||
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
|
||||
}
|
||||
|
||||
// Whether child sits strictly under parent.
|
||||
@@ -492,6 +571,7 @@ function bootWorkspace() {
|
||||
saveWorkspace(ws);
|
||||
}
|
||||
checkFolders(ws);
|
||||
followSpecDir(stateNow);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1403,6 +1483,24 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// Which list the workspace is: a spec's, or the project's (`spec` empty).
|
||||
// The dashboard's picker sends it as the selection moves and before a
|
||||
// launch, so a skill opens on the list of the spec it was launched for.
|
||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const spec = typeof body.spec === "string" ? body.spec : "";
|
||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
||||
try {
|
||||
setScope(workspaceNow(), spec, "project");
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
return json(res, 200, workspaceView());
|
||||
});
|
||||
}
|
||||
|
||||
// Only ever returns a path: the page then adds it through /workspace/add.
|
||||
if (pathname === "/workspace/browse" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
@@ -1561,6 +1659,9 @@ function checkState() {
|
||||
try {
|
||||
ensureConversation(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
followSpecDir(parsed);
|
||||
} catch {}
|
||||
pushState();
|
||||
}
|
||||
lastStateStamp = stamp;
|
||||
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-02",
|
||||
"releaseDate": "2026-10-04",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env node
|
||||
// agent-files.mjs: find other AI agents' config files and point them at AGENTS.md.
|
||||
//
|
||||
// Init and Init Update both end with the same step: detect CLAUDE.md, GEMINI.md,
|
||||
// .cursorrules, the Copilot instructions and the Cursor / Windsurf rule folders,
|
||||
// and (only for the ones the user confirms) replace each with a short pointer
|
||||
// to AGENTS.md. Which files exist, how long they are, the relative path back to
|
||||
// AGENTS.md and the replacement text are all fixed, so they live here.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
agent-files.mjs: detect AI agent config files and replace them with AGENTS.md pointers. JSON on stdout.
|
||||
|
||||
node agent-files.mjs detect [--root <dir>]
|
||||
Every config file present, with its line count, whether it has custom
|
||||
content (more than 10 lines) and the pointer it would get.
|
||||
|
||||
node agent-files.mjs apply <id> [<id> ...] [--root <dir>] [--dry-run]
|
||||
node agent-files.mjs apply --all [--root <dir>] [--dry-run]
|
||||
Replace the confirmed entries (ids from detect: CLAUDE.md, GEMINI.md,
|
||||
.cursorrules, .github/copilot-instructions.md, .cursor/rules,
|
||||
.windsurf/rules). A rules folder loses its .md files (and .mdc, for Cursor) and gets one
|
||||
reference.md. Only run this for entries the user confirmed.
|
||||
An entry that is AGENTS.md itself through a symlink or hard link
|
||||
(detect: linkedToAgents) is refused by id and skipped by --all
|
||||
("skipped-linked"). A symlink to any other file is removed and replaced,
|
||||
never written through.
|
||||
|
||||
Exit: 0 ok · 2 bad arguments · 3 AGENTS.md missing or an id not present ·
|
||||
5 refused (an entry linked to AGENTS.md).
|
||||
`;
|
||||
|
||||
// id, title, where the pointer goes, and the relative path back to AGENTS.md.
|
||||
const TARGETS = [
|
||||
{ id: "CLAUDE.md", title: "CLAUDE.md", file: "CLAUDE.md", ref: "./AGENTS.md" },
|
||||
{ id: "GEMINI.md", title: "GEMINI.md", file: "GEMINI.md", ref: "./AGENTS.md" },
|
||||
{ id: ".cursorrules", title: ".cursorrules", file: ".cursorrules", ref: "./AGENTS.md" },
|
||||
{ id: ".github/copilot-instructions.md", title: "Copilot Instructions", file: ".github/copilot-instructions.md", ref: "../AGENTS.md" },
|
||||
{ id: ".cursor/rules", title: "Project Rules", dir: ".cursor/rules", ref: "../../AGENTS.md" },
|
||||
{ id: ".windsurf/rules", title: "Project Rules", dir: ".windsurf/rules", ref: "../../AGENTS.md" },
|
||||
];
|
||||
|
||||
const CUSTOM_LINES = 10;
|
||||
|
||||
// CLAUDE.md gets its own template: Claude Code auto-loads it, so it carries the
|
||||
// directive that makes AGENTS.md the mandatory first read.
|
||||
function claudeTemplate() {
|
||||
return [
|
||||
"# CLAUDE.md",
|
||||
"",
|
||||
"**CRITICAL — MANDATORY FIRST STEP: You MUST read [AGENTS.md](./AGENTS.md) before responding to ANY user message, including simple questions. Do NOT skip this step regardless of how trivial the request appears. No exceptions.**",
|
||||
"",
|
||||
"See AGENTS.md for complete project documentation including:",
|
||||
"- Development commands and setup",
|
||||
"- Architecture overview",
|
||||
"- Environment variables",
|
||||
"- Testing patterns",
|
||||
"- Deployment guides",
|
||||
"- Keeping this file current / Failure log",
|
||||
"- Section details in .agents-docs/",
|
||||
"",
|
||||
"This file exists for Claude Code auto-loading. All AI coding agents should reference AGENTS.md.",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function referenceTemplate(title, ref) {
|
||||
return [
|
||||
`# ${title}`,
|
||||
"",
|
||||
`See [AGENTS.md](${ref}) for complete project documentation including:`,
|
||||
"- Development commands and setup",
|
||||
"- Architecture overview",
|
||||
"- Environment variables",
|
||||
"- Testing patterns",
|
||||
"- Deployment guides",
|
||||
"- Keeping this file current / Failure log",
|
||||
"- Section details in .agents-docs/",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function templateFor(t) {
|
||||
return t.id === "CLAUDE.md" ? claudeTemplate() : referenceTemplate(t.title, t.ref);
|
||||
}
|
||||
|
||||
// A CRLF checkout of a pointer file is still the pointer.
|
||||
function lf(text) {
|
||||
return text === null ? null : text.replace(/\r\n/g, "\n");
|
||||
}
|
||||
|
||||
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
||||
|
||||
// True when p is AGENTS.md itself: a symlink resolving to it, or a hard link to
|
||||
// the same inode. Writing a pointer through either would replace AGENTS.md.
|
||||
// Some platforms report ino 0 for every file, so 0 never counts as a match.
|
||||
function isAgentsFile(p, agents) {
|
||||
try {
|
||||
if (samePath(fs.realpathSync.native(p), fs.realpathSync.native(agents))) return true;
|
||||
const a = fs.statSync(p, { bigint: true });
|
||||
const b = fs.statSync(agents, { bigint: true });
|
||||
return a.ino !== 0n && a.ino === b.ino && a.dev === b.dev;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function lineCount(text) {
|
||||
if (!text) return 0;
|
||||
return text.replace(/\r?\n$/, "").split(/\r?\n/).length;
|
||||
}
|
||||
|
||||
function detect(root) {
|
||||
const agents = path.join(root, "AGENTS.md");
|
||||
const found = [];
|
||||
for (const t of TARGETS) {
|
||||
if (t.file) {
|
||||
const text = readText(path.join(root, t.file));
|
||||
if (text === null) continue;
|
||||
const lines = lineCount(text);
|
||||
found.push({
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
files: [{ path: t.file, lines }],
|
||||
lines,
|
||||
custom: lines > CUSTOM_LINES,
|
||||
alreadyPointer: lf(text) === templateFor(t),
|
||||
linkedToAgents: isAgentsFile(path.join(root, t.file), agents),
|
||||
writes: t.file,
|
||||
pointsTo: t.ref,
|
||||
});
|
||||
} else {
|
||||
const dir = path.join(root, t.dir);
|
||||
if (!isDir(dir)) continue;
|
||||
// Cursor's own rule files are .mdc; leaving them would keep a second source of rules.
|
||||
const exts = t.id === ".cursor/rules" ? [".md", ".mdc"] : [".md"];
|
||||
const mds = fs.readdirSync(dir).filter((n) => exts.some((e) => n.toLowerCase().endsWith(e)) && !isDir(path.join(dir, n))).sort();
|
||||
if (!mds.length) continue;
|
||||
const files = mds.map((n) => ({ path: `${t.dir}/${n}`, lines: lineCount(readText(path.join(dir, n))) }));
|
||||
const lines = files.reduce((n, f) => n + f.lines, 0);
|
||||
found.push({
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
files,
|
||||
lines,
|
||||
custom: files.some((f) => f.lines > CUSTOM_LINES),
|
||||
alreadyPointer: mds.length === 1 && mds[0] === "reference.md" && lf(readText(path.join(dir, "reference.md"))) === templateFor(t),
|
||||
linkedToAgents: mds.some((n) => isAgentsFile(path.join(dir, n), agents)),
|
||||
writes: `${t.dir}/reference.md`,
|
||||
deletes: files.map((f) => f.path).filter((p) => !p.endsWith("/reference.md")),
|
||||
pointsTo: t.ref,
|
||||
});
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { booleans: ["dry-run", "all"], values: ["root"] });
|
||||
const cmd = args._[0];
|
||||
const root = path.resolve(args.root || ".");
|
||||
const hasAgents = fs.existsSync(path.join(root, "AGENTS.md"));
|
||||
|
||||
if (cmd === "detect") {
|
||||
const found = detect(root);
|
||||
out({
|
||||
ok: true,
|
||||
root,
|
||||
hasAgents,
|
||||
found,
|
||||
warnings: found.filter((f) => f.custom && !f.alreadyPointer && !f.linkedToAgents).map((f) => `${f.id} has custom content that will be replaced (${f.lines} lines).`),
|
||||
...(found.length ? {} : { note: "No AI agent config files found: skip this step silently." }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd !== "apply") fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: detect, apply. Run with --help.");
|
||||
if (!hasAgents) fail(EXIT.NOT_FOUND, "no-agents-md", "AGENTS.md does not exist, so there is nothing to point these files at.", "Create AGENTS.md first.");
|
||||
const ids = args._.slice(1);
|
||||
if (!args.all && !ids.length) fail(EXIT.USAGE, "nothing-selected", "Name the entries to replace, or pass --all.", "Use the ids `detect` printed, for the entries the user confirmed.");
|
||||
const found = detect(root);
|
||||
const chosen = args.all ? found : ids.map((id) => {
|
||||
const hit = found.find((f) => f.id === id.replace(/\\/g, "/").replace(/\/$/, ""));
|
||||
if (!hit) fail(EXIT.NOT_FOUND, "not-present", `"${id}" is not one of the detected entries (${found.map((f) => f.id).join(", ") || "none"}).`, "Run `detect` and use its ids.");
|
||||
return hit;
|
||||
});
|
||||
// Checked before anything is written, so a refusal leaves every file as it was.
|
||||
const linked = chosen.find((c) => c.linkedToAgents);
|
||||
if (linked && !args.all) {
|
||||
fail(EXIT.REFUSED, "linked-to-agents", `${linked.id} is AGENTS.md itself (via a symlink or hard link); replacing it would overwrite AGENTS.md with the pointer.`, `Leave ${linked.id} as it is: it already serves AGENTS.md. Rerun apply without it.`);
|
||||
}
|
||||
|
||||
const actions = [];
|
||||
for (const entry of chosen) {
|
||||
if (entry.linkedToAgents) {
|
||||
actions.push({ action: "skipped-linked", path: entry.writes });
|
||||
continue;
|
||||
}
|
||||
const t = TARGETS.find((x) => x.id === entry.id);
|
||||
const content = templateFor(t);
|
||||
for (const del of entry.deletes || []) {
|
||||
actions.push({ action: "delete", path: del });
|
||||
if (!args["dry-run"]) fs.rmSync(path.join(root, del), { force: true });
|
||||
}
|
||||
const target = path.join(root, entry.writes);
|
||||
const changed = lf(readText(target)) !== content;
|
||||
actions.push({ action: changed ? "write" : "unchanged", path: entry.writes });
|
||||
if (changed && !args["dry-run"]) {
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
// A symlink (or a hard link) to some other file is replaced, not written
|
||||
// through, so the file it shares content with is left alone.
|
||||
let st = null;
|
||||
try {
|
||||
st = fs.lstatSync(target);
|
||||
} catch {}
|
||||
if (st && (st.isSymbolicLink() || st.nlink > 1)) fs.rmSync(target, { force: true });
|
||||
fs.writeFileSync(target, content);
|
||||
}
|
||||
}
|
||||
out({ ok: true, root, dryRun: !!args["dry-run"], updated: chosen.filter((c) => !c.linkedToAgents).map((c) => c.id), actions });
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env node
|
||||
// agents-md.mjs: the shape of a project's AGENTS.md, read from disk.
|
||||
//
|
||||
// Init and Init Update both start by establishing facts about AGENTS.md: does
|
||||
// it exist, how long is it, which sections does it have, is it a single file
|
||||
// or an index over .agents-docs/, which section files exist, which links are
|
||||
// broken, which section files nothing links to. All of that is mechanical;
|
||||
// what to write about it is not.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
agents-md.mjs: inspect AGENTS.md and .agents-docs/. JSON on stdout.
|
||||
|
||||
node agents-md.mjs inspect [--root <dir>]
|
||||
exists, line count against the 500-line budget, structure
|
||||
(progressive or single-file), every ## section with its line count and
|
||||
its Details link, the always-inline sections, .agents-docs/ files with
|
||||
their breadcrumb check, broken links, orphan section files (no link from
|
||||
AGENTS.md).
|
||||
|
||||
node agents-md.mjs filename "<Section Name>"
|
||||
The detail file for a section: AGENTS-<kebab-case>.md, its link line
|
||||
and its two header lines.
|
||||
|
||||
Exit: 0 ok (check "exists") · 2 bad arguments.
|
||||
`;
|
||||
|
||||
const LIMIT = 500;
|
||||
const ALWAYS_INLINE = ["Project Overview", "How to Use This File", "Keeping this file current", "Failure log"];
|
||||
const BREADCRUMB = "> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.";
|
||||
|
||||
function kebab(name) {
|
||||
return name
|
||||
.normalize("NFKD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/&/g, " and ")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
function lineCount(text) {
|
||||
return text ? text.replace(/\r?\n$/, "").split(/\r?\n/).length : 0;
|
||||
}
|
||||
|
||||
function sectionsOf(text) {
|
||||
const lines = text.split(/\r?\n/);
|
||||
const outList = [];
|
||||
let inFence = false;
|
||||
lines.forEach((l, i) => {
|
||||
if (/^\s*(```|~~~)/.test(l)) inFence = !inFence;
|
||||
if (inFence) return;
|
||||
const m = l.match(/^## +(.+?)\s*$/);
|
||||
if (m) outList.push({ name: m[1].trim(), line: i + 1 });
|
||||
});
|
||||
outList.forEach((s, i) => {
|
||||
const end = i + 1 < outList.length ? outList[i + 1].line - 1 : lines.length;
|
||||
const body = lines.slice(s.line, end).join("\n");
|
||||
s.lines = end - s.line + 1;
|
||||
const link = body.match(/\]\((\.\/)?\.agents-docs\/([^)\s#]+)/);
|
||||
s.details = link ? `.agents-docs/${link[2]}` : null;
|
||||
});
|
||||
return outList;
|
||||
}
|
||||
|
||||
function inspect(root) {
|
||||
const file = path.join(root, "AGENTS.md");
|
||||
const text = readText(file);
|
||||
const docsDir = path.join(root, ".agents-docs");
|
||||
const hasDocs = isDir(docsDir);
|
||||
const docFiles = hasDocs
|
||||
? fs.readdirSync(docsDir).filter((n) => n.toLowerCase().endsWith(".md")).sort().map((n) => {
|
||||
const t = readText(path.join(docsDir, n)) || "";
|
||||
const lines = t.split(/\r?\n/);
|
||||
const h1 = lines.find((l) => /^# /.test(l));
|
||||
return {
|
||||
path: `.agents-docs/${n}`,
|
||||
lines: lineCount(t),
|
||||
title: h1 ? h1.replace(/^# +/, "").trim() : null,
|
||||
breadcrumb: lines.slice(0, 6).some((l) => l.trim() === BREADCRUMB || /^> Part of \[AGENTS\.md\]\(\.\.\/AGENTS\.md\)/.test(l.trim())),
|
||||
namedLikeConvention: /^AGENTS-[a-z0-9]+(-[a-z0-9]+)*\.md$/.test(n),
|
||||
};
|
||||
})
|
||||
: [];
|
||||
if (text === null) {
|
||||
return { ok: true, root, exists: false, hasAgentsDocs: hasDocs, agentsDocs: docFiles, otherFiles: ["CLAUDE.md", "README.md", "PROJECT.md", "GEMINI.md", ".cursorrules", ".github/copilot-instructions.md"].filter((f) => fs.existsSync(path.join(root, f))) };
|
||||
}
|
||||
const sections = sectionsOf(text);
|
||||
const linked = new Set();
|
||||
for (const m of text.matchAll(/\]\((?:\.\/)?(\.agents-docs\/[^)\s#]+)/g)) linked.add(m[1]);
|
||||
const broken = [...linked].filter((l) => !fs.existsSync(path.join(root, l)));
|
||||
// A section file nothing in AGENTS.md links to is an orphan, unless another
|
||||
// section file links to it: that one is reached indirectly, and deleting it
|
||||
// would break a link, so it is reported apart and never offered for removal.
|
||||
const fromDocs = new Set();
|
||||
for (const d of docFiles) {
|
||||
const t = readText(path.join(root, d.path)) || "";
|
||||
for (const m of t.matchAll(/\]\((?:\.\/)?([^)\s#]+\.md)/g)) {
|
||||
const target = path.posix.normalize(path.posix.join(".agents-docs", m[1]));
|
||||
if (target !== d.path) fromDocs.add(target);
|
||||
}
|
||||
}
|
||||
const unlinked = docFiles.map((d) => d.path).filter((p) => !linked.has(p));
|
||||
const orphans = unlinked.filter((p) => !fromDocs.has(p));
|
||||
const indirect = unlinked.filter((p) => fromDocs.has(p));
|
||||
const inline = ALWAYS_INLINE.map((name) => {
|
||||
const s = sections.find((x) => x.name.toLowerCase() === name.toLowerCase());
|
||||
return { name, present: !!s, splitOut: !!(s && s.details) };
|
||||
});
|
||||
const count = lineCount(text);
|
||||
return {
|
||||
ok: true,
|
||||
root,
|
||||
exists: true,
|
||||
lines: count,
|
||||
budget: `${count}/${LIMIT}`,
|
||||
nearLimit: count > LIMIT * 0.9,
|
||||
overLimit: count > LIMIT,
|
||||
structure: hasDocs ? "progressive" : "single-file",
|
||||
sections,
|
||||
alwaysInline: inline,
|
||||
hasAgentsDocs: hasDocs,
|
||||
agentsDocs: docFiles,
|
||||
brokenLinks: broken,
|
||||
orphans,
|
||||
indirect,
|
||||
problems: [
|
||||
...broken.map((b) => `AGENTS.md links to ${b}, which does not exist`),
|
||||
...orphans.map((o) => `${o} has no link from AGENTS.md (orphan: offer to remove it)`),
|
||||
...inline.filter((s) => s.splitOut).map((s) => `${s.name} must stay inline in AGENTS.md but links out to a section file`),
|
||||
...docFiles.filter((d) => !d.breadcrumb).map((d) => `${d.path} lacks the "> Part of [AGENTS.md](../AGENTS.md)" breadcrumb`),
|
||||
...docFiles.filter((d) => !d.namedLikeConvention).map((d) => `${d.path} is not named AGENTS-<kebab-case>.md`),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { values: ["root"] });
|
||||
const cmd = args._[0];
|
||||
if (cmd === "inspect") {
|
||||
out(inspect(path.resolve(args.root || ".")));
|
||||
return;
|
||||
}
|
||||
if (cmd === "filename") {
|
||||
const name = args._.slice(1).join(" ").trim();
|
||||
if (!name) fail(EXIT.USAGE, "missing-name", "Give the section name.", 'Example: filename "Development Commands"');
|
||||
const slug = kebab(name);
|
||||
if (!slug) fail(EXIT.USAGE, "bad-name", `"${name}" has no letters or digits to name a file from.`, "Use the section's heading text.");
|
||||
const file = `.agents-docs/AGENTS-${slug}.md`;
|
||||
out({ ok: true, section: name, file, link: `Details: [${name}](./${file})`, header: [`# ${name}`, BREADCRUMB] });
|
||||
return;
|
||||
}
|
||||
fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: inspect, filename. Run with --help.");
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
// Plan2Code skill scripts: shared plumbing.
|
||||
//
|
||||
// Every script in a skill's scripts/ directory imports this file. It owns the
|
||||
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
|
||||
//
|
||||
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
|
||||
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
|
||||
// on a handled failure.
|
||||
// stderr a one-line human diagnostic on failure (the same message + next).
|
||||
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
|
||||
// 4 invalid input or a check that failed · 5 refused (would clobber
|
||||
// or break a rule).
|
||||
//
|
||||
// Node 18+ built-ins only, no build step: this ships inside every skill.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
|
||||
|
||||
export class CliError extends Error {
|
||||
constructor(exit, error, message, next) {
|
||||
super(message);
|
||||
this.exit = exit;
|
||||
this.error = error;
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
|
||||
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
|
||||
export function fail(exit, error, message, next) {
|
||||
throw new CliError(exit, error, message, next);
|
||||
}
|
||||
|
||||
export function out(obj) {
|
||||
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse argv into { _: positionals, <flag>: value }.
|
||||
* `booleans` names flags that take no value; every other `--flag` takes the
|
||||
* next argument, and repeats of a flag listed in `lists` collect into an array.
|
||||
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
|
||||
* silently changes behavior.
|
||||
*/
|
||||
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
|
||||
const known = new Set([...booleans, ...values, ...lists, "help"]);
|
||||
const args = { _: [] };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (!a.startsWith("--")) {
|
||||
args._.push(a);
|
||||
continue;
|
||||
}
|
||||
let name = a.slice(2);
|
||||
let value;
|
||||
const eq = name.indexOf("=");
|
||||
if (eq !== -1) {
|
||||
value = name.slice(eq + 1);
|
||||
name = name.slice(0, eq);
|
||||
}
|
||||
if (!known.has(name)) {
|
||||
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
|
||||
}
|
||||
if (name === "help" || booleans.includes(name)) {
|
||||
args[name] = true;
|
||||
continue;
|
||||
}
|
||||
if (value === undefined) {
|
||||
if (i + 1 >= argv.length) {
|
||||
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
|
||||
}
|
||||
value = argv[++i];
|
||||
}
|
||||
if (lists.includes(name)) (args[name] ||= []).push(value);
|
||||
else args[name] = value;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
|
||||
* failure shape plus an exit code, and anything else into exit 1 with the stack
|
||||
* on stderr. Sets process.exitCode rather than calling process.exit(), so
|
||||
* stdout is never cut off mid-write.
|
||||
*/
|
||||
export async function run(usage, main) {
|
||||
try {
|
||||
const argv = process.argv.slice(2);
|
||||
if (argv.includes("--help") || argv.includes("-h")) {
|
||||
process.stdout.write(usage.trim() + "\n");
|
||||
return;
|
||||
}
|
||||
await main(argv);
|
||||
} catch (err) {
|
||||
if (err instanceof CliError) {
|
||||
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
|
||||
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
|
||||
process.exitCode = err.exit;
|
||||
return;
|
||||
}
|
||||
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
|
||||
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
|
||||
process.exitCode = EXIT.CRASH;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ time */
|
||||
|
||||
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
|
||||
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
|
||||
// is what "today" means to the person reading the date in their files.
|
||||
export function now() {
|
||||
const pinned = process.env.PLAN2CODE_NOW;
|
||||
if (pinned) {
|
||||
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
|
||||
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
|
||||
const d = new Date(pinned);
|
||||
if (!Number.isNaN(d.getTime())) return d;
|
||||
}
|
||||
return new Date();
|
||||
}
|
||||
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
|
||||
/** YYYY-MM-DD */
|
||||
export function isoDate(d = now()) {
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
}
|
||||
|
||||
/** YYYYMMDD */
|
||||
export function compactDate(d = now()) {
|
||||
return isoDate(d).replace(/-/g, "");
|
||||
}
|
||||
|
||||
/** YYYY-MM-DD HH:mm */
|
||||
export function stamp(d = now()) {
|
||||
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** HHMMSS */
|
||||
export function clock(d = now()) {
|
||||
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- files */
|
||||
|
||||
export function readText(file) {
|
||||
try {
|
||||
return fs.readFileSync(file, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isDir(p) {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Write a file only when its content changes. Returns true when it wrote. */
|
||||
export function writeIfChanged(file, content) {
|
||||
const current = readText(file);
|
||||
if (current === content) return false;
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, content);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Normalise line endings for parsing; keep the original for writing back. */
|
||||
export function eol(text) {
|
||||
return text.includes("\r\n") ? "\r\n" : "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
|
||||
* such as phase-1-old.md; more than one candidate is reported, never guessed.
|
||||
* Shared so every script that counts a spec's tasks reads the same files.
|
||||
*/
|
||||
export function phaseFiles(dir) {
|
||||
const files = new Map();
|
||||
const extra = new Map();
|
||||
for (const name of fs.readdirSync(dir).sort()) {
|
||||
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
|
||||
if (!m) continue;
|
||||
const n = Number(m[1]);
|
||||
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
|
||||
if (!files.has(n)) files.set(n, name);
|
||||
else if (exact) {
|
||||
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
|
||||
files.set(n, name);
|
||||
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
|
||||
}
|
||||
files.extra = extra;
|
||||
return files;
|
||||
}
|
||||
|
||||
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
|
||||
export function rel(root, p) {
|
||||
return path.relative(root, p).split(path.sep).join("/") || ".";
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- the web console */
|
||||
|
||||
// The web console ships beside these scripts in every installed skill
|
||||
// (references/web-console/), and in this repo it sits at src/web-console/. Its
|
||||
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
|
||||
// metrics-bait scan, so the scripts import it rather than keep a second copy.
|
||||
const CONSOLE_LIB_CANDIDATES = [
|
||||
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
|
||||
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
|
||||
];
|
||||
|
||||
let consoleLibPromise;
|
||||
export function consoleLib() {
|
||||
consoleLibPromise ||= (async () => {
|
||||
for (const candidate of CONSOLE_LIB_CANDIDATES) {
|
||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
||||
}
|
||||
fail(
|
||||
EXIT.NOT_FOUND,
|
||||
"console-lib-missing",
|
||||
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
|
||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
||||
);
|
||||
})();
|
||||
return consoleLibPromise;
|
||||
}
|
||||
|
||||
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
|
||||
export function version() {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const text = readText(file);
|
||||
if (!text) continue;
|
||||
try {
|
||||
const v = JSON.parse(text).version;
|
||||
if (typeof v === "string") return v;
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
"workflow",
|
||||
"development",
|
||||
"planning",
|
||||
"implementation",
|
||||
"plan"
|
||||
],
|
||||
"author": "Justin Parker",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"mode": "utility"
|
||||
}
|
||||
Reference in new issue
Block a user