peaks-cli 1.0.21 → 1.0.22

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 (39) hide show
  1. package/dist/src/cli/commands/capability-commands.d.ts +1 -1
  2. package/dist/src/cli/commands/capability-commands.js +2 -5
  3. package/dist/src/cli/commands/config-commands.js +2 -85
  4. package/dist/src/cli/commands/core-artifact-commands.js +6 -1
  5. package/dist/src/cli/commands/request-commands.js +82 -2
  6. package/dist/src/cli/commands/scan-commands.js +30 -0
  7. package/dist/src/cli/commands/workflow-commands.js +9 -5
  8. package/dist/src/services/artifacts/artifact-prerequisites.js +53 -13
  9. package/dist/src/services/artifacts/artifact-service.js +2 -2
  10. package/dist/src/services/artifacts/request-artifact-service.d.ts +32 -0
  11. package/dist/src/services/artifacts/request-artifact-service.js +148 -16
  12. package/dist/src/services/artifacts/workspace-service.js +8 -9
  13. package/dist/src/services/config/config-service.js +54 -69
  14. package/dist/src/services/config/config-types.d.ts +0 -2
  15. package/dist/src/services/config/config-types.js +0 -2
  16. package/dist/src/services/mode/bypass-tracker.d.ts +4 -0
  17. package/dist/src/services/mode/bypass-tracker.js +31 -0
  18. package/dist/src/services/mode/mode-enforcement.d.ts +14 -0
  19. package/dist/src/services/mode/mode-enforcement.js +81 -0
  20. package/dist/src/services/sc/sc-service.js +5 -5
  21. package/dist/src/services/scan/file-size-scan.d.ts +19 -0
  22. package/dist/src/services/scan/file-size-scan.js +44 -0
  23. package/dist/src/services/session/index.d.ts +1 -0
  24. package/dist/src/services/session/index.js +1 -0
  25. package/dist/src/services/session/session-manager.d.ts +60 -0
  26. package/dist/src/services/session/session-manager.js +150 -0
  27. package/dist/src/services/skills/skill-presence-service.d.ts +4 -1
  28. package/dist/src/services/skills/skill-presence-service.js +11 -1
  29. package/dist/src/services/workspace/workspace-service.js +6 -0
  30. package/dist/src/shared/change-id.d.ts +13 -0
  31. package/dist/src/shared/change-id.js +32 -1
  32. package/dist/src/shared/incrementing-number.d.ts +31 -0
  33. package/dist/src/shared/incrementing-number.js +58 -0
  34. package/dist/src/shared/version.d.ts +1 -1
  35. package/dist/src/shared/version.js +1 -1
  36. package/package.json +1 -1
  37. package/skills/peaks-rd/SKILL.md +3 -0
  38. package/skills/peaks-solo/SKILL.md +9 -11
  39. package/skills/peaks-ui/SKILL.md +3 -0
@@ -0,0 +1,81 @@
1
+ import * as readline from 'node:readline';
2
+ import { getSkillPresence } from '../skills/skill-presence-service.js';
3
+ const ASSISTED_CONFIRM_TRANSITIONS = new Set([
4
+ 'prd:confirmed-by-user',
5
+ 'rd:qa-handoff',
6
+ 'qa:verdict-issued'
7
+ ]);
8
+ export function requiresConfirmation(mode, transitionKey) {
9
+ if (mode === 'full-auto' || mode === 'swarm') {
10
+ return false;
11
+ }
12
+ if (mode === 'strict') {
13
+ return true;
14
+ }
15
+ // assisted: only specific transitions
16
+ return ASSISTED_CONFIRM_TRANSITIONS.has(transitionKey);
17
+ }
18
+ function describeTransition(transitionKey) {
19
+ const parts = transitionKey.split(':');
20
+ const role = parts[0] ?? 'unknown';
21
+ const state = parts[1] ?? 'unknown';
22
+ return `Transition ${role.toUpperCase()} → ${state}`;
23
+ }
24
+ export class ConfirmationRequiredError extends Error {
25
+ constructor(transitionKey) {
26
+ const description = describeTransition(transitionKey);
27
+ super(`Confirmation required for: ${description}\n` +
28
+ 'Add --confirm to proceed non-interactively, or run in an interactive terminal.\n' +
29
+ 'In assisted/strict mode, major workflow boundaries require explicit user approval.');
30
+ this.name = 'ConfirmationRequiredError';
31
+ }
32
+ }
33
+ export async function requireUserConfirmation(options) {
34
+ const presence = getSkillPresence();
35
+ if (!presence?.mode) {
36
+ return;
37
+ }
38
+ const mode = presence.mode;
39
+ if (!requiresConfirmation(mode, options.transitionKey)) {
40
+ return;
41
+ }
42
+ // --confirm flag bypasses interactive prompt
43
+ if (options.confirmed) {
44
+ return;
45
+ }
46
+ // PEAKS_AUTO_CONFIRM=1 only works for full-auto/swarm (already returned above)
47
+ // For assisted/strict, env var is ignored unless --force-confirm is also set
48
+ if (process.env.PEAKS_AUTO_CONFIRM === '1') {
49
+ if (options.forceConfirm) {
50
+ console.error(`[WARNING] --force-confirm used in ${mode} mode. ` +
51
+ 'This bypasses user confirmation. Use with caution.');
52
+ return;
53
+ }
54
+ throw new ConfirmationRequiredError(options.transitionKey);
55
+ }
56
+ // --force-confirm without env var
57
+ if (options.forceConfirm) {
58
+ console.error(`[WARNING] --force-confirm used in ${mode} mode. ` +
59
+ 'This bypasses user confirmation. Use with caution.');
60
+ return;
61
+ }
62
+ // Interactive prompt
63
+ const rl = readline.createInterface({
64
+ input: process.stdin,
65
+ output: process.stderr
66
+ });
67
+ return new Promise((resolve, reject) => {
68
+ const description = describeTransition(options.transitionKey);
69
+ const prompt = `\n[CONFIRM] ${description}\nProceed? (y/N) `;
70
+ rl.question(prompt, (answer) => {
71
+ rl.close();
72
+ const normalized = answer.trim().toLowerCase();
73
+ if (normalized === 'y' || normalized === 'yes') {
74
+ resolve();
75
+ }
76
+ else {
77
+ reject(new ConfirmationRequiredError(options.transitionKey));
78
+ }
79
+ });
80
+ });
81
+ }
@@ -2,7 +2,7 @@ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
2
2
  import { execFileSync } from 'node:child_process';
3
3
  import { basename, relative, resolve } from 'node:path';
4
4
  import { isInsidePath } from '../../shared/path-utils.js';
5
- import { getCurrentWorkspaceConfig } from '../config/config-service.js';
5
+ import { getWorkspaceConfigForPath } from '../config/config-service.js';
6
6
  import { getArtifactRemoteRepo, getArtifactWorkspaceStatus, getLocalArtifactPath } from '../artifacts/workspace-service.js';
7
7
  const REQUIRED_ARTIFACTS = [
8
8
  { name: 'retention-boundary.md', path: ['sc', 'retention-boundary.md'] },
@@ -109,7 +109,7 @@ function isRetainedArtifactFile(filePath, artifactWorkspacePath, changesRoot, ch
109
109
  }
110
110
  }
111
111
  export function getChangeTraceabilityStatus() {
112
- const workspace = getCurrentWorkspaceConfig();
112
+ const workspace = getWorkspaceConfigForPath(process.cwd());
113
113
  const artifactStatus = getArtifactWorkspaceStatus(workspace?.workspaceId);
114
114
  if (!workspace) {
115
115
  return {
@@ -155,7 +155,7 @@ export function getChangeTraceabilityStatus() {
155
155
  };
156
156
  }
157
157
  export function createChangeImpact(options) {
158
- const workspace = getCurrentWorkspaceConfig();
158
+ const workspace = getWorkspaceConfigForPath(process.cwd());
159
159
  const artifactRepo = workspace ? getArtifactRemoteRepo(workspace) : null;
160
160
  return {
161
161
  changeId: options.changeId,
@@ -193,7 +193,7 @@ export function createArtifactRetentionReport(options) {
193
193
  };
194
194
  }
195
195
  export function recordCommitBoundary(options) {
196
- const workspace = getCurrentWorkspaceConfig();
196
+ const workspace = getWorkspaceConfigForPath(process.cwd());
197
197
  const artifactStatus = getArtifactWorkspaceStatus(workspace?.workspaceId);
198
198
  const commitHash = getCurrentCommitHash(workspace?.rootPath);
199
199
  return {
@@ -207,7 +207,7 @@ export function recordCommitBoundary(options) {
207
207
  };
208
208
  }
209
209
  export function validateArtifactRetention(sliceId) {
210
- const workspace = getCurrentWorkspaceConfig();
210
+ const workspace = getWorkspaceConfigForPath(process.cwd());
211
211
  if (!workspace) {
212
212
  return {
213
213
  valid: false,
@@ -0,0 +1,19 @@
1
+ export declare const DEFAULT_FILE_SIZE_THRESHOLD = 800;
2
+ export type FileSizeViolation = {
3
+ file: string;
4
+ lines: number;
5
+ };
6
+ export type FileSizeScanResult = {
7
+ ok: boolean;
8
+ threshold: number;
9
+ checkedFiles: number;
10
+ violations: FileSizeViolation[];
11
+ };
12
+ export type FileSizeScanOptions = {
13
+ projectRoot: string;
14
+ /** Compare working tree against this ref. Default 'HEAD'. */
15
+ baseRef?: string;
16
+ /** Line count threshold. Default 800. */
17
+ threshold?: number;
18
+ };
19
+ export declare function scanFileSize(options: FileSizeScanOptions): FileSizeScanResult;
@@ -0,0 +1,44 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ export const DEFAULT_FILE_SIZE_THRESHOLD = 800;
5
+ function getChangedFiles(projectRoot, baseRef) {
6
+ try {
7
+ const trackedRaw = execFileSync('git', ['-C', projectRoot, 'diff', '--name-only', baseRef], { encoding: 'utf8' });
8
+ const tracked = trackedRaw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
9
+ const untrackedRaw = execFileSync('git', ['-C', projectRoot, 'ls-files', '--others', '--exclude-standard'], { encoding: 'utf8' });
10
+ const untracked = untrackedRaw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
11
+ return Array.from(new Set([...tracked, ...untracked]));
12
+ }
13
+ catch {
14
+ return [];
15
+ }
16
+ }
17
+ function countLines(filePath) {
18
+ try {
19
+ const content = readFileSync(filePath, 'utf8');
20
+ return content.split(/\r?\n/).length;
21
+ }
22
+ catch {
23
+ return 0;
24
+ }
25
+ }
26
+ export function scanFileSize(options) {
27
+ const baseRef = options.baseRef ?? 'HEAD';
28
+ const threshold = options.threshold ?? DEFAULT_FILE_SIZE_THRESHOLD;
29
+ const files = getChangedFiles(options.projectRoot, baseRef);
30
+ const violations = [];
31
+ for (const file of files) {
32
+ const absolute = join(options.projectRoot, file);
33
+ const lines = countLines(absolute);
34
+ if (lines > threshold) {
35
+ violations.push({ file, lines });
36
+ }
37
+ }
38
+ return {
39
+ ok: violations.length === 0,
40
+ threshold,
41
+ checkedFiles: files.length,
42
+ violations
43
+ };
44
+ }
@@ -0,0 +1 @@
1
+ export { ensureSession, getSessionId, getCurrentSessionDir, listSessions, getProjectScanPath, hasProjectScan, type SessionInfo } from './session-manager.js';
@@ -0,0 +1 @@
1
+ export { ensureSession, getSessionId, getCurrentSessionDir, listSessions, getProjectScanPath, hasProjectScan } from './session-manager.js';
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Session management service for Peaks artifact storage.
3
+ * Manages session lifecycle: creation, retrieval, and directory initialization.
4
+ *
5
+ * Sessions are automatically created when any skill is invoked.
6
+ * Each session gets a unique directory under .peaks/ with incrementing numbered files.
7
+ */
8
+ export type SessionInfo = {
9
+ sessionId: string;
10
+ createdAt: string;
11
+ projectRoot: string;
12
+ };
13
+ /**
14
+ * Get or create the current session for a project.
15
+ * If a valid session already exists, returns it.
16
+ * Otherwise, creates a new session with auto-generated ID.
17
+ *
18
+ * @param projectRoot - Root directory of the project
19
+ * @returns Session ID (e.g., "2026-05-26-session-a3f8b1")
20
+ */
21
+ export declare function ensureSession(projectRoot: string): Promise<string>;
22
+ /**
23
+ * Get the current session ID without creating a new one.
24
+ * Returns null if no session exists.
25
+ *
26
+ * @param projectRoot - Root directory of the project
27
+ * @returns Session ID or null
28
+ */
29
+ export declare function getSessionId(projectRoot: string): string | null;
30
+ /**
31
+ * Get the absolute path to the current session directory.
32
+ * Creates the session if it doesn't exist.
33
+ *
34
+ * @param projectRoot - Root directory of the project
35
+ * @returns Absolute path to session directory (e.g., "/path/to/project/.peaks/2026-05-26-session-a3f8b1")
36
+ */
37
+ export declare function getCurrentSessionDir(projectRoot: string): Promise<string>;
38
+ /**
39
+ * List all session directories in the .peaks folder.
40
+ * Returns session IDs (directory names) sorted by date.
41
+ *
42
+ * @param projectRoot - Root directory of the project
43
+ * @returns Array of session IDs
44
+ */
45
+ export declare function listSessions(projectRoot: string): string[];
46
+ /**
47
+ * Get the path to project-scan.md for the current session.
48
+ * Creates the session if it doesn't exist.
49
+ *
50
+ * @param projectRoot - Root directory of the project
51
+ * @returns Absolute path to project-scan.md
52
+ */
53
+ export declare function getProjectScanPath(projectRoot: string): Promise<string>;
54
+ /**
55
+ * Check if project-scan.md exists for the current session.
56
+ *
57
+ * @param projectRoot - Root directory of the project
58
+ * @returns true if project-scan.md exists
59
+ */
60
+ export declare function hasProjectScan(projectRoot: string): boolean;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Session management service for Peaks artifact storage.
3
+ * Manages session lifecycle: creation, retrieval, and directory initialization.
4
+ *
5
+ * Sessions are automatically created when any skill is invoked.
6
+ * Each session gets a unique directory under .peaks/ with incrementing numbered files.
7
+ */
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { randomBytes } from 'node:crypto';
11
+ import { initWorkspace } from '../workspace/workspace-service.js';
12
+ const SESSION_FILE = '.session.json';
13
+ /**
14
+ * Generate a new session ID.
15
+ * Format: YYYY-MM-DD-session-<6位hex>
16
+ * Example: 2026-05-26-session-a3f8b1
17
+ */
18
+ function generateSessionId() {
19
+ const now = new Date();
20
+ const year = now.getFullYear();
21
+ const month = String(now.getMonth() + 1).padStart(2, '0');
22
+ const day = String(now.getDate()).padStart(2, '0');
23
+ const date = `${year}-${month}-${day}`;
24
+ const random = randomBytes(3).toString('hex'); // 6位hex
25
+ return `${date}-session-${random}`;
26
+ }
27
+ /**
28
+ * Get the path to the session file for a project.
29
+ */
30
+ function getSessionFilePath(projectRoot) {
31
+ return join(projectRoot, '.peaks', SESSION_FILE);
32
+ }
33
+ /**
34
+ * Read existing session info from disk.
35
+ * Returns null if no session file exists or if it's invalid.
36
+ */
37
+ function readSessionFile(projectRoot) {
38
+ const sessionFile = getSessionFilePath(projectRoot);
39
+ if (!existsSync(sessionFile))
40
+ return null;
41
+ try {
42
+ const data = JSON.parse(readFileSync(sessionFile, 'utf8'));
43
+ if (data.sessionId && data.projectRoot === projectRoot) {
44
+ return data;
45
+ }
46
+ return null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ /**
53
+ * Write session info to disk.
54
+ */
55
+ function writeSessionFile(projectRoot, info) {
56
+ const sessionFile = getSessionFilePath(projectRoot);
57
+ const dir = join(projectRoot, '.peaks');
58
+ if (!existsSync(dir)) {
59
+ mkdirSync(dir, { recursive: true });
60
+ }
61
+ writeFileSync(sessionFile, JSON.stringify(info, null, 2), 'utf8');
62
+ }
63
+ /**
64
+ * Get or create the current session for a project.
65
+ * If a valid session already exists, returns it.
66
+ * Otherwise, creates a new session with auto-generated ID.
67
+ *
68
+ * @param projectRoot - Root directory of the project
69
+ * @returns Session ID (e.g., "2026-05-26-session-a3f8b1")
70
+ */
71
+ export async function ensureSession(projectRoot) {
72
+ const existing = readSessionFile(projectRoot);
73
+ if (existing) {
74
+ return existing.sessionId;
75
+ }
76
+ const sessionId = generateSessionId();
77
+ const info = {
78
+ sessionId,
79
+ createdAt: new Date().toISOString(),
80
+ projectRoot
81
+ };
82
+ writeSessionFile(projectRoot, info);
83
+ await initWorkspace({ projectRoot, sessionId });
84
+ return sessionId;
85
+ }
86
+ /**
87
+ * Get the current session ID without creating a new one.
88
+ * Returns null if no session exists.
89
+ *
90
+ * @param projectRoot - Root directory of the project
91
+ * @returns Session ID or null
92
+ */
93
+ export function getSessionId(projectRoot) {
94
+ const info = readSessionFile(projectRoot);
95
+ return info?.sessionId ?? null;
96
+ }
97
+ /**
98
+ * Get the absolute path to the current session directory.
99
+ * Creates the session if it doesn't exist.
100
+ *
101
+ * @param projectRoot - Root directory of the project
102
+ * @returns Absolute path to session directory (e.g., "/path/to/project/.peaks/2026-05-26-session-a3f8b1")
103
+ */
104
+ export async function getCurrentSessionDir(projectRoot) {
105
+ const sessionId = await ensureSession(projectRoot);
106
+ return join(projectRoot, '.peaks', sessionId);
107
+ }
108
+ /**
109
+ * List all session directories in the .peaks folder.
110
+ * Returns session IDs (directory names) sorted by date.
111
+ *
112
+ * @param projectRoot - Root directory of the project
113
+ * @returns Array of session IDs
114
+ */
115
+ export function listSessions(projectRoot) {
116
+ const peaksRoot = join(projectRoot, '.peaks');
117
+ if (!existsSync(peaksRoot))
118
+ return [];
119
+ const { readdirSync } = require('node:fs');
120
+ const entries = readdirSync(peaksRoot, { withFileTypes: true });
121
+ return entries
122
+ .filter((entry) => entry.isDirectory() && /^\d{4}-\d{2}-\d{2}-session-[a-f0-9]+$/.test(entry.name))
123
+ .map((entry) => entry.name)
124
+ .sort()
125
+ .reverse(); // Most recent first
126
+ }
127
+ /**
128
+ * Get the path to project-scan.md for the current session.
129
+ * Creates the session if it doesn't exist.
130
+ *
131
+ * @param projectRoot - Root directory of the project
132
+ * @returns Absolute path to project-scan.md
133
+ */
134
+ export async function getProjectScanPath(projectRoot) {
135
+ const sessionId = await ensureSession(projectRoot);
136
+ return join(projectRoot, '.peaks', sessionId, 'rd', 'project-scan.md');
137
+ }
138
+ /**
139
+ * Check if project-scan.md exists for the current session.
140
+ *
141
+ * @param projectRoot - Root directory of the project
142
+ * @returns true if project-scan.md exists
143
+ */
144
+ export function hasProjectScan(projectRoot) {
145
+ const info = readSessionFile(projectRoot);
146
+ if (!info)
147
+ return false;
148
+ const scanPath = join(projectRoot, '.peaks', info.sessionId, 'rd', 'project-scan.md');
149
+ return existsSync(scanPath);
150
+ }
@@ -1,6 +1,9 @@
1
+ export type SkillPresenceMode = 'full-auto' | 'assisted' | 'swarm' | 'strict';
2
+ export declare const VALID_SKILL_PRESENCE_MODES: ReadonlyArray<SkillPresenceMode>;
3
+ export declare function isSkillPresenceMode(value: string): value is SkillPresenceMode;
1
4
  export type SkillPresence = {
2
5
  skill: string;
3
- mode?: string;
6
+ mode?: SkillPresenceMode;
4
7
  gate?: string;
5
8
  setAt: string;
6
9
  };
@@ -1,5 +1,14 @@
1
1
  import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, resolve } from 'node:path';
3
+ export const VALID_SKILL_PRESENCE_MODES = [
4
+ 'full-auto',
5
+ 'assisted',
6
+ 'swarm',
7
+ 'strict'
8
+ ];
9
+ export function isSkillPresenceMode(value) {
10
+ return VALID_SKILL_PRESENCE_MODES.includes(value);
11
+ }
3
12
  const PRESENCE_FILE = '.peaks/.active-skill.json';
4
13
  function resolvePresencePath() {
5
14
  return resolve(process.cwd(), PRESENCE_FILE);
@@ -8,9 +17,10 @@ export function exportSkillPresence() {
8
17
  return resolvePresencePath();
9
18
  }
10
19
  export function setSkillPresence(skill, mode, gate) {
20
+ const validatedMode = mode && isSkillPresenceMode(mode) ? mode : undefined;
11
21
  const presence = {
12
22
  skill,
13
- ...(mode ? { mode } : {}),
23
+ ...(validatedMode ? { mode: validatedMode } : {}),
14
24
  ...(gate ? { gate } : {}),
15
25
  setAt: new Date().toISOString()
16
26
  };
@@ -15,6 +15,8 @@ const SUBDIRECTORIES = [
15
15
  ];
16
16
  const SESSION_ID_PATTERN = /^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9-]*[a-z0-9]$/;
17
17
  const PROHIBITED_SUFFIXES = ['session', 'work', 'task', 'test', 'temp', 'tmp'];
18
+ // Auto-generated session ID pattern: YYYY-MM-DD-session-<6位hex>
19
+ const AUTO_SESSION_PATTERN = /^\d{4}-\d{2}-\d{2}-session-[a-f0-9]{6}$/;
18
20
  export class InvalidSessionIdError extends Error {
19
21
  code = 'INVALID_SESSION_ID';
20
22
  constructor(message) {
@@ -23,6 +25,10 @@ export class InvalidSessionIdError extends Error {
23
25
  }
24
26
  }
25
27
  export function validateSessionId(sessionId) {
28
+ // Auto-generated session IDs (YYYY-MM-DD-session-<hex>) bypass manual validation
29
+ if (AUTO_SESSION_PATTERN.test(sessionId)) {
30
+ return;
31
+ }
26
32
  if (/^\d+$/.test(sessionId)) {
27
33
  throw new InvalidSessionIdError(`Session id "${sessionId}" is numeric-only. Use the format YYYY-MM-DD-<kebab-slug> with a 2-5 word topic description.`);
28
34
  }
@@ -11,5 +11,18 @@ export declare class ChangeIdValidationError extends Error {
11
11
  constructor(changeId: string);
12
12
  }
13
13
  export declare function isUnsafeArtifactPath(path: string): boolean;
14
+ /**
15
+ * Build an artifact-relative path using session-based storage.
16
+ *
17
+ * If a session exists, files are stored in:
18
+ * .peaks/<sessionId>/<role>/<number>-<changeId>.md
19
+ *
20
+ * If no session exists, falls back to legacy behavior:
21
+ * .peaks/<changeId>/<segments>
22
+ *
23
+ * @param changeId - Used as file description/slug (e.g., "auth-system", "add-user-auth")
24
+ * @param segments - Optional path segments (first segment is typically the role: 'prd', 'rd', 'qa', etc.)
25
+ * @returns Relative path to the artifact file
26
+ */
14
27
  export declare function buildArtifactRelativePath(changeId: string, ...segments: string[]): string;
15
28
  export declare function isPathInsideArtifactRoot(path: string, artifactRoot: string): boolean;
@@ -3,7 +3,9 @@
3
3
  * All Peaks planner commands must use these to prevent path traversal
4
4
  * and keep artifacts inside the Peaks artifact workspace.
5
5
  */
6
- import { posix } from 'node:path';
6
+ import { posix, join } from 'node:path';
7
+ import { getNextNumber, buildNumberedFilename } from './incrementing-number.js';
8
+ import { getSessionId } from '../services/session/session-manager.js';
7
9
  const CHANGE_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
8
10
  function normalizeForwardSlashes(input) {
9
11
  return input.replace(/\\/g, '/');
@@ -58,8 +60,37 @@ export class ChangeIdValidationError extends Error {
58
60
  export function isUnsafeArtifactPath(path) {
59
61
  return isUnsafePathInput(path);
60
62
  }
63
+ /**
64
+ * Build an artifact-relative path using session-based storage.
65
+ *
66
+ * If a session exists, files are stored in:
67
+ * .peaks/<sessionId>/<role>/<number>-<changeId>.md
68
+ *
69
+ * If no session exists, falls back to legacy behavior:
70
+ * .peaks/<changeId>/<segments>
71
+ *
72
+ * @param changeId - Used as file description/slug (e.g., "auth-system", "add-user-auth")
73
+ * @param segments - Optional path segments (first segment is typically the role: 'prd', 'rd', 'qa', etc.)
74
+ * @returns Relative path to the artifact file
75
+ */
61
76
  export function buildArtifactRelativePath(changeId, ...segments) {
62
77
  validateChangeIdOrThrow(changeId);
78
+ const sessionId = getSessionId(process.cwd());
79
+ if (sessionId && segments.length > 0 && segments[0]) {
80
+ const role = normalizeForwardSlashes(segments[0]);
81
+ const dirPath = join(process.cwd(), '.peaks', sessionId, role);
82
+ if (isUnsafeArtifactPath(role) || isUnsafeArtifactPath(sessionId)) {
83
+ throw new ChangeIdValidationError(changeId);
84
+ }
85
+ const number = getNextNumber(dirPath);
86
+ const filename = buildNumberedFilename(number, changeId);
87
+ const candidatePath = `.peaks/${sessionId}/${role}/${filename}`;
88
+ if (isUnsafeArtifactPath(candidatePath)) {
89
+ throw new ChangeIdValidationError(changeId);
90
+ }
91
+ return normalizeArtifactPath(candidatePath);
92
+ }
93
+ // Fallback: no session or no segments - use legacy behavior
63
94
  const joined = segments.map((segment) => normalizeForwardSlashes(segment)).join('/');
64
95
  const candidatePath = `.peaks/${changeId}/${joined}`;
65
96
  if (isUnsafeArtifactPath(joined) || isUnsafeArtifactPath(candidatePath)) {
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Utilities for generating incrementing numbered filenames.
3
+ * Used by session-based artifact storage to create files like 001-feature.md.
4
+ */
5
+ /**
6
+ * Get the next available number in a directory.
7
+ * Scans existing .md files and finds the highest numeric prefix.
8
+ * Returns 1 if directory is empty or doesn't exist.
9
+ *
10
+ * @param dirPath - Directory to scan for numbered files
11
+ * @returns Next available number (1, 2, 3, ...)
12
+ */
13
+ export declare function getNextNumber(dirPath: string): number;
14
+ /**
15
+ * Build a numbered filename from a number and description.
16
+ * Format: 001-description-slug.md
17
+ *
18
+ * @param number - The file number (will be zero-padded to 3 digits)
19
+ * @param description - Human-readable description (converted to kebab-case slug)
20
+ * @returns Formatted filename like "001-feature-name.md"
21
+ */
22
+ export declare function buildNumberedFilename(number: number, description: string): string;
23
+ /**
24
+ * Get the next numbered file path in a directory.
25
+ * Combines getNextNumber() and buildNumberedFilename().
26
+ *
27
+ * @param dirPath - Directory to scan
28
+ * @param description - Description for the filename
29
+ * @returns Full path to the new numbered file
30
+ */
31
+ export declare function getNextNumberedFilePath(dirPath: string, description: string): string;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Utilities for generating incrementing numbered filenames.
3
+ * Used by session-based artifact storage to create files like 001-feature.md.
4
+ */
5
+ import { existsSync, readdirSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ /**
8
+ * Get the next available number in a directory.
9
+ * Scans existing .md files and finds the highest numeric prefix.
10
+ * Returns 1 if directory is empty or doesn't exist.
11
+ *
12
+ * @param dirPath - Directory to scan for numbered files
13
+ * @returns Next available number (1, 2, 3, ...)
14
+ */
15
+ export function getNextNumber(dirPath) {
16
+ if (!existsSync(dirPath))
17
+ return 1;
18
+ const files = readdirSync(dirPath).filter(f => f.endsWith('.md'));
19
+ if (files.length === 0)
20
+ return 1;
21
+ const numbers = files
22
+ .map(f => {
23
+ const match = /^(\d+)-/.exec(f);
24
+ return match && match[1] ? parseInt(match[1], 10) : NaN;
25
+ })
26
+ .filter(n => !isNaN(n));
27
+ return numbers.length > 0 ? Math.max(...numbers) + 1 : 1;
28
+ }
29
+ /**
30
+ * Build a numbered filename from a number and description.
31
+ * Format: 001-description-slug.md
32
+ *
33
+ * @param number - The file number (will be zero-padded to 3 digits)
34
+ * @param description - Human-readable description (converted to kebab-case slug)
35
+ * @returns Formatted filename like "001-feature-name.md"
36
+ */
37
+ export function buildNumberedFilename(number, description) {
38
+ const padded = String(number).padStart(3, '0');
39
+ const slug = description
40
+ .toLowerCase()
41
+ .replace(/[^a-z0-9]+/g, '-')
42
+ .replace(/^-|-$/g, '')
43
+ .slice(0, 50); // Limit slug length
44
+ return `${padded}-${slug}.md`;
45
+ }
46
+ /**
47
+ * Get the next numbered file path in a directory.
48
+ * Combines getNextNumber() and buildNumberedFilename().
49
+ *
50
+ * @param dirPath - Directory to scan
51
+ * @param description - Description for the filename
52
+ * @returns Full path to the new numbered file
53
+ */
54
+ export function getNextNumberedFilePath(dirPath, description) {
55
+ const number = getNextNumber(dirPath);
56
+ const filename = buildNumberedFilename(number, description);
57
+ return join(dirPath, filename);
58
+ }
@@ -1 +1 @@
1
- export declare const CLI_VERSION = "1.0.21";
1
+ export declare const CLI_VERSION = "1.0.22";
@@ -1 +1 @@
1
- export const CLI_VERSION = "1.0.21";
1
+ export const CLI_VERSION = "1.0.22";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peaks-cli",
3
- "version": "1.0.21",
3
+ "version": "1.0.22",
4
4
  "description": "Peaks CLI and short skill family for Claude Code automation.",
5
5
  "author": "SquabbyZ",
6
6
  "license": "MIT",
@@ -68,6 +68,9 @@ peaks codegraph affected --project <repo> <changed-files...> --json
68
68
  # **STOP if .peaks/<session-id>/rd/project-scan.md does not exist.**
69
69
  # **Do not write any code, do not plan any implementation, do not pass go.**
70
70
  # **Create the project-scan first, then proceed.**
71
+ # NOTE: project-scan.md is a session-scoped singleton. Check if it already exists
72
+ # before regenerating (e.g. via `ls .peaks/<id>/rd/project-scan.md`). If it exists
73
+ # and is complete (has `## Archetype` and `## Project mode` sections), reuse it.
71
74
  # Required sections in project-scan:
72
75
  # - build tool and framework
73
76
  # - component library (antd, MUI, shadcn, etc.) and version