@jackjtaylor/pi-sdlc-modes 0.0.0-stage → 0.2.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,54 @@
1
+ {
2
+ "cycleShortcut": "ctrl+shift+m",
3
+ "initialMode": "explore",
4
+ "modes": [
5
+ {
6
+ "id": "explore",
7
+ "name": "Explore and Explain",
8
+ "description": "Research and explain a topic, technology, system, or change to build understanding.",
9
+ "instructions": "Research and explain topics, technologies, stacks, code, systems, or changes to help the user understand them. Choose appropriate sources, check version-sensitive or current claims where relevant, cite evidence, and distinguish verified facts from assumptions. For systems, explain their purpose, entry points, main components, and how data and control flow between them. For changes or pull requests, inspect the available description and relevant context, then explain what changed, how it works, why, and what it affects in a logical order. Cite relevant files or symbols, use a diagram when it clarifies the flow, and start with a focused overview before going deeper on request. Understanding is the goal: do not evaluate options, recommend a solution, hunt for issues, or propose fixes unless asked. If you notice a significant concern, briefly flag it and suggest review when appropriate. For bug reports, describe the behavior and symptoms without diagnosing causes or proposing fixes unless asked. Do not edit code or post comments unless requested. 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": "Define Specification and Acceptance Criteria",
14
+ "description": "Define the problem, users, scope, expected behavior, and observable acceptance criteria for a change.",
15
+ "instructions": "Define a specification and observable acceptance criteria with the user, starting with the problem, intended users, desired outcome, constraints, and what is in and out of scope. Inspect existing behavior when useful to ground the discussion. Ask focused questions about unclear behavior, including relevant edge, empty, permission, error, and recovery cases; do not guess unresolved answers. Consider who will use the feature and how its impact can be measured. Favor work close to the mission and work that repairs user trust; avoid jumping between unused features that add tech debt and limit future options. Summarise the agreement as user stories and observable acceptance criteria, with success measures where practical and any open assumptions. 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 a Solution",
20
+ "description": "Compare approaches, design a solution, and produce an actionable implementation and verification plan for approval.",
21
+ "instructions": "Design a solution and create an actionable plan against the agreed criteria. If important criteria are unclear, clarify them with the user. Inspect relevant code and compare feasible approaches in proportion to the decision. Explain the recommended design, trade-offs, risks, compatibility, and any relevant migration or rollout effects, and confirm the direction with the user. Provide an ordered plan naming files, relevant locations, intended changes, and verification steps, with concrete code or signatures when useful. Include appropriate tests, observability, reliability, and underlying plumbing, as well as relevant rollout or rollback steps and open questions. Weigh tech debt, pipeline work, and new features against each other; do not add unused features. Do not implement or edit project code in this mode; writing a plan document is allowed. Obtain approval before building when required."
22
+ },
23
+ {
24
+ "id": "build-and-test",
25
+ "name": "Build and Test Changes",
26
+ "description": "Implement the requested or approved change, add appropriate tests, and run relevant checks.",
27
+ "instructions": "Build and test the requested or approved change within the agreed scope. Follow repository conventions, keep the diff focused, and preserve unrelated user changes. If a material change to the agreed scope or approach is needed, discuss it with the user. Add or update relevant tests, build in appropriate observability and reliability, and run the applicable checks; fix failures caused by your changes and report checks that could not run. When a suitable subagent or CLI-based Pi route is available, delegate bounded tasks that avoid conflicting edits, tell child agents not to delegate further, then coordinate, integrate, and verify their work. Otherwise work directly and do not claim delegation. Leave time for verification and judgement. Summarise what changed, the checks performed, and any remaining risks."
28
+ },
29
+ {
30
+ "id": "review",
31
+ "name": "Find Issues and Risks (Review)",
32
+ "description": "Critically review code or changes to identify substantiated, actionable issues, bugs, risks, and gaps.",
33
+ "instructions": "Independently review code or changes for actionable issues and misalignment with the intended goals. Establish the intent from available context, then inspect the diff and relevant surrounding code, callers, contracts, and tests. Consider correctness, regressions, edge cases, security, compatibility, performance, and relevant testing, observability, reliability, and rollout gaps. Consider whether new features are likely to be used. Verify candidate findings against the code; do not present speculation as fact. Report significant findings first, ordered by severity, with a precise file and location, evidence, concrete impact, and a suggested fix when useful. Provide enough context for a reader unfamiliar with the changes and distinguish known reasons from assumptions. If no significant issues are found, say so and note remaining uncertainties or coverage gaps. Use subagents for bounded, independent review when available; otherwise review directly and never claim delegation. Do not change code or submit a review unless the user asks."
34
+ },
35
+ {
36
+ "id": "release",
37
+ "name": "Prepare and Release Changes",
38
+ "description": "Assess release readiness, prepare a safe rollout and rollback, and carry out approved release actions.",
39
+ "instructions": "Prepare changes for release and help carry out the rollout safely. Assess readiness against available evidence, including relevant checks, approvals, dependencies, configuration, migrations, flags, and compatibility. Summarise readiness, blockers, and what could not be checked; do not claim readiness without evidence. Prepare ordered rollout, verification, monitoring, and rollback or roll-forward steps appropriate to the change. Explain consequential actions and their effects, and deploy, alter production, or take another consequential release action only with explicit approval and required human checkpoints. Stop and report unexpected results. After shipping, suggest monitoring and hold a short mini-retro to consider whether the next work should be tech debt, pipeline and reliability work, or a new feature. Check whether shipped features are actually used, and avoid placing features on prominent surfaces just to make them visible."
40
+ },
41
+ {
42
+ "id": "monitor",
43
+ "name": "Monitor Release, Analyze Logs",
44
+ "description": "Monitor release or system health and adoption using available logs, metrics, traces, alerts, and other signals.",
45
+ "instructions": "Assess whether a release, change, or system is healthy and working as intended. Establish the time window, affected services, expected behavior, and an appropriate baseline where possible. Analyze available logs, metrics, traces, alerts, and relevant usage or adoption signals. Report the observed status, signals checked, trends or anomalies compared with the baseline, potential user impact, and access or coverage gaps; include numbers and time windows where available. Cite evidence and distinguish observations and correlations from hypotheses. Recommend whether to keep watching, investigate a possible bug, or consider rollback; do not claim a root cause without evidence. Do not imply access to unavailable systems or expose secrets or unnecessary personal data. Do not change code, production, monitoring configuration, or issue states unless the user asks and any required approval is given."
46
+ },
47
+ {
48
+ "id": "debug",
49
+ "name": "Diagnose and Fix Bugs (Debug)",
50
+ "description": "Investigate a failure, identify its cause using evidence, and make and verify a fix when requested.",
51
+ "instructions": "Diagnose a bug using code, logs, and other available evidence, and fix it when the user asks. Clarify expected versus observed behavior and scope, then try to reproduce the failure before fixing it. If reproduction is unavailable, state the limitation and evidence needed. Test hypotheses methodically, separating confirmed facts from assumptions; establish the root cause before making a fix. Change one thing at a time and check the result, cleaning up failed experiments without disturbing unrelated work. When a fix is requested, make the smallest logical change that addresses the cause, and add a regression test or other verification where practical. Report the diagnosis, supporting evidence, changes, checks, and unresolved uncertainty. If the fix requires a broader design decision, discuss it with the user. Do not imply access to unavailable systems or expose secrets or unnecessary personal data. Do not change code or systems unless the user has asked you to fix the issue."
52
+ }
53
+ ]
54
+ }
package/README.md CHANGED
@@ -1,3 +1,49 @@
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 package 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
+ ## Select Modes
14
+
15
+ - Press `Ctrl+Shift+M` to cycle through the modes (or configure another shortcut).
16
+ - Run `/sdlc` to choose a mode from the interactive picker.
17
+ - Run `/sdlc off` to disable the extension for this session, or `/sdlc on` to re-enable the extension. The extension is enabled for new sessions by default.
18
+
19
+ 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.
20
+
21
+ When the extension is off, Pi won't be able to change modes, and it won't see any system prompt info or context about the extension. If you re-enable the extension, the tool will be available again for Pi to use, and it'll see context about the selected mode.
22
+
23
+ ### Start Sessions in a Mode
24
+
25
+ You can set flags when starting Pi, for example, with a subagent.
26
+
27
+ ```bash
28
+ pi -p --sdlc-mode build-and-test "Please read the plan and..."
29
+ pi -p --sdlc-off "Please answer my question..."
30
+ ```
31
+
32
+ - `--sdlc-mode <id>` starts a new session in that mode.
33
+ - `--sdlc-off` starts a new session with the extension disabled.
34
+
35
+ The flags apply only to new sessions. If you resume a session, it'll keep its mode and enabled or disabled state.
36
+
37
+ ## Configure
38
+
39
+ The defaults are in `DEFAULTS.json`.
40
+ To customise the modes or shortcut, create `~/.pi/agent/extensions/pi-sdlc-modes/config.json` and use the same schema as in `DEFAULTS.json`.
41
+ If you find a better prompt or a mode that would be useful, please let me know!
42
+
43
+ ## Security
44
+
45
+ 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.
46
+
47
+ ## Stability
48
+
49
+ As this is a very early version, I'm actively developing and changing this, so it's possible in the future some of the tools or modes may change. If so, you should be able to ask Pi and it'll help update your workflows or configuration accordingly.
package/index.ts ADDED
@@ -0,0 +1,331 @@
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 "./modeConfig.ts";
6
+
7
+ const STATE_ENTRY_TYPE = "sdlc-mode-state";
8
+ const ENABLED_STATE_ENTRY_TYPE = "sdlc-mode-enabled-state";
9
+ const WIDGET_ID = "sdlc-mode";
10
+ const SYSTEM_PROMPT_SECTION = "sdlc_mode";
11
+ const SET_MODE_TOOL_NAME = "sdlc_set_mode";
12
+ const EnabledStateEntrySchema = Type.Object({
13
+ enabled: Type.Boolean(),
14
+ changedAt: Type.Number(),
15
+ });
16
+ type EnabledStateEntry = { enabled: boolean; changedAt: number };
17
+
18
+ export default function sdlcModesExtension(pi: ExtensionAPI): void {
19
+ const config = loadConfig();
20
+ let activeModeId = config.initialMode;
21
+ let sdlcEnabled = true;
22
+ // The tool list from --tools is process-wide, so exclusion is decided once, on the first
23
+ // session start, before SDLC has touched the tools. Later sessions reuse that decision.
24
+ let modeToolExclusionChecked = false;
25
+ let modeToolExcludedByUser = false;
26
+
27
+ const firstConfiguredMode = config.modes[0];
28
+ if (!firstConfiguredMode) throw new Error("SDLC configuration must contain at least one mode.");
29
+
30
+ const getActiveMode = (): ModeDefinition =>
31
+ config.modes.find((mode) => mode.id === activeModeId) ?? firstConfiguredMode;
32
+
33
+ const restoreModeFromBranch = (ctx: ExtensionContext): void => {
34
+ const entries = ctx.sessionManager.getBranch();
35
+ for (let index = entries.length - 1; index >= 0; index--) {
36
+ const entry = entries[index];
37
+ if (!entry || entry.type !== "custom" || entry.customType !== STATE_ENTRY_TYPE) continue;
38
+ const stateData: unknown = entry.data;
39
+ if (!Value.Check(ModeStateEntrySchema, stateData)) continue;
40
+ if (config.modes.some((mode) => mode.id === stateData.modeId)) {
41
+ activeModeId = stateData.modeId;
42
+ return;
43
+ }
44
+ }
45
+ activeModeId = config.initialMode;
46
+ };
47
+
48
+ const restoreEnabledStateFromBranch = (ctx: ExtensionContext): void => {
49
+ const entries = ctx.sessionManager.getBranch();
50
+ for (let index = entries.length - 1; index >= 0; index--) {
51
+ const entry = entries[index];
52
+ if (!entry || entry.type !== "custom" || entry.customType !== ENABLED_STATE_ENTRY_TYPE) continue;
53
+ const stateData: unknown = entry.data;
54
+ if (!Value.Check(EnabledStateEntrySchema, stateData)) continue;
55
+ sdlcEnabled = stateData.enabled;
56
+ return;
57
+ }
58
+ sdlcEnabled = true;
59
+ };
60
+
61
+ const updateModeIndicator = (ctx: ExtensionContext): void => {
62
+ if (!sdlcEnabled) {
63
+ ctx.ui.setWidget(WIDGET_ID, undefined);
64
+ ctx.ui.setStatus(WIDGET_ID, undefined);
65
+ return;
66
+ }
67
+ const mode = getActiveMode();
68
+ if (ctx.mode === "tui") {
69
+ ctx.ui.setWidget(
70
+ WIDGET_ID,
71
+ (_tui, theme) =>
72
+ new Text(
73
+ `${theme.fg("accent", theme.bold(`SDLC · ${mode.name}`))} ${theme.fg("dim", `[${config.cycleShortcut}]`)}\n${theme.fg("muted", mode.description)}`,
74
+ 0,
75
+ 0,
76
+ ),
77
+ );
78
+ ctx.ui.setStatus(WIDGET_ID, undefined);
79
+ return;
80
+ }
81
+ if (ctx.hasUI) {
82
+ ctx.ui.setStatus(WIDGET_ID, `SDLC · ${mode.name} — ${mode.description}`);
83
+ }
84
+ };
85
+
86
+ const changeMode = (
87
+ modeId: string,
88
+ ctx: ExtensionContext,
89
+ ): { kind: "changed" | "already-active" | "unknown"; message: string } => {
90
+ const mode = config.modes.find((candidate) => candidate.id === modeId);
91
+ if (!mode) return { kind: "unknown", message: `Unknown SDLC mode: ${modeId}` };
92
+ if (activeModeId === mode.id) return { kind: "already-active", message: `Already in ${mode.name}.` };
93
+
94
+ activeModeId = mode.id;
95
+ pi.appendEntry<ModeStateEntry>(STATE_ENTRY_TYPE, {
96
+ modeId: mode.id,
97
+ modeName: mode.name,
98
+ description: mode.description,
99
+ changedAt: Date.now(),
100
+ });
101
+ updateModeIndicator(ctx);
102
+ return { kind: "changed", message: `Switched to ${mode.name}.` };
103
+ };
104
+
105
+ const setMode = (modeId: string, ctx: ExtensionContext): void => {
106
+ const result = changeMode(modeId, ctx);
107
+ if (result.kind !== "changed") {
108
+ ctx.ui.notify(result.message, result.kind === "unknown" ? "error" : "info");
109
+ }
110
+ };
111
+
112
+ const cycleMode = (ctx: ExtensionContext): void => {
113
+ if (!sdlcEnabled) return;
114
+ const activeIndex = config.modes.findIndex((mode) => mode.id === activeModeId);
115
+ const nextMode = config.modes[(activeIndex + 1 + config.modes.length) % config.modes.length] ?? firstConfiguredMode;
116
+ setMode(nextMode.id, ctx);
117
+ };
118
+
119
+ const hasSdlcHistory = (ctx: ExtensionContext): boolean =>
120
+ ctx.sessionManager
121
+ .getBranch()
122
+ .some(
123
+ (entry) =>
124
+ entry.type === "custom" &&
125
+ (entry.customType === STATE_ENTRY_TYPE || entry.customType === ENABLED_STATE_ENTRY_TYPE),
126
+ );
127
+
128
+ const updateModeToolExclusion = (): void => {
129
+ if (modeToolExclusionChecked) return;
130
+ modeToolExclusionChecked = true;
131
+ // Inactive is not the same as excluded: a resumed branch may have turned SDLC off.
132
+ // getAllTools omits tools filtered out by --tools / --exclude-tools.
133
+ modeToolExcludedByUser = !pi.getAllTools().some((tool) => tool.name === SET_MODE_TOOL_NAME);
134
+ };
135
+
136
+ // --sdlc-mode and --sdlc-off set the starting state of a new session only. Resumed or
137
+ // branched sessions keep their saved state. The chosen values are recorded in the session.
138
+ // A startup error (an unknown --sdlc-mode) is kept and blocks every prompt. Pi has no
139
+ // startup abort, and ctx.shutdown() is a no-op in print mode, so input is refused instead.
140
+ let startupError: string | undefined;
141
+
142
+ const applyStartupFlags = (ctx: ExtensionContext): void => {
143
+ startupError = undefined;
144
+ if (hasSdlcHistory(ctx)) return;
145
+
146
+ const requestedModeId = pi.getFlag("sdlc-mode");
147
+ if (typeof requestedModeId === "string" && requestedModeId.length > 0) {
148
+ const requestedMode = config.modes.find((mode) => mode.id === requestedModeId);
149
+ if (!requestedMode) {
150
+ const availableModes = config.modes.map((mode) => mode.id).join(", ");
151
+ startupError = `Unknown SDLC mode "${requestedModeId}" for --sdlc-mode. Available: ${availableModes}.`;
152
+ ctx.ui.notify(startupError, "error");
153
+ return;
154
+ }
155
+ activeModeId = requestedMode.id;
156
+ pi.appendEntry<ModeStateEntry>(STATE_ENTRY_TYPE, {
157
+ modeId: requestedMode.id,
158
+ modeName: requestedMode.name,
159
+ description: requestedMode.description,
160
+ changedAt: Date.now(),
161
+ });
162
+ }
163
+
164
+ if (pi.getFlag("sdlc-off") === true) {
165
+ sdlcEnabled = false;
166
+ pi.appendEntry<EnabledStateEntry>(ENABLED_STATE_ENTRY_TYPE, { enabled: false, changedAt: Date.now() });
167
+ }
168
+ };
169
+
170
+ // Pi only declares a tool's guidelines to the model while the tool is active, so
171
+ // disabling SDLC also removes the mode-switch tool and its rules from the prompt.
172
+ // A tool the user excluded stays excluded, even when SDLC is on.
173
+ const syncModeToolActivation = (): void => {
174
+ const otherActiveToolNames = pi.getActiveTools().filter((name) => name !== SET_MODE_TOOL_NAME);
175
+ const includeModeTool = sdlcEnabled && !modeToolExcludedByUser;
176
+ pi.setActiveTools(includeModeTool ? [...otherActiveToolNames, SET_MODE_TOOL_NAME] : otherActiveToolNames);
177
+ };
178
+
179
+ const setSdlcEnabled = (enabled: boolean, ctx: ExtensionContext): void => {
180
+ if (sdlcEnabled === enabled) {
181
+ ctx.ui.notify(`SDLC is already ${enabled ? "on" : "off"}.`, "info");
182
+ return;
183
+ }
184
+ sdlcEnabled = enabled;
185
+ syncModeToolActivation();
186
+ pi.appendEntry<EnabledStateEntry>(ENABLED_STATE_ENTRY_TYPE, { enabled, changedAt: Date.now() });
187
+ updateModeIndicator(ctx);
188
+ if (enabled && modeToolExcludedByUser) {
189
+ ctx.ui.notify(`SDLC turned on, but ${SET_MODE_TOOL_NAME} is excluded from the session's tools.`, "warning");
190
+ return;
191
+ }
192
+ ctx.ui.notify(`SDLC turned ${enabled ? "on" : "off"}.`, "info");
193
+ };
194
+
195
+ const selectMode = async (args: string, ctx: ExtensionContext): Promise<void> => {
196
+ const selector = args.trim().toLowerCase();
197
+ if (selector === "on" || selector === "off") {
198
+ setSdlcEnabled(selector === "on", ctx);
199
+ return;
200
+ }
201
+ if (selector.length > 0) {
202
+ ctx.ui.notify("Use /sdlc to choose a mode, or /sdlc on|off to enable or disable SDLC.", "error");
203
+ return;
204
+ }
205
+ if (!ctx.hasUI) {
206
+ ctx.ui.notify(`Current mode: ${getActiveMode().name}. The mode picker requires an interactive UI.`, "info");
207
+ return;
208
+ }
209
+ const selectedName = await ctx.ui.select(
210
+ "Choose an SDLC mode",
211
+ config.modes.map((mode) => mode.name),
212
+ );
213
+ if (!selectedName) return;
214
+ const selectedMode = config.modes.find((mode) => mode.name === selectedName);
215
+ if (selectedMode) setMode(selectedMode.id, ctx);
216
+ };
217
+
218
+ pi.registerEntryRenderer<ModeStateEntry>(STATE_ENTRY_TYPE, (entry, _options, theme) => {
219
+ const data = Value.Check(ModeStateEntrySchema, entry.data) ? entry.data : undefined;
220
+ if (!data) return new Text(theme.fg("dim", "SDLC mode changed"), 0, 0);
221
+ return new Text(theme.fg("dim", `SDLC · ${data.modeName} — ${data.description}`), 0, 0);
222
+ });
223
+
224
+ pi.registerEntryRenderer<EnabledStateEntry>(ENABLED_STATE_ENTRY_TYPE, (entry, _options, theme) => {
225
+ const data = Value.Check(EnabledStateEntrySchema, entry.data) ? entry.data : undefined;
226
+ if (!data) return new Text(theme.fg("dim", "SDLC availability changed"), 0, 0);
227
+ return new Text(theme.fg("dim", `SDLC turned ${data.enabled ? "on" : "off"}`), 0, 0);
228
+ });
229
+
230
+ pi.registerTool({
231
+ name: SET_MODE_TOOL_NAME,
232
+ label: "Set SDLC Mode",
233
+ description:
234
+ "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.",
235
+ promptSnippet: "Change the active SDLC mode only with clear user authorization.",
236
+ promptGuidelines: [
237
+ "Only switch modes when the user explicitly requests the switch or clearly authorizes moving to that phase.",
238
+ "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.",
239
+ ],
240
+ parameters: Type.Object({
241
+ mode: Type.String({
242
+ description: "Configured SDLC mode ID to switch to.",
243
+ enum: config.modes.map((mode) => mode.id),
244
+ }),
245
+ }),
246
+ annotations: { readOnlyHint: false, idempotentHint: true },
247
+ execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
248
+ const result = changeMode(params.mode, ctx);
249
+ return {
250
+ content: [{ type: "text", text: result.message }],
251
+ details: { modeId: params.mode, changed: result.kind === "changed" },
252
+ isError: result.kind === "unknown",
253
+ };
254
+ },
255
+ });
256
+
257
+ pi.registerCommand("sdlc", {
258
+ description: "Choose an SDLC mode or turn SDLC on or off",
259
+ getArgumentCompletions: (prefix) => {
260
+ const choices = [
261
+ { value: "on", label: "on", description: "Enable SDLC for this session" },
262
+ { value: "off", label: "off", description: "Disable SDLC for this session" },
263
+ ];
264
+ const matches = choices.filter((choice) => choice.value.startsWith(prefix.toLowerCase()));
265
+ return matches.length > 0 ? matches : null;
266
+ },
267
+ handler: async (args, ctx) => selectMode(args, ctx),
268
+ });
269
+
270
+ pi.registerFlag("sdlc-mode", {
271
+ description: "Start a new session in this SDLC mode ID",
272
+ type: "string",
273
+ });
274
+
275
+ pi.registerFlag("sdlc-off", {
276
+ description: "Start a new session with SDLC turned off",
277
+ type: "boolean",
278
+ default: false,
279
+ });
280
+
281
+ pi.registerShortcut(config.cycleShortcut, {
282
+ description: "Advance to the next SDLC mode when SDLC is on",
283
+ handler: async (ctx) => cycleMode(ctx),
284
+ });
285
+
286
+ pi.on("session_start", async (_event, ctx) => {
287
+ restoreModeFromBranch(ctx);
288
+ restoreEnabledStateFromBranch(ctx);
289
+ updateModeToolExclusion();
290
+ applyStartupFlags(ctx);
291
+ syncModeToolActivation();
292
+ updateModeIndicator(ctx);
293
+ });
294
+
295
+ pi.on("session_tree", async (_event, ctx) => {
296
+ restoreModeFromBranch(ctx);
297
+ restoreEnabledStateFromBranch(ctx);
298
+ updateModeToolExclusion();
299
+ syncModeToolActivation();
300
+ updateModeIndicator(ctx);
301
+ });
302
+
303
+ pi.on("input", (_event, ctx) => {
304
+ if (startupError === undefined) return { action: "continue" };
305
+ ctx.ui.notify(startupError, "error");
306
+ process.exitCode = 1;
307
+ return { action: "handled" };
308
+ });
309
+
310
+ pi.on("before_agent_start", (event) => {
311
+ if (!sdlcEnabled) {
312
+ delete event.systemPromptOptions.sections[SYSTEM_PROMPT_SECTION];
313
+ return;
314
+ }
315
+ const mode = getActiveMode();
316
+ event.systemPromptOptions.sections[SYSTEM_PROMPT_SECTION] = [
317
+ `## Active SDLC Mode: ${mode.name}`,
318
+ mode.description,
319
+ "",
320
+ mode.instructions,
321
+ "",
322
+ ...(modeToolExcludedByUser
323
+ ? []
324
+ : [
325
+ "## Changing SDLC Modes",
326
+ "Use sdlc_set_mode only when the user explicitly requests a mode change or clearly authorizes moving to that phase.",
327
+ "Do not switch merely because another mode seems useful. If the user's intent is unclear, ask and wait for confirmation.",
328
+ ]),
329
+ ].join("\n");
330
+ });
331
+ }
package/modeConfig.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.2.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
+ "modeConfig.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
+ }