@phren/cli 0.3.39 → 0.3.41

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,117 @@
1
+ /**
2
+ * What a store sync leaves behind when something dies halfway: Git's own
3
+ * merge/rebase state and index lock, Phren's lock files, pre-merge backup refs
4
+ * and worktrees whose folders are gone. Each is removed only once it is
5
+ * clearly abandoned, never while a process could still own it.
6
+ */
7
+ import * as fs from "fs";
8
+ import * as path from "path";
9
+ import { runtimeDir } from "../phren-paths.js";
10
+ import { gitOperationRecovery, inProgressGitOperation } from "./git-state.js";
11
+ import { BACKUP_REF_PREFIX } from "./store-merge.js";
12
+ /** Git state untouched this long is abandoned: no Phren step holds a merge open for minutes. */
13
+ export const STALE_GIT_STATE_MS = 60 * 60 * 1000;
14
+ export const STALE_INDEX_LOCK_MS = 10 * 60 * 1000;
15
+ export const BACKUP_REF_KEEP_DAYS = 14;
16
+ function gitDir(store) {
17
+ const dotGit = path.join(store, ".git");
18
+ try {
19
+ const stat = fs.statSync(dotGit);
20
+ if (stat.isDirectory())
21
+ return dotGit;
22
+ const match = /^gitdir:\s*(.+)\s*$/i.exec(fs.readFileSync(dotGit, "utf8"));
23
+ return match ? path.resolve(store, match[1]) : undefined;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ function ageMs(file, now) {
30
+ try {
31
+ return now - fs.statSync(file).mtimeMs;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ function pidAlive(pid) {
38
+ if (!(pid > 0))
39
+ return false;
40
+ try {
41
+ process.kill(pid, 0);
42
+ return true;
43
+ }
44
+ catch (error) {
45
+ return error.code !== "ESRCH";
46
+ }
47
+ }
48
+ /** Removes abandoned sync leftovers and says what it removed, one line each. */
49
+ export async function cleanupStore(store, git, options = {}) {
50
+ const now = options.now ?? Date.now();
51
+ const done = [];
52
+ const dir = gitDir(store);
53
+ if (!dir)
54
+ return done;
55
+ const operation = inProgressGitOperation(store);
56
+ if (operation === "index lock") {
57
+ const age = ageMs(path.join(dir, "index.lock"), now);
58
+ if (age !== undefined && age > STALE_INDEX_LOCK_MS) {
59
+ fs.rmSync(path.join(dir, "index.lock"), { force: true });
60
+ done.push(`removed a Git index lock left ${Math.round(age / 60_000)} minutes ago`);
61
+ }
62
+ }
63
+ else if (operation && operation !== "sequencer") {
64
+ const marker = { rebase: fs.existsSync(path.join(dir, "rebase-merge")) ? "rebase-merge" : "rebase-apply", merge: "MERGE_HEAD", "cherry-pick": "CHERRY_PICK_HEAD", revert: "REVERT_HEAD" }[operation];
65
+ // The newest of the marker and the index: someone resolving by hand keeps touching the index.
66
+ const ages = [ageMs(path.join(dir, marker), now), ageMs(path.join(dir, "index"), now)].filter((age) => age !== undefined);
67
+ if (ages.length && Math.min(...ages) > STALE_GIT_STATE_MS) {
68
+ const abort = gitOperationRecovery(operation).split(" ").slice(1);
69
+ if ((await git(store, abort)).ok)
70
+ done.push(`aborted a ${operation} abandoned ${Math.round(Math.min(...ages) / 3_600_000)} hours ago`);
71
+ }
72
+ }
73
+ const keepMs = (options.backupKeepDays ?? BACKUP_REF_KEEP_DAYS) * 86_400_000;
74
+ const refs = await git(store, ["for-each-ref", "--format=%(refname)", BACKUP_REF_PREFIX]);
75
+ if (refs.ok) {
76
+ const old = refs.output.split("\n").filter((ref) => {
77
+ const at = Number(ref.slice(BACKUP_REF_PREFIX.length));
78
+ return Number.isFinite(at) && at > 0 && now - at > keepMs;
79
+ });
80
+ for (const ref of old)
81
+ if ((await git(store, ["update-ref", "-d", ref])).ok)
82
+ done.push(`deleted backup ${ref.slice("refs/".length)}`);
83
+ }
84
+ const before = await git(store, ["worktree", "list", "--porcelain"]);
85
+ if ((await git(store, ["worktree", "prune"])).ok) {
86
+ const after = await git(store, ["worktree", "list", "--porcelain"]);
87
+ const count = (text) => text.split("\n").filter((line) => line.startsWith("worktree ")).length;
88
+ const pruned = before.ok && after.ok ? count(before.output) - count(after.output) : 0;
89
+ if (pruned > 0)
90
+ done.push(`pruned ${pruned} worktree record(s) whose folders were gone`);
91
+ }
92
+ // Phren's own locks recover from a dead owner when next taken; one nobody
93
+ // takes again (a renamed lock, a crashed one-off) would otherwise stay forever.
94
+ let entries = [];
95
+ try {
96
+ entries = fs.readdirSync(runtimeDir(store));
97
+ }
98
+ catch { /* no runtime folder yet */ }
99
+ for (const name of entries.filter((entry) => entry.endsWith(".lock"))) {
100
+ const file = path.join(runtimeDir(store), name);
101
+ const age = ageMs(file, now);
102
+ if (age === undefined || age < STALE_INDEX_LOCK_MS)
103
+ continue;
104
+ let pid = Number.NaN;
105
+ try {
106
+ pid = Number.parseInt(fs.readFileSync(file, "utf8").split("\n")[0], 10);
107
+ }
108
+ catch {
109
+ continue;
110
+ }
111
+ if (pidAlive(pid))
112
+ continue;
113
+ fs.rmSync(file, { force: true });
114
+ done.push(`removed lock ${name} left by a process that has exited`);
115
+ }
116
+ return done;
117
+ }
@@ -10,7 +10,11 @@ export interface StoreMergeResult {
10
10
  detail: string;
11
11
  conflicts?: string[];
12
12
  committedLocalWrites?: boolean;
13
+ /** Where the pre-merge HEAD was kept when local and remote had both moved. */
14
+ backupRef?: string;
13
15
  }
16
+ /** Pre-merge HEADs, one ref per diverged merge, named by the time it was taken (store-cleanup.ts prunes them). */
17
+ export declare const BACKUP_REF_PREFIX = "refs/phren/backup/";
14
18
  export interface StoreMergeOptions {
15
19
  git: RunStoreGit;
16
20
  /** A head advertised by ls-remote. Lets polling avoid an unnecessary fetch. */
@@ -1,6 +1,8 @@
1
1
  import { resolveStoreConflicts } from "./conflict-resolve.js";
2
2
  import { gitOperationRecovery, inProgressGitOperation, storeAutoCommitBlocker } from "./git-state.js";
3
3
  import { storeCommitMessage } from "../machine-identity.js";
4
+ /** Pre-merge HEADs, one ref per diverged merge, named by the time it was taken (store-cleanup.ts prunes them). */
5
+ export const BACKUP_REF_PREFIX = "refs/phren/backup/";
4
6
  /** The staged diff, added lines only, for `storeAutoCommitBlocker`. */
5
7
  export const STAGED_DIFF = ["diff", "--cached", "--no-color", "--no-ext-diff", "-U0"];
6
8
  const SENSITIVE_STORE_PATHSPECS = [".env", "**/.env", "*.pem", "*.key", ".config/auth-profiles.json"];
@@ -86,14 +88,24 @@ export async function mergeStoreUpstream(cwd, options) {
86
88
  };
87
89
  }
88
90
  const canFastForward = (await git(cwd, ["merge-base", "--is-ancestor", "HEAD", target.output])).ok;
91
+ // Both sides moved: keep the local history reachable before merging into it.
92
+ let backupRef;
93
+ if (!canFastForward) {
94
+ const ref = `${BACKUP_REF_PREFIX}${Date.now()}`;
95
+ if (!(await git(cwd, ["update-ref", ref, "HEAD"])).ok) {
96
+ return { status: "error", detail: "Cannot keep a backup of the store's history before merging.", committedLocalWrites };
97
+ }
98
+ backupRef = ref;
99
+ }
89
100
  const merged = await git(cwd, canFastForward
90
101
  ? ["merge", "--ff-only", target.output]
91
- : ["merge", "--no-edit", target.output]);
102
+ : ["-c", "commit.gpgsign=false", "merge", "--no-edit", target.output]);
92
103
  if (merged.ok) {
93
104
  return {
94
105
  status: "updated",
95
106
  detail: canFastForward ? "Store fast-forwarded to the remote." : "Store merged with the remote.",
96
107
  committedLocalWrites,
108
+ ...(backupRef ? { backupRef } : {}),
97
109
  };
98
110
  }
99
111
  const initialConflicts = await conflictedPaths(cwd, git);
@@ -112,6 +124,7 @@ export async function mergeStoreUpstream(cwd, options) {
112
124
  detail: `Store merged with the remote; resolved conflicts in ${initialConflicts.join(", ")}.`,
113
125
  conflicts: initialConflicts,
114
126
  committedLocalWrites,
127
+ ...(backupRef ? { backupRef } : {}),
115
128
  };
116
129
  }
117
130
  }
@@ -0,0 +1,60 @@
1
+ import { type SyncStatus } from "../governance/policy.js";
2
+ import { type AheadBehind } from "./outcome.js";
3
+ import { type RunStoreGit } from "./store-merge.js";
4
+ export type StoreSyncStatus = "unchanged" | "updated" | "pushed" | "conflict" | "busy" | "error" | "skipped";
5
+ export interface StoreSyncOutcome {
6
+ status: StoreSyncStatus;
7
+ detail: string;
8
+ counts?: AheadBehind;
9
+ backupRef?: string;
10
+ /** Abandoned state removed before syncing, one line each. */
11
+ cleaned: string[];
12
+ }
13
+ export interface StoreSyncOptions {
14
+ git?: RunStoreGit;
15
+ now?: number;
16
+ /** A pull-only store never pushes. */
17
+ push?: boolean;
18
+ /** Names the caller in background-sync.log. */
19
+ source?: string;
20
+ }
21
+ /** Hook store sync cadence; `PHREN_STORE_SYNC_SECONDS=0` turns it off. */
22
+ export declare const DEFAULT_STORE_SYNC_SECONDS = 300;
23
+ export declare function storeSyncSeconds(env?: NodeJS.ProcessEnv): number;
24
+ export declare function syncStore(store: string, options?: StoreSyncOptions): Promise<StoreSyncOutcome>;
25
+ /** Every store this computer has, in turn: a readonly or pull-only store only pulls. */
26
+ export declare function syncAllStores(primary: string, options?: Omit<StoreSyncOptions, "push">): Promise<Array<{
27
+ name: string;
28
+ outcome: StoreSyncOutcome;
29
+ }>>;
30
+ /** The Hook's sync loop: the first pass a minute after start, then every `seconds`. */
31
+ export declare function startStoreSyncLoop(primary: string, seconds?: number): {
32
+ stop: () => void;
33
+ };
34
+ /** A store with a remote that has not synced for this long is flagged. */
35
+ export declare const STORE_STALE_MS: number;
36
+ /** Diverged, stale and failing in one sentence, most urgent first. */
37
+ export declare function storeWarning(store: {
38
+ name: string;
39
+ ahead?: number;
40
+ behind?: number;
41
+ diverged?: boolean;
42
+ stale?: boolean;
43
+ error?: string;
44
+ lastSyncedAt?: string;
45
+ }, now?: number): string | undefined;
46
+ /** The newest successful pull or push in a store's sync record. */
47
+ export declare function lastSyncedAt(sync: SyncStatus | undefined): string | undefined;
48
+ export interface StoreSyncState {
49
+ name: string;
50
+ upstream?: string;
51
+ ahead?: number;
52
+ behind?: number;
53
+ lastSyncedAt?: string;
54
+ diverged: boolean;
55
+ stale: boolean;
56
+ error?: string;
57
+ warning?: string;
58
+ }
59
+ /** Where a store stands against its last-fetched upstream and its sync record; nothing is fetched. */
60
+ export declare function storeSyncState(name: string, store: string, git?: RunStoreGit, now?: number): Promise<StoreSyncState>;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * One full reconcile of a store with its remote: clean up abandoned state,
3
+ * commit pending writes, merge the remote (diverged history included, see
4
+ * store-merge.ts), push what the remote lacks, and record the outcome where
5
+ * the Hook, `phren status` and doctor read it. The Hook runs this on a timer
6
+ * for every store, so a computer nobody is typing on still converges.
7
+ */
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import { tryFileLock } from "../governance/locks.js";
11
+ import { getRuntimeHealth, updateRuntimeHealth } from "../governance/policy.js";
12
+ import { runtimeFile } from "../phren-paths.js";
13
+ import { isGitAuthFailure, withStoreAuthBackoff } from "./auth.js";
14
+ import { aheadBehind, firstLine, logSyncOutcome } from "./outcome.js";
15
+ import { periodicPullEnabled, runGitWithin, runPollGit } from "./pull.js";
16
+ import { resolveAllStores } from "../store-registry.js";
17
+ import { debugLog } from "../shared.js";
18
+ import { errorMessage } from "../utils.js";
19
+ import { cleanupStore } from "./store-cleanup.js";
20
+ import { mergeStoreUpstream } from "./store-merge.js";
21
+ /** Hook store sync cadence; `PHREN_STORE_SYNC_SECONDS=0` turns it off. */
22
+ export const DEFAULT_STORE_SYNC_SECONDS = 300;
23
+ export function storeSyncSeconds(env = process.env) {
24
+ const raw = env.PHREN_STORE_SYNC_SECONDS;
25
+ if (raw === undefined || raw === "")
26
+ return DEFAULT_STORE_SYNC_SECONDS;
27
+ if (raw === "off")
28
+ return 0;
29
+ const seconds = Number(raw);
30
+ return Number.isInteger(seconds) && seconds >= 0 ? (seconds === 0 ? 0 : Math.max(30, seconds)) : DEFAULT_STORE_SYNC_SECONDS;
31
+ }
32
+ export async function syncStore(store, options = {}) {
33
+ const now = options.now ?? Date.now();
34
+ // A long-diverged store fetches and pushes far more than a poll's 10 s allows.
35
+ const raw = options.git ?? ((cwd, args) => runGitWithin(120_000, cwd, args));
36
+ const source = options.source ?? "store-sync";
37
+ if (!fs.existsSync(path.join(store, ".git")))
38
+ return { status: "skipped", detail: "The store is not a Git repository.", cleaned: [] };
39
+ const release = tryFileLock(runtimeFile(store, "git-op"));
40
+ if (!release)
41
+ return { status: "busy", detail: "Another Phren Git operation is running.", cleaned: [] };
42
+ let outcome;
43
+ try {
44
+ const cleaned = await cleanupStore(store, raw, { now });
45
+ outcome = { ...(await reconcile(store, withStoreAuthBackoff(raw, () => now), options.push !== false)), cleaned };
46
+ }
47
+ finally {
48
+ release();
49
+ }
50
+ record(store, source, outcome, now);
51
+ return outcome;
52
+ }
53
+ async function reconcile(store, git, push) {
54
+ const merge = () => mergeStoreUpstream(store, { git, commitMessage: "auto-save phren (store sync)" });
55
+ let merged = await merge();
56
+ let backupRef = merged.backupRef;
57
+ if (merged.status === "busy" || merged.status === "conflict" || merged.status === "error") {
58
+ return { status: merged.status, detail: merged.detail, counts: await aheadBehind(store, git) };
59
+ }
60
+ let counts = await aheadBehind(store, git);
61
+ if (!push || !counts || counts.ahead === 0) {
62
+ return { status: merged.status, detail: merged.detail, counts, ...(backupRef ? { backupRef } : {}) };
63
+ }
64
+ let pushed = await git(store, ["push", "--quiet"]);
65
+ // The remote moved between the merge and the push: merge once more.
66
+ if (!pushed.ok && !isGitAuthFailure(pushed.error)) {
67
+ merged = await merge();
68
+ backupRef ??= merged.backupRef;
69
+ if (merged.status === "updated" || merged.status === "unchanged")
70
+ pushed = await git(store, ["push", "--quiet"]);
71
+ else
72
+ return { status: merged.status === "busy" ? "busy" : merged.status, detail: merged.detail, counts: await aheadBehind(store, git) };
73
+ }
74
+ counts = await aheadBehind(store, git);
75
+ if (!pushed.ok)
76
+ return { status: "error", detail: `Push failed: ${firstLine(pushed.error, 400) || "unknown Git error"}`, counts };
77
+ return { status: "pushed", detail: `${merged.detail} Pushed local commits.`, counts, ...(backupRef ? { backupRef } : {}) };
78
+ }
79
+ function record(store, source, outcome, now) {
80
+ if (outcome.status === "skipped" || outcome.status === "busy")
81
+ return;
82
+ const at = new Date(now).toISOString();
83
+ const ok = outcome.status === "unchanged" || outcome.status === "updated" || outcome.status === "pushed";
84
+ const previous = getRuntimeHealth(store).lastSync;
85
+ const counts = outcome.counts ?? {};
86
+ const patch = ok
87
+ ? {
88
+ lastPullAt: at, lastPullStatus: "ok", lastPullDetail: outcome.detail, lastSuccessfulPullAt: at,
89
+ ...(outcome.status === "pushed" || outcome.counts?.ahead === 0
90
+ ? { lastPushAt: at, lastPushStatus: "saved-pushed", lastPushDetail: outcome.detail, lastSuccessfulPushAt: at, consecutiveFailures: 0, unsyncedCommits: 0 }
91
+ : { unsyncedCommits: outcome.counts?.ahead ?? previous?.unsyncedCommits }),
92
+ lastError: undefined, lastErrorAt: undefined,
93
+ ...counts,
94
+ }
95
+ : {
96
+ lastPullAt: at, lastPullStatus: "error", lastPullDetail: outcome.detail,
97
+ lastPushAt: at, lastPushStatus: outcome.status === "conflict" ? "pull-failed" : "error", lastPushDetail: outcome.detail,
98
+ consecutiveFailures: (previous?.consecutiveFailures ?? 0) + 1,
99
+ lastError: firstLine(outcome.detail, 1000), lastErrorAt: at,
100
+ ...(typeof outcome.counts?.ahead === "number" ? { unsyncedCommits: outcome.counts.ahead } : {}),
101
+ ...counts,
102
+ };
103
+ updateRuntimeHealth(store, { lastSync: patch });
104
+ // A quiet success is logged only when it follows a failure or changed something.
105
+ if (!ok || outcome.status !== "unchanged" || previous?.lastError || outcome.cleaned.length) {
106
+ const extra = [outcome.backupRef ? `kept ${outcome.backupRef}` : "", ...outcome.cleaned].filter(Boolean).join("; ");
107
+ logSyncOutcome(store, source, { ok, detail: `${outcome.status}: ${outcome.detail}${extra ? ` (${extra})` : ""}`, counts: outcome.counts });
108
+ }
109
+ }
110
+ /** Every store this computer has, in turn: a readonly or pull-only store only pulls. */
111
+ export async function syncAllStores(primary, options = {}) {
112
+ if (!periodicPullEnabled(primary))
113
+ return [];
114
+ const results = [];
115
+ for (const entry of resolveAllStores(primary).filter((store) => store.available !== false).slice(0, 16)) {
116
+ const push = entry.role !== "readonly" && entry.sync !== "pull-only";
117
+ results.push({ name: entry.name, outcome: await syncStore(entry.path, { ...options, push }) });
118
+ }
119
+ return results;
120
+ }
121
+ /** The Hook's sync loop: the first pass a minute after start, then every `seconds`. */
122
+ export function startStoreSyncLoop(primary, seconds = storeSyncSeconds()) {
123
+ if (!seconds)
124
+ return { stop: () => { } };
125
+ let running = false;
126
+ const tick = () => {
127
+ if (running)
128
+ return;
129
+ running = true;
130
+ void syncAllStores(primary, { source: "hook-sync" })
131
+ .catch((err) => debugLog(`hook store sync: ${errorMessage(err)}`))
132
+ .finally(() => { running = false; });
133
+ };
134
+ const first = setTimeout(tick, Math.min(60_000, seconds * 1000));
135
+ const timer = setInterval(tick, seconds * 1000);
136
+ first.unref();
137
+ timer.unref();
138
+ return { stop: () => { clearTimeout(first); clearInterval(timer); } };
139
+ }
140
+ /** A store with a remote that has not synced for this long is flagged. */
141
+ export const STORE_STALE_MS = 60 * 60 * 1000;
142
+ /** Diverged, stale and failing in one sentence, most urgent first. */
143
+ export function storeWarning(store, now = Date.now()) {
144
+ const parts = [];
145
+ if (store.diverged)
146
+ parts.push(`diverged from its remote (${store.ahead} ahead, ${store.behind} behind)`);
147
+ if (store.stale) {
148
+ const at = store.lastSyncedAt ? Date.parse(store.lastSyncedAt) : Number.NaN;
149
+ parts.push(Number.isNaN(at) ? "has not synced yet" : `has not synced for ${Math.max(1, Math.round((now - at) / 3_600_000))} h`);
150
+ }
151
+ if (store.error)
152
+ parts.push(`last error: ${store.error}`);
153
+ return parts.length ? `Store ${store.name} ${parts.join("; ")}` : undefined;
154
+ }
155
+ /** The newest successful pull or push in a store's sync record. */
156
+ export function lastSyncedAt(sync) {
157
+ return [sync?.lastSuccessfulPullAt, sync?.lastSuccessfulPushAt].filter((at) => !!at && !Number.isNaN(Date.parse(at)))
158
+ .sort((a, b) => Date.parse(b) - Date.parse(a))[0];
159
+ }
160
+ /** Where a store stands against its last-fetched upstream and its sync record; nothing is fetched. */
161
+ export async function storeSyncState(name, store, git = runPollGit, now = Date.now()) {
162
+ const upstream = await git(store, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
163
+ const state = { name, diverged: false, stale: false };
164
+ const sync = getRuntimeHealth(store).lastSync;
165
+ const synced = lastSyncedAt(sync);
166
+ if (synced)
167
+ state.lastSyncedAt = synced;
168
+ if (sync?.lastError)
169
+ state.error = sync.lastError;
170
+ if (upstream.ok && upstream.output) {
171
+ state.upstream = upstream.output;
172
+ const counts = await aheadBehind(store, git);
173
+ if (counts)
174
+ Object.assign(state, counts);
175
+ state.diverged = (state.ahead ?? 0) > 0 && (state.behind ?? 0) > 0;
176
+ state.stale = !synced || now - Date.parse(synced) > STORE_STALE_MS;
177
+ }
178
+ const warning = storeWarning(state, now);
179
+ if (warning)
180
+ state.warning = warning;
181
+ return state;
182
+ }
@@ -3,6 +3,11 @@ interface TaskEntry {
3
3
  section: string;
4
4
  lines: string[];
5
5
  }
6
+ /** A tasks file with each repeated task id collapsed to its richest record; unchanged text when none repeat. */
7
+ export declare function dedupeTaskIds(content: string): {
8
+ content: string;
9
+ dropped: number;
10
+ };
6
11
  /** The winning version of one task, or undefined when it is removed. */
7
12
  export declare function pickTask<T extends TaskEntry>(base: T | undefined, ours: T | undefined, theirs: T | undefined): T | undefined;
8
13
  /**
@@ -41,6 +41,56 @@ function parse(content) {
41
41
  }
42
42
  return sections;
43
43
  }
44
+ /**
45
+ * The copy of a repeated task to keep: a completed copy, then the Active one,
46
+ * then the one with the most text. A section move that left the old record
47
+ * behind (or a hand-resolved conflict that kept both sides) is how one id
48
+ * ends up twice in a file.
49
+ */
50
+ function richer(a, b) {
51
+ if (completed(a) !== completed(b))
52
+ return completed(a) ? a : b;
53
+ if ((a.section === "Active") !== (b.section === "Active"))
54
+ return a.section === "Active" ? a : b;
55
+ return b.lines.join("\n").length > a.lines.join("\n").length ? b : a;
56
+ }
57
+ /** Leaves one record per task id, in place of the copy it keeps. Returns how many it dropped. */
58
+ function dedupeSections(sections) {
59
+ const keep = new Map();
60
+ for (const section of sections)
61
+ for (const row of section.rows) {
62
+ if (row.kind !== "task" || !row.entry.key.startsWith("bid:"))
63
+ continue;
64
+ const kept = keep.get(row.entry.key);
65
+ keep.set(row.entry.key, kept ? richer(kept, row.entry) : row.entry);
66
+ }
67
+ let dropped = 0;
68
+ for (const section of sections) {
69
+ section.rows = section.rows.filter((row) => {
70
+ if (row.kind !== "task" || !row.entry.key.startsWith("bid:") || keep.get(row.entry.key) === row.entry)
71
+ return true;
72
+ dropped++;
73
+ return false;
74
+ });
75
+ }
76
+ return dropped;
77
+ }
78
+ function render(sections) {
79
+ const out = [];
80
+ for (const section of sections) {
81
+ if (section.heading !== null)
82
+ out.push(section.heading);
83
+ for (const row of section.rows)
84
+ out.push(...(row.kind === "task" ? row.entry.lines : [row.text]));
85
+ }
86
+ return out.join("\n");
87
+ }
88
+ /** A tasks file with each repeated task id collapsed to its richest record; unchanged text when none repeat. */
89
+ export function dedupeTaskIds(content) {
90
+ const sections = parse(content);
91
+ const dropped = dedupeSections(sections);
92
+ return dropped ? { content: render(sections), dropped } : { content, dropped: 0 };
93
+ }
44
94
  function index(sections) {
45
95
  const map = new Map();
46
96
  for (const section of sections) {
@@ -105,25 +155,17 @@ function mergeContract(base, ours, theirs, winner) {
105
155
  * added on both sides.
106
156
  */
107
157
  export function mergeTasksByBid(base, ours, theirs) {
158
+ // A repeated id on any side is collapsed to its richest record first.
159
+ // Refusing instead aborted every later sync of the store: a duplicate that
160
+ // reached the remote kept every computer diverged until someone noticed.
161
+ const baseSections = parse(base);
108
162
  const oursSections = parse(ours);
109
163
  const theirsSections = parse(theirs);
110
- const b = index(parse(base));
164
+ for (const sections of [baseSections, oursSections, theirsSections])
165
+ dedupeSections(sections);
166
+ const b = index(baseSections);
111
167
  const o = index(oursSections);
112
168
  const t = index(theirsSections);
113
- // A duplicated identity cannot be reconciled by first-win indexing. Leave
114
- // the sync conflict unresolved, retaining both original files for repair.
115
- for (const sections of [parse(base), oursSections, theirsSections]) {
116
- const seen = new Set();
117
- for (const section of sections)
118
- for (const row of section.rows) {
119
- if (row.kind !== "task" || !row.entry.key.startsWith("bid:"))
120
- continue;
121
- if (seen.has(row.entry.key) || [...row.entry.lines[0].matchAll(/<!--\s*bid:([a-f0-9]{8})\b[^>]*-->/g)].length !== 1) {
122
- throw new Error("Task merge requires unique, unambiguous stable IDs; repair the conflicting records first.");
123
- }
124
- seen.add(row.entry.key);
125
- }
126
- }
127
169
  const chosen = new Map();
128
170
  for (const key of new Set([...b.keys(), ...o.keys(), ...t.keys()])) {
129
171
  const winner = pickTask(b.get(key), o.get(key), t.get(key));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.39",
3
+ "version": "0.3.41",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {