@jackjtaylor/pi-sdlc-modes 0.0.0-stage → 0.1.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.
package/DEFAULTS.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "cycleShortcut": "ctrl+alt+m",
3
+ "initialMode": "explore",
4
+ "modes": [
5
+ {
6
+ "id": "explore",
7
+ "name": "Explore",
8
+ "description": "Explore how the code works and how systems are designed before suggesting any changes.",
9
+ "instructions": "Explain the system's purpose, main components, and how they interact or move data; inspect the code and cite relevant files or symbols, using a diagram when it clarifies the design. Keep the overview focused, answer follow-up questions, and distinguish verified facts from assumptions. For bug reports, describe the behavior and symptoms without diagnosing causes or proposing fixes unless asked. Delegate bounded, independent research when a suitable route is available; otherwise investigate directly and never claim delegation."
10
+ },
11
+ {
12
+ "id": "specification-and-acceptance-criteria",
13
+ "name": "Specification and Acceptance Criteria",
14
+ "description": "Describe the problem, scope, user experience, and testable acceptance criteria.",
15
+ "instructions": "Work with the user to describe the problem, intended users, desired experience, scope, and constraints. Ask focused questions about unclear behavior, including important edge, error, and recovery cases. Summarize the agreement as user stories and observable acceptance criteria; call out unresolved assumptions instead of guessing. Do not begin design or implementation until the scope and criteria are clear."
16
+ },
17
+ {
18
+ "id": "design-and-plan",
19
+ "name": "Design and Plan",
20
+ "description": "Select an approach and turn the criteria into an actionable plan.",
21
+ "instructions": "Inspect the relevant code and compare feasible approaches against the agreed criteria. Explain the recommended design, key trade-offs, risks, and compatibility effects, and confirm the direction with the user. Then give an ordered plan naming files, relevant locations, intended changes, and verification steps; note open questions and tests. Do not edit files in this mode."
22
+ },
23
+ {
24
+ "id": "build",
25
+ "name": "Build",
26
+ "description": "Implement the approved design or plan, preserve existing work, and verify the result.",
27
+ "instructions": "Implement the approved design or plan within the agreed scope. Follow repository conventions, keep the diff focused, and preserve unrelated user changes. Add or update relevant tests and run appropriate checks. When a suitable sub-agent or CLI-based Pi route is available, delegate bounded tasks that avoid conflicting edits; coordinate, integrate, and verify the result, and tell child agents not to delegate further. Otherwise work directly and do not claim delegation."
28
+ },
29
+ {
30
+ "id": "review",
31
+ "name": "Review",
32
+ "description": "Review changes for concrete defects, regressions, security risks, and missing tests.",
33
+ "instructions": "Review the changes without modifying files. Prioritize concrete defects, regressions, security risks, and missing tests; support each finding with a file and line reference and explain its impact. Separate confirmed findings from uncertainty, and state clearly if you find none. For substantial changes, delegate bounded, independent review areas when a suitable route is available; otherwise review directly."
34
+ },
35
+ {
36
+ "id": "release",
37
+ "name": "Release",
38
+ "description": "Assess release readiness and prepare verification, rollout, and rollback checks.",
39
+ "instructions": "Prepare release-readiness checks and a practical rollout, verification, and rollback checklist. Base conclusions on available evidence; use only accessible tools, services, logs, and metrics, and state what could not be checked. Do not claim readiness without evidence or deploy, alter production, or take another consequential release action without explicit approval."
40
+ },
41
+ {
42
+ "id": "debug-and-log",
43
+ "name": "Debug and Log",
44
+ "description": "Investigate failures using reproducible evidence and available logs to identify likely causes.",
45
+ "instructions": "Clarify expected versus observed behavior, reproduce the failure when practical, and inspect relevant code plus only logs or diagnostics you can access. Use evidence to trace likely causes; separate confirmed facts from hypotheses and state useful next steps. Do not imply access to unavailable systems or expose secrets or unnecessary personal data from logs. Do not change code or systems unless asked."
46
+ }
47
+ ]
48
+ }
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @jackjtaylor/pi-sdlc-modes
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This packages has modes to guide Pi through the stages of software development, from exploring a codebase to preparing a release.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install npm:@jackjtaylor/pi-sdlc-modes
9
+ ```
10
+
11
+ You can update this package with `pi update --extensions`.
12
+
13
+ ```bash
14
+ pi remove npm:@jackjtaylor/pi-sdlc-modes
15
+ ```
16
+
17
+ ## Select Modes
18
+
19
+ - Press `Ctrl+Alt+M` to cycle through the modes (or create your own in a configuration file).
20
+ - Run `/sdlc` to pick a mode, or `/sdlc <mode>` to select one by name.
21
+ - Run `/sdlc next` to move to the next mode.
22
+
23
+ The selected mode appears above the editor in the terminal user interface. Your new sessions start in `Explore` by default. Pi remembers the mode you selected, even when you're resuming a session later.
24
+
25
+ The modes guide Pi's responses and how it should work. They don't forbid tools, restrict context, or change what Pi has access to. The modes are also not extension or package-specific, so you can ask Pi to, for example, create plans using an extension, or by creating files.
26
+
27
+ ## Configure
28
+
29
+ The defaults are in `DEFAULTS.json`.
30
+ To customise the modes or shortcut, create `~/.pi/agent/extensions/pi-sdlc-modes/config.json` and use the same schema as in `DEFAULTS.json`.
31
+
32
+ ## Security
33
+
34
+ In this very early stage of development, I haven't reviewed or verified the code line-by-line, so keep that in mind when using this package.
package/index.ts ADDED
@@ -0,0 +1,213 @@
1
+ import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
3
+ import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { Text } from "@earendil-works/pi-tui";
5
+ import { loadConfig, ModeStateEntrySchema, type ModeDefinition, type ModeStateEntry } from "./mode-config.ts";
6
+
7
+ const STATE_ENTRY_TYPE = "sdlc-mode-state";
8
+ const WIDGET_ID = "sdlc-mode";
9
+ const SYSTEM_PROMPT_SECTION = "sdlc_mode";
10
+
11
+ function normalizeModeSelector(value: string): string {
12
+ return value
13
+ .trim()
14
+ .toLowerCase()
15
+ .replace(/&/g, " ")
16
+ .replace(/[^a-z0-9]+/g, "-")
17
+ .replace(/^-|-$/g, "");
18
+ }
19
+
20
+ export default function sdlcModesExtension(pi: ExtensionAPI): void {
21
+ const config = loadConfig();
22
+ let activeModeId = config.initialMode;
23
+
24
+ const firstConfiguredMode = config.modes[0];
25
+ if (!firstConfiguredMode) throw new Error("SDLC configuration must contain at least one mode.");
26
+
27
+ const getActiveMode = (): ModeDefinition =>
28
+ config.modes.find((mode) => mode.id === activeModeId) ?? firstConfiguredMode;
29
+
30
+ const restoreModeFromBranch = (ctx: ExtensionContext): void => {
31
+ const entries = ctx.sessionManager.getBranch();
32
+ for (let index = entries.length - 1; index >= 0; index--) {
33
+ const entry = entries[index];
34
+ if (!entry || entry.type !== "custom" || entry.customType !== STATE_ENTRY_TYPE) continue;
35
+ const stateData: unknown = entry.data;
36
+ if (!Value.Check(ModeStateEntrySchema, stateData)) continue;
37
+ if (config.modes.some((mode) => mode.id === stateData.modeId)) {
38
+ activeModeId = stateData.modeId;
39
+ return;
40
+ }
41
+ }
42
+ activeModeId = config.initialMode;
43
+ };
44
+
45
+ const updateModeIndicator = (ctx: ExtensionContext): void => {
46
+ const mode = getActiveMode();
47
+ if (ctx.mode === "tui") {
48
+ ctx.ui.setWidget(
49
+ WIDGET_ID,
50
+ (_tui, theme) =>
51
+ new Text(
52
+ `${theme.fg("accent", theme.bold(`SDLC · ${mode.name}`))} ${theme.fg("dim", `[${config.cycleShortcut}]`)}\n${theme.fg("muted", mode.description)}`,
53
+ 0,
54
+ 0,
55
+ ),
56
+ );
57
+ ctx.ui.setStatus(WIDGET_ID, undefined);
58
+ return;
59
+ }
60
+ if (ctx.hasUI) {
61
+ ctx.ui.setStatus(WIDGET_ID, `SDLC · ${mode.name} — ${mode.description}`);
62
+ }
63
+ };
64
+
65
+ const changeMode = (
66
+ modeId: string,
67
+ ctx: ExtensionContext,
68
+ ): { kind: "changed" | "already-active" | "unknown"; message: string } => {
69
+ const mode = config.modes.find((candidate) => candidate.id === modeId);
70
+ if (!mode) return { kind: "unknown", message: `Unknown SDLC mode: ${modeId}` };
71
+ if (activeModeId === mode.id) return { kind: "already-active", message: `Already in ${mode.name}.` };
72
+
73
+ activeModeId = mode.id;
74
+ pi.appendEntry<ModeStateEntry>(STATE_ENTRY_TYPE, {
75
+ modeId: mode.id,
76
+ modeName: mode.name,
77
+ description: mode.description,
78
+ changedAt: Date.now(),
79
+ });
80
+ updateModeIndicator(ctx);
81
+ return { kind: "changed", message: `Switched to ${mode.name}.` };
82
+ };
83
+
84
+ const setMode = (modeId: string, ctx: ExtensionContext): void => {
85
+ const result = changeMode(modeId, ctx);
86
+ if (result.kind !== "changed") {
87
+ ctx.ui.notify(result.message, result.kind === "unknown" ? "error" : "info");
88
+ }
89
+ };
90
+
91
+ const cycleMode = (ctx: ExtensionContext): void => {
92
+ const activeIndex = config.modes.findIndex((mode) => mode.id === activeModeId);
93
+ const nextMode = config.modes[(activeIndex + 1 + config.modes.length) % config.modes.length] ?? firstConfiguredMode;
94
+ setMode(nextMode.id, ctx);
95
+ };
96
+
97
+ const selectMode = async (args: string, ctx: ExtensionContext): Promise<void> => {
98
+ const selector = args.trim();
99
+ if (selector.length === 0) {
100
+ if (!ctx.hasUI) {
101
+ ctx.ui.notify(`Current mode: ${getActiveMode().name}. Use /sdlc next or /sdlc <mode>.`, "info");
102
+ return;
103
+ }
104
+ const selectedName = await ctx.ui.select(
105
+ "Choose an SDLC mode",
106
+ config.modes.map((mode) => mode.name),
107
+ );
108
+ if (!selectedName) return;
109
+ const selectedMode = config.modes.find((mode) => mode.name === selectedName);
110
+ if (selectedMode) setMode(selectedMode.id, ctx);
111
+ return;
112
+ }
113
+
114
+ if (selector.toLowerCase() === "next") {
115
+ cycleMode(ctx);
116
+ return;
117
+ }
118
+
119
+ const normalizedSelector = normalizeModeSelector(selector);
120
+ const selectedMode = config.modes.find(
121
+ (mode) => mode.id === normalizedSelector || normalizeModeSelector(mode.name) === normalizedSelector,
122
+ );
123
+ if (!selectedMode) {
124
+ const availableModes = config.modes.map((mode) => mode.id).join(", ");
125
+ ctx.ui.notify(`Unknown SDLC mode "${selector}". Available: ${availableModes}, next.`, "error");
126
+ return;
127
+ }
128
+ setMode(selectedMode.id, ctx);
129
+ };
130
+
131
+ pi.registerEntryRenderer<ModeStateEntry>(STATE_ENTRY_TYPE, (entry, _options, theme) => {
132
+ const data = Value.Check(ModeStateEntrySchema, entry.data) ? entry.data : undefined;
133
+ if (!data) return new Text(theme.fg("dim", "SDLC mode changed"), 0, 0);
134
+ return new Text(theme.fg("dim", `SDLC · ${data.modeName} — ${data.description}`), 0, 0);
135
+ });
136
+
137
+ pi.registerTool({
138
+ name: "sdlc_set_mode",
139
+ label: "Set SDLC Mode",
140
+ description:
141
+ "Change the active SDLC mode after the user explicitly requests or clearly authorizes that phase change. If the user's intent is unclear, ask and wait for confirmation instead of switching.",
142
+ promptSnippet: "Change the active SDLC mode only with clear user authorization.",
143
+ promptGuidelines: [
144
+ "Only switch modes when the user explicitly requests the switch or clearly authorizes moving to that phase.",
145
+ "A task request alone is not permission if it is unclear whether the user wants a mode change. Ask and wait for confirmation when uncertain.",
146
+ ],
147
+ parameters: Type.Object({
148
+ mode: Type.String({
149
+ description: "Configured SDLC mode ID to switch to.",
150
+ enum: config.modes.map((mode) => mode.id),
151
+ }),
152
+ }),
153
+ annotations: { readOnlyHint: false, idempotentHint: true },
154
+ execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
155
+ const result = changeMode(params.mode, ctx);
156
+ return {
157
+ content: [{ type: "text", text: result.message }],
158
+ details: { modeId: params.mode, changed: result.kind === "changed" },
159
+ isError: result.kind === "unknown",
160
+ };
161
+ },
162
+ });
163
+
164
+ pi.registerCommand("sdlc", {
165
+ description: "Choose an SDLC mode, use /sdlc next, or select /sdlc <mode>",
166
+ getArgumentCompletions: (prefix) => {
167
+ const choices = [
168
+ {
169
+ value: "next",
170
+ label: "next",
171
+ description: "Advance to the next SDLC mode",
172
+ },
173
+ ...config.modes.map((mode) => ({
174
+ value: mode.id,
175
+ label: mode.name,
176
+ description: mode.description,
177
+ })),
178
+ ];
179
+ const matches = choices.filter((choice) => choice.value.startsWith(prefix.toLowerCase()));
180
+ return matches.length > 0 ? matches : null;
181
+ },
182
+ handler: async (args, ctx) => selectMode(args, ctx),
183
+ });
184
+
185
+ pi.registerShortcut(config.cycleShortcut, {
186
+ description: "Advance to the next SDLC mode",
187
+ handler: async (ctx) => cycleMode(ctx),
188
+ });
189
+
190
+ pi.on("session_start", async (_event, ctx) => {
191
+ restoreModeFromBranch(ctx);
192
+ updateModeIndicator(ctx);
193
+ });
194
+
195
+ pi.on("session_tree", async (_event, ctx) => {
196
+ restoreModeFromBranch(ctx);
197
+ updateModeIndicator(ctx);
198
+ });
199
+
200
+ pi.on("before_agent_start", (event) => {
201
+ const mode = getActiveMode();
202
+ event.systemPromptOptions.sections[SYSTEM_PROMPT_SECTION] = [
203
+ `## Active SDLC Mode: ${mode.name}`,
204
+ mode.description,
205
+ "",
206
+ mode.instructions,
207
+ "",
208
+ "## Changing SDLC Modes",
209
+ "Use sdlc_set_mode only when the user explicitly requests a mode change or clearly authorizes moving to that phase.",
210
+ "Do not switch merely because another mode seems useful. If the user's intent is unclear, ask and wait for confirmation.",
211
+ ].join("\n");
212
+ });
213
+ }
package/mode-config.ts ADDED
@@ -0,0 +1,124 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import { Key, type KeyId } from "@earendil-works/pi-tui";
5
+ import { Type, type Static } from "typebox";
6
+ import { Value } from "typebox/value";
7
+
8
+ const EXTENSION_DIRECTORY = "pi-sdlc-modes";
9
+ const CONFIG_FILE = "config.json";
10
+
11
+ const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
12
+ const BASE_KEYS: Set<string> = new Set(Object.values(Key).filter((key) => typeof key === "string"));
13
+
14
+ function isKeyId(value: unknown): value is KeyId {
15
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) return false;
16
+ if (value === "+") return true;
17
+
18
+ const isPlusKey = value.endsWith("++");
19
+ const keySeparator = value.lastIndexOf("+");
20
+ const prefix = isPlusKey ? value.slice(0, -2) : keySeparator === -1 ? "" : value.slice(0, keySeparator);
21
+ const key = isPlusKey ? "+" : keySeparator === -1 ? value : value.slice(keySeparator + 1);
22
+ const modifiers = prefix.length === 0 ? [] : prefix.split("+");
23
+
24
+ if (!BASE_KEYS.has(key) && !/^[a-z0-9]$/.test(key)) return false;
25
+ if (modifiers.length > 4 || modifiers.some((modifier) => !MODIFIERS.has(modifier))) return false;
26
+ return new Set(modifiers).size === modifiers.length;
27
+ }
28
+
29
+ const NonblankStringSchema = Type.Refine(Type.String(), (value) => value.trim().length > 0);
30
+ const ModeIdSchema = Type.Refine(Type.String(), (value) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value));
31
+ const CycleShortcutSchema = Type.Refine(Type.Unsafe<KeyId>(Type.String()), isKeyId);
32
+
33
+ export const ModeDefinitionSchema = Type.Object({
34
+ id: ModeIdSchema,
35
+ name: NonblankStringSchema,
36
+ description: NonblankStringSchema,
37
+ instructions: NonblankStringSchema,
38
+ });
39
+
40
+ const ModesSchema = Type.Array(ModeDefinitionSchema, { minItems: 1 });
41
+
42
+ export const ModeConfigSchema = Type.Refine(
43
+ Type.Object({
44
+ cycleShortcut: CycleShortcutSchema,
45
+ initialMode: ModeIdSchema,
46
+ modes: ModesSchema,
47
+ }),
48
+ (config) => {
49
+ const ids = new Set(config.modes.map((mode) => mode.id));
50
+ const names = new Set(config.modes.map((mode) => mode.name.trim().toLowerCase()));
51
+ return ids.size === config.modes.length && names.size === config.modes.length && ids.has(config.initialMode);
52
+ },
53
+ );
54
+
55
+ export const ModeStateEntrySchema = Type.Object({
56
+ modeId: Type.String(),
57
+ modeName: Type.String(),
58
+ description: Type.String(),
59
+ changedAt: Type.Number(),
60
+ });
61
+
62
+ export type ModeDefinition = Static<typeof ModeDefinitionSchema>;
63
+ export type SdlcConfig = Static<typeof ModeConfigSchema>;
64
+ export type ModeStateEntry = Static<typeof ModeStateEntrySchema>;
65
+
66
+ function cleanConfig(value: SdlcConfig): SdlcConfig {
67
+ return {
68
+ cycleShortcut: value.cycleShortcut,
69
+ initialMode: value.initialMode,
70
+ modes: value.modes.map((mode) => ({
71
+ id: mode.id,
72
+ name: mode.name.trim(),
73
+ description: mode.description.trim(),
74
+ instructions: mode.instructions.trim(),
75
+ })),
76
+ };
77
+ }
78
+
79
+ function readBundledConfig(): SdlcConfig {
80
+ let parsed: unknown;
81
+ try {
82
+ parsed = JSON.parse(readFileSync(new URL("./DEFAULTS.json", import.meta.url), "utf8"));
83
+ } catch (error) {
84
+ throw new Error(`Could not read bundled DEFAULTS.json: ${String(error)}`);
85
+ }
86
+
87
+ if (!Value.Check(ModeConfigSchema, parsed)) {
88
+ throw new Error("Invalid bundled DEFAULTS.json: it does not satisfy the SDLC configuration schema.");
89
+ }
90
+ return cleanConfig(parsed);
91
+ }
92
+
93
+ export const DEFAULT_CONFIG = readBundledConfig();
94
+
95
+ function isMissingFile(error: unknown): boolean {
96
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
97
+ }
98
+
99
+ export function loadConfig(): SdlcConfig {
100
+ const configPath = join(getAgentDir(), "extensions", EXTENSION_DIRECTORY, CONFIG_FILE);
101
+ let contents: string;
102
+ try {
103
+ contents = readFileSync(configPath, "utf8");
104
+ } catch (error) {
105
+ if (!isMissingFile(error)) {
106
+ console.warn(`[pi-sdlc-modes] Could not read ${configPath}; using bundled defaults. ${String(error)}`);
107
+ }
108
+ return DEFAULT_CONFIG;
109
+ }
110
+
111
+ let parsed: unknown;
112
+ try {
113
+ parsed = JSON.parse(contents);
114
+ } catch (error) {
115
+ console.warn(`[pi-sdlc-modes] Invalid JSON in ${configPath}; using bundled defaults. ${String(error)}`);
116
+ return DEFAULT_CONFIG;
117
+ }
118
+
119
+ if (!Value.Check(ModeConfigSchema, parsed)) {
120
+ console.warn(`[pi-sdlc-modes] Invalid configuration in ${configPath}; using bundled defaults.`);
121
+ return DEFAULT_CONFIG;
122
+ }
123
+ return cleanConfig(parsed);
124
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@jackjtaylor/pi-sdlc-modes",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Guide Pi through the Software Development Lifecycle (SDLC) with customisable modes.",
5
+ "type": "module",
6
+ "scripts": {
7
+ "test": "node --test",
8
+ "lint": "eslint .",
9
+ "format": "prettier --write .",
10
+ "format:check": "prettier --check ."
11
+ },
12
+ "keywords": [
13
+ "pi-package"
14
+ ],
15
+ "files": [
16
+ "index.ts",
17
+ "mode-config.ts",
18
+ "DEFAULTS.json",
19
+ "README.md"
20
+ ],
21
+ "peerDependencies": {
22
+ "@earendil-works/pi-coding-agent": "*",
23
+ "@earendil-works/pi-tui": "*",
24
+ "typebox": "*"
25
+ },
26
+ "pi": {
27
+ "extensions": [
28
+ "./index.ts"
29
+ ]
30
+ },
31
+ "devDependencies": {
32
+ "@eslint/js": "^9.39.5",
33
+ "eslint": "^9.39.5",
34
+ "eslint-config-prettier": "^10.1.8",
35
+ "globals": "^17.14.0",
36
+ "prettier": "^3.9.10",
37
+ "typescript": "^6.0.3",
38
+ "typescript-eslint": "^8.72.1"
39
+ }
40
+ }