@dreadedzombie/pi-init 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +50 -0
  2. package/package.json +36 -0
  3. package/src/index.ts +256 -0
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # pi-init
2
+
3
+ Adds `/init` to [Pi](https://pi.dev/) — generates or updates an AGENTS.md in your current project directory.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install https://github.com/joenilan/pi-init
9
+ ```
10
+
11
+ Pi clones the repo and loads the extension automatically on next start.
12
+
13
+ ## Usage
14
+
15
+ ```
16
+ /init Explore-first project analysis → AGENTS.md
17
+ /init code Same as bare /init
18
+ /init research Research protocol with incremental findings tracking
19
+ /init debug Debug protocol — carries forward research findings automatically
20
+ ```
21
+
22
+ ## What each type does
23
+
24
+ **`/init` / `/init code`** — Pi explores the project first (reads package.json, scans
25
+ structure, reads key source files, checks for `.cursorrules`/`CLAUDE.md`), then writes
26
+ a filled-in AGENTS.md. If AGENTS.md already has content, running `/init` again flags it
27
+ for update — Pi re-explores and refreshes stale sections without wiping human-authored notes.
28
+
29
+ **`/init research`** — Writes a research protocol: minimum source count, citation
30
+ requirements, when to use Playwright vs fetch, sequential-thinking for multi-step
31
+ reasoning, memory for long sessions. Includes a `## Research Findings` section Pi
32
+ updates incrementally — each topic gets saved to `research/<topic>.md` and linked here.
33
+
34
+ **`/init debug`** — Writes an investigative protocol: verify before assuming, read logs
35
+ first, checkpoint with `pi-rewind` before changes, trace backward from the error. If
36
+ you ran `/init research` first, the Research Findings section carries forward
37
+ automatically — Pi reads those files at step 1 before touching any code.
38
+
39
+ ## Research → Debug workflow
40
+
41
+ ```
42
+ /init research # set up research protocol
43
+ # describe your topic — Pi searches, reads sources, saves to research/*.md
44
+
45
+ /init debug # switch to debug — research findings carry forward automatically
46
+ # Pi reads linked research files before starting any investigation
47
+ ```
48
+
49
+ Colony agents read AGENTS.md from the working directory on every action, so they see
50
+ research findings and debug context the same way a single-agent session does.
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@dreadedzombie/pi-init",
3
+ "version": "1.0.0",
4
+ "description": "Generates a typed AGENTS.md for your project — /init, /init research, /init debug, /init code",
5
+ "license": "MIT",
6
+ "author": "DreadedZombie",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DreadedZombie/pi-init.git"
10
+ },
11
+ "homepage": "https://github.com/DreadedZombie/pi-init#readme",
12
+ "keywords": [
13
+ "pi",
14
+ "pi-coding-agent",
15
+ "pi-extension",
16
+ "pi-package",
17
+ "agents",
18
+ "agents-md",
19
+ "init",
20
+ "scaffold",
21
+ "research",
22
+ "debug"
23
+ ],
24
+ "files": [
25
+ "src/",
26
+ "README.md"
27
+ ],
28
+ "pi": {
29
+ "extensions": [
30
+ "./src/index.ts"
31
+ ]
32
+ },
33
+ "devDependencies": {
34
+ "@mariozechner/pi-coding-agent": "*"
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * pi-init — /init slash command
3
+ *
4
+ * Generates or updates an AGENTS.md in the current working directory.
5
+ *
6
+ * Usage:
7
+ * /init Explore-first project analysis → AGENTS.md
8
+ * /init code Same as bare /init
9
+ * /init research Research protocol with incremental findings tracking
10
+ * /init debug Debug protocol — carries forward Research Findings from prior /init research
11
+ */
12
+
13
+ import type { ExtensionAPI, ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+
17
+ // ─── Templates ────────────────────────────────────────────────────────────────
18
+
19
+ const TEMPLATE_CODE = `# Project Agent
20
+
21
+ <!-- Pi: before writing anything, explore this project:
22
+ 1. Read package.json / pyproject.toml / Cargo.toml / go.mod — identify stack and versions
23
+ 2. Scan directory structure: rg --files | head -60
24
+ 3. Read 3-5 key source files to understand patterns and conventions
25
+ 4. Check for .cursorrules, CLAUDE.md, .eslintrc, prettier.config — existing AI/style config
26
+ Then fill in each section below based on what you actually find.
27
+ Adapt or add sections if the project has unique needs.
28
+ -->
29
+
30
+ **Generated:** <!-- Pi: insert today's date (YYYY-MM-DD) -->
31
+
32
+ ## Stack
33
+ <!-- Pi: languages, frameworks, key libraries and their versions -->
34
+
35
+ ## Structure
36
+ <!-- Pi: key directories and what each contains — a mental map, not a full file list -->
37
+
38
+ ## Commands
39
+ | Action | Command |
40
+ |---------|---------|
41
+ | Install | |
42
+ | Build | |
43
+ | Test | |
44
+ | Run | |
45
+
46
+ ## Conventions
47
+ <!-- Pi: coding style, patterns in use, formatter/linter config, naming conventions -->
48
+
49
+ ## Key Files
50
+ <!-- Pi: the 5-10 most important files and what each one does -->
51
+
52
+ ## What to Avoid
53
+ <!-- Pi: patterns or changes that would break things or go against project style -->
54
+
55
+ ## Notes
56
+ <!-- Pi: existing AI config files (.cursorrules, CLAUDE.md), gotchas, constraints, anything a new agent must know -->
57
+ `;
58
+
59
+ const TEMPLATE_RESEARCH = `# Research Agent
60
+
61
+ **Started:** <!-- Pi: insert today's date (YYYY-MM-DD) -->
62
+
63
+ ## Search Protocol
64
+ - Run at least **4 distinct queries** approaching the topic from different angles before drawing conclusions
65
+ - Read the **full content** of at least 6 sources — not just summaries or snippets
66
+ - For JS-heavy or dynamically rendered pages where \`fetch\` returns sparse HTML, use **Playwright** to render and extract
67
+ - Cross-reference findings across sources before responding
68
+ - Do **not** respond until you have read multiple sources and built a complete picture
69
+
70
+ ## Source Quality Standards
71
+ - Prefer primary sources: official documentation, research papers, original announcements
72
+ - Flag secondary sources: forums, blog posts, aggregators — note them as such
73
+ - When sources conflict, surface the contradiction explicitly — do not silently pick one
74
+ - Cite every factual claim with its source URL
75
+
76
+ ## Research Process
77
+ 1. **Map** — 3-4 broad queries to understand the landscape and identify the key sources
78
+ 2. **Dive** — read the full content of the 5-6 most relevant sources
79
+ 3. **Cross-reference** — identify what sources agree and disagree on
80
+ 4. **Synthesize** — build a coherent picture with citations
81
+ 5. **Save** — write findings to \`research/<topic>.md\`, one file per topic or question
82
+ 6. **Update** — add each saved file to the Research Findings section below with a one-line summary
83
+ 7. **Gaps** — explicitly note what you could not find or verify
84
+
85
+ ## Tools
86
+ - \`searxng\` — start here for all searches (private, no tracking)
87
+ - \`fetch\` — static pages, documentation, GitHub READMEs
88
+ - \`playwright\` — JS-rendered pages, React/Vue apps, login-gated content, anything fetch returns blank for
89
+ - \`sequential-thinking\` — use when the research has multiple dependent steps or requires structured reasoning
90
+ - \`memory\` — persist key findings across a long session so nothing gets lost to context limits
91
+ - \`pi-docparser\` — for PDFs, papers, Word docs, spreadsheets
92
+
93
+ ## Research Findings
94
+ <!-- Pi: as you complete each topic, save findings to research/<topic>.md and add a line here:
95
+ - [Topic title](research/filename.md) — one-line summary of what was found
96
+ Update this section incrementally — do not wait until the end. -->
97
+ `;
98
+
99
+ const TEMPLATE_DEBUG = `# Debug Agent
100
+
101
+ ## Research Findings
102
+ <!-- Pi: read every file linked here before starting investigation — prior research is your context -->
103
+
104
+ ## Investigative Stance
105
+ - **Never assume** — verify everything against logs, actual code, and runtime behavior
106
+ - Read error messages and stack traces **in full** before proposing any fix
107
+ - Trace from the error **backward** to the root cause — not forward from a guess
108
+ - Document every finding, including dead ends — they matter for context
109
+
110
+ ## Before Any Fix
111
+ - Checkpoint the current state with \`pi-rewind\` before touching anything
112
+ - Understand the full failure chain before writing a single line
113
+ - Identify whether the issue is: **configuration**, **code logic**, **dependencies**, **environment**, or **data**
114
+
115
+ ## Investigation Order
116
+ 1. Read all Research Findings files linked above — prior research changes what you look for
117
+ 2. Read all available logs — error, build, runtime, access
118
+ 3. Trace the startup / execution sequence from the entry point
119
+ 4. Check dependency versions and compatibility
120
+ 5. Verify environment variables and configuration files
121
+ 6. Isolate the **earliest** point of failure — fixes belong there, not downstream
122
+
123
+ ## Current State
124
+ <!-- Pi: read this directory now and fill in:
125
+ - What is this project supposed to do?
126
+ - What is currently broken — exact error messages and symptoms
127
+ - Where does it fail — startup, build, runtime, specific operation?
128
+ - What has already been tried?
129
+ - Key files to investigate first
130
+ -->
131
+
132
+ ## Constraints
133
+ - Use \`pi-rewind\` before every destructive or speculative change
134
+ - If you find multiple possible causes, list them ranked by likelihood before acting
135
+ - Confirm before deleting files, dropping data, or resetting state
136
+ `;
137
+
138
+ // Prepended to existing AGENTS.md when /init code is run on a project that already has one
139
+ const UPDATE_BANNER = `<!-- Pi: UPDATE MODE
140
+ This AGENTS.md was generated in a prior session. Your job:
141
+ 1. Re-explore the project (rg --files, re-read key source files)
142
+ 2. Check for new or changed .cursorrules, CLAUDE.md, or other AI config files
143
+ 3. Update every section below with fresh findings — fix stale info, fill gaps
144
+ 4. Preserve any human-authored notes that don't conflict with current reality
145
+ -->
146
+
147
+ `;
148
+
149
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
150
+
151
+ type InitType = "code" | "research" | "debug";
152
+
153
+ function parseType(args: string): InitType {
154
+ const t = (args || "").trim().toLowerCase();
155
+ if (t === "research") return "research";
156
+ if (t === "debug") return "debug";
157
+ return "code";
158
+ }
159
+
160
+ function getFollowUp(type: InitType): string {
161
+ switch (type) {
162
+ case "research":
163
+ return "AGENTS.md written with the research protocol. Describe what you want to research — Pi will search, read sources, save findings to research/ files, and update the Research Findings section as it goes.";
164
+ case "debug":
165
+ return "AGENTS.md written with the debug protocol. Ask Pi to read this directory and fill in the Current State section before starting any investigation.";
166
+ default:
167
+ return "AGENTS.md written. Ask Pi to explore this project and fill in all sections — it will read the codebase first, then generate.";
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Returns true if the file has meaningful filled-in content beyond placeholders.
173
+ */
174
+ function hasFilledContent(content: string): boolean {
175
+ const withoutComments = content.replace(/<!--[\s\S]*?-->/g, "").trim();
176
+ const withoutHeaders = withoutComments.replace(/^#+.*$/gm, "").replace(/^\*\*Generated:?\*\*.*$/gm, "").trim();
177
+ return withoutHeaders.length > 80;
178
+ }
179
+
180
+ /**
181
+ * Extracts the body of the ## Research Findings section from an existing AGENTS.md.
182
+ * Returns empty string if section is missing or contains only the placeholder comment.
183
+ */
184
+ function extractResearchFindings(content: string): string {
185
+ const m = content.match(/^## Research Findings\n([\s\S]*?)(?=\n## |\n# |$)/m);
186
+ if (!m) return "";
187
+ const body = m[1].trim();
188
+ if (body.startsWith("<!--") && body.endsWith("-->")) return "";
189
+ return body;
190
+ }
191
+
192
+ /**
193
+ * Injects research findings into the debug template, replacing the placeholder comment.
194
+ */
195
+ function buildDebugWithFindings(findings: string): string {
196
+ return TEMPLATE_DEBUG.replace(
197
+ "<!-- Pi: read every file linked here before starting investigation — prior research is your context -->",
198
+ findings
199
+ );
200
+ }
201
+
202
+ // ─── Extension entry ──────────────────────────────────────────────────────────
203
+
204
+ export default function (pi: ExtensionAPI) {
205
+ pi.registerCommand("init", {
206
+ description: "Generate or update an AGENTS.md for this project. Usage: /init [code|research|debug]",
207
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
208
+ const type = parseType(args);
209
+ const cwd: string = ctx.cwd ?? process.cwd();
210
+ const dest = path.join(cwd, "AGENTS.md");
211
+ const exists = fs.existsSync(dest);
212
+
213
+ // ── Debug: carry forward Research Findings from a prior research session ──
214
+ if (type === "debug" && exists) {
215
+ const existing = fs.readFileSync(dest, "utf8");
216
+ const findings = extractResearchFindings(existing);
217
+ if (findings) {
218
+ fs.writeFileSync(dest, buildDebugWithFindings(findings), "utf8");
219
+ ctx.ui.notify(`[pi-init] AGENTS.md switched to debug protocol — research findings carried forward`, "info");
220
+ ctx.ui.notify(getFollowUp("debug"), "info");
221
+ return;
222
+ }
223
+ }
224
+
225
+ // ── Code: update mode if AGENTS.md has real content (no overwrite prompt) ──
226
+ if (type === "code" && exists) {
227
+ const existing = fs.readFileSync(dest, "utf8");
228
+ if (hasFilledContent(existing)) {
229
+ fs.writeFileSync(dest, UPDATE_BANNER + existing, "utf8");
230
+ ctx.ui.notify(`[pi-init] AGENTS.md flagged for update — ask Pi to re-explore and refresh all sections`, "info");
231
+ return;
232
+ }
233
+ }
234
+
235
+ // ── All other cases: confirm overwrite if file exists ──
236
+ if (exists) {
237
+ const overwrite = await ctx.ui.confirm(
238
+ `AGENTS.md already exists in:\n${cwd}`,
239
+ "Overwrite it?"
240
+ );
241
+ if (!overwrite) {
242
+ ctx.ui.notify("Cancelled — existing AGENTS.md kept.", "info");
243
+ return;
244
+ }
245
+ }
246
+
247
+ const content = type === "research" ? TEMPLATE_RESEARCH
248
+ : type === "debug" ? TEMPLATE_DEBUG
249
+ : TEMPLATE_CODE;
250
+
251
+ fs.writeFileSync(dest, content, "utf8");
252
+ ctx.ui.notify(`[pi-init] AGENTS.md (${type}) written to ${cwd}`, "info");
253
+ ctx.ui.notify(getFollowUp(type), "info");
254
+ },
255
+ });
256
+ }