@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.
@@ -0,0 +1,366 @@
1
+ import { loadConfig } from "../config.mjs";
2
+ import { fail, findRepoRoot } from "../git.mjs";
3
+ import { resolveNotesRef, syncNotesWithRemote } from "../notes.mjs";
4
+ import { archiveFeatureFileToNotes, runLegacyMigration } from "../notes-migrate.mjs";
5
+ import {
6
+ historyForPaths,
7
+ listFeatureRecords,
8
+ searchFeatureRecords,
9
+ showFeatureRecord,
10
+ } from "../notes-query.mjs";
11
+
12
+ const USAGE = `
13
+ Usage:
14
+ featflow notes <subcommand> [options]
15
+
16
+ Subcommands:
17
+ list List feature records across notes, legacy features/, and local .featflow/features/
18
+ show Show full feature record(s) by ID, legacy path, or commit SHA
19
+ search Search feature records across refs/notes/featflow and legacy features/
20
+ history Find past feature records touching file/directory paths (commit + Changed Files)
21
+ archive Archive an active or completed feature record into Git Notes
22
+ sync Fetch, conflict-free framed merge, and push refs/notes/featflow
23
+ migrate Migrate legacy features/done/*.md onto their historical commits (SHA-256 verified)
24
+
25
+ Top-level aliases:
26
+ featflow list | show | search | history
27
+
28
+ Run "featflow notes <subcommand> --help" for details.
29
+ `.trim();
30
+
31
+ function parseCommonFlags(argv, allowedValueFlags = [], allowedBoolFlags = []) {
32
+ const options = { positional: [], json: false, help: false };
33
+ for (const key of allowedBoolFlags) options[key] = false;
34
+ for (const key of allowedValueFlags) options[key] = "";
35
+
36
+ const valueSet = new Set(allowedValueFlags);
37
+ const boolSet = new Set([...allowedBoolFlags, "json"]);
38
+
39
+ for (let i = 0; i < argv.length; i += 1) {
40
+ const arg = argv[i];
41
+ if (arg === "-h" || arg === "--help") {
42
+ options.help = true;
43
+ continue;
44
+ }
45
+ if (arg.startsWith("--")) {
46
+ const eq = arg.indexOf("=");
47
+ const flag = eq >= 0 ? arg.slice(2, eq) : arg.slice(2);
48
+ const camel = flag.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
49
+ if (boolSet.has(camel) && eq === -1) {
50
+ options[camel] = true;
51
+ continue;
52
+ }
53
+ if (valueSet.has(camel)) {
54
+ const val = eq >= 0 ? arg.slice(eq + 1) : (argv[++i] ?? "");
55
+ if (!val) fail(`Missing value for --${flag}.`);
56
+ options[camel] = val;
57
+ continue;
58
+ }
59
+ fail(`Unknown option: ${arg}`);
60
+ }
61
+ if (arg.startsWith("-")) {
62
+ fail(`Unknown option: ${arg}`);
63
+ }
64
+ options.positional.push(arg);
65
+ }
66
+ return options;
67
+ }
68
+
69
+ function summarizeRecord(rec) {
70
+ return {
71
+ id: rec.id,
72
+ title: rec.title,
73
+ status: rec.status,
74
+ source: rec.source,
75
+ commitSha: rec.commitSha,
76
+ path: rec.path,
77
+ branch: rec.branch,
78
+ owner: rec.owner,
79
+ updated: rec.updated,
80
+ surfaces: rec.surfaces,
81
+ intent: rec.intent,
82
+ decisions: rec.decisions,
83
+ };
84
+ }
85
+
86
+ function handleList(repoRoot, config, argv) {
87
+ const opts = parseCommonFlags(argv, ["status", "source", "limit"]);
88
+ if (opts.help) {
89
+ console.log("Usage: featflow list [--status active|paused|done|all] [--source all|files|notes] [--limit N] [--json]");
90
+ return;
91
+ }
92
+ const records = listFeatureRecords(repoRoot, config, {
93
+ status: opts.status || "all",
94
+ source: opts.source || "all",
95
+ limit: opts.limit ? Number(opts.limit) : 0,
96
+ });
97
+ if (opts.json) {
98
+ console.log(JSON.stringify({ notesRef: resolveNotesRef(config), count: records.length, records: records.map(summarizeRecord) }, null, 2));
99
+ return;
100
+ }
101
+ if (records.length === 0) {
102
+ console.log("No matching feature records found.");
103
+ return;
104
+ }
105
+ for (const rec of records) {
106
+ const loc = rec.source === "note" ? `note@${rec.commitSha?.slice(0, 8)}` : rec.path;
107
+ console.log(`[${rec.status}] ${rec.id} (${loc}) — ${rec.title}`);
108
+ }
109
+ }
110
+
111
+ function handleShow(repoRoot, config, argv) {
112
+ const opts = parseCommonFlags(argv);
113
+ if (opts.help || opts.positional.length === 0) {
114
+ console.log("Usage: featflow show <feature-id|legacy-path|commit-sha> [--json]");
115
+ if (!opts.help) process.exit(1);
116
+ return;
117
+ }
118
+ const result = showFeatureRecord(repoRoot, config, opts.positional[0]);
119
+ if (result.records.length === 0) {
120
+ if (opts.json) {
121
+ console.log(JSON.stringify({ found: false, query: opts.positional[0], candidates: result.candidates ?? [] }, null, 2));
122
+ } else {
123
+ console.error(`error: Feature record not found: ${opts.positional[0]}`);
124
+ if (result.candidates?.length) {
125
+ console.error(`Did you mean:\n${result.candidates.map((c) => ` - ${c}`).join("\n")}`);
126
+ }
127
+ }
128
+ process.exit(1);
129
+ }
130
+ if (opts.json) {
131
+ console.log(JSON.stringify({ found: true, matchedBy: result.matchedBy, records: result.records }, null, 2));
132
+ return;
133
+ }
134
+ for (let idx = 0; idx < result.records.length; idx += 1) {
135
+ const rec = result.records[idx];
136
+ if (idx > 0) console.log("\n========================================\n");
137
+ const loc = rec.source === "note" ? `note@${rec.commitSha?.slice(0, 8)}` : rec.path;
138
+ console.log(`# [${rec.source}] ${rec.id} (${loc})\n`);
139
+ process.stdout.write(rec.content.endsWith("\n") ? rec.content : `${rec.content}\n`);
140
+ }
141
+ }
142
+
143
+ function handleSearch(repoRoot, config, argv) {
144
+ const opts = parseCommonFlags(argv, ["source", "limit"]);
145
+ if (opts.help || opts.positional.length === 0) {
146
+ console.log("Usage: featflow search <query> [--source all|files|notes] [--limit N] [--json]");
147
+ if (!opts.help) process.exit(1);
148
+ return;
149
+ }
150
+ const query = opts.positional.join(" ");
151
+ const hits = searchFeatureRecords(repoRoot, config, query, {
152
+ source: opts.source || "all",
153
+ limit: opts.limit ? Number(opts.limit) : 20,
154
+ });
155
+ if (opts.json) {
156
+ console.log(
157
+ JSON.stringify(
158
+ {
159
+ query,
160
+ count: hits.length,
161
+ results: hits.map((h) => ({ ...summarizeRecord(h), snippets: h.snippets ?? [] })),
162
+ },
163
+ null,
164
+ 2,
165
+ ),
166
+ );
167
+ return;
168
+ }
169
+ if (hits.length === 0) {
170
+ console.log(`No feature records matched "${query}".`);
171
+ return;
172
+ }
173
+ for (const hit of hits) {
174
+ const loc = hit.source === "note" ? `note@${hit.commitSha?.slice(0, 8)}` : hit.path;
175
+ console.log(`[${hit.status}] ${hit.id} (${loc}) — ${hit.title}`);
176
+ for (const snip of (hit.snippets ?? []).slice(0, 2)) {
177
+ console.log(` L${snip.line}: ${snip.text}`);
178
+ }
179
+ }
180
+ }
181
+
182
+ function handleHistory(repoRoot, config, argv) {
183
+ const opts = parseCommonFlags(argv, ["limit"], ["changed"]);
184
+ if (opts.help || (!opts.changed && opts.positional.length === 0)) {
185
+ console.log("Usage: featflow history <path...> [--limit N] [--json]\n featflow history --changed [--limit N] [--json]");
186
+ if (!opts.help) process.exit(1);
187
+ return;
188
+ }
189
+ const result = historyForPaths(repoRoot, config, opts.positional, {
190
+ changed: opts.changed,
191
+ limit: opts.limit ? Number(opts.limit) : 10,
192
+ });
193
+ if (opts.json) {
194
+ console.log(
195
+ JSON.stringify(
196
+ {
197
+ paths: result.paths,
198
+ count: result.records.length,
199
+ records: result.records.map((r) => ({
200
+ ...summarizeRecord(r),
201
+ matchedBy: r.matchedBy,
202
+ matchedPaths: r.matchedPaths,
203
+ })),
204
+ },
205
+ null,
206
+ 2,
207
+ ),
208
+ );
209
+ return;
210
+ }
211
+ if (result.records.length === 0) {
212
+ console.log(`No historical feature records found for: ${result.paths.join(", ") || "(no changed files)"}`);
213
+ return;
214
+ }
215
+ for (const rec of result.records) {
216
+ const loc = rec.source === "note" ? `note@${rec.commitSha?.slice(0, 8)}` : rec.path;
217
+ console.log(`[${rec.status}] ${rec.id} (${loc}, matched via ${rec.matchedBy}) — ${rec.title}`);
218
+ if (rec.intent) {
219
+ console.log(` Intent: ${rec.intent.slice(0, 180)}`);
220
+ }
221
+ for (const dec of rec.decisions.slice(0, 2)) {
222
+ console.log(` Decision: ${dec.slice(0, 180)}`);
223
+ }
224
+ }
225
+ }
226
+
227
+ function handleArchive(repoRoot, config, argv) {
228
+ const opts = parseCommonFlags(argv, ["commit", "remote"], ["noPush", "deleteSource", "dryRun", "keepStatus"]);
229
+ if (opts.help) {
230
+ console.log("Usage: featflow notes archive [record-path] [--commit <sha>] [--delete-source] [--no-push] [--dry-run] [--json]");
231
+ return;
232
+ }
233
+ const res = archiveFeatureFileToNotes(repoRoot, config, {
234
+ filePath: opts.positional[0] || "",
235
+ commit: opts.commit || "HEAD",
236
+ remote: opts.remote || "",
237
+ markDone: !opts.keepStatus,
238
+ deleteSource: opts.deleteSource,
239
+ dryRun: opts.dryRun,
240
+ sync: !opts.noPush,
241
+ push: !opts.noPush,
242
+ });
243
+ if (!res.archived) {
244
+ fail("No active feature record found to archive. Specify a record path explicitly.");
245
+ }
246
+ if (opts.json) {
247
+ console.log(JSON.stringify(res, null, 2));
248
+ return;
249
+ }
250
+ const verb = res.dryRun ? "[dry-run] Would archive" : "Archived";
251
+ console.log(`${verb} ${res.id} -> ${res.notesRef} @ ${res.commitSha.slice(0, 8)} (source: ${res.sourcePath})`);
252
+ if (res.syncResult?.pushed) {
253
+ console.log(`Synced ${res.notesRef} to ${res.syncResult.remote}.`);
254
+ }
255
+ }
256
+
257
+ function handleSync(repoRoot, config, argv) {
258
+ const opts = parseCommonFlags(argv, ["remote"], ["noPush", "dryRun"]);
259
+ if (opts.help) {
260
+ console.log("Usage: featflow notes sync [--remote <name>] [--no-push] [--dry-run] [--json]");
261
+ return;
262
+ }
263
+ const res = syncNotesWithRemote(repoRoot, config, {
264
+ remote: opts.remote || "",
265
+ push: !opts.noPush,
266
+ dryRun: opts.dryRun,
267
+ });
268
+ if (opts.json) {
269
+ console.log(JSON.stringify(res, null, 2));
270
+ return;
271
+ }
272
+ console.log(`Notes sync (${res.notesRef}): ${res.status}${res.pushed ? ` -> pushed to ${res.remote}` : ""}`);
273
+ }
274
+
275
+ function handleMigrate(repoRoot, config, argv) {
276
+ const opts = parseCommonFlags(argv, ["remote"], ["dryRun", "pruneLegacy", "noPush", "allowUnmapped"]);
277
+ if (opts.help) {
278
+ console.log("Usage: featflow notes migrate [--dry-run] [--prune-legacy] [--no-push] [--remote <name>] [--json]");
279
+ return;
280
+ }
281
+ const res = runLegacyMigration(repoRoot, config, {
282
+ dryRun: opts.dryRun,
283
+ pruneLegacy: opts.pruneLegacy,
284
+ noPush: opts.noPush,
285
+ remote: opts.remote || "",
286
+ allowUnmapped: opts.allowUnmapped,
287
+ });
288
+ if (opts.json) {
289
+ const payload = {
290
+ dryRun: res.dryRun,
291
+ notesRef: res.notesRef,
292
+ totalFiles: res.totalFiles,
293
+ mappedCount: res.mappedCount,
294
+ unmappedFiles: res.unmappedFiles,
295
+ withCodeInSameCommit: res.withCodeInSameCommit,
296
+ docsOnlyCommit: res.docsOnlyCommit,
297
+ uniqueCommits: res.uniqueCommits,
298
+ multiFileCommits: res.multiFileCommits,
299
+ migratedCount: res.migratedCount,
300
+ verifiedCount: res.verifiedCount,
301
+ prunedCount: res.prunedCount,
302
+ syncResult: res.syncResult,
303
+ };
304
+ console.log(JSON.stringify(payload, null, 2));
305
+ return;
306
+ }
307
+
308
+ console.log(`Legacy migration ${res.dryRun ? "(dry-run) " : ""}for ${res.featuresDir}/done/ -> ${res.notesRef}`);
309
+ console.log(` Total done/*.md files: ${res.totalFiles}`);
310
+ console.log(` Mapped to historical commits: ${res.mappedCount} (unmapped: ${res.unmappedFiles.length})`);
311
+ console.log(` Same commit as code: ${res.withCodeInSameCommit} | Docs-only commit: ${res.docsOnlyCommit}`);
312
+ console.log(` Unique target commits: ${res.uniqueCommits} (multi-file commits: ${res.multiFileCommits.length})`);
313
+ if (res.multiFileCommits.length > 0) {
314
+ for (const multi of res.multiFileCommits.slice(0, 5)) {
315
+ console.log(` - ${multi.commitSha.slice(0, 8)} (${multi.count} files): ${multi.commitSubject}`);
316
+ }
317
+ if (res.multiFileCommits.length > 5) {
318
+ console.log(` ... and ${res.multiFileCommits.length - 5} more multi-file commit(s)`);
319
+ }
320
+ }
321
+ if (!res.dryRun) {
322
+ console.log(` Migrated & SHA-256 verified: ${res.verifiedCount}/${res.mappedCount}`);
323
+ if (res.syncResult?.pushed) {
324
+ console.log(` Pushed ${res.notesRef} to ${res.syncResult.remote}.`);
325
+ }
326
+ if (res.prunedCount > 0) {
327
+ console.log(` Pruned legacy working-tree files: ${res.prunedCount} (commit the deletion on a task branch when ready).`);
328
+ } else if (res.verifiedCount > 0) {
329
+ console.log(" Legacy files kept intact (pass --prune-legacy to remove verified features/done/*.md from working tree).");
330
+ }
331
+ }
332
+ }
333
+
334
+ export async function runNotes(argv, forcedSubcommand = "") {
335
+ const [rawSub, ...rest] = forcedSubcommand ? [forcedSubcommand, ...argv] : argv;
336
+ if (!rawSub || rawSub === "-h" || rawSub === "--help") {
337
+ console.log(USAGE);
338
+ return;
339
+ }
340
+
341
+ const repoRoot = findRepoRoot(process.cwd());
342
+ if (!repoRoot) {
343
+ fail("Not inside a Git repository.");
344
+ }
345
+ const { config } = loadConfig(repoRoot);
346
+
347
+ const handlers = {
348
+ list: handleList,
349
+ show: handleShow,
350
+ search: handleSearch,
351
+ history: handleHistory,
352
+ archive: handleArchive,
353
+ sync: handleSync,
354
+ migrate: handleMigrate,
355
+ };
356
+
357
+ const handler = handlers[rawSub];
358
+ if (!handler) {
359
+ fail(`Unknown notes subcommand "${rawSub}".`, USAGE);
360
+ }
361
+ try {
362
+ handler(repoRoot, config, rest);
363
+ } catch (error) {
364
+ fail(error instanceof Error ? error.message : String(error));
365
+ }
366
+ }
@@ -14,6 +14,14 @@ import {
14
14
  runRead,
15
15
  runWrite,
16
16
  } from "../git.mjs";
17
+ import {
18
+ copyCommitNotes,
19
+ isNotesStorageEnabled,
20
+ refExists,
21
+ resolveNotesRef,
22
+ syncNotesWithRemote,
23
+ } from "../notes.mjs";
24
+ import { archiveFeatureFileToNotes } from "../notes-migrate.mjs";
17
25
 
18
26
  const usage = `
19
27
  Usage:
@@ -155,6 +163,51 @@ export async function runPrCleanup(argv) {
155
163
  fail(`Local ${baseBranch} does not contain merge commit ${mergeCommitOid}. Pull before cleanup.`);
156
164
  }
157
165
 
166
+ const notesRef = resolveNotesRef(config);
167
+ const notesActive =
168
+ isNotesStorageEnabled(config) || Boolean(config.notes) || refExists(notesRef, baseWorktree.path);
169
+ if (notesActive) {
170
+ syncNotesWithRemote(baseWorktree.path, config, {
171
+ remote,
172
+ push: false,
173
+ dryRun: options.dryRun,
174
+ bestEffort: true,
175
+ });
176
+
177
+ let notesUpdated = false;
178
+ const targetCommitOid = mergeCommitOid || expectedHeadOid;
179
+ if (targetWorktree && isNotesStorageEnabled(config) && config.notes?.autoArchiveOnFinish !== false && targetCommitOid) {
180
+ const arch = archiveFeatureFileToNotes(baseWorktree.path, config, {
181
+ worktreePath: targetWorktree.path,
182
+ branch: branchName,
183
+ commit: targetCommitOid,
184
+ dryRun: options.dryRun,
185
+ sync: false,
186
+ });
187
+ if (arch.archived) {
188
+ notesUpdated = true;
189
+ const verb = options.dryRun ? "[dry-run] Would archive" : "Archived";
190
+ console.log(`${verb} feature record ${arch.id} -> ${notesRef} @ ${shortOid(targetCommitOid)}`);
191
+ }
192
+ }
193
+
194
+ if (!options.dryRun && expectedHeadOid && mergeCommitOid && expectedHeadOid !== mergeCommitOid) {
195
+ const copied = copyCommitNotes(expectedHeadOid, mergeCommitOid, baseWorktree.path, notesRef);
196
+ if (copied.copied) {
197
+ notesUpdated = true;
198
+ console.log(`Copied ${copied.count} feature note(s) from ${shortOid(expectedHeadOid)} -> ${shortOid(mergeCommitOid)}`);
199
+ }
200
+ }
201
+
202
+ if (notesUpdated && !options.dryRun) {
203
+ syncNotesWithRemote(baseWorktree.path, config, {
204
+ remote,
205
+ push: true,
206
+ bestEffort: true,
207
+ });
208
+ }
209
+ }
210
+
158
211
  if (targetWorktree) {
159
212
  ensureCleanWorktree(targetWorktree.path, "PR");
160
213
  runWrite("git", ["worktree", "remove", targetWorktree.path], baseWorktree.path, { dryRun: options.dryRun });
@@ -14,6 +14,7 @@ import {
14
14
  validateDeveloperBranchName,
15
15
  } from "../git.mjs";
16
16
  import { createPromptReader, createSmartPrompter, promptSingleSelect } from "../tui-select.mjs";
17
+ import { configureNotesGitConfig, isNotesStorageEnabled, syncNotesWithRemote } from "../notes.mjs";
17
18
  import { configureGitHooksSafely } from "./hooks-cmd.mjs";
18
19
 
19
20
  export { createPromptReader };
@@ -333,6 +334,23 @@ export async function runSetup(argv) {
333
334
  }
334
335
  }
335
336
 
337
+ if (isNotesStorageEnabled(config) || config.notes) {
338
+ const notesCfg = configureNotesGitConfig(repoRoot, config, { remote: options.remote });
339
+ if (notesCfg.applied.length > 0) {
340
+ console.log(`Git notes configured (${notesCfg.notesRef}): ${notesCfg.applied.join(", ")}`);
341
+ }
342
+ if (!options.localOnly && config.notes?.autoSync !== false) {
343
+ const pullRes = syncNotesWithRemote(repoRoot, config, {
344
+ remote: options.remote,
345
+ push: false,
346
+ bestEffort: true,
347
+ });
348
+ if (pullRes.status === "fast-forwarded" || pullRes.status === "merged" || pullRes.status === "merged-framed") {
349
+ console.log(`Synced existing remote notes (${notesCfg.notesRef}: ${pullRes.status}).`);
350
+ }
351
+ }
352
+ }
353
+
336
354
  console.log("");
337
355
  console.log("Next steps:");
338
356
  const sampleBranch =
@@ -10,7 +10,9 @@ import {
10
10
  remoteTrackingBranchExists,
11
11
  } from "../git.mjs";
12
12
  import { listFeatureFiles } from "../plan.mjs";
13
+ import { isNotesStorageEnabled, listNoteEntries, resolveNotesRef } from "../notes.mjs";
13
14
  import { setupInstructions } from "../policy.mjs";
15
+ import { countCommitsBehind } from "./sync-dev.mjs";
14
16
 
15
17
  const usage = `
16
18
  Usage:
@@ -56,6 +58,13 @@ export async function runStatus(argv) {
56
58
  if (pausedFeatures.length > 0) {
57
59
  console.log(`Paused feature records: ${pausedFeatures.join(", ")}`);
58
60
  }
61
+ const notesRef = resolveNotesRef(config);
62
+ const noteEntries = listNoteEntries(repoRoot, notesRef);
63
+ if (isNotesStorageEnabled(config) || noteEntries.length > 0) {
64
+ console.log(
65
+ `Feature storage: ${config.featureStorage} (${notesRef}, ${noteEntries.length} annotated commit(s))`,
66
+ );
67
+ }
59
68
 
60
69
  let targetBranch = config.baseBranch;
61
70
  if (config.mode === "developer-branch") {
@@ -80,6 +89,22 @@ export async function runStatus(argv) {
80
89
  }
81
90
  const devWt = findWorktreeForBranch(worktrees, devBranch);
82
91
  console.log(`Developer worktree: ${devWt?.path ?? "(not checked out)"}`);
92
+ const integrationRef =
93
+ hasRemote && remoteTrackingBranchExists(config.remote, config.integrationBranch, repoRoot)
94
+ ? `${config.remote}/${config.integrationBranch}`
95
+ : localBranchExists(config.integrationBranch, repoRoot)
96
+ ? config.integrationBranch
97
+ : "";
98
+ if (integrationRef && localBranchExists(devBranch, repoRoot)) {
99
+ const behind = countCommitsBehind(devBranch, integrationRef, repoRoot);
100
+ if (behind !== null) {
101
+ console.log(
102
+ behind > 0
103
+ ? `Sync with ${integrationRef}: behind by ${String(behind)} commit(s) (run \`featflow sync-dev\`)`
104
+ : `Sync with ${integrationRef}: up to date`,
105
+ );
106
+ }
107
+ }
83
108
  }
84
109
 
85
110
  console.log(`Worktrees (${worktrees.length}):`);