@planu/cli 5.7.21 → 5.7.23

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 (92) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/.planu-build.json +1 -1
  3. package/dist/cli/commands/release.js +23 -10
  4. package/dist/cli/commands/spec.js +2 -32
  5. package/dist/config/registries/error-recovery.json +18 -18
  6. package/dist/config/registries/legacy-guidance.json +33 -1
  7. package/dist/config/server-instructions.js +16 -20
  8. package/dist/config/skill-templates/planu-release.md +3 -3
  9. package/dist/config/token-waste-autopilot.json +1 -1
  10. package/dist/core/shared/object.d.ts +3 -0
  11. package/dist/core/shared/object.js +12 -0
  12. package/dist/engine/config-loader.js +24 -32
  13. package/dist/engine/conventions-ttl.d.ts +2 -0
  14. package/dist/engine/conventions-ttl.js +1 -1
  15. package/dist/engine/detectors/library-detector-langs3b.d.ts +0 -5
  16. package/dist/engine/detectors/library-detector-langs3b.js +2 -16
  17. package/dist/engine/detectors/library-detector-langs5.d.ts +0 -1
  18. package/dist/engine/detectors/library-detector-langs5.js +2 -16
  19. package/dist/engine/detectors/otel-detector.js +4 -3
  20. package/dist/engine/detectors/otel-ecosystem-detectors.d.ts +0 -4
  21. package/dist/engine/detectors/otel-ecosystem-detectors.js +2 -14
  22. package/dist/engine/detectors/toml-dependencies.d.ts +2 -0
  23. package/dist/engine/detectors/toml-dependencies.js +16 -0
  24. package/dist/engine/drift-detection/release-status-drift.js +2 -17
  25. package/dist/engine/errors/registry-loader.js +3 -2
  26. package/dist/engine/evidence-gates/artifact-reader.d.ts +78 -0
  27. package/dist/engine/evidence-gates/artifact-reader.js +19 -7
  28. package/dist/engine/health/auto-fixer.js +2 -2
  29. package/dist/engine/minimality/policy-loader.js +1 -11
  30. package/dist/engine/model-tier-resolver.js +3 -11
  31. package/dist/engine/platform-detector/desktop.js +3 -13
  32. package/dist/engine/platform-detector/games.js +3 -13
  33. package/dist/engine/release-pipeline/release-spec-closer.d.ts +1 -0
  34. package/dist/engine/release-pipeline/release-spec-closer.js +1 -1
  35. package/dist/engine/safety/cross-process-lock.js +6 -21
  36. package/dist/engine/safety/lock-scavenger.d.ts +3 -1
  37. package/dist/engine/safety/lock-scavenger.js +3 -3
  38. package/dist/engine/score-to-grade.d.ts +2 -0
  39. package/dist/engine/score-to-grade.js +16 -0
  40. package/dist/engine/spec-grounding/contract.js +2 -1
  41. package/dist/engine/spec-grounding/grounding-entry-parser.d.ts +0 -1
  42. package/dist/engine/spec-grounding/grounding-entry-parser.js +1 -3
  43. package/dist/engine/telemetry/health-checker.js +2 -20
  44. package/dist/engine/telemetry/telemetry-client.d.ts +1 -0
  45. package/dist/engine/telemetry/telemetry-client.js +1 -1
  46. package/dist/engine/test-scaffold-generator/advanced-scaffold.js +1 -24
  47. package/dist/engine/token-optimizer/analytics.d.ts +1 -1
  48. package/dist/engine/token-optimizer/analytics.js +2 -22
  49. package/dist/engine/token-optimizer/policy-loader.js +1 -11
  50. package/dist/engine/validation-evidence-ledger.d.ts +1 -0
  51. package/dist/engine/validation-evidence-ledger.js +44 -3
  52. package/dist/engine/workers/handlers/code-map.js +4 -46
  53. package/dist/engine/workers/handlers/collect-files.d.ts +3 -0
  54. package/dist/engine/workers/handlers/collect-files.js +53 -0
  55. package/dist/engine/workers/handlers/documentation.js +4 -49
  56. package/dist/engine/workers/handlers/optimization.js +4 -46
  57. package/dist/engine/workers/handlers/security-audit.js +4 -45
  58. package/dist/hosts/codex/config-scaffold.js +1 -1
  59. package/dist/hosts/gemini/config-scaffold.js +1 -1
  60. package/dist/storage/spec-index.js +8 -3
  61. package/dist/storage/token-ledger-store.d.ts +1 -1
  62. package/dist/storage/token-ledger-store.js +2 -22
  63. package/dist/tools/audit.js +1 -15
  64. package/dist/tools/claude-settings-file.d.ts +3 -0
  65. package/dist/tools/claude-settings-file.js +19 -0
  66. package/dist/tools/create-spec/post-creation.d.ts +1 -1
  67. package/dist/tools/create-spec/post-creation.js +7 -49
  68. package/dist/tools/create-spec.js +1 -1
  69. package/dist/tools/facilitate.js +6 -6
  70. package/dist/tools/init-project/result-builder.js +4 -4
  71. package/dist/tools/reconcile-interactive-question-hooks.js +3 -18
  72. package/dist/tools/reconcile-session-safeguard-hook.js +3 -18
  73. package/dist/tools/reconcile-spec-sanctity-hook.js +4 -19
  74. package/dist/tools/safe-handler.js +1 -1
  75. package/dist/tools/status-handler.js +1 -1
  76. package/dist/tools/tool-registry/core-tools.js +3 -1
  77. package/dist/tools/update-status/evidence-payload.d.ts +180 -0
  78. package/dist/tools/update-status/evidence-payload.js +76 -0
  79. package/dist/tools/update-status/index.js +30 -0
  80. package/dist/tools/validate.js +2 -16
  81. package/dist/types/evidence-gates.d.ts +9 -0
  82. package/dist/types/lifecycle.d.ts +1 -10
  83. package/dist/types/spec/inputs.d.ts +2 -1
  84. package/dist/types/token-ledger.d.ts +1 -0
  85. package/dist/types/token-ledger.js +21 -1
  86. package/package.json +1 -1
  87. package/planu-plugin.json +14 -4
  88. package/src/i18n/messages/en.json +2 -2
  89. package/src/i18n/messages/es.json +2 -2
  90. package/src/i18n/messages/pt.json +2 -2
  91. package/dist/engine/detectors/cicd-detector.d.ts +0 -7
  92. package/dist/engine/detectors/cicd-detector.js +0 -170
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync } from
3
3
  import { join, dirname } from 'node:path';
4
4
  import { reportClassifiedDegradation } from '../errors/classified-degradation.js';
5
5
  import { withFileLock } from './file-mutex.js';
6
+ import { emptyLedgerAggregation, } from '../types/index.js';
6
7
  const MAX_FILE_SIZE_MB = 10;
7
8
  const ROTATION_MONTHS = 6;
8
9
  // ---------------------------------------------------------------------------
@@ -112,7 +113,7 @@ function trimToMaxSize(sorted) {
112
113
  // ---------------------------------------------------------------------------
113
114
  function computeAggregation(entries) {
114
115
  if (entries.length === 0) {
115
- return emptyAggregation();
116
+ return emptyLedgerAggregation();
116
117
  }
117
118
  const tokensByTool = {};
118
119
  const costByTool = {};
@@ -186,27 +187,6 @@ function computeOverEstimationPercent(actual, estimated, count) {
186
187
  }
187
188
  return ((estimated - actual) / actual) * 100;
188
189
  }
189
- function emptyAggregation() {
190
- return {
191
- totalTokens: 0,
192
- totalInputTokens: 0,
193
- totalOutputTokens: 0,
194
- totalCostUsd: 0,
195
- totalEstimatedCostUsd: 0,
196
- entryCount: 0,
197
- uniqueTools: 0,
198
- uniqueModels: 0,
199
- uniqueSessions: 0,
200
- avgTokensPerCall: 0,
201
- avgCostPerCall: 0,
202
- tokensByTool: {},
203
- costByTool: {},
204
- tokensByModel: {},
205
- costByModel: {},
206
- estimationAccuracy: 100,
207
- overEstimationPercent: 0,
208
- };
209
- }
210
190
  // ---------------------------------------------------------------------------
211
191
  // Multi-month entry loading (for all_time filter)
212
192
  // ---------------------------------------------------------------------------
@@ -3,6 +3,7 @@
3
3
  import { specStore, knowledgeStore } from '../storage/index.js';
4
4
  import { auditCode } from '../engine/auditor.js';
5
5
  import { calcQualityScore } from '../engine/auditor-scoring.js';
6
+ import { scoreToGrade } from '../engine/score-to-grade.js';
6
7
  import { parseProjectQualityRules } from '../engine/auditor-claude-md.js';
7
8
  import { auditSolidityProject } from '../engine/solidity-auditor.js';
8
9
  import { t, ti } from '../i18n/index.js';
@@ -143,19 +144,4 @@ export async function handleAudit(args) {
143
144
  structuredContent: output,
144
145
  };
145
146
  }
146
- function scoreToGrade(score) {
147
- if (score >= 90) {
148
- return 'A';
149
- }
150
- if (score >= 80) {
151
- return 'B';
152
- }
153
- if (score >= 70) {
154
- return 'C';
155
- }
156
- if (score >= 60) {
157
- return 'D';
158
- }
159
- return 'F';
160
- }
161
147
  //# sourceMappingURL=audit.js.map
@@ -0,0 +1,3 @@
1
+ export declare function readClaudeSettings<T extends object>(projectPath: string): Promise<T>;
2
+ export declare function writeClaudeSettings(projectPath: string, data: object): Promise<void>;
3
+ //# sourceMappingURL=claude-settings-file.d.ts.map
@@ -0,0 +1,19 @@
1
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
2
+ import { join, dirname } from 'node:path';
3
+ const CLAUDE_SETTINGS_PATH = '.claude/settings.json';
4
+ export async function readClaudeSettings(projectPath) {
5
+ const settingsFile = join(projectPath, CLAUDE_SETTINGS_PATH);
6
+ try {
7
+ const raw = await readFile(settingsFile, 'utf-8');
8
+ return JSON.parse(raw);
9
+ }
10
+ catch {
11
+ return {};
12
+ }
13
+ }
14
+ export async function writeClaudeSettings(projectPath, data) {
15
+ const settingsFile = join(projectPath, CLAUDE_SETTINGS_PATH);
16
+ await mkdir(dirname(settingsFile), { recursive: true });
17
+ await writeFile(settingsFile, JSON.stringify(data, null, 2) + '\n', 'utf-8');
18
+ }
19
+ //# sourceMappingURL=claude-settings-file.js.map
@@ -11,7 +11,7 @@ export declare function checkContradictions(projectId: string, specId: string, d
11
11
  /** Dispatches the on_spec_created hook event (fire-and-forget). */
12
12
  export declare function fireSpecCreatedHook(projectId: string, spec: Spec, projectPath: string): void;
13
13
  /** Generates post-creation suggestions based on project state and spec description. Best-effort: never throws. */
14
- export declare function generatePostCreationSuggestions(projectPath: string, description: string, knowledge?: ProjectKnowledge): Promise<PostCreationSuggestion[]>;
14
+ export declare function generatePostCreationSuggestions(_projectPath: string, description: string, knowledge?: ProjectKnowledge): Promise<PostCreationSuggestion[]>;
15
15
  /** Formats a structured post-creation suggestion for human-readable next steps. */
16
16
  export declare function formatPostCreationSuggestion(suggestion: PostCreationSuggestion): string;
17
17
  /**
@@ -1,7 +1,6 @@
1
1
  import { technologyValue } from '../../engine/technology-registry.js';
2
2
  import { specStore } from '../../storage/index.js';
3
3
  import { detectContradictions } from '../../engine/contradiction-detector.js';
4
- import { detectCiCd } from '../../engine/detectors/cicd-detector.js';
5
4
  import { tryAutoSetupGit } from '../create-spec-helpers.js';
6
5
  import { emitAutopilotEvent } from '../../engine/autopilot/event-bus.js';
7
6
  import { incrementSpecCount } from '../../engine/autopilot/state-updater.js';
@@ -80,8 +79,8 @@ export async function checkContradictions(projectId, specId, description) {
80
79
  }
81
80
  const blockers = newSpecContradictions.filter((c) => c.severity === 'blocker');
82
81
  return blockers.length > 0
83
- ? `[CONFLICT] ${blockers.length} potential blocker contradiction(s) detected. Run detect_contradictions for details.`
84
- : `[WARNING] ${newSpecContradictions.length} potential contradiction(s) detected. Run detect_contradictions for details.`;
82
+ ? `[CONFLICT] ${blockers.length} potential blocker contradiction(s) detected. Run challenge_spec for details.`
83
+ : `[WARNING] ${newSpecContradictions.length} potential contradiction(s) detected. Run challenge_spec for details.`;
85
84
  }
86
85
  catch {
87
86
  return undefined;
@@ -167,67 +166,26 @@ function isServerlessKnowledge(knowledge) {
167
166
  const deployPlatform = (knowledge.conventions?.['deploy-platform'] ?? '').toLowerCase();
168
167
  return SERVERLESS_PLATFORMS.some((p) => services.some((s) => s.includes(p)) || deployPlatform.includes(p));
169
168
  }
170
- // === Template pattern matching ===
171
- const TEMPLATE_PATTERNS = [
172
- { pattern: /\b(?:crud|create\s+read\s+update\s+delete|rest\s+api)\b/i, category: 'crud' },
173
- { pattern: /\b(?:auth|login|signup|authentication)\b/i, category: 'auth' },
174
- { pattern: /\b(?:payment|checkout|billing|stripe)\b/i, category: 'payments' },
175
- { pattern: /\b(?:notification|email|push\s+notification)\b/i, category: 'notifications' },
176
- ];
177
169
  /** Generates post-creation suggestions based on project state and spec description. Best-effort: never throws. */
178
- export async function generatePostCreationSuggestions(projectPath, description, knowledge) {
170
+ export function generatePostCreationSuggestions(_projectPath, description, knowledge) {
179
171
  const suggestions = [];
180
- // Item 1: Suggest generate_ci when no CI detected
181
- try {
182
- const ciResult = await detectCiCd(projectPath);
183
- if (ciResult.platform === null) {
184
- suggestions.push({
185
- tool: 'generate_planu_ci',
186
- reason: 'No CI/CD configuration detected. Run generate_planu_ci to set up automated testing and deployment.',
187
- });
188
- }
189
- }
190
- catch {
191
- // Best-effort: if detection fails, skip suggestion
192
- }
193
- // Item 2: Suggest version verification when description references technology stacks
194
172
  if (hasTechStackReferences(description)) {
195
173
  suggestions.push({
196
- tool: 'verify_versions',
174
+ tool: 'challenge_spec',
197
175
  reason: 'IMPORTANT: Before approving, verify all technology versions in this spec against official sources (npm registry, GitHub releases, Docker Hub, official docs). Outdated versions can cause security vulnerabilities and compatibility issues.',
198
176
  });
199
177
  }
200
- // Item 3: Warn about in-memory state anti-patterns in serverless environments
201
178
  if (isServerlessKnowledge(knowledge)) {
202
179
  suggestions.push({
203
- tool: 'scan_project',
180
+ tool: 'challenge_spec',
204
181
  reason: '[SERVERLESS WARNING] Module-level mutable state may reset on cold starts. Confirm the required state lifetime and storage strategy before implementation.',
205
182
  });
206
183
  }
207
- // Item 4: Suggest templates only when the user explicitly requests one.
208
- for (const { pattern, category } of TEMPLATE_PATTERNS) {
209
- if (hasAffirmedPattern(description, pattern) && explicitlyRequestsTemplate(description)) {
210
- suggestions.push({
211
- tool: 'apply_template',
212
- reason: `Description matches "${category}" pattern. Consider using an ${category} template.`,
213
- templateCategory: category,
214
- });
215
- }
216
- }
217
- // Item 4: Suggest committing progress with conventional commits
218
- suggestions.push({
219
- tool: 'manage_git',
220
- reason: 'Save progress with git after implementing: `git commit -m "feat(SPEC-XXX): implementation checkpoint"` — include the spec ID for traceability',
221
- });
222
- return suggestions;
223
- }
224
- function explicitlyRequestsTemplate(description) {
225
- return /\b(?:use|apply|start from|base (?:this|it) on)\s+(?:an?\s+)?(?:[\w-]+\s+)?template\b/i.test(description);
184
+ return Promise.resolve(suggestions);
226
185
  }
227
186
  /** Formats a structured post-creation suggestion for human-readable next steps. */
228
187
  export function formatPostCreationSuggestion(suggestion) {
229
- const templateSuffix = suggestion.templateCategory !== undefined ? ` (${suggestion.templateCategory})` : '';
230
- return `${suggestion.tool}${templateSuffix}: ${suggestion.reason}`;
188
+ return `${suggestion.tool}: ${suggestion.reason}`;
231
189
  }
232
190
  /**
233
191
  * SPEC-781: Run heavy analysis (contradiction detection, complexity advice) in a
@@ -1119,7 +1119,7 @@ async function prepareCreateSpecCandidate(initialParams) {
1119
1119
  content: [
1120
1120
  {
1121
1121
  type: 'text',
1122
- text: `💡 **Idea captured**: "${params.description}"\n\nThe description is too brief for a full spec. Use \`capture_idea\` to save it to the backlog, or provide more detail (>10 words) to create a spec.`,
1122
+ text: `💡 **Idea captured**: "${params.description}"\n\nThe description is too brief for a full spec. Provide more detail (>10 words) to create a spec.`,
1123
1123
  },
1124
1124
  ],
1125
1125
  });
@@ -51,12 +51,12 @@ const PROBLEM_TO_TOOL = [
51
51
  [/validat/i, 'validate', 'validate a spec'],
52
52
  [/spec|user stor/i, 'create_spec', 'create a spec/user story'],
53
53
  [/estimat/i, 'estimate', 'estimate effort and cost'],
54
- [/document|doc/i, 'generate_docs', 'generate documentation'],
55
- [/drift|diverge/i, 'detect_drift', 'detect spec drift'],
56
- [/schema|database|db/i, 'design_schema', 'design a database schema'],
57
- [/ui|interface|screen/i, 'define_ui_contract', 'define a UI contract'],
58
- [/execution|plan|roadmap/i, 'generate_execution_plan', 'generate an execution plan'],
59
- [/checklist/i, 'generate_checklist', 'generate a checklist'],
54
+ [/document|doc/i, 'create_spec', 'create a spec for the documentation change'],
55
+ [/drift|diverge/i, 'reconcile_spec', 'reconcile the spec with the implementation'],
56
+ [/schema|database|db/i, 'create_spec', 'create a spec for the data model change'],
57
+ [/ui|interface|screen/i, 'create_spec', 'create a spec for the UI change'],
58
+ [/execution|plan|roadmap/i, 'package_handoff', 'package the implementation handoff'],
59
+ [/checklist/i, 'check_readiness', 'check the readiness checklist of the spec'],
60
60
  ];
61
61
  function buildConcreteProblemResponse(description) {
62
62
  const match = PROBLEM_TO_TOOL.find(([re]) => re.test(description));
@@ -134,7 +134,7 @@ export function buildInitProjectResult(input) {
134
134
  skillsSkipped: input.skillsSkipped,
135
135
  skillsPendingInstall: input.skillsPendingInstall,
136
136
  skillInstallHint: input.skillsPendingInstall.length > 0
137
- ? `Run skill_install to install recommended skills: ${input.skillsPendingInstall.join(', ')}`
137
+ ? `Re-run init_project to install the recommended skills: ${input.skillsPendingInstall.join(', ')}`
138
138
  : null,
139
139
  planuConfig: input.planuConfigGenerated
140
140
  ? { generated: true, path: input.planuConfigPath }
@@ -194,7 +194,7 @@ export function buildInitProjectResult(input) {
194
194
  const framework = result.framework ?? 'no framework detected';
195
195
  const action = isUpdate ? 'updated' : 'initialized';
196
196
  const telemetryNote = input.telemetryOptInPrompt
197
- ? `\n\n---\n💡 **Help improve Planu** — run \`configure_telemetry\` with action=enable, then set a valid \`PLANU_TELEMETRY_ENDPOINT\` and secret \`PLANU_TELEMETRY_TOKEN\` to share anonymous usage stats (no paths, no emails, no personal data). You can opt out anytime.`
197
+ ? `\n\n---\n💡 **Help improve Planu** — set \`PLANU_TELEMETRY=on\` and \`PLANU_TELEMETRY_CONSENT_VERSION=1\` (both are required by \`isTelemetryEnabled\` in \`src/engine/telemetry/telemetry-store.ts:76-78\`), then set a valid \`PLANU_TELEMETRY_ENDPOINT\` and secret \`PLANU_TELEMETRY_TOKEN\` to share anonymous usage stats (no paths, no emails, no personal data). You can opt out anytime.`
198
198
  : '';
199
199
  const tokenTip = `\n\n💡 Token tip: Add CLAUDE_CODE_SUBAGENT_MODEL=haiku to your .env — makes all read-only subagents ` +
200
200
  `(search, grep, file reads) use Haiku instead of your session model (4–18x cheaper for those tasks).`;
@@ -224,9 +224,9 @@ export function buildInitProjectResult(input) {
224
224
  options: [
225
225
  {
226
226
  label: 'Yes, install now',
227
- description: 'Runs skill_install for each recommended skill automatically.',
227
+ description: 'Re-runs init_project so it installs each recommended skill.',
228
228
  },
229
- { label: 'Skip for now', description: 'You can install later with skill_install.' },
229
+ { label: 'Skip for now', description: 'You can install later by re-running init_project.' },
230
230
  ],
231
231
  });
232
232
  }
@@ -6,31 +6,16 @@ import { existsSync } from 'node:fs';
6
6
  import { join, dirname, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { compactResult } from './output-formatter.js';
9
+ import { readClaudeSettings, writeClaudeSettings } from './claude-settings-file.js';
9
10
  const __filename = fileURLToPath(import.meta.url);
10
11
  const __dirname = dirname(__filename);
11
12
  const HOOK_TEMPLATE_PATH = resolve(__dirname, '../config/hook-templates/planu-force-ask-user-question.sh');
12
13
  const HOOK_RELATIVE_PATH = '.claude/hooks/planu-force-ask-user-question.sh';
13
- const SETTINGS_PATH = '.claude/settings.json';
14
14
  const PLANU_MATCHER = 'mcp__planu__.*';
15
15
  const PLANU_POSTTOOLUSE_ENTRY = {
16
16
  matcher: PLANU_MATCHER,
17
17
  hooks: [{ type: 'command', command: 'bash .claude/hooks/planu-force-ask-user-question.sh' }],
18
18
  };
19
- async function readSettings(projectPath) {
20
- const settingsFile = join(projectPath, SETTINGS_PATH);
21
- try {
22
- const raw = await readFile(settingsFile, 'utf-8');
23
- return JSON.parse(raw);
24
- }
25
- catch {
26
- return {};
27
- }
28
- }
29
- async function writeSettings(projectPath, data) {
30
- const settingsFile = join(projectPath, SETTINGS_PATH);
31
- await mkdir(dirname(settingsFile), { recursive: true });
32
- await writeFile(settingsFile, JSON.stringify(data, null, 2) + '\n', 'utf-8');
33
- }
34
19
  async function installHookFile(projectPath) {
35
20
  const hookDest = join(projectPath, HOOK_RELATIVE_PATH);
36
21
  const alreadyExists = existsSync(hookDest);
@@ -71,7 +56,7 @@ function matcherAlreadyPresent(settings) {
71
56
  return postToolUse.some((entry) => entry.matcher === PLANU_MATCHER);
72
57
  }
73
58
  async function mergeSettings(projectPath) {
74
- const settings = await readSettings(projectPath);
59
+ const settings = await readClaudeSettings(projectPath);
75
60
  if (matcherAlreadyPresent(settings)) {
76
61
  return false;
77
62
  }
@@ -85,7 +70,7 @@ async function mergeSettings(projectPath) {
85
70
  PostToolUse: [...existingPostToolUse, PLANU_POSTTOOLUSE_ENTRY],
86
71
  },
87
72
  };
88
- await writeSettings(projectPath, updated);
73
+ await writeClaudeSettings(projectPath, updated);
89
74
  return true;
90
75
  }
91
76
  export async function reconcileInteractiveQuestionHooks(projectPath) {
@@ -5,11 +5,11 @@ import { readFile, writeFile, mkdir, chmod } from 'node:fs/promises';
5
5
  import { existsSync } from 'node:fs';
6
6
  import { join, dirname, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { readClaudeSettings, writeClaudeSettings } from './claude-settings-file.js';
8
9
  const __filename = fileURLToPath(import.meta.url);
9
10
  const __dirname = dirname(__filename);
10
11
  const HOOK_TEMPLATE_PATH = resolve(__dirname, '../config/hook-templates/planu-session-safeguard.sh');
11
12
  const HOOK_RELATIVE_PATH = '.claude/hooks/planu-session-safeguard.sh';
12
- const SETTINGS_PATH = '.claude/settings.json';
13
13
  const HOOK_COMMAND = 'bash .claude/hooks/planu-session-safeguard.sh';
14
14
  /** Detect whether PreCompaction hook type is supported by checking CLAUDE_CODE_VERSION env var. */
15
15
  function detectHookType() {
@@ -21,21 +21,6 @@ function detectHookType() {
21
21
  // PreCompaction was introduced in Claude Code. Any version string present is treated as supporting it.
22
22
  return 'PreCompaction';
23
23
  }
24
- async function readSettings(projectPath) {
25
- const settingsFile = join(projectPath, SETTINGS_PATH);
26
- try {
27
- const raw = await readFile(settingsFile, 'utf-8');
28
- return JSON.parse(raw);
29
- }
30
- catch {
31
- return {};
32
- }
33
- }
34
- async function writeSettings(projectPath, data) {
35
- const settingsFile = join(projectPath, SETTINGS_PATH);
36
- await mkdir(dirname(settingsFile), { recursive: true });
37
- await writeFile(settingsFile, JSON.stringify(data, null, 2) + '\n', 'utf-8');
38
- }
39
24
  function hookAlreadyRegistered(settings, hookType) {
40
25
  const entries = settings.hooks?.[hookType];
41
26
  if (!Array.isArray(entries)) {
@@ -92,7 +77,7 @@ async function installHookFile(projectPath) {
92
77
  return !alreadyExists;
93
78
  }
94
79
  async function registerHookInSettings(projectPath, hookType) {
95
- const settings = await readSettings(projectPath);
80
+ const settings = await readClaudeSettings(projectPath);
96
81
  if (hookAlreadyRegistered(settings, hookType)) {
97
82
  return false;
98
83
  }
@@ -110,7 +95,7 @@ async function registerHookInSettings(projectPath, hookType) {
110
95
  [hookType]: [...existing, entry],
111
96
  },
112
97
  };
113
- await writeSettings(projectPath, updated);
98
+ await writeClaudeSettings(projectPath, updated);
114
99
  return true;
115
100
  }
116
101
  /** Install the session-safeguard hook file and register it in .claude/settings.json. Idempotent. */
@@ -2,31 +2,16 @@ import { readFile, writeFile, mkdir, chmod } from 'node:fs/promises';
2
2
  import { join, dirname, resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { renderSpecSanctityHook } from '../engine/spec-folder-sanctity.js';
5
+ import { readClaudeSettings, writeClaudeSettings } from './claude-settings-file.js';
5
6
  const __filename = fileURLToPath(import.meta.url);
6
7
  const __dirname = dirname(__filename);
7
8
  const HOOK_TEMPLATE_PATH = resolve(__dirname, '../config/hook-templates/planu-spec-sanctity.sh');
8
9
  const HOOK_RELATIVE_PATH = '.claude/hooks/planu-spec-sanctity.sh';
9
- const SETTINGS_PATH = '.claude/settings.json';
10
10
  const HOOK_COMMAND = 'bash .claude/hooks/planu-spec-sanctity.sh';
11
11
  const PRE_TOOL_USE_ENTRY = {
12
12
  matcher: 'Write|Edit|MultiEdit',
13
13
  hooks: [{ type: 'command', command: HOOK_COMMAND }],
14
14
  };
15
- async function readSettings(projectPath) {
16
- const settingsFile = join(projectPath, SETTINGS_PATH);
17
- try {
18
- const raw = await readFile(settingsFile, 'utf-8');
19
- return JSON.parse(raw);
20
- }
21
- catch {
22
- return {};
23
- }
24
- }
25
- async function writeSettings(projectPath, data) {
26
- const settingsFile = join(projectPath, SETTINGS_PATH);
27
- await mkdir(dirname(settingsFile), { recursive: true });
28
- await writeFile(settingsFile, JSON.stringify(data, null, 2) + '\n', 'utf-8');
29
- }
30
15
  function entryAlreadyPresent(settings) {
31
16
  return (settings.hooks?.PreToolUse?.some((entry) => Array.isArray(entry.hooks) && entry.hooks.some((hook) => hook.command === HOOK_COMMAND)) ?? false);
32
17
  }
@@ -43,7 +28,7 @@ async function installHookFile(projectPath) {
43
28
  return true;
44
29
  }
45
30
  async function mergeSettings(projectPath) {
46
- const settings = await readSettings(projectPath);
31
+ const settings = await readClaudeSettings(projectPath);
47
32
  if (entryAlreadyPresent(settings)) {
48
33
  return;
49
34
  }
@@ -57,13 +42,13 @@ async function mergeSettings(projectPath) {
57
42
  PreToolUse: [...existingPreToolUse, PRE_TOOL_USE_ENTRY],
58
43
  },
59
44
  };
60
- await writeSettings(projectPath, updated);
45
+ await writeClaudeSettings(projectPath, updated);
61
46
  }
62
47
  export async function installSpecSanctityHook(projectPath) {
63
48
  const resolved = resolve(projectPath);
64
49
  const hookWritten = await installHookFile(resolved).catch(() => false);
65
50
  await mergeSettings(resolved).catch(() => undefined);
66
- const settingsAfter = await readSettings(resolved);
51
+ const settingsAfter = await readClaudeSettings(resolved);
67
52
  const settingsRegistered = entryAlreadyPresent(settingsAfter);
68
53
  return { hookWritten, settingsRegistered };
69
54
  }
@@ -113,7 +113,7 @@ async function checkPendingDriftBanner(projectPath, signal) {
113
113
  const maxScore = Math.max(...pending.map((e) => e.driftScore));
114
114
  return {
115
115
  banner: `\n⚠️ Auto-drift alert: specs [${specIds}] may have drifted ` +
116
- `(score: ${maxScore.toFixed(2)}). Run detect_drift to review.`,
116
+ `(score: ${maxScore.toFixed(2)}). Run reconcile_spec to review.`,
117
117
  acknowledge: () => {
118
118
  /* v8 ignore start */
119
119
  void store.markAllShown().catch((err) => {
@@ -242,7 +242,7 @@ export async function handlePlanStatus(args, signal = getToolExecutionSignal())
242
242
  const sessionAgeMinutes = sessionState !== null ? computeSessionAgeMinutes(sessionState.savedAt) : null;
243
243
  const SESSION_TIP_THRESHOLD_MIN = 60;
244
244
  const sessionTip = sessionAgeMinutes !== null && sessionAgeMinutes > SESSION_TIP_THRESHOLD_MIN
245
- ? `Last checkpoint ${String(sessionAgeMinutes)}min ago — run session_handoff then start a fresh session to cut token costs`
245
+ ? `Last checkpoint ${String(sessionAgeMinutes)}min ago — run session_checkpoint then start a fresh session to cut token costs`
246
246
  : undefined;
247
247
  const tokenWasteThresholdMin = tokenWastePolicy?.context.staleSessionMinutes;
248
248
  const tokenWasteHint = tokenWasteThresholdMin !== undefined &&
@@ -25,6 +25,7 @@ import { handlePlanStatus } from '../status-handler.js';
25
25
  import { handleSessionCheckpoint } from '../session-checkpoint.js';
26
26
  import { handleGetJob, handleRestartJob } from '../jobs/handlers.js';
27
27
  import { handleFacilitate } from '../facilitate.js';
28
+ import { UpdateStatusEvidenceTransportSchema } from '../update-status/evidence-payload.js';
28
29
  const INIT_PROJECT_INPUT_SCHEMA = {
29
30
  projectPath: z
30
31
  .string()
@@ -479,7 +480,7 @@ const coreToolsRegistry = [
479
480
  description: 'Persist a host-LLM-synthesized spec.md body and retire the legacy files it replaces: ' +
480
481
  'each retired file/directory is backed up with a timestamped .bak copy, deleted, and ' +
481
482
  'git-untracked. Call this after synthesizing mergedBody from the legacyFiles listed in a ' +
482
- 'migrate_legacy_spec directive (from init_project, list_specs, or heal_spec_docs).',
483
+ 'migrate_legacy_spec directive (from init_project or list_specs).',
483
484
  schema: migrateLegacySpecInputSchema,
484
485
  handler: (args) => migrateLegacySpec(args),
485
486
  annotations: { readOnlyHint: false, destructiveHint: true, title: 'Migrate Legacy Spec' },
@@ -821,6 +822,7 @@ const coreToolsRegistry = [
821
822
  .boolean()
822
823
  .optional()
823
824
  .describe('SPEC-769: Force-approve a spec that scored below 70 on the readiness gate. Warnings are stored in spec.md frontmatter. Use when the LLM has explicitly confirmed the spec is ready despite a low readiness score.'),
825
+ evidence: UpdateStatusEvidenceTransportSchema.optional().describe('Optional. Evidence artifacts to persist into the handoff store before the gates run: discovery (approved), taskPlan (implementing), traceabilityMatrix, contractValidation, reviewFeedback (review → approved, reviewer.agent must be planu-spec-reviewer) and implementationReview (done, reviewer.agent must be planu-implementation-reviewer with a sessionId different from the implementer). Ignored under dry_run. Files are overwritten.'),
824
826
  },
825
827
  handler: async (args) => runWithTrustedLocalMcpContext(() => handleUpdateStatus(args)),
826
828
  wrap: 'tracked',
@@ -0,0 +1,180 @@
1
+ import { z } from 'zod';
2
+ import type { UpdateStatusEvidencePayload } from '../../types/evidence-gates.js';
3
+ export declare const UpdateStatusEvidencePayloadSchema: z.ZodObject<{
4
+ discovery: z.ZodOptional<z.ZodObject<{
5
+ version: z.ZodLiteral<1>;
6
+ provenance: z.ZodOptional<z.ZodObject<{
7
+ receiptId: z.ZodString;
8
+ artifactDigest: z.ZodString;
9
+ specId: z.ZodString;
10
+ issuerId: z.ZodString;
11
+ }, z.core.$strict>>;
12
+ rules: z.ZodArray<z.ZodString>;
13
+ examples: z.ZodArray<z.ZodObject<{
14
+ rule: z.ZodString;
15
+ example: z.ZodString;
16
+ }, z.core.$strict>>;
17
+ openQuestions: z.ZodArray<z.ZodObject<{
18
+ question: z.ZodString;
19
+ status: z.ZodEnum<{
20
+ open: "open";
21
+ out_of_scope: "out_of_scope";
22
+ resolved: "resolved";
23
+ }>;
24
+ resolution: z.ZodOptional<z.ZodString>;
25
+ }, z.core.$strict>>;
26
+ outOfScope: z.ZodArray<z.ZodString>;
27
+ glossary: z.ZodArray<z.ZodObject<{
28
+ term: z.ZodString;
29
+ meaning: z.ZodString;
30
+ }, z.core.$strict>>;
31
+ }, z.core.$strict>>;
32
+ taskPlan: z.ZodOptional<z.ZodObject<{
33
+ version: z.ZodLiteral<1>;
34
+ provenance: z.ZodOptional<z.ZodObject<{
35
+ receiptId: z.ZodString;
36
+ artifactDigest: z.ZodString;
37
+ specId: z.ZodString;
38
+ issuerId: z.ZodString;
39
+ }, z.core.$strict>>;
40
+ generatedBy: z.ZodOptional<z.ZodLiteral<"planu-evidence-skeleton">>;
41
+ tasks: z.ZodArray<z.ZodObject<{
42
+ id: z.ZodString;
43
+ title: z.ZodString;
44
+ acceptanceCriteria: z.ZodArray<z.ZodString>;
45
+ status: z.ZodEnum<{
46
+ doing: "doing";
47
+ done: "done";
48
+ pending: "pending";
49
+ }>;
50
+ }, z.core.$strict>>;
51
+ }, z.core.$strict>>;
52
+ traceabilityMatrix: z.ZodOptional<z.ZodObject<{
53
+ version: z.ZodLiteral<1>;
54
+ provenance: z.ZodOptional<z.ZodObject<{
55
+ receiptId: z.ZodString;
56
+ artifactDigest: z.ZodString;
57
+ specId: z.ZodString;
58
+ issuerId: z.ZodString;
59
+ }, z.core.$strict>>;
60
+ rows: z.ZodArray<z.ZodObject<{
61
+ acceptanceCriterion: z.ZodString;
62
+ scenario: z.ZodOptional<z.ZodString>;
63
+ testEvidence: z.ZodOptional<z.ZodArray<z.ZodString>>;
64
+ contractEvidence: z.ZodOptional<z.ZodArray<z.ZodString>>;
65
+ manualEvidence: z.ZodOptional<z.ZodString>;
66
+ changedFiles: z.ZodArray<z.ZodString>;
67
+ validationEvidence: z.ZodOptional<z.ZodString>;
68
+ reviewerEvidence: z.ZodOptional<z.ZodString>;
69
+ commandEvidence: z.ZodOptional<z.ZodObject<{
70
+ capability: z.ZodEnum<{
71
+ contract: "contract";
72
+ coverage: "coverage";
73
+ "fault-injection": "fault-injection";
74
+ lint: "lint";
75
+ migration: "migration";
76
+ native: "native";
77
+ reproducibility: "reproducibility";
78
+ security: "security";
79
+ "test-full": "test-full";
80
+ "test-related": "test-related";
81
+ typecheck: "typecheck";
82
+ website: "website";
83
+ }>;
84
+ command: z.ZodString;
85
+ scope: z.ZodArray<z.ZodString>;
86
+ relevantPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
87
+ evidenceKey: z.ZodString;
88
+ }, z.core.$strict>>;
89
+ }, z.core.$strict>>;
90
+ }, z.core.$strict>>;
91
+ contractValidation: z.ZodOptional<z.ZodObject<{
92
+ version: z.ZodLiteral<1>;
93
+ provenance: z.ZodOptional<z.ZodObject<{
94
+ receiptId: z.ZodString;
95
+ artifactDigest: z.ZodString;
96
+ specId: z.ZodString;
97
+ issuerId: z.ZodString;
98
+ }, z.core.$strict>>;
99
+ kind: z.ZodEnum<{
100
+ api: "api";
101
+ event: "event";
102
+ graphql: "graphql";
103
+ mcp: "mcp";
104
+ ui: "ui";
105
+ }>;
106
+ passed: z.ZodBoolean;
107
+ reportPath: z.ZodOptional<z.ZodString>;
108
+ summary: z.ZodOptional<z.ZodString>;
109
+ }, z.core.$strict>>;
110
+ reviewFeedback: z.ZodOptional<z.ZodObject<{
111
+ schema_version: z.ZodString;
112
+ specId: z.ZodString;
113
+ verdict: z.ZodEnum<{
114
+ approved: "approved";
115
+ "changes-requested": "changes-requested";
116
+ }>;
117
+ reviewer: z.ZodObject<{
118
+ kind: z.ZodEnum<{
119
+ automation: "automation";
120
+ human: "human";
121
+ "spec-review-agent": "spec-review-agent";
122
+ }>;
123
+ agent: z.ZodString;
124
+ verdict: z.ZodEnum<{
125
+ approved: "approved";
126
+ "changes-requested": "changes-requested";
127
+ }>;
128
+ }, z.core.$strip>;
129
+ blockers: z.ZodArray<z.ZodString>;
130
+ suggestions: z.ZodArray<z.ZodString>;
131
+ body: z.ZodString;
132
+ reviewedAt: z.ZodISODateTime;
133
+ }, z.core.$strip>>;
134
+ implementationReview: z.ZodOptional<z.ZodObject<{
135
+ schema_version: z.ZodString;
136
+ specId: z.ZodString;
137
+ verdict: z.ZodEnum<{
138
+ approved: "approved";
139
+ "changes-requested": "changes-requested";
140
+ }>;
141
+ reviewer: z.ZodObject<{
142
+ kind: z.ZodEnum<{
143
+ human: "human";
144
+ "implementation-review-agent": "implementation-review-agent";
145
+ }>;
146
+ agent: z.ZodString;
147
+ verdict: z.ZodEnum<{
148
+ approved: "approved";
149
+ "changes-requested": "changes-requested";
150
+ }>;
151
+ sessionId: z.ZodOptional<z.ZodString>;
152
+ }, z.core.$strip>;
153
+ blockers: z.ZodArray<z.ZodString>;
154
+ suggestions: z.ZodArray<z.ZodString>;
155
+ body: z.ZodString;
156
+ reviewedAt: z.ZodISODateTime;
157
+ }, z.core.$strip>>;
158
+ }, z.core.$strip>;
159
+ export declare const UpdateStatusEvidenceTransportSchema: z.ZodObject<{
160
+ discovery: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
161
+ taskPlan: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
162
+ traceabilityMatrix: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
163
+ contractValidation: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
164
+ reviewFeedback: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
165
+ implementationReview: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
166
+ }, z.core.$strip>;
167
+ type PersistedEvidence = {
168
+ ok: true;
169
+ written: string[];
170
+ } | {
171
+ ok: false;
172
+ errors: string[];
173
+ };
174
+ export declare function persistEvidencePayload(args: {
175
+ projectId: string;
176
+ specId: string;
177
+ evidence: UpdateStatusEvidencePayload;
178
+ }): Promise<PersistedEvidence>;
179
+ export {};
180
+ //# sourceMappingURL=evidence-payload.d.ts.map