Files
msd-core/get-shit-done/bin/lib/template.cjs
Ned Malki f8526b5c01 fix: complete planningDir migration for config CRUD, template fill, and verify (#1986)
* fix(config): route CRUD through planningDir to honor GSD_PROJECT

PR #1484 added planningDir(cwd) and the GSD_PROJECT env var so a workspace
can host multiple projects under .planning/{project}/. loadConfig() in
core.cjs (line 256) was migrated at the time, but the four CRUD entry points
in config.cjs and the planningPaths() helper in core.cjs were left resolving
against planningRoot(cwd).

The result was a silent split-brain in any multi-project workspace:

  - cmdConfigGet, setConfigValue, ensureConfigFile, cmdConfigNewProject
    all wrote to and read from .planning/config.json
  - loadConfig read from .planning/{GSD_PROJECT}/config.json

So `gsd-tools config-get workflow.discuss_mode` returned "unset" even when
the value was correctly stored in the project-routed file, because the
reader and writer pointed at different paths.

planningPaths() carried a comment that "Shared paths (project, config)
always resolve to the root .planning/" which described the original intent,
but loadConfig() already contradicted that intent for config.json. project
and config now both resolve through planningDir() so the contract matches
the only function that successfully read config.json in the multi-project
case.

Single-project users (no GSD_PROJECT set) are unaffected: planningRoot()
and planningDir() return the same path when no project is configured.

Verification: in a workspace with .planning/projectA/config.json and
GSD_PROJECT=projectA, `gsd-tools config-get workflow.discuss_mode` now
returns the value instead of "Error: Key not found". Backward compat
verified by running the same command without GSD_PROJECT in a
single-project layout.

Affected sites:
- get-shit-done/bin/lib/config.cjs cmdConfigNewProject (line 199)
- get-shit-done/bin/lib/config.cjs ensureConfigFile (line 244)
- get-shit-done/bin/lib/config.cjs setConfigValue (line 294)
- get-shit-done/bin/lib/config.cjs cmdConfigGet (line 367)
- get-shit-done/bin/lib/core.cjs planningPaths.config (line 706)
- get-shit-done/bin/lib/core.cjs planningPaths.project (line 705)

* fix(template): emit project-aware references in template fill plan

The template fill plan body hardcoded `@.planning/PROJECT.md`,
`@.planning/ROADMAP.md`, and `@.planning/STATE.md` references. In a
multi-project workspace these resolve to nothing because the actual
project, roadmap, and state files live under .planning/{GSD_PROJECT}/.

`gsd-tools verify references` reports them as missing on every PLAN.md
generated by template fill in any GSD_PROJECT-routed workspace.

Fix: route the references through planningDir(cwd), normalize via the
existing toPosixPath helper for cross-platform path consistency, and
embed them as `@<relative-path>` matching the phase-relative reference
pattern used elsewhere in the file.

Single-project users (no GSD_PROJECT set) get exactly the same output
as before because planningDir() falls back to .planning/ when no project
is active.

Affected site: get-shit-done/bin/lib/template.cjs cmdTemplateFill plan
branch (lines 142-145, the @.planning/ refs in the Context section).

* fix(verify): planningDir for cmdValidateHealth and regenerateState

cmdValidateHealth resolved projectPath and configPath via planningRoot(cwd)
while ROADMAP/STATE/phases/requirements went through planningDir(cwd). The
inconsistency reported "missing PROJECT.md" and "missing config.json" in
multi-project layouts even when the project-routed copies existed and the
config CRUD writers (now also routed by the previous commit in this PR)
were writing to them.

regenerateState (the /gsd:health --repair STATE.md regeneration path)
hardcoded `See: .planning/PROJECT.md` in the generated body, which fails
the same reference check it just regenerated for in any GSD_PROJECT-routed
workspace.

Fix: route both sites through planningDir(cwd). For regenerateState, derive
a POSIX-style relative reference from the resolved path so the reference
matches verify references' resolution rules. Also dropped the planningRoot
import from verify.cjs since it is no longer used after this change.

Single-project users (no GSD_PROJECT set) get the same paths as before:
planningDir() falls back to .planning/ when no project is configured.

Affected sites:
- get-shit-done/bin/lib/verify.cjs cmdValidateHealth (lines 536-541)
- get-shit-done/bin/lib/verify.cjs regenerateState repair (line 865)
- get-shit-done/bin/lib/verify.cjs core.cjs import (line 8, dropped unused
  planningRoot)
2026-04-10 10:49:42 -04:00

227 lines
7.4 KiB
JavaScript

/**
* Template — Template selection and fill operations
*/
const fs = require('fs');
const path = require('path');
const { normalizePhaseName, findPhaseInternal, generateSlugInternal, normalizeMd, toPosixPath, planningDir, output, error } = require('./core.cjs');
const { reconstructFrontmatter } = require('./frontmatter.cjs');
function cmdTemplateSelect(cwd, planPath, raw) {
if (!planPath) {
error('plan-path required');
}
try {
const fullPath = path.join(cwd, planPath);
const content = fs.readFileSync(fullPath, 'utf-8');
// Simple heuristics
const taskMatch = content.match(/###\s*Task\s*\d+/g) || [];
const taskCount = taskMatch.length;
const decisionMatch = content.match(/decision/gi) || [];
const hasDecisions = decisionMatch.length > 0;
// Count file mentions
const fileMentions = new Set();
const filePattern = /`([^`]+\.[a-zA-Z]+)`/g;
let m;
while ((m = filePattern.exec(content)) !== null) {
if (m[1].includes('/') && !m[1].startsWith('http')) {
fileMentions.add(m[1]);
}
}
const fileCount = fileMentions.size;
let template = 'templates/summary-standard.md';
let type = 'standard';
if (taskCount <= 2 && fileCount <= 3 && !hasDecisions) {
template = 'templates/summary-minimal.md';
type = 'minimal';
} else if (hasDecisions || fileCount > 6 || taskCount > 5) {
template = 'templates/summary-complex.md';
type = 'complex';
}
const result = { template, type, taskCount, fileCount, hasDecisions };
output(result, raw, template);
} catch (e) {
// Fallback to standard
output({ template: 'templates/summary-standard.md', type: 'standard', error: e.message }, raw, 'templates/summary-standard.md');
}
}
function cmdTemplateFill(cwd, templateType, options, raw) {
if (!templateType) { error('template type required: summary, plan, or verification'); }
if (!options.phase) { error('--phase required'); }
const phaseInfo = findPhaseInternal(cwd, options.phase);
if (!phaseInfo || !phaseInfo.found) { output({ error: 'Phase not found', phase: options.phase }, raw); return; }
const padded = normalizePhaseName(options.phase);
const today = new Date().toISOString().split('T')[0];
const phaseName = options.name || phaseInfo.phase_name || 'Unnamed';
const phaseSlug = phaseInfo.phase_slug || generateSlugInternal(phaseName);
const phaseId = `${padded}-${phaseSlug}`;
const planNum = (options.plan || '01').padStart(2, '0');
const fields = options.fields || {};
let frontmatter, body, fileName;
switch (templateType) {
case 'summary': {
frontmatter = {
phase: phaseId,
plan: planNum,
subsystem: '[primary category]',
tags: [],
provides: [],
affects: [],
'tech-stack': { added: [], patterns: [] },
'key-files': { created: [], modified: [] },
'key-decisions': [],
'patterns-established': [],
duration: '[X]min',
completed: today,
...fields,
};
body = [
`# Phase ${options.phase}: ${phaseName} Summary`,
'',
'**[Substantive one-liner describing outcome]**',
'',
'## Performance',
'- **Duration:** [time]',
'- **Tasks:** [count completed]',
'- **Files modified:** [count]',
'',
'## Accomplishments',
'- [Key outcome 1]',
'- [Key outcome 2]',
'',
'## Task Commits',
'1. **Task 1: [task name]** - `hash`',
'',
'## Files Created/Modified',
'- `path/to/file.ts` - What it does',
'',
'## Decisions & Deviations',
'[Key decisions or "None - followed plan as specified"]',
'',
'## Next Phase Readiness',
'[What\'s ready for next phase]',
].join('\n');
fileName = `${padded}-${planNum}-SUMMARY.md`;
break;
}
case 'plan': {
const planType = options.type || 'execute';
const wave = parseInt(options.wave) || 1;
frontmatter = {
phase: phaseId,
plan: planNum,
type: planType,
wave,
depends_on: [],
files_modified: [],
autonomous: true,
user_setup: [],
must_haves: { truths: [], artifacts: [], key_links: [] },
...fields,
};
const planBase = planningDir(cwd);
const projectRef = toPosixPath(path.relative(cwd, path.join(planBase, 'PROJECT.md')));
const roadmapRef = toPosixPath(path.relative(cwd, path.join(planBase, 'ROADMAP.md')));
const stateRef = toPosixPath(path.relative(cwd, path.join(planBase, 'STATE.md')));
body = [
`# Phase ${options.phase} Plan ${planNum}: [Title]`,
'',
'## Objective',
'- **What:** [What this plan builds]',
'- **Why:** [Why it matters for the phase goal]',
'- **Output:** [Concrete deliverable]',
'',
'## Context',
`@${projectRef}`,
`@${roadmapRef}`,
`@${stateRef}`,
'',
'## Tasks',
'',
'<task type="code">',
' <name>[Task name]</name>',
' <files>[file paths]</files>',
' <action>[What to do]</action>',
' <verify>[How to verify]</verify>',
' <done>[Definition of done]</done>',
'</task>',
'',
'## Verification',
'[How to verify this plan achieved its objective]',
'',
'## Success Criteria',
'- [ ] [Criterion 1]',
'- [ ] [Criterion 2]',
].join('\n');
fileName = `${padded}-${planNum}-PLAN.md`;
break;
}
case 'verification': {
frontmatter = {
phase: phaseId,
verified: new Date().toISOString(),
status: 'pending',
score: '0/0 must-haves verified',
...fields,
};
body = [
`# Phase ${options.phase}: ${phaseName} — Verification`,
'',
'## Observable Truths',
'| # | Truth | Status | Evidence |',
'|---|-------|--------|----------|',
'| 1 | [Truth] | pending | |',
'',
'## Required Artifacts',
'| Artifact | Expected | Status | Details |',
'|----------|----------|--------|---------|',
'| [path] | [what] | pending | |',
'',
'## Key Link Verification',
'| From | To | Via | Status | Details |',
'|------|----|----|--------|---------|',
'| [source] | [target] | [connection] | pending | |',
'',
'## Requirements Coverage',
'| Requirement | Status | Blocking Issue |',
'|-------------|--------|----------------|',
'| [req] | pending | |',
'',
'## Result',
'[Pending verification]',
].join('\n');
fileName = `${padded}-VERIFICATION.md`;
break;
}
default:
error(`Unknown template type: ${templateType}. Available: summary, plan, verification`);
return;
}
const fullContent = `---\n${reconstructFrontmatter(frontmatter)}\n---\n\n${body}\n`;
const outPath = path.join(cwd, phaseInfo.directory, fileName);
if (fs.existsSync(outPath)) {
output({ error: 'File already exists', path: toPosixPath(path.relative(cwd, outPath)) }, raw);
return;
}
fs.writeFileSync(outPath, normalizeMd(fullContent), 'utf-8');
const relPath = toPosixPath(path.relative(cwd, outPath));
output({ created: true, path: relPath, template: templateType }, raw, relPath);
}
module.exports = { cmdTemplateSelect, cmdTemplateFill };