@danielstyle/featflow 0.6.4 → 0.7.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.
@@ -4,7 +4,9 @@ import path from "node:path";
4
4
 
5
5
  import { changedFiles, matchesPattern } from "./changed-files.mjs";
6
6
  import { currentBranch } from "./git.mjs";
7
- import { validateActiveFeaturePlan } from "./plan.mjs";
7
+ import { refExists, resolveNotesRef } from "./notes.mjs";
8
+ import { recallFeaturesForPrompt } from "./notes-recall.mjs";
9
+ import { listFeatureFiles, validateActiveFeaturePlan } from "./plan.mjs";
8
10
  import { checkWorkflowReady } from "./policy.mjs";
9
11
  import { evaluateFileSizeBudget } from "./size-check.mjs";
10
12
 
@@ -272,7 +274,7 @@ export function evaluatePreToolUse(repoRoot, config, payload, env = process.env)
272
274
  return { decision: "allow" };
273
275
  }
274
276
 
275
- export function evaluateUserPrompt(config, payload) {
277
+ export function evaluateUserPrompt(config, payload, options = {}) {
276
278
  const lower = (payload.prompt ?? "").toLowerCase();
277
279
  const reminders = [];
278
280
 
@@ -304,17 +306,45 @@ export function evaluateUserPrompt(config, payload) {
304
306
  );
305
307
  }
306
308
 
307
- if (reminders.length === 0) {
308
- return { additionalContext: "" };
309
+ const sections = [];
310
+ if (reminders.length > 0) {
311
+ const modeNote =
312
+ config.mode === "developer-branch"
313
+ ? `Branch mode: developer-branch (base from \`git config ${config.developerBranchConfigKey}\`, finish with \`featflow finish <branch>\`).`
314
+ : `Branch mode: trunk (base from \`${config.baseBranch}\`, finish with \`featflow finish <branch>\`).`;
315
+ sections.push(`featflow reminders:\n- ${modeNote}\n- ${reminders.join("\n- ")}`);
309
316
  }
310
317
 
311
- const modeNote =
312
- config.mode === "developer-branch"
313
- ? `Branch mode: developer-branch (base from \`git config ${config.developerBranchConfigKey}\`, finish with \`featflow finish <branch>\`).`
314
- : `Branch mode: trunk (base from \`${config.baseBranch}\`, finish with \`featflow finish <branch>\`).`;
318
+ const repoRoot = options.repoRoot || "";
319
+ const shouldRecall =
320
+ Boolean(repoRoot) &&
321
+ config?.notes?.recallInPromptHook !== false &&
322
+ (config?.featureStorage === "notes" || Boolean(config?.notes) || refExists(resolveNotesRef(config), repoRoot));
323
+
324
+ if (shouldRecall && payload.prompt) {
325
+ try {
326
+ const recalled = recallFeaturesForPrompt(repoRoot, config, payload.prompt);
327
+ if (recalled.length > 0) {
328
+ const lines = recalled.map((item) => {
329
+ const loc = item.source === "note" ? `note@${item.commitSha?.slice(0, 8)}` : item.path;
330
+ const dec = item.decision ? ` | Decision: ${item.decision.slice(0, 120)}` : "";
331
+ return `- ${item.id} (${loc}): ${item.title}${dec}`;
332
+ });
333
+ sections.push(
334
+ [
335
+ "featflow related history (auto-recalled from git notes & legacy records):",
336
+ ...lines,
337
+ "Run `featflow show <id>` or `featflow history <path>` for full Plan / Decisions / Verification context.",
338
+ ].join("\n"),
339
+ );
340
+ }
341
+ } catch {
342
+ // Never block prompt submission on history recall errors
343
+ }
344
+ }
315
345
 
316
346
  return {
317
- additionalContext: `featflow reminders:\n- ${modeNote}\n- ${reminders.join("\n- ")}`,
347
+ additionalContext: sections.join("\n\n"),
318
348
  };
319
349
  }
320
350
 
@@ -394,6 +424,13 @@ export function evaluateStopGate(repoRoot, config, env = process.env) {
394
424
 
395
425
  if (files.some((file) => file.startsWith(`${config.featuresDir}/`))) {
396
426
  recommendations.push("Feature records changed: ensure `Verification` and `Handoff` sections reflect actual results.");
427
+ } else if (
428
+ config.featureStorage === "notes" &&
429
+ listFeatureFiles(repoRoot, ".featflow/features", "active").length > 0
430
+ ) {
431
+ recommendations.push(
432
+ `Active local feature record present: ensure \`Verification\` and \`Handoff\` are updated before \`featflow finish\` archives it to \`${resolveNotesRef(config)}\`.`,
433
+ );
397
434
  }
398
435
 
399
436
  if (recommendations.length === 0) {
package/src/index.mjs CHANGED
@@ -12,3 +12,7 @@ export * from "./issues.mjs";
12
12
  export * from "./size-check.mjs";
13
13
  export * from "./regression.mjs";
14
14
  export * from "./skills-manager.mjs";
15
+ export * from "./notes.mjs";
16
+ export * from "./notes-query.mjs";
17
+ export * from "./notes-recall.mjs";
18
+ export * from "./notes-migrate.mjs";
package/src/init-args.mjs CHANGED
@@ -16,6 +16,8 @@ Options:
16
16
  --mode <trunk|developer-branch> Branch topology preset (default: trunk, or prompted on TTY).
17
17
  --finish-target <merge|pr> In trunk mode, whether "finish" merges into base or pushes for PR (default: merge).
18
18
  --features-dir <dir> Custom directory for feature records (default: features).
19
+ --feature-storage <files|notes> Store completed feature records as repo files or Git Notes (refs/notes/featflow).
20
+ --notes-storage Shortcut for --feature-storage notes.
19
21
  --local-features Store feature records locally (.gitignore features/) instead of tracking in Git.
20
22
  --track-pointer Track features/current-feature.md in Git instead of ignoring it locally.
21
23
  --with-githooks Copy tracked .githooks/ and enable core.hooksPath when not claimed by Husky/Lefthook.
@@ -63,6 +65,7 @@ export function parseInitArgs(argv) {
63
65
  finishTarget: "",
64
66
  finishTargetExplicit: false,
65
67
  featuresDir: "",
68
+ featureStorage: "",
66
69
  localFeatures: false,
67
70
  trackPointer: false,
68
71
  withGithooks: false,
@@ -137,6 +140,20 @@ export function parseInitArgs(argv) {
137
140
  if (!options.featuresDir) fail("Missing value for --features-dir.", INIT_USAGE);
138
141
  continue;
139
142
  }
143
+ if (arg === "--feature-storage" || arg.startsWith("--feature-storage=")) {
144
+ const val = arg.startsWith("--feature-storage=")
145
+ ? arg.slice("--feature-storage=".length)
146
+ : (argv[++i] ?? "");
147
+ if (!["files", "notes"].includes(val)) {
148
+ fail(`Invalid value for --feature-storage "${val}". Expected "files" or "notes".`, INIT_USAGE);
149
+ }
150
+ options.featureStorage = val;
151
+ continue;
152
+ }
153
+ if (arg === "--notes-storage") {
154
+ options.featureStorage = "notes";
155
+ continue;
156
+ }
140
157
  if (arg === "--local-features") {
141
158
  options.localFeatures = true;
142
159
  continue;
@@ -0,0 +1,399 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ readRecordsFromCommit,
6
+ resolveNotesRef,
7
+ runGitRaw,
8
+ sha256Text,
9
+ syncNotesWithRemote,
10
+ upsertRecordsOnCommit,
11
+ } from "./notes.mjs";
12
+ import { extractFrontmatter, listFeatureFiles, resolveActiveFeaturePath } from "./plan.mjs";
13
+
14
+ const LOCAL_FEATURES_DIR = ".featflow/features";
15
+
16
+ function formatIsoNow(date = new Date()) {
17
+ const pad = (n) => String(n).padStart(2, "0");
18
+ const offsetMinutes = -date.getTimezoneOffset();
19
+ const sign = offsetMinutes >= 0 ? "+" : "-";
20
+ const absOffset = Math.abs(offsetMinutes);
21
+ const tz = offsetMinutes === 0 ? "Z" : `${sign}${pad(Math.floor(absOffset / 60))}:${pad(absOffset % 60)}`;
22
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}${tz}`;
23
+ }
24
+
25
+ export function markRecordDoneContent(markdown, nowIso = formatIsoNow()) {
26
+ let content = String(markdown ?? "");
27
+ if (/^---\r?\n[\s\S]*?\r?\n---/.test(content)) {
28
+ content = content.replace(/^status:\s*.*$/m, "status: done");
29
+ if (/^updated:\s*.*$/m.test(content)) {
30
+ content = content.replace(/^updated:\s*.*$/m, `updated: ${nowIso}`);
31
+ }
32
+ }
33
+ return content;
34
+ }
35
+
36
+ export function findTaskActiveFeatureRecord(worktreeRoot, config, branchName = "") {
37
+ const featuresDir = config?.featuresDir || "features";
38
+ const candidates = [
39
+ ...listFeatureFiles(worktreeRoot, LOCAL_FEATURES_DIR, "active"),
40
+ ...(featuresDir === LOCAL_FEATURES_DIR ? [] : listFeatureFiles(worktreeRoot, featuresDir, "active")),
41
+ ];
42
+
43
+ if (candidates.length === 1) {
44
+ return candidates[0];
45
+ }
46
+
47
+ if (candidates.length > 1 && branchName) {
48
+ for (const relPath of candidates) {
49
+ const absPath = path.resolve(worktreeRoot, relPath);
50
+ if (!existsSync(absPath)) continue;
51
+ const fm = extractFrontmatter(readFileSync(absPath, "utf8"));
52
+ if (fm.branch === branchName) {
53
+ return relPath;
54
+ }
55
+ }
56
+ }
57
+
58
+ const pointerResolved = resolveActiveFeaturePath(worktreeRoot, featuresDir);
59
+ if (pointerResolved && existsSync(path.resolve(worktreeRoot, pointerResolved))) {
60
+ return pointerResolved;
61
+ }
62
+
63
+ return null;
64
+ }
65
+
66
+ export function archiveFeatureFileToNotes(repoRoot, config, options = {}) {
67
+ const notesRef = resolveNotesRef(config);
68
+ const targetCwd = options.worktreePath || repoRoot;
69
+ const recordRelPath =
70
+ options.filePath ||
71
+ findTaskActiveFeatureRecord(targetCwd, config, options.branch || "");
72
+
73
+ if (!recordRelPath) {
74
+ return { archived: false, reason: "no-active-record" };
75
+ }
76
+
77
+ const absPath = path.resolve(targetCwd, recordRelPath);
78
+ if (!existsSync(absPath)) {
79
+ throw new Error(`Feature record not found: ${recordRelPath}`);
80
+ }
81
+
82
+ const commitRef = options.commit || "HEAD";
83
+ const revRes = runGitRaw(["rev-parse", "--verify", `${commitRef}^{commit}`], repoRoot);
84
+ if (revRes.status !== 0 || !revRes.stdout.trim()) {
85
+ throw new Error(`Could not resolve target commit "${commitRef}" for archiving feature note.`);
86
+ }
87
+ const commitSha = revRes.stdout.trim();
88
+
89
+ const rawContent = readFileSync(absPath, "utf8");
90
+ const finalContent = options.markDone !== false ? markRecordDoneContent(rawContent) : rawContent;
91
+ const fm = extractFrontmatter(finalContent);
92
+ const id = fm.id || path.basename(absPath, ".md");
93
+ const normalizedRel = recordRelPath.replaceAll("\\", "/");
94
+
95
+ if (options.dryRun) {
96
+ return {
97
+ archived: true,
98
+ dryRun: true,
99
+ id,
100
+ commitSha,
101
+ notesRef,
102
+ sourcePath: normalizedRel,
103
+ };
104
+ }
105
+
106
+ const writeRes = upsertRecordsOnCommit(
107
+ commitSha,
108
+ { id, content: finalContent, legacyPath: normalizedRel },
109
+ repoRoot,
110
+ notesRef,
111
+ );
112
+
113
+ let sourceDisposition = "kept";
114
+ if (options.deleteSource) {
115
+ rmSync(absPath, { force: true });
116
+ sourceDisposition = "deleted";
117
+ } else if (options.moveLocalDone && normalizedRel.startsWith(`${LOCAL_FEATURES_DIR}/active/`)) {
118
+ const donePath = path.resolve(targetCwd, LOCAL_FEATURES_DIR, "done", `${id}.md`);
119
+ mkdirSync(path.dirname(donePath), { recursive: true });
120
+ writeFileSync(donePath, finalContent, "utf8");
121
+ rmSync(absPath, { force: true });
122
+ sourceDisposition = "moved-local-done";
123
+ }
124
+
125
+ let syncResult = null;
126
+ if (options.sync) {
127
+ syncResult = syncNotesWithRemote(repoRoot, config, {
128
+ notesRef,
129
+ remote: options.remote,
130
+ push: options.push !== false,
131
+ bestEffort: Boolean(options.bestEffortSync),
132
+ });
133
+ }
134
+
135
+ return {
136
+ archived: true,
137
+ dryRun: false,
138
+ id,
139
+ commitSha,
140
+ blobSha: writeRes.blobSha,
141
+ notesRef,
142
+ sourcePath: normalizedRel,
143
+ sourceDisposition,
144
+ syncResult,
145
+ };
146
+ }
147
+
148
+ function scanHistoryForDoneFiles(repoRoot, donePrefix, currentSet, includeMerges = false) {
149
+ const args = [
150
+ "log",
151
+ ...(includeMerges ? [] : ["--no-merges"]),
152
+ "--no-renames",
153
+ "--name-status",
154
+ "--format=___COMMIT___%H\t%s",
155
+ ];
156
+ const res = runGitRaw(args, repoRoot, { maxBuffer: 128 * 1024 * 1024 });
157
+ if (res.status !== 0) {
158
+ throw new Error(`git log failed while scanning legacy feature records${res.stderr ? `:\n${res.stderr}` : "."}`);
159
+ }
160
+
161
+ const commits = [];
162
+ let current = null;
163
+ for (const line of res.stdout.split(/\r?\n/)) {
164
+ if (line.startsWith("___COMMIT___")) {
165
+ const [sha, ...subjectParts] = line.slice("___COMMIT___".length).split("\t");
166
+ current = { sha, subject: subjectParts.join("\t"), hasCode: false, added: [], touched: [] };
167
+ commits.push(current);
168
+ continue;
169
+ }
170
+ if (!current || !line) continue;
171
+ const [status, filePath] = line.split("\t");
172
+ if (!filePath) continue;
173
+ if (!filePath.startsWith("features/") && !filePath.startsWith(donePrefix.split("/")[0] + "/")) {
174
+ current.hasCode = true;
175
+ }
176
+ if (filePath.startsWith(donePrefix)) {
177
+ const base = filePath.slice(donePrefix.length);
178
+ if (currentSet.has(base)) {
179
+ current.touched.push(base);
180
+ if (status === "A") {
181
+ current.added.push(base);
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ const mapped = new Map();
188
+ for (const commit of commits) {
189
+ for (const file of commit.added) {
190
+ if (!mapped.has(file)) {
191
+ mapped.set(file, commit);
192
+ }
193
+ }
194
+ }
195
+ for (const commit of commits) {
196
+ for (const file of commit.touched) {
197
+ if (!mapped.has(file)) {
198
+ mapped.set(file, commit);
199
+ }
200
+ }
201
+ }
202
+ return mapped;
203
+ }
204
+
205
+ export function planLegacyMigration(repoRoot, config) {
206
+ const featuresDir = (config?.featuresDir || "features").replaceAll("\\", "/").replace(/\/+$/, "");
207
+ const doneDir = path.resolve(repoRoot, featuresDir, "done");
208
+ if (!existsSync(doneDir)) {
209
+ return {
210
+ featuresDir,
211
+ doneDir,
212
+ totalFiles: 0,
213
+ mappedCount: 0,
214
+ unmappedFiles: [],
215
+ withCodeInSameCommit: 0,
216
+ docsOnlyCommit: 0,
217
+ uniqueCommits: 0,
218
+ multiFileCommits: [],
219
+ entries: [],
220
+ groups: [],
221
+ };
222
+ }
223
+
224
+ const fileNames = readdirSync(doneDir)
225
+ .filter((name) => name.endsWith(".md") && !name.startsWith("_"))
226
+ .sort();
227
+ const currentSet = new Set(fileNames);
228
+ const donePrefix = `${featuresDir}/done/`;
229
+
230
+ const mapped = scanHistoryForDoneFiles(repoRoot, donePrefix, currentSet, false);
231
+ const missingAfterNoMerges = fileNames.filter((name) => !mapped.has(name));
232
+ if (missingAfterNoMerges.length > 0) {
233
+ const mergeMapped = scanHistoryForDoneFiles(repoRoot, donePrefix, new Set(missingAfterNoMerges), true);
234
+ for (const [name, commit] of mergeMapped.entries()) {
235
+ if (!mapped.has(name)) {
236
+ mapped.set(name, commit);
237
+ }
238
+ }
239
+ }
240
+
241
+ const entries = [];
242
+ const unmappedFiles = [];
243
+ const groupsMap = new Map();
244
+ let withCodeInSameCommit = 0;
245
+ let docsOnlyCommit = 0;
246
+
247
+ for (const name of fileNames) {
248
+ const relPath = `${donePrefix}${name}`;
249
+ const absPath = path.join(doneDir, name);
250
+ const content = readFileSync(absPath, "utf8");
251
+ const fm = extractFrontmatter(content);
252
+ const id = fm.id || path.basename(name, ".md");
253
+ const commit = mapped.get(name);
254
+ if (!commit) {
255
+ unmappedFiles.push(relPath);
256
+ continue;
257
+ }
258
+ if (commit.hasCode) withCodeInSameCommit += 1;
259
+ else docsOnlyCommit += 1;
260
+
261
+ const entry = {
262
+ id,
263
+ fileName: name,
264
+ relPath,
265
+ absPath,
266
+ commitSha: commit.sha,
267
+ commitSubject: commit.subject,
268
+ hasCodeInCommit: commit.hasCode,
269
+ sha256: sha256Text(content),
270
+ content,
271
+ };
272
+ entries.push(entry);
273
+
274
+ if (!groupsMap.has(commit.sha)) {
275
+ groupsMap.set(commit.sha, {
276
+ commitSha: commit.sha,
277
+ commitSubject: commit.subject,
278
+ hasCodeInCommit: commit.hasCode,
279
+ entries: [],
280
+ });
281
+ }
282
+ groupsMap.get(commit.sha).entries.push(entry);
283
+ }
284
+
285
+ const groups = [...groupsMap.values()];
286
+ const multiFileCommits = groups
287
+ .filter((g) => g.entries.length > 1)
288
+ .map((g) => ({
289
+ commitSha: g.commitSha,
290
+ commitSubject: g.commitSubject,
291
+ count: g.entries.length,
292
+ files: g.entries.map((e) => e.fileName),
293
+ }));
294
+
295
+ return {
296
+ featuresDir,
297
+ doneDir,
298
+ totalFiles: fileNames.length,
299
+ mappedCount: entries.length,
300
+ unmappedFiles,
301
+ withCodeInSameCommit,
302
+ docsOnlyCommit,
303
+ uniqueCommits: groups.length,
304
+ multiFileCommits,
305
+ entries,
306
+ groups,
307
+ };
308
+ }
309
+
310
+ export function runLegacyMigration(repoRoot, config, options = {}) {
311
+ const notesRef = resolveNotesRef(config);
312
+ const plan = planLegacyMigration(repoRoot, config);
313
+
314
+ if (options.dryRun || plan.totalFiles === 0) {
315
+ return {
316
+ dryRun: Boolean(options.dryRun),
317
+ notesRef,
318
+ ...plan,
319
+ migratedCount: 0,
320
+ verifiedCount: 0,
321
+ prunedCount: 0,
322
+ syncResult: null,
323
+ };
324
+ }
325
+
326
+ if (plan.unmappedFiles.length > 0 && !options.allowUnmapped) {
327
+ throw new Error(
328
+ `Refusing to migrate because ${plan.unmappedFiles.length} file(s) in ${plan.featuresDir}/done/ have no Git commit history yet:\n` +
329
+ plan.unmappedFiles.map((f) => ` - ${f}`).join("\n"),
330
+ );
331
+ }
332
+
333
+ for (const group of plan.groups) {
334
+ upsertRecordsOnCommit(
335
+ group.commitSha,
336
+ group.entries.map((entry) => ({
337
+ id: entry.id,
338
+ legacyPath: entry.relPath,
339
+ content: entry.content,
340
+ })),
341
+ repoRoot,
342
+ notesRef,
343
+ );
344
+ }
345
+
346
+ let verifiedCount = 0;
347
+ const mismatches = [];
348
+ for (const group of plan.groups) {
349
+ const readBack = readRecordsFromCommit(group.commitSha, repoRoot, notesRef);
350
+ const byId = new Map(readBack.map((rec) => [rec.id, rec]));
351
+ for (const entry of group.entries) {
352
+ const stored = byId.get(entry.id);
353
+ if (!stored) {
354
+ mismatches.push(`${entry.relPath}: missing record "${entry.id}" on ${group.commitSha}`);
355
+ continue;
356
+ }
357
+ const actualHash = sha256Text(stored.content);
358
+ if (actualHash !== entry.sha256) {
359
+ mismatches.push(`${entry.relPath}: SHA-256 mismatch (expected ${entry.sha256}, got ${actualHash})`);
360
+ continue;
361
+ }
362
+ verifiedCount += 1;
363
+ }
364
+ }
365
+
366
+ if (mismatches.length > 0 || verifiedCount !== plan.entries.length) {
367
+ throw new Error(
368
+ `Migration integrity verification failed (${verifiedCount}/${plan.entries.length} verified). Legacy files were NOT deleted:\n` +
369
+ mismatches.slice(0, 10).map((m) => ` - ${m}`).join("\n"),
370
+ );
371
+ }
372
+
373
+ let syncResult = null;
374
+ if (!options.noPush) {
375
+ syncResult = syncNotesWithRemote(repoRoot, config, {
376
+ notesRef,
377
+ remote: options.remote,
378
+ push: true,
379
+ });
380
+ }
381
+
382
+ let prunedCount = 0;
383
+ if (options.pruneLegacy) {
384
+ for (const entry of plan.entries) {
385
+ rmSync(entry.absPath, { force: true });
386
+ prunedCount += 1;
387
+ }
388
+ }
389
+
390
+ return {
391
+ dryRun: false,
392
+ notesRef,
393
+ ...plan,
394
+ migratedCount: plan.entries.length,
395
+ verifiedCount,
396
+ prunedCount,
397
+ syncResult,
398
+ };
399
+ }