@cmnwlth/sync 0.1.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.
- package/LICENSE +202 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +582 -0
- package/dist/index.js.map +1 -0
- package/package.json +35 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Kristof Feys
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import path4 from "path";
|
|
5
|
+
import { parseArgs } from "util";
|
|
6
|
+
import { resolveBrainDir } from "@cmnwlth/core";
|
|
7
|
+
|
|
8
|
+
// src/daemon.ts
|
|
9
|
+
import { promises as fs3 } from "fs";
|
|
10
|
+
import path3 from "path";
|
|
11
|
+
import chokidar from "chokidar";
|
|
12
|
+
|
|
13
|
+
// src/engine.ts
|
|
14
|
+
import { buildIndex, regenerateDerived } from "@cmnwlth/core";
|
|
15
|
+
|
|
16
|
+
// src/conflict.ts
|
|
17
|
+
import { promises as fs2 } from "fs";
|
|
18
|
+
import path2 from "path";
|
|
19
|
+
import { makeNoteId, parseNote, serializeNote, writeNote } from "@cmnwlth/core";
|
|
20
|
+
|
|
21
|
+
// src/git.ts
|
|
22
|
+
import { promises as fs } from "fs";
|
|
23
|
+
import path from "path";
|
|
24
|
+
import { findSecrets, loadBrainConfig, scanOptions } from "@cmnwlth/core";
|
|
25
|
+
import { simpleGit } from "simple-git";
|
|
26
|
+
var NOTE_DIRS = ["memory", "decisions", "work-state", "people"];
|
|
27
|
+
function isNoteFile(rel) {
|
|
28
|
+
if (!rel.endsWith(".md")) return false;
|
|
29
|
+
const parts = rel.split("/");
|
|
30
|
+
const name = parts[parts.length - 1];
|
|
31
|
+
const parent = parts[parts.length - 2];
|
|
32
|
+
if (name === "INDEX.md") return false;
|
|
33
|
+
return parent !== void 0 && NOTE_DIRS.includes(parent);
|
|
34
|
+
}
|
|
35
|
+
function isScannableForSecrets(rel) {
|
|
36
|
+
if (isNoteFile(rel)) return true;
|
|
37
|
+
const name = rel.split("/").pop();
|
|
38
|
+
return name === "COMMONWEALTH.md" || name === "INDEX.md";
|
|
39
|
+
}
|
|
40
|
+
function openRepo(dir) {
|
|
41
|
+
return simpleGit(dir, {
|
|
42
|
+
// core.quotepath=false: git otherwise octal-escapes and double-quotes non-ASCII paths in
|
|
43
|
+
// porcelain output (e.g. `"caf\303\251/x.md"`), which broke `isNoteFile` — the trailing quote
|
|
44
|
+
// fails the `.md` check — so a secret in a non-ASCII-named note was never scanned (#99).
|
|
45
|
+
config: ["core.editor=true", "core.quotepath=false"],
|
|
46
|
+
// core.editor is on simple-git's block list; we set it to the non-interactive `true`
|
|
47
|
+
// binary purely so unattended `rebase --continue` can record its commit.
|
|
48
|
+
unsafe: { allowUnsafeEditor: true }
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async function stagedFiles(dir) {
|
|
52
|
+
const out = await openRepo(dir).diff(["--cached", "--name-only", "-z"]);
|
|
53
|
+
return out.split("\0").filter((l) => l.length > 0);
|
|
54
|
+
}
|
|
55
|
+
async function unstage(dir, files) {
|
|
56
|
+
if (files.length === 0) return;
|
|
57
|
+
await openRepo(dir).raw(["reset", "-q", "--", ...files]);
|
|
58
|
+
}
|
|
59
|
+
async function commitAllExceptSecrets(dir, message) {
|
|
60
|
+
const git = openRepo(dir);
|
|
61
|
+
await git.add(["-A"]);
|
|
62
|
+
const secretsBlocked = await scrubStagedSecrets(dir);
|
|
63
|
+
const status = await git.status();
|
|
64
|
+
if (status.staged.length === 0) return { committed: false, secretsBlocked };
|
|
65
|
+
await git.commit(message);
|
|
66
|
+
return { committed: true, secretsBlocked };
|
|
67
|
+
}
|
|
68
|
+
async function scrubStagedSecrets(dir) {
|
|
69
|
+
const opts = scanOptions(await loadBrainConfig(dir));
|
|
70
|
+
const secretsBlocked = [];
|
|
71
|
+
for (const rel of await stagedFiles(dir)) {
|
|
72
|
+
if (!isScannableForSecrets(rel)) continue;
|
|
73
|
+
let content;
|
|
74
|
+
try {
|
|
75
|
+
content = await fs.readFile(path.join(dir, rel), "utf8");
|
|
76
|
+
} catch {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (findSecrets(content, opts).length > 0) secretsBlocked.push(rel);
|
|
80
|
+
}
|
|
81
|
+
await unstage(dir, secretsBlocked);
|
|
82
|
+
return secretsBlocked;
|
|
83
|
+
}
|
|
84
|
+
async function hasRemote(dir) {
|
|
85
|
+
const remotes = await openRepo(dir).getRemotes();
|
|
86
|
+
return remotes.some((r) => r.name === "origin");
|
|
87
|
+
}
|
|
88
|
+
async function conflictedPaths(dir) {
|
|
89
|
+
return (await openRepo(dir).status()).conflicted;
|
|
90
|
+
}
|
|
91
|
+
async function pullRebase(dir) {
|
|
92
|
+
const git = openRepo(dir);
|
|
93
|
+
if (!await hasRemote(dir)) return { conflicts: false };
|
|
94
|
+
const status = await git.status();
|
|
95
|
+
const branch = status.current;
|
|
96
|
+
if (!branch) return { conflicts: false };
|
|
97
|
+
await git.fetch("origin");
|
|
98
|
+
let upstream = status.tracking;
|
|
99
|
+
if (!upstream) {
|
|
100
|
+
const remoteBranches = await git.branch(["-r"]);
|
|
101
|
+
const candidate = `origin/${branch}`;
|
|
102
|
+
if (remoteBranches.all.includes(candidate)) upstream = candidate;
|
|
103
|
+
}
|
|
104
|
+
if (!upstream) return { conflicts: false };
|
|
105
|
+
try {
|
|
106
|
+
await git.raw(["rebase", "--autostash", upstream]);
|
|
107
|
+
return { conflicts: false };
|
|
108
|
+
} catch (err) {
|
|
109
|
+
const conflicted = (await git.status()).conflicted;
|
|
110
|
+
if (conflicted.length > 0) return { conflicts: true };
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async function abortRebase(dir) {
|
|
115
|
+
try {
|
|
116
|
+
await openRepo(dir).raw(["rebase", "--abort"]);
|
|
117
|
+
} catch {
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async function isRebasing(dir) {
|
|
121
|
+
const gitDir = (await openRepo(dir).revparse(["--git-dir"])).trim();
|
|
122
|
+
const base = path.isAbsolute(gitDir) ? gitDir : path.join(dir, gitDir);
|
|
123
|
+
for (const name of ["rebase-merge", "rebase-apply"]) {
|
|
124
|
+
try {
|
|
125
|
+
await fs.access(path.join(base, name));
|
|
126
|
+
return true;
|
|
127
|
+
} catch {
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
async function needsPush(dir) {
|
|
133
|
+
if (!await hasRemote(dir)) return false;
|
|
134
|
+
const status = await openRepo(dir).status();
|
|
135
|
+
if (!status.current) return false;
|
|
136
|
+
if (!status.tracking) return true;
|
|
137
|
+
return status.ahead > 0;
|
|
138
|
+
}
|
|
139
|
+
async function push(dir) {
|
|
140
|
+
const git = openRepo(dir);
|
|
141
|
+
if (!await hasRemote(dir)) return;
|
|
142
|
+
const branch = (await git.status()).current;
|
|
143
|
+
if (!branch) return;
|
|
144
|
+
await git.push(["-u", "origin", branch]);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/conflict.ts
|
|
148
|
+
async function showStage(dir, stage, relPath) {
|
|
149
|
+
try {
|
|
150
|
+
return await openRepo(dir).raw(["show", `:${stage}:${relPath}`]);
|
|
151
|
+
} catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async function writeSibling(brainDir, relPath, raw, side) {
|
|
156
|
+
const dir = path2.posix.dirname(relPath);
|
|
157
|
+
const base = path2.posix.basename(relPath, ".md");
|
|
158
|
+
let note = null;
|
|
159
|
+
try {
|
|
160
|
+
note = parseNote(raw, relPath);
|
|
161
|
+
} catch {
|
|
162
|
+
note = null;
|
|
163
|
+
}
|
|
164
|
+
if (note) {
|
|
165
|
+
const newId = makeNoteId(`${note.frontmatter.title} (${side})`, note.frontmatter.created);
|
|
166
|
+
const newRel2 = `${dir}/${newId}.md`;
|
|
167
|
+
const rewritten = {
|
|
168
|
+
...note,
|
|
169
|
+
frontmatter: { ...note.frontmatter, id: newId },
|
|
170
|
+
path: newRel2
|
|
171
|
+
};
|
|
172
|
+
await fs2.writeFile(path2.join(brainDir, newRel2), serializeNote(rewritten), "utf8");
|
|
173
|
+
return newRel2;
|
|
174
|
+
}
|
|
175
|
+
const newRel = `${dir}/${base}-${side}-${randomTag()}.md`;
|
|
176
|
+
await fs2.writeFile(path2.join(brainDir, newRel), raw, "utf8");
|
|
177
|
+
return newRel;
|
|
178
|
+
}
|
|
179
|
+
function randomTag() {
|
|
180
|
+
return Math.random().toString(36).slice(2, 6);
|
|
181
|
+
}
|
|
182
|
+
async function resolveConflictsAsSiblings(brainDir, conflictedPaths2) {
|
|
183
|
+
const git = openRepo(brainDir);
|
|
184
|
+
const resolved = [];
|
|
185
|
+
for (const relPath of conflictedPaths2) {
|
|
186
|
+
const remoteRaw = await showStage(brainDir, 2, relPath);
|
|
187
|
+
const localRaw = await showStage(brainDir, 3, relPath);
|
|
188
|
+
const abs = path2.join(brainDir, relPath);
|
|
189
|
+
if (localRaw !== null && remoteRaw !== null) {
|
|
190
|
+
const oursPath = await writeSibling(brainDir, relPath, localRaw, "ours");
|
|
191
|
+
const theirsPath = await writeSibling(brainDir, relPath, remoteRaw, "theirs");
|
|
192
|
+
await fs2.rm(abs, { force: true });
|
|
193
|
+
resolved.push({ original: relPath, oursPath, theirsPath });
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const survivor = localRaw ?? remoteRaw;
|
|
197
|
+
if (survivor !== null) {
|
|
198
|
+
await fs2.writeFile(abs, survivor, "utf8");
|
|
199
|
+
resolved.push({ original: relPath, oursPath: relPath, theirsPath: relPath });
|
|
200
|
+
} else {
|
|
201
|
+
await fs2.rm(abs, { force: true });
|
|
202
|
+
resolved.push({ original: relPath, oursPath: relPath, theirsPath: relPath });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (resolved.length > 0) {
|
|
206
|
+
const lines = resolved.map(
|
|
207
|
+
(r) => `- \`${r.original}\` \u2192 ours: \`${r.oursPath}\`, theirs: \`${r.theirsPath}\``
|
|
208
|
+
);
|
|
209
|
+
await writeNote(brainDir, {
|
|
210
|
+
kind: "memory",
|
|
211
|
+
title: `Sync conflict resolved as siblings (${resolved.length})`,
|
|
212
|
+
tags: ["conflict"],
|
|
213
|
+
body: [
|
|
214
|
+
"A same-file sync conflict was auto-resolved without data loss: both versions",
|
|
215
|
+
"were kept as separate sibling notes for review. Reconcile and supersede as needed.",
|
|
216
|
+
"",
|
|
217
|
+
...lines
|
|
218
|
+
].join("\n")
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
await git.add(["-A"]);
|
|
222
|
+
await scrubStagedSecrets(brainDir);
|
|
223
|
+
try {
|
|
224
|
+
await git.raw(["rebase", "--continue"]);
|
|
225
|
+
} catch {
|
|
226
|
+
const status = await git.status();
|
|
227
|
+
if (status.conflicted.length === 0) {
|
|
228
|
+
try {
|
|
229
|
+
await git.raw(["rebase", "--skip"]);
|
|
230
|
+
} catch {
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return resolved;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// src/lock.ts
|
|
238
|
+
import { acquireSyncLock } from "@cmnwlth/core";
|
|
239
|
+
|
|
240
|
+
// src/queue.ts
|
|
241
|
+
var SerialQueue = class {
|
|
242
|
+
/** Tail of the promise chain; each enqueue appends to it. */
|
|
243
|
+
tail = Promise.resolve();
|
|
244
|
+
/**
|
|
245
|
+
* Run `fn` after every previously-enqueued task has settled. Returns a promise for
|
|
246
|
+
* `fn`'s result. A rejection in one task does not break the chain — later tasks still
|
|
247
|
+
* run — but it is propagated to that task's own caller.
|
|
248
|
+
*/
|
|
249
|
+
enqueue(fn) {
|
|
250
|
+
const run = this.tail.then(() => fn());
|
|
251
|
+
this.tail = run.then(
|
|
252
|
+
() => void 0,
|
|
253
|
+
() => void 0
|
|
254
|
+
);
|
|
255
|
+
return run;
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
// src/engine.ts
|
|
260
|
+
var NOOP_SUMMARY = {
|
|
261
|
+
committed: false,
|
|
262
|
+
pulled: false,
|
|
263
|
+
pushed: false,
|
|
264
|
+
conflicts: [],
|
|
265
|
+
secretsBlocked: []
|
|
266
|
+
};
|
|
267
|
+
var MAX_REBASE_ROUNDS = 50;
|
|
268
|
+
var SyncEngine = class {
|
|
269
|
+
brainDir;
|
|
270
|
+
queue;
|
|
271
|
+
constructor(brainDir, opts = {}) {
|
|
272
|
+
this.brainDir = brainDir;
|
|
273
|
+
this.queue = opts.queue ?? new SerialQueue();
|
|
274
|
+
}
|
|
275
|
+
/** Run one full sync cycle, serialized against every other queued mutation. */
|
|
276
|
+
syncOnce() {
|
|
277
|
+
return this.queue.enqueue(() => this.runSyncOnce());
|
|
278
|
+
}
|
|
279
|
+
async runSyncOnce() {
|
|
280
|
+
const dir = this.brainDir;
|
|
281
|
+
const release = await acquireSyncLock(dir);
|
|
282
|
+
if (!release) return { ...NOOP_SUMMARY };
|
|
283
|
+
try {
|
|
284
|
+
if (await isRebasing(dir)) await abortRebase(dir);
|
|
285
|
+
return await this.syncLocked(dir);
|
|
286
|
+
} finally {
|
|
287
|
+
await release();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** The sync cycle proper, run while holding the cross-process lock (see {@link runSyncOnce}). */
|
|
291
|
+
async syncLocked(dir) {
|
|
292
|
+
const { committed, secretsBlocked } = await commitAllExceptSecrets(
|
|
293
|
+
dir,
|
|
294
|
+
"commonwealth: sync local changes"
|
|
295
|
+
);
|
|
296
|
+
const remote = await hasRemote(dir);
|
|
297
|
+
let pulled = false;
|
|
298
|
+
const conflicts = [];
|
|
299
|
+
if (remote) {
|
|
300
|
+
const { conflicts: hadConflict } = await pullRebase(dir);
|
|
301
|
+
pulled = true;
|
|
302
|
+
if (hadConflict) {
|
|
303
|
+
let rounds = 0;
|
|
304
|
+
while (await isRebasing(dir)) {
|
|
305
|
+
if (rounds++ >= MAX_REBASE_ROUNDS) {
|
|
306
|
+
throw new Error(`Rebase did not converge after ${MAX_REBASE_ROUNDS} rounds`);
|
|
307
|
+
}
|
|
308
|
+
const paths = await conflictedPaths(dir);
|
|
309
|
+
if (paths.length === 0) break;
|
|
310
|
+
conflicts.push(...await resolveConflictsAsSiblings(dir, paths));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
await buildIndex(dir);
|
|
315
|
+
await regenerateDerived(dir);
|
|
316
|
+
const derived = await commitAllExceptSecrets(dir, "commonwealth: regenerate derived index");
|
|
317
|
+
for (const p of derived.secretsBlocked) {
|
|
318
|
+
if (!secretsBlocked.includes(p)) secretsBlocked.push(p);
|
|
319
|
+
}
|
|
320
|
+
let pushed = false;
|
|
321
|
+
if (remote && await needsPush(dir)) {
|
|
322
|
+
await push(dir);
|
|
323
|
+
pushed = true;
|
|
324
|
+
}
|
|
325
|
+
return { committed, pulled, pushed, conflicts, secretsBlocked };
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
// src/daemon.ts
|
|
330
|
+
var COMMONWEALTH_DIR = ".commonwealth";
|
|
331
|
+
var PID_FILE = "sync.pid";
|
|
332
|
+
function makeIgnored(brainDir) {
|
|
333
|
+
const gitDir = path3.join(brainDir, ".git");
|
|
334
|
+
const indexDir = path3.join(brainDir, "index");
|
|
335
|
+
const commonwealthDir = path3.join(brainDir, COMMONWEALTH_DIR);
|
|
336
|
+
const stagingDir = path3.join(brainDir, "staging");
|
|
337
|
+
const commonwealthMd = path3.join(brainDir, "COMMONWEALTH.md");
|
|
338
|
+
return (p) => {
|
|
339
|
+
if (p === gitDir || p.startsWith(gitDir + path3.sep)) return true;
|
|
340
|
+
if (p === indexDir || p.startsWith(indexDir + path3.sep)) return true;
|
|
341
|
+
if (p === commonwealthDir || p.startsWith(commonwealthDir + path3.sep)) return true;
|
|
342
|
+
if (p === stagingDir || p.startsWith(stagingDir + path3.sep)) return true;
|
|
343
|
+
if (/\.db(-shm|-wal)?$/.test(p)) return true;
|
|
344
|
+
if (p.endsWith(".tmp")) return true;
|
|
345
|
+
if (p === commonwealthMd) return true;
|
|
346
|
+
if (path3.basename(p) === "INDEX.md") return true;
|
|
347
|
+
return false;
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
var DRAIN_TIMEOUT_MS = 3e4;
|
|
351
|
+
var Daemon = class {
|
|
352
|
+
engine;
|
|
353
|
+
watcher;
|
|
354
|
+
timer;
|
|
355
|
+
debounceTimer;
|
|
356
|
+
queue = new SerialQueue();
|
|
357
|
+
opts = {};
|
|
358
|
+
/** True while a sync is running; a trigger during it coalesces into one re-run. */
|
|
359
|
+
syncing = false;
|
|
360
|
+
/** A trigger arrived while `syncing` — run exactly one more pass when the current one ends. */
|
|
361
|
+
rerun = false;
|
|
362
|
+
stopping = false;
|
|
363
|
+
/**
|
|
364
|
+
* Start watching + polling `brainDir`. Runs an initial sync, then wires the watcher and
|
|
365
|
+
* poll loop. Writes a PID file so a separate CLI `status`/`stop` can find this process.
|
|
366
|
+
* Refuses to start if another daemon is already running for this brain (#100), so two
|
|
367
|
+
* daemons never race the same repo.
|
|
368
|
+
*/
|
|
369
|
+
async start(brainDir, opts = {}) {
|
|
370
|
+
if (await isRunning(brainDir)) {
|
|
371
|
+
throw new Error(
|
|
372
|
+
`A Commonwealth sync daemon is already running for ${brainDir} (pid ${await readPid(brainDir)}). Stop it first, or run \`commonwealth sync stop\`.`
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
const intervalMs = opts.intervalMs ?? 15e3;
|
|
376
|
+
const debounceMs = opts.debounceMs ?? 500;
|
|
377
|
+
this.opts = opts;
|
|
378
|
+
this.engine = new SyncEngine(brainDir, { queue: this.queue });
|
|
379
|
+
await writePid(brainDir);
|
|
380
|
+
await this.runSync();
|
|
381
|
+
this.watcher = chokidar.watch(brainDir, {
|
|
382
|
+
ignored: makeIgnored(brainDir),
|
|
383
|
+
ignoreInitial: true,
|
|
384
|
+
persistent: true
|
|
385
|
+
});
|
|
386
|
+
const onFsEvent = () => {
|
|
387
|
+
if (this.debounceTimer) clearTimeout(this.debounceTimer);
|
|
388
|
+
this.debounceTimer = setTimeout(() => void this.runSync(), debounceMs);
|
|
389
|
+
};
|
|
390
|
+
this.watcher.on("add", onFsEvent).on("change", onFsEvent).on("unlink", onFsEvent);
|
|
391
|
+
this.timer = setInterval(() => void this.runSync(), intervalMs);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Run a sync, COALESCING concurrent triggers (#100). The watcher and the poll timer both call
|
|
395
|
+
* this; if a sync is already running, we just mark `rerun` instead of enqueuing another — so a
|
|
396
|
+
* sync that outlasts the poll interval can never grow an unbounded backlog. When the running
|
|
397
|
+
* pass ends, we do exactly one more if any trigger arrived meanwhile.
|
|
398
|
+
*/
|
|
399
|
+
async runSync() {
|
|
400
|
+
if (this.syncing) {
|
|
401
|
+
this.rerun = true;
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
this.syncing = true;
|
|
405
|
+
try {
|
|
406
|
+
do {
|
|
407
|
+
this.rerun = false;
|
|
408
|
+
if (this.stopping) return;
|
|
409
|
+
try {
|
|
410
|
+
const summary = await this.engine.syncOnce();
|
|
411
|
+
this.opts.onSync?.(summary);
|
|
412
|
+
} catch (err) {
|
|
413
|
+
this.opts.onError?.(err);
|
|
414
|
+
}
|
|
415
|
+
} while (this.rerun);
|
|
416
|
+
} finally {
|
|
417
|
+
this.syncing = false;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Tear down watcher + timers, DRAIN any in-flight sync (bounded by {@link DRAIN_TIMEOUT_MS}),
|
|
422
|
+
* then remove the PID file. Draining means a SIGTERM no longer exits mid `git commit`/`rebase`/
|
|
423
|
+
* `push`, which would strand the repo (#100). Safe to call more than once.
|
|
424
|
+
*/
|
|
425
|
+
async stop() {
|
|
426
|
+
this.stopping = true;
|
|
427
|
+
if (this.debounceTimer) {
|
|
428
|
+
clearTimeout(this.debounceTimer);
|
|
429
|
+
this.debounceTimer = void 0;
|
|
430
|
+
}
|
|
431
|
+
if (this.timer) {
|
|
432
|
+
clearInterval(this.timer);
|
|
433
|
+
this.timer = void 0;
|
|
434
|
+
}
|
|
435
|
+
if (this.watcher) {
|
|
436
|
+
await this.watcher.close();
|
|
437
|
+
this.watcher = void 0;
|
|
438
|
+
}
|
|
439
|
+
await Promise.race([
|
|
440
|
+
this.queue.enqueue(() => Promise.resolve()),
|
|
441
|
+
new Promise((resolve) => setTimeout(resolve, DRAIN_TIMEOUT_MS))
|
|
442
|
+
]);
|
|
443
|
+
if (this.engine) {
|
|
444
|
+
await removePid(this.engine.brainDir);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
function pidPath(brainDir) {
|
|
449
|
+
return path3.join(brainDir, COMMONWEALTH_DIR, PID_FILE);
|
|
450
|
+
}
|
|
451
|
+
async function writePid(brainDir) {
|
|
452
|
+
const file = pidPath(brainDir);
|
|
453
|
+
await fs3.mkdir(path3.dirname(file), { recursive: true });
|
|
454
|
+
await fs3.writeFile(file, `${process.pid}
|
|
455
|
+
`, "utf8");
|
|
456
|
+
}
|
|
457
|
+
async function readPid(brainDir) {
|
|
458
|
+
try {
|
|
459
|
+
const raw = await fs3.readFile(pidPath(brainDir), "utf8");
|
|
460
|
+
const pid = Number.parseInt(raw.trim(), 10);
|
|
461
|
+
return Number.isFinite(pid) ? pid : null;
|
|
462
|
+
} catch {
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
async function isRunning(brainDir) {
|
|
467
|
+
const pid = await readPid(brainDir);
|
|
468
|
+
if (pid === null) return false;
|
|
469
|
+
try {
|
|
470
|
+
process.kill(pid, 0);
|
|
471
|
+
return true;
|
|
472
|
+
} catch {
|
|
473
|
+
return false;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
async function removePid(brainDir) {
|
|
477
|
+
await fs3.rm(pidPath(brainDir), { force: true });
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// src/format.ts
|
|
481
|
+
function formatSyncSummary(s) {
|
|
482
|
+
let line = `[commonwealth-sync] sync: committed=${s.committed} pulled=${s.pulled} pushed=${s.pushed} conflicts=${s.conflicts.length}`;
|
|
483
|
+
if (s.secretsBlocked.length > 0) {
|
|
484
|
+
line += `
|
|
485
|
+
[commonwealth-sync] withheld ${s.secretsBlocked.length} note(s) containing a secret (not committed/pushed): ${s.secretsBlocked.join(", ")}`;
|
|
486
|
+
}
|
|
487
|
+
return line;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// src/index.ts
|
|
491
|
+
async function resolveDir(dirFlag) {
|
|
492
|
+
if (dirFlag && dirFlag.length > 0) return path4.resolve(dirFlag);
|
|
493
|
+
const env = process.env.COMMONWEALTH_BRAIN_DIR;
|
|
494
|
+
if (env && env.length > 0) return path4.resolve(env);
|
|
495
|
+
return resolveBrainDir(process.cwd());
|
|
496
|
+
}
|
|
497
|
+
async function cmdSync(dir) {
|
|
498
|
+
const engine = new SyncEngine(dir);
|
|
499
|
+
const summary = await engine.syncOnce();
|
|
500
|
+
console.error(formatSyncSummary(summary));
|
|
501
|
+
}
|
|
502
|
+
async function cmdStart(dir, intervalMs) {
|
|
503
|
+
const daemon = new Daemon();
|
|
504
|
+
await daemon.start(dir, {
|
|
505
|
+
intervalMs,
|
|
506
|
+
onSync: (s) => console.error(formatSyncSummary(s)),
|
|
507
|
+
onError: (err) => console.error("[commonwealth-sync] sync error:", err)
|
|
508
|
+
});
|
|
509
|
+
console.error(`[commonwealth-sync] daemon started on ${dir} (pid ${process.pid})`);
|
|
510
|
+
const shutdown = async () => {
|
|
511
|
+
console.error("[commonwealth-sync] shutting down");
|
|
512
|
+
await daemon.stop();
|
|
513
|
+
process.exit(0);
|
|
514
|
+
};
|
|
515
|
+
process.on("SIGINT", () => void shutdown());
|
|
516
|
+
process.on("SIGTERM", () => void shutdown());
|
|
517
|
+
}
|
|
518
|
+
async function cmdStatus(dir) {
|
|
519
|
+
const running = await isRunning(dir);
|
|
520
|
+
const pid = await readPid(dir);
|
|
521
|
+
if (running) {
|
|
522
|
+
console.error(`[commonwealth-sync] running on ${dir} (pid ${pid})`);
|
|
523
|
+
} else {
|
|
524
|
+
console.error(`[commonwealth-sync] not running on ${dir}`);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
async function cmdStop(dir) {
|
|
528
|
+
const running = await isRunning(dir);
|
|
529
|
+
const pid = await readPid(dir);
|
|
530
|
+
if (running && pid !== null) {
|
|
531
|
+
process.kill(pid, "SIGTERM");
|
|
532
|
+
console.error(`[commonwealth-sync] sent SIGTERM to pid ${pid}`);
|
|
533
|
+
} else {
|
|
534
|
+
console.error(`[commonwealth-sync] no running daemon on ${dir}`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
async function main() {
|
|
538
|
+
const { values, positionals } = parseArgs({
|
|
539
|
+
allowPositionals: true,
|
|
540
|
+
options: {
|
|
541
|
+
dir: { type: "string" },
|
|
542
|
+
interval: { type: "string" }
|
|
543
|
+
}
|
|
544
|
+
});
|
|
545
|
+
const sub = positionals[0];
|
|
546
|
+
const dir = await resolveDir(values.dir);
|
|
547
|
+
if (dir === null) {
|
|
548
|
+
console.error(
|
|
549
|
+
`[commonwealth-sync] no Commonwealth brain configured for ${process.cwd()} \u2014 run \`commonwealth init\` here, add a registry mapping, or pass --dir <brain>.`
|
|
550
|
+
);
|
|
551
|
+
process.exit(1);
|
|
552
|
+
}
|
|
553
|
+
const interval = values.interval ? Number.parseInt(values.interval, 10) : void 0;
|
|
554
|
+
switch (sub) {
|
|
555
|
+
case "sync":
|
|
556
|
+
await cmdSync(dir);
|
|
557
|
+
return;
|
|
558
|
+
case "start":
|
|
559
|
+
await cmdStart(
|
|
560
|
+
dir,
|
|
561
|
+
interval !== void 0 && Number.isFinite(interval) ? interval : void 0
|
|
562
|
+
);
|
|
563
|
+
return;
|
|
564
|
+
// daemon keeps the event loop alive
|
|
565
|
+
case "status":
|
|
566
|
+
await cmdStatus(dir);
|
|
567
|
+
return;
|
|
568
|
+
case "stop":
|
|
569
|
+
await cmdStop(dir);
|
|
570
|
+
return;
|
|
571
|
+
default:
|
|
572
|
+
console.error(
|
|
573
|
+
"usage: commonwealth-sync <sync|start|status|stop> [--dir DIR] [--interval MS]"
|
|
574
|
+
);
|
|
575
|
+
process.exit(sub ? 1 : 2);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
main().catch((err) => {
|
|
579
|
+
console.error("[commonwealth-sync] fatal:", err);
|
|
580
|
+
process.exit(1);
|
|
581
|
+
});
|
|
582
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/daemon.ts","../src/engine.ts","../src/conflict.ts","../src/git.ts","../src/lock.ts","../src/queue.ts","../src/format.ts"],"sourcesContent":["import path from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport { resolveBrainDir } from \"@cmnwlth/core\";\nimport { Daemon, isRunning, readPid } from \"./daemon.js\";\nimport { SyncEngine } from \"./engine.js\";\nimport { formatSyncSummary } from \"./format.js\";\n\n/**\n * Commonwealth sync CLI (`commonwealth-sync`). Subcommands:\n * sync [--dir DIR] one-shot syncOnce, then exit\n * start [--dir DIR] [--interval MS] run the resident daemon in the foreground\n * status [--dir DIR] report whether a daemon is running\n * stop [--dir DIR] signal a running daemon to exit\n *\n * DIR resolves as: `--dir` → `$COMMONWEALTH_BRAIN_DIR` → `@cmnwlth/core`'s registry\n * resolver against the cwd (marker → ancestor-brain → user registry, #69) → `null`. This\n * file carries NO shebang — tsup's banner adds exactly one at build time.\n */\n\n/**\n * Resolve the brain dir for the cwd, or `null` when none is configured (#69). Consulting the\n * registry (not just cwd) means `commonwealth-sync status` reports on the brain the working\n * directory actually maps to — the same one the MCP server and hooks use.\n */\nasync function resolveDir(dirFlag: string | undefined): Promise<string | null> {\n if (dirFlag && dirFlag.length > 0) return path.resolve(dirFlag);\n const env = process.env.COMMONWEALTH_BRAIN_DIR;\n if (env && env.length > 0) return path.resolve(env);\n return resolveBrainDir(process.cwd());\n}\n\nasync function cmdSync(dir: string): Promise<void> {\n const engine = new SyncEngine(dir);\n const summary = await engine.syncOnce();\n console.error(formatSyncSummary(summary));\n}\n\nasync function cmdStart(dir: string, intervalMs: number | undefined): Promise<void> {\n const daemon = new Daemon();\n await daemon.start(dir, {\n intervalMs,\n onSync: (s) => console.error(formatSyncSummary(s)),\n onError: (err) => console.error(\"[commonwealth-sync] sync error:\", err),\n });\n console.error(`[commonwealth-sync] daemon started on ${dir} (pid ${process.pid})`);\n\n // Keep the process alive; tear down cleanly on termination signals.\n const shutdown = async (): Promise<void> => {\n console.error(\"[commonwealth-sync] shutting down\");\n await daemon.stop();\n process.exit(0);\n };\n process.on(\"SIGINT\", () => void shutdown());\n process.on(\"SIGTERM\", () => void shutdown());\n}\n\nasync function cmdStatus(dir: string): Promise<void> {\n const running = await isRunning(dir);\n const pid = await readPid(dir);\n if (running) {\n console.error(`[commonwealth-sync] running on ${dir} (pid ${pid})`);\n } else {\n console.error(`[commonwealth-sync] not running on ${dir}`);\n }\n}\n\nasync function cmdStop(dir: string): Promise<void> {\n const running = await isRunning(dir);\n const pid = await readPid(dir);\n if (running && pid !== null) {\n process.kill(pid, \"SIGTERM\");\n console.error(`[commonwealth-sync] sent SIGTERM to pid ${pid}`);\n } else {\n console.error(`[commonwealth-sync] no running daemon on ${dir}`);\n }\n}\n\nasync function main(): Promise<void> {\n const { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n dir: { type: \"string\" },\n interval: { type: \"string\" },\n },\n });\n\n const sub = positionals[0];\n const dir = await resolveDir(values.dir);\n if (dir === null) {\n console.error(\n `[commonwealth-sync] no Commonwealth brain configured for ${process.cwd()} — run ` +\n `\\`commonwealth init\\` here, add a registry mapping, or pass --dir <brain>.`,\n );\n process.exit(1);\n }\n const interval = values.interval ? Number.parseInt(values.interval, 10) : undefined;\n\n switch (sub) {\n case \"sync\":\n await cmdSync(dir);\n return;\n case \"start\":\n await cmdStart(\n dir,\n interval !== undefined && Number.isFinite(interval) ? interval : undefined,\n );\n return; // daemon keeps the event loop alive\n case \"status\":\n await cmdStatus(dir);\n return;\n case \"stop\":\n await cmdStop(dir);\n return;\n default:\n console.error(\n \"usage: commonwealth-sync <sync|start|status|stop> [--dir DIR] [--interval MS]\",\n );\n process.exit(sub ? 1 : 2);\n }\n}\n\nmain().catch((err) => {\n console.error(\"[commonwealth-sync] fatal:\", err);\n process.exit(1);\n});\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport chokidar, { type FSWatcher } from \"chokidar\";\nimport { SyncEngine, type SyncSummary } from \"./engine.js\";\nimport { SerialQueue } from \"./queue.js\";\n\n/** Options for {@link Daemon.start}. */\nexport interface DaemonOptions {\n /** Background poll interval for inbound teammate changes (ms). Default 15000. */\n intervalMs?: number;\n /** Debounce window for filesystem-triggered syncs (ms). Default 500. */\n debounceMs?: number;\n /** Called after each background sync completes (for tests / logging). */\n onSync?: (summary: SyncSummary) => void;\n /** Called if a background sync throws (for tests / logging). */\n onError?: (err: unknown) => void;\n}\n\n/** Directory Commonwealth owns for local process state (PID file, etc.). */\nconst COMMONWEALTH_DIR = \".commonwealth\";\nconst PID_FILE = \"sync.pid\";\n\n/**\n * Chokidar v4 `ignored` predicate. v4 takes a FUNCTION (not globs): the full path is\n * tested. We skip git internals, the derived (gitignored) index, sqlite sidecars, and\n * temp files — none of which should trigger a sync.\n */\nfunction makeIgnored(brainDir: string): (p: string) => boolean {\n const gitDir = path.join(brainDir, \".git\");\n const indexDir = path.join(brainDir, \"index\");\n const commonwealthDir = path.join(brainDir, COMMONWEALTH_DIR);\n const stagingDir = path.join(brainDir, \"staging\");\n const commonwealthMd = path.join(brainDir, \"COMMONWEALTH.md\");\n return (p: string): boolean => {\n if (p === gitDir || p.startsWith(gitDir + path.sep)) return true;\n if (p === indexDir || p.startsWith(indexDir + path.sep)) return true;\n if (p === commonwealthDir || p.startsWith(commonwealthDir + path.sep)) return true;\n // Per-user review queue: local-only, never synced (ADR-0008).\n if (p === stagingDir || p.startsWith(stagingDir + path.sep)) return true;\n if (/\\.db(-shm|-wal)?$/.test(p)) return true;\n if (p.endsWith(\".tmp\")) return true;\n // Derived artifacts are rewritten by every sync (regenerateDerived); watching them\n // would make each sync retrigger the next — an unbounded loop. They are never a\n // legitimate sync trigger, so ignore them.\n if (p === commonwealthMd) return true;\n if (path.basename(p) === \"INDEX.md\") return true;\n return false;\n };\n}\n\n/**\n * The resident sync daemon (ADR-0006): watches a brain working copy and continuously\n * converges it with the remote. On any filesystem change it debounces then runs a sync;\n * a periodic poll pulls inbound teammate changes even without local edits. Every sync\n * runs through the engine's serial queue, so watcher and poll can never race.\n */\n/** How long {@link Daemon.stop} waits for an in-flight sync to finish before giving up. */\nconst DRAIN_TIMEOUT_MS = 30_000;\n\nexport class Daemon {\n private engine?: SyncEngine;\n private watcher?: FSWatcher;\n private timer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private readonly queue = new SerialQueue();\n private opts: DaemonOptions = {};\n /** True while a sync is running; a trigger during it coalesces into one re-run. */\n private syncing = false;\n /** A trigger arrived while `syncing` — run exactly one more pass when the current one ends. */\n private rerun = false;\n private stopping = false;\n\n /**\n * Start watching + polling `brainDir`. Runs an initial sync, then wires the watcher and\n * poll loop. Writes a PID file so a separate CLI `status`/`stop` can find this process.\n * Refuses to start if another daemon is already running for this brain (#100), so two\n * daemons never race the same repo.\n */\n async start(brainDir: string, opts: DaemonOptions = {}): Promise<void> {\n if (await isRunning(brainDir)) {\n throw new Error(\n `A Commonwealth sync daemon is already running for ${brainDir} (pid ${await readPid(brainDir)}). ` +\n `Stop it first, or run \\`commonwealth sync stop\\`.`,\n );\n }\n\n const intervalMs = opts.intervalMs ?? 15_000;\n const debounceMs = opts.debounceMs ?? 500;\n this.opts = opts;\n this.engine = new SyncEngine(brainDir, { queue: this.queue });\n\n await writePid(brainDir);\n\n // Initial reconcile on startup.\n await this.runSync();\n\n // Filesystem watch → debounced sync. v4 `ignored` is a predicate over the full path.\n this.watcher = chokidar.watch(brainDir, {\n ignored: makeIgnored(brainDir),\n ignoreInitial: true,\n persistent: true,\n });\n const onFsEvent = (): void => {\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => void this.runSync(), debounceMs);\n };\n this.watcher.on(\"add\", onFsEvent).on(\"change\", onFsEvent).on(\"unlink\", onFsEvent);\n\n // Periodic poll for inbound changes.\n this.timer = setInterval(() => void this.runSync(), intervalMs);\n }\n\n /**\n * Run a sync, COALESCING concurrent triggers (#100). The watcher and the poll timer both call\n * this; if a sync is already running, we just mark `rerun` instead of enqueuing another — so a\n * sync that outlasts the poll interval can never grow an unbounded backlog. When the running\n * pass ends, we do exactly one more if any trigger arrived meanwhile.\n */\n private async runSync(): Promise<void> {\n if (this.syncing) {\n this.rerun = true;\n return;\n }\n this.syncing = true;\n try {\n do {\n this.rerun = false;\n if (this.stopping) return;\n try {\n const summary = await this.engine!.syncOnce();\n this.opts.onSync?.(summary);\n } catch (err) {\n this.opts.onError?.(err);\n }\n } while (this.rerun);\n } finally {\n this.syncing = false;\n }\n }\n\n /**\n * Tear down watcher + timers, DRAIN any in-flight sync (bounded by {@link DRAIN_TIMEOUT_MS}),\n * then remove the PID file. Draining means a SIGTERM no longer exits mid `git commit`/`rebase`/\n * `push`, which would strand the repo (#100). Safe to call more than once.\n */\n async stop(): Promise<void> {\n this.stopping = true;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = undefined;\n }\n // Wait for whatever is already queued to settle (enqueuing an empty task resolves only after\n // all prior queued work does), but never block shutdown forever on a hung git op.\n await Promise.race([\n this.queue.enqueue(() => Promise.resolve()),\n new Promise<void>((resolve) => setTimeout(resolve, DRAIN_TIMEOUT_MS)),\n ]);\n if (this.engine) {\n await removePid(this.engine.brainDir);\n }\n }\n}\n\n/** Absolute path of the daemon PID file for a brain. */\nfunction pidPath(brainDir: string): string {\n return path.join(brainDir, COMMONWEALTH_DIR, PID_FILE);\n}\n\n/** Write the current process id to the brain's PID file. */\nexport async function writePid(brainDir: string): Promise<void> {\n const file = pidPath(brainDir);\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.writeFile(file, `${process.pid}\\n`, \"utf8\");\n}\n\n/** Read the recorded PID, or null if there is no PID file. */\nexport async function readPid(brainDir: string): Promise<number | null> {\n try {\n const raw = await fs.readFile(pidPath(brainDir), \"utf8\");\n const pid = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(pid) ? pid : null;\n } catch {\n return null;\n }\n}\n\n/** True if a daemon PID is recorded AND that process is currently alive. */\nexport async function isRunning(brainDir: string): Promise<boolean> {\n const pid = await readPid(brainDir);\n if (pid === null) return false;\n try {\n process.kill(pid, 0); // signal 0 = existence check, doesn't actually signal\n return true;\n } catch {\n return false; // no such process (or not permitted) → treat as not running\n }\n}\n\n/** Remove the PID file if present. */\nexport async function removePid(brainDir: string): Promise<void> {\n await fs.rm(pidPath(brainDir), { force: true });\n}\n","import { buildIndex, regenerateDerived } from \"@cmnwlth/core\";\nimport { resolveConflictsAsSiblings, type ResolvedConflict } from \"./conflict.js\";\nimport {\n abortRebase,\n commitAllExceptSecrets,\n conflictedPaths,\n hasRemote,\n isRebasing,\n needsPush,\n pullRebase,\n push,\n} from \"./git.js\";\nimport { acquireSyncLock } from \"./lock.js\";\nimport { SerialQueue } from \"./queue.js\";\n\n/** A pass that did nothing (no lock, or nothing to do): every flag false, no conflicts/secrets. */\nconst NOOP_SUMMARY: SyncSummary = {\n committed: false,\n pulled: false,\n pushed: false,\n conflicts: [],\n secretsBlocked: [],\n};\n\n/** Options for constructing a {@link SyncEngine}. */\nexport interface SyncEngineOptions {\n /** Existing serial queue to share (e.g. with a daemon). One is created if omitted. */\n queue?: SerialQueue;\n}\n\n/** Outcome of a single {@link SyncEngine.syncOnce} pass. */\nexport interface SyncSummary {\n /** A commit of local (pre-pull) changes was created. */\n committed: boolean;\n /** A pull/rebase actually ran (a remote + upstream existed). */\n pulled: boolean;\n /** A push to origin ran. */\n pushed: boolean;\n /** Same-file conflicts that were resolved as siblings this pass. */\n conflicts: ResolvedConflict[];\n /**\n * Repo-relative note paths withheld from the local commit because they contained a\n * secret (#16). They remain modified/uncommitted in the working tree for the user to fix.\n */\n secretsBlocked: string[];\n}\n\n/** Safety valve so a pathological rebase can't spin forever. */\nconst MAX_REBASE_ROUNDS = 50;\n\n/**\n * The testable sync core over a single brain working copy. `syncOnce` runs the full\n * cycle THROUGH a serial queue so concurrent callers (watcher, poll, CLI) never race\n * (issue #7): commit local → pull/rebase → resolve conflicts as siblings → rebuild\n * derived index → commit derived → push. Degrades gracefully with no remote configured.\n */\nexport class SyncEngine {\n readonly brainDir: string;\n readonly queue: SerialQueue;\n\n constructor(brainDir: string, opts: SyncEngineOptions = {}) {\n this.brainDir = brainDir;\n this.queue = opts.queue ?? new SerialQueue();\n }\n\n /** Run one full sync cycle, serialized against every other queued mutation. */\n syncOnce(): Promise<SyncSummary> {\n return this.queue.enqueue(() => this.runSyncOnce());\n }\n\n private async runSyncOnce(): Promise<SyncSummary> {\n const dir = this.brainDir;\n\n // 0a. Cross-process lock: another process (a one-shot `sync`, or a second daemon) may be\n // mid-sync on this same repo. The in-process SerialQueue can't see it, so acquire a\n // file lock; if a live process holds it, skip this pass rather than race its git ops\n // (#100). The daemon/poll will sync again shortly; a one-shot defers to the running one.\n const release = await acquireSyncLock(dir);\n if (!release) return { ...NOOP_SUMMARY };\n try {\n // 0b. Recover a rebase stranded by a previously crashed/killed pass (#100). Committing new\n // work while mid-rebase would land it on a detached HEAD and then the pullRebase below\n // fails. Abort first so we start from a clean branch tip with local commits intact.\n if (await isRebasing(dir)) await abortRebase(dir);\n return await this.syncLocked(dir);\n } finally {\n await release();\n }\n }\n\n /** The sync cycle proper, run while holding the cross-process lock (see {@link runSyncOnce}). */\n private async syncLocked(dir: string): Promise<SyncSummary> {\n // 1. Commit local changes first, so the rebase replays them onto teammates' work.\n // Scrub secrets pre-commit (#16): note files carrying a credential are unstaged and\n // left uncommitted, so a leaked secret is never committed or pushed.\n const { committed, secretsBlocked } = await commitAllExceptSecrets(\n dir,\n \"commonwealth: sync local changes\",\n );\n\n // 2. Pull with rebase; resolve any same-file conflicts as siblings, then finish.\n const remote = await hasRemote(dir);\n let pulled = false;\n const conflicts: ResolvedConflict[] = [];\n\n if (remote) {\n const { conflicts: hadConflict } = await pullRebase(dir);\n pulled = true;\n if (hadConflict) {\n // A rebase can stop on several commits in turn; resolve each round until done.\n let rounds = 0;\n while (await isRebasing(dir)) {\n if (rounds++ >= MAX_REBASE_ROUNDS) {\n throw new Error(`Rebase did not converge after ${MAX_REBASE_ROUNDS} rounds`);\n }\n const paths = await conflictedPaths(dir);\n if (paths.length === 0) break; // stopped for a non-conflict reason; loop guards it\n conflicts.push(...(await resolveConflictsAsSiblings(dir, paths)));\n }\n }\n }\n\n // 3. Rebuild derived artifacts from the (now-merged) note set.\n await buildIndex(dir);\n await regenerateDerived(dir);\n\n // 4. Commit derived changes (COMMONWEALTH.md / INDEX.md) if regeneration moved anything.\n // Re-scrub: `add -A` here would otherwise re-stage a secret note left in the working\n // tree by step 1, so route this commit through the same guard and merge the results.\n const derived = await commitAllExceptSecrets(dir, \"commonwealth: regenerate derived index\");\n for (const p of derived.secretsBlocked) {\n if (!secretsBlocked.includes(p)) secretsBlocked.push(p);\n }\n\n // 5. Push only when the branch is actually ahead of its upstream — so an idle poll\n // doesn't hit the remote every interval, while still pushing commits made outside\n // the engine (e.g. a raw `git commit`) or left unpushed by an earlier failure.\n let pushed = false;\n if (remote && (await needsPush(dir))) {\n await push(dir);\n pushed = true;\n }\n\n return { committed, pulled, pushed, conflicts, secretsBlocked };\n }\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { makeNoteId, parseNote, serializeNote, writeNote, type Note } from \"@cmnwlth/core\";\nimport { openRepo, scrubStagedSecrets } from \"./git.js\";\n\n/** One conflicting note, split into its two surviving sibling files. */\nexport interface ResolvedConflict {\n /** The path git reported as conflicted (repo-relative). */\n original: string;\n /** Repo-relative path of the file holding the local (\"ours\", stage :2) content. */\n oursPath: string;\n /** Repo-relative path of the file holding the incoming (\"theirs\", stage :3) content. */\n theirsPath: string;\n}\n\n/** Read a specific merge stage of a path via `git show :<stage>:<path>`; null if absent. */\nasync function showStage(dir: string, stage: 2 | 3, relPath: string): Promise<string | null> {\n try {\n return await openRepo(dir).raw([\"show\", `:${stage}:${relPath}`]);\n } catch {\n return null; // add/add on one side only, or the stage doesn't exist\n }\n}\n\n/**\n * Rewrite one side's raw content so it lands as a NEW, distinct note file: fresh id +\n * matching filename, so ours and theirs coexist instead of overwriting each other.\n * Falls back to writing the raw bytes verbatim (under `suffix`) if it isn't parseable\n * frontmatter — we never lose content.\n */\nasync function writeSibling(\n brainDir: string,\n relPath: string,\n raw: string,\n side: \"ours\" | \"theirs\",\n): Promise<string> {\n const dir = path.posix.dirname(relPath);\n const base = path.posix.basename(relPath, \".md\");\n\n let note: Note | null = null;\n try {\n note = parseNote(raw, relPath);\n } catch {\n note = null;\n }\n\n if (note) {\n // Give it a brand-new id/filename so it can never collide with the other side.\n const newId = makeNoteId(`${note.frontmatter.title} (${side})`, note.frontmatter.created);\n const newRel = `${dir}/${newId}.md`;\n const rewritten: Note = {\n ...note,\n frontmatter: { ...note.frontmatter, id: newId },\n path: newRel,\n };\n await fs.writeFile(path.join(brainDir, newRel), serializeNote(rewritten), \"utf8\");\n return newRel;\n }\n\n // Unparseable — preserve raw bytes under a unique, obviously-derived name.\n const newRel = `${dir}/${base}-${side}-${randomTag()}.md`;\n await fs.writeFile(path.join(brainDir, newRel), raw, \"utf8\");\n return newRel;\n}\n\nfunction randomTag(): string {\n return Math.random().toString(36).slice(2, 6);\n}\n\n/**\n * Resolve same-file conflicts without data loss (ADR-0003 §c / issue #8). For each\n * conflicted note:\n * - extract BOTH the local (\"ours\", stage :2) and incoming (\"theirs\", stage :3) content,\n * - write each as a SEPARATE sibling note (at least one gets a fresh {@link makeNoteId}\n * id/filename so they coexist),\n * - remove the original conflicted path (its content survives in the siblings, with no\n * git conflict markers anywhere),\n * - record a `conflict`-tagged memory note naming the two siblings for human review.\n * Then stage everything and continue the in-progress rebase to completion.\n */\nexport async function resolveConflictsAsSiblings(\n brainDir: string,\n conflictedPaths: string[],\n): Promise<ResolvedConflict[]> {\n const git = openRepo(brainDir);\n const resolved: ResolvedConflict[] = [];\n\n for (const relPath of conflictedPaths) {\n // These stages are always reached via a REBASE (engine pullRebase → `rebase upstream`), and\n // a rebase inverts the usual sense of ours/theirs: stage :2 is the branch being replayed onto\n // (upstream = the teammate's REMOTE content) and stage :3 is our own replayed commit (LOCAL).\n // Label accordingly so the sibling filenames and the review note aren't backwards (#100).\n const remoteRaw = await showStage(brainDir, 2, relPath);\n const localRaw = await showStage(brainDir, 3, relPath);\n const abs = path.join(brainDir, relPath);\n\n // Both sides present: split into two siblings, drop the marker-laden original.\n if (localRaw !== null && remoteRaw !== null) {\n const oursPath = await writeSibling(brainDir, relPath, localRaw, \"ours\");\n const theirsPath = await writeSibling(brainDir, relPath, remoteRaw, \"theirs\");\n await fs.rm(abs, { force: true });\n resolved.push({ original: relPath, oursPath, theirsPath });\n continue;\n }\n\n // One side only (add/delete): keep whichever content exists, verbatim, no markers.\n const survivor = localRaw ?? remoteRaw;\n if (survivor !== null) {\n await fs.writeFile(abs, survivor, \"utf8\");\n resolved.push({ original: relPath, oursPath: relPath, theirsPath: relPath });\n } else {\n // Neither stage has content (delete/delete) — accept the deletion.\n await fs.rm(abs, { force: true });\n resolved.push({ original: relPath, oursPath: relPath, theirsPath: relPath });\n }\n }\n\n // File a review record BEFORE staging, so it's committed alongside the resolution.\n if (resolved.length > 0) {\n const lines = resolved.map(\n (r) => `- \\`${r.original}\\` → ours: \\`${r.oursPath}\\`, theirs: \\`${r.theirsPath}\\``,\n );\n await writeNote(brainDir, {\n kind: \"memory\",\n title: `Sync conflict resolved as siblings (${resolved.length})`,\n tags: [\"conflict\"],\n body: [\n \"A same-file sync conflict was auto-resolved without data loss: both versions\",\n \"were kept as separate sibling notes for review. Reconcile and supersede as needed.\",\n \"\",\n ...lines,\n ].join(\"\\n\"),\n });\n }\n\n // Stage the resolution and advance the rebase. `--continue` may stop again on the next\n // replayed commit's conflict (nonzero exit) — that's expected; the engine loops back and\n // calls us again. An emptied commit needs `--skip` instead. Swallow both; only a truly\n // unexpected failure with no conflicts and no rebase left in progress re-throws.\n await git.add([\"-A\"]);\n // Re-scrub before committing: `add -A` above (re)stages EVERYTHING in the worktree, including\n // a secret note that the engine's pre-commit scrub deliberately left unstaged (and, for a new\n // note, untracked — which `rebase --autostash` does not stash). Without this, `rebase --continue`\n // would fold that secret into the resolution commit and the engine would push it (#98). The\n // unstaged secret note stays in the worktree and is reported by the engine's step-4 scrub.\n await scrubStagedSecrets(brainDir);\n try {\n // openRepo injects core.editor=true, so --continue records the resolution commit\n // non-interactively instead of trying to open an editor.\n await git.raw([\"rebase\", \"--continue\"]);\n } catch {\n const status = await git.status();\n if (status.conflicted.length === 0) {\n // Nothing conflicting left but continue failed → likely an emptied commit; skip it.\n try {\n await git.raw([\"rebase\", \"--skip\"]);\n } catch {\n // Fall through — engine re-checks rebase state and will surface a real failure.\n }\n }\n }\n\n return resolved;\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { findSecrets, loadBrainConfig, scanOptions } from \"@cmnwlth/core\";\nimport { simpleGit, type SimpleGit } from \"simple-git\";\n\n/** Note-kind folders whose markdown is scanned for secrets before commit. */\nconst NOTE_DIRS = [\"memory\", \"decisions\", \"work-state\", \"people\"] as const;\n\n/**\n * True if a repo-relative path is a markdown note file — i.e. its immediate parent folder is a\n * note-kind folder (`INDEX.md` excluded). Works for both the flat kind root (`memory/x.md`) and\n * per-project subtrees (`<project>/memory/x.md`, ADR-0015), so the secret scrub keeps covering\n * every note regardless of layout.\n */\nfunction isNoteFile(rel: string): boolean {\n if (!rel.endsWith(\".md\")) return false;\n const parts = rel.split(\"/\");\n const name = parts[parts.length - 1];\n const parent = parts[parts.length - 2];\n if (name === \"INDEX.md\") return false;\n return parent !== undefined && (NOTE_DIRS as readonly string[]).includes(parent);\n}\n\n/**\n * Files the pre-commit scrub must scan for secrets: note files PLUS the generated router/index\n * (COMMONWEALTH.md, every INDEX.md). Those derived files embed note TITLES, so a secret in a\n * title would ride into them and get pushed even though the note file itself is blocked — the\n * derived files aren't note-files and so escaped the scrub entirely (#79). Scanning them closes\n * the leak; they're regenerated each sync, so a blocked derived file self-heals once the secret\n * is removed from the source note.\n */\nfunction isScannableForSecrets(rel: string): boolean {\n if (isNoteFile(rel)) return true;\n const name = rel.split(\"/\").pop();\n return name === \"COMMONWEALTH.md\" || name === \"INDEX.md\";\n}\n\n/**\n * Open a simple-git handle bound to a working directory. `core.editor=true` is injected\n * into every invocation (via `-c`) so non-interactive steps that would otherwise open an\n * editor — notably `rebase --continue` recording a resolution commit — never block.\n */\nexport function openRepo(dir: string): SimpleGit {\n return simpleGit(dir, {\n // core.quotepath=false: git otherwise octal-escapes and double-quotes non-ASCII paths in\n // porcelain output (e.g. `\"caf\\303\\251/x.md\"`), which broke `isNoteFile` — the trailing quote\n // fails the `.md` check — so a secret in a non-ASCII-named note was never scanned (#99).\n config: [\"core.editor=true\", \"core.quotepath=false\"],\n // core.editor is on simple-git's block list; we set it to the non-interactive `true`\n // binary purely so unattended `rebase --continue` can record its commit.\n unsafe: { allowUnsafeEditor: true },\n });\n}\n\n/** True if the working tree has staged, unstaged, or untracked changes. */\nexport async function hasChanges(dir: string): Promise<boolean> {\n const status = await openRepo(dir).status();\n return !status.isClean();\n}\n\n/**\n * Stage everything and commit — but only if there is something to commit. Returns true\n * if a commit was actually created, false when the tree was already clean (so callers\n * can report whether local work landed without probing git themselves).\n */\nexport async function commitAll(dir: string, message: string): Promise<boolean> {\n const git = openRepo(dir);\n await git.add([\"-A\"]);\n const status = await git.status();\n if (status.isClean()) return false;\n await git.commit(message);\n return true;\n}\n\n/**\n * Repo-relative paths that are currently staged (`git diff --cached --name-only`).\n * Used by the pre-commit secret scrub to know which files a commit is about to include.\n */\nexport async function stagedFiles(dir: string): Promise<string[]> {\n // `-z`: NUL-delimited and never quoted/escaped, so non-ASCII paths (and paths with spaces)\n // come through verbatim and the secret scrub sees every staged note file (#99).\n const out = await openRepo(dir).diff([\"--cached\", \"--name-only\", \"-z\"]);\n return out.split(\"\\0\").filter((l) => l.length > 0);\n}\n\n/** Remove `files` from the index (`git reset -q -- <files>`), leaving the working tree. */\nexport async function unstage(dir: string, files: string[]): Promise<void> {\n if (files.length === 0) return;\n await openRepo(dir).raw([\"reset\", \"-q\", \"--\", ...files]);\n}\n\n/** Outcome of {@link commitAllExceptSecrets}: commit status plus any blocked note paths. */\nexport interface GuardedCommit {\n /** A commit was actually created (there were staged changes after scrubbing). */\n committed: boolean;\n /** Repo-relative note paths withheld because they contained a secret. */\n secretsBlocked: string[];\n}\n\n/**\n * Pre-commit secret scrub (#16, defense-in-depth for hand-edited files). Stage everything\n * (`add -A`), scan every staged MARKDOWN note file for secrets, and unstage any offenders\n * so they are neither committed nor pushed. Commit the remainder only if staged changes\n * survive. Blocked files are left modified/uncommitted in the working tree for the user to\n * fix. Returns whether a commit landed and which note paths were withheld.\n */\nexport async function commitAllExceptSecrets(dir: string, message: string): Promise<GuardedCommit> {\n const git = openRepo(dir);\n await git.add([\"-A\"]);\n\n const secretsBlocked = await scrubStagedSecrets(dir);\n\n const status = await git.status();\n if (status.staged.length === 0) return { committed: false, secretsBlocked };\n await git.commit(message);\n return { committed: true, secretsBlocked };\n}\n\n/**\n * Scan every currently-STAGED markdown note file for secrets and unstage any offenders,\n * returning the repo-relative paths withheld. Leaves the files modified/uncommitted in the\n * working tree. This is the reusable core of the pre-commit scrub — call it before ANY commit\n * that stages with `add -A`, including the conflict-resolution `rebase --continue` path, so a\n * blocked secret note can never ride along into a commit and get pushed (#98).\n */\nexport async function scrubStagedSecrets(dir: string): Promise<string[]> {\n // Honor the brain's secret-scanner tuning (#46): entropy detection + allowlist, off by default.\n const opts = scanOptions(await loadBrainConfig(dir));\n const secretsBlocked: string[] = [];\n for (const rel of await stagedFiles(dir)) {\n if (!isScannableForSecrets(rel)) continue;\n let content: string;\n try {\n content = await fs.readFile(path.join(dir, rel), \"utf8\");\n } catch {\n continue; // deletion or unreadable — nothing to scan\n }\n if (findSecrets(content, opts).length > 0) secretsBlocked.push(rel);\n }\n await unstage(dir, secretsBlocked);\n return secretsBlocked;\n}\n\n/** The current branch name, or null if detached / no commits yet. */\nexport async function currentBranch(dir: string): Promise<string | null> {\n return (await openRepo(dir).status()).current;\n}\n\n/** True if the repo has an `origin` remote configured. */\nexport async function hasRemote(dir: string): Promise<boolean> {\n const remotes = await openRepo(dir).getRemotes();\n return remotes.some((r) => r.name === \"origin\");\n}\n\n/** Repo-relative paths that are currently in a merge/rebase conflict state. */\nexport async function conflictedPaths(dir: string): Promise<string[]> {\n return (await openRepo(dir).status()).conflicted;\n}\n\n/**\n * Fetch and rebase the current branch onto its upstream (`--autostash` so local WIP is\n * preserved). Returns `{ conflicts }` — true when the rebase stopped on a conflict that\n * the caller must resolve. Other rebase failures are re-thrown.\n *\n * No-ops (returns `{ conflicts: false }`) when there is no `origin` remote or the branch\n * has no upstream tracking ref, so a local-only brain syncs without error.\n */\nexport async function pullRebase(dir: string): Promise<{ conflicts: boolean }> {\n const git = openRepo(dir);\n if (!(await hasRemote(dir))) return { conflicts: false };\n\n const status = await git.status();\n const branch = status.current;\n if (!branch) return { conflicts: false };\n\n await git.fetch(\"origin\");\n\n // Determine the upstream: prefer the tracked ref, else fall back to origin/<branch>\n // if the remote actually has it (first push may not have set tracking yet).\n let upstream = status.tracking;\n if (!upstream) {\n const remoteBranches = await git.branch([\"-r\"]);\n const candidate = `origin/${branch}`;\n if (remoteBranches.all.includes(candidate)) upstream = candidate;\n }\n if (!upstream) return { conflicts: false };\n\n try {\n await git.raw([\"rebase\", \"--autostash\", upstream]);\n return { conflicts: false };\n } catch (err) {\n // A conflict leaves us mid-rebase with entries in `conflicted`; anything else is fatal.\n const conflicted = (await git.status()).conflicted;\n if (conflicted.length > 0) return { conflicts: true };\n throw err;\n }\n}\n\n/**\n * Abort an in-progress rebase, restoring the branch to its pre-rebase tip (local commits intact).\n * Best-effort: if there is somehow no rebase to abort, git errors and we swallow it — the caller\n * only calls this after {@link isRebasing} returned true, to recover a rebase stranded by a prior\n * crashed pass (#100).\n */\nexport async function abortRebase(dir: string): Promise<void> {\n try {\n await openRepo(dir).raw([\"rebase\", \"--abort\"]);\n } catch {\n // Nothing to abort / already clean — nothing to recover.\n }\n}\n\n/** True if a rebase is currently in progress (a `.git/rebase-*` dir exists). */\nexport async function isRebasing(dir: string): Promise<boolean> {\n const gitDir = (await openRepo(dir).revparse([\"--git-dir\"])).trim();\n const base = path.isAbsolute(gitDir) ? gitDir : path.join(dir, gitDir);\n for (const name of [\"rebase-merge\", \"rebase-apply\"]) {\n try {\n await fs.access(path.join(base, name));\n return true;\n } catch {\n // not present — check the next\n }\n }\n return false;\n}\n\n/**\n * True when there is something to push: no upstream yet (first push, to set tracking) or\n * the branch is ahead of its upstream. Lets callers skip idle pushes without missing\n * commits made outside the engine (e.g. a raw `git commit`). Assumes a recent fetch.\n */\nexport async function needsPush(dir: string): Promise<boolean> {\n if (!(await hasRemote(dir))) return false;\n const status = await openRepo(dir).status();\n if (!status.current) return false;\n if (!status.tracking) return true; // upstream not set yet → push to establish it\n return status.ahead > 0;\n}\n\n/** Push the current branch to `origin`, setting upstream so future pulls track it. */\nexport async function push(dir: string): Promise<void> {\n const git = openRepo(dir);\n if (!(await hasRemote(dir))) return;\n const branch = (await git.status()).current;\n if (!branch) return;\n await git.push([\"-u\", \"origin\", branch]);\n}\n","// The cross-process sync lock now lives in @cmnwlth/core so both the sync engine and the\n// curate consolidation pass can share it (#29). Re-exported here for existing importers.\nexport { acquireSyncLock } from \"@cmnwlth/core\";\n","/**\n * A strict FIFO async mutex. Every task passed to {@link SerialQueue.enqueue} runs\n * to completion (or rejection) before the next one starts, so overlapping callers can\n * never interleave. This is the sync write queue (issue #7): ALL git mutations funnel\n * through one instance so concurrent triggers (watcher, poll, CLI) never race.\n */\nexport class SerialQueue {\n /** Tail of the promise chain; each enqueue appends to it. */\n private tail: Promise<unknown> = Promise.resolve();\n\n /**\n * Run `fn` after every previously-enqueued task has settled. Returns a promise for\n * `fn`'s result. A rejection in one task does not break the chain — later tasks still\n * run — but it is propagated to that task's own caller.\n */\n enqueue<T>(fn: () => Promise<T>): Promise<T> {\n // Chain onto the current tail, swallowing prior errors so the chain never wedges.\n const run = this.tail.then(() => fn());\n // Advance the tail to this task's settlement, ignoring its outcome for chaining.\n this.tail = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n","import type { SyncSummary } from \"./engine.js\";\n\n/**\n * One-line (occasionally two-line) human summary of a sync pass for the CLI/daemon log. The\n * second line is emitted only when notes were withheld for containing a secret (#99): a\n * silently-withheld note is a trust problem, so the user must always see which paths were held\n * back (they remain uncommitted in the working tree to fix). Pure function.\n */\nexport function formatSyncSummary(s: SyncSummary): string {\n let line =\n `[commonwealth-sync] sync: committed=${s.committed} pulled=${s.pulled} ` +\n `pushed=${s.pushed} conflicts=${s.conflicts.length}`;\n if (s.secretsBlocked.length > 0) {\n line += `\\n[commonwealth-sync] withheld ${s.secretsBlocked.length} note(s) containing a secret (not committed/pushed): ${s.secretsBlocked.join(\", \")}`;\n }\n return line;\n}\n"],"mappings":";;;AAAA,OAAOA,WAAU;AACjB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;;;ACFhC,SAAS,YAAYC,WAAU;AAC/B,OAAOC,WAAU;AACjB,OAAO,cAAkC;;;ACFzC,SAAS,YAAY,yBAAyB;;;ACA9C,SAAS,YAAYC,WAAU;AAC/B,OAAOC,WAAU;AACjB,SAAS,YAAY,WAAW,eAAe,iBAA4B;;;ACF3E,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AACjB,SAAS,aAAa,iBAAiB,mBAAmB;AAC1D,SAAS,iBAAiC;AAG1C,IAAM,YAAY,CAAC,UAAU,aAAa,cAAc,QAAQ;AAQhE,SAAS,WAAW,KAAsB;AACxC,MAAI,CAAC,IAAI,SAAS,KAAK,EAAG,QAAO;AACjC,QAAM,QAAQ,IAAI,MAAM,GAAG;AAC3B,QAAM,OAAO,MAAM,MAAM,SAAS,CAAC;AACnC,QAAM,SAAS,MAAM,MAAM,SAAS,CAAC;AACrC,MAAI,SAAS,WAAY,QAAO;AAChC,SAAO,WAAW,UAAc,UAAgC,SAAS,MAAM;AACjF;AAUA,SAAS,sBAAsB,KAAsB;AACnD,MAAI,WAAW,GAAG,EAAG,QAAO;AAC5B,QAAM,OAAO,IAAI,MAAM,GAAG,EAAE,IAAI;AAChC,SAAO,SAAS,qBAAqB,SAAS;AAChD;AAOO,SAAS,SAAS,KAAwB;AAC/C,SAAO,UAAU,KAAK;AAAA;AAAA;AAAA;AAAA,IAIpB,QAAQ,CAAC,oBAAoB,sBAAsB;AAAA;AAAA;AAAA,IAGnD,QAAQ,EAAE,mBAA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,UAAU,EAAE,IAAI;AAE1E,UAAQ,KAAK;AAAA,IACX,KAAK;AACH,YAAM,QAAQ,GAAG;AACjB;AAAA,IACF,KAAK;AACH,YAAM;AAAA,QACJ;AAAA,QACA,aAAa,UAAa,OAAO,SAAS,QAAQ,IAAI,WAAW;AAAA,MACnE;AACA;AAAA;AAAA,IACF,KAAK;AACH,YAAM,UAAU,GAAG;AACnB;AAAA,IACF,KAAK;AACH,YAAM,QAAQ,GAAG;AACjB;AAAA,IACF;AACE,cAAQ;AAAA,QACN;AAAA,MACF;AACA,cAAQ,KAAK,MAAM,IAAI,CAAC;AAAA,EAC5B;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,8BAA8B,GAAG;AAC/C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["path","fs","path","fs","path","path","newRel","fs","conflictedPaths","path","fs","path"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cmnwlth/sync",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Resident sync daemon + engine: git pull/commit/push, write queue, conflict-as-siblings",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"commonwealth-sync": "./dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"main": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"chokidar": "^4.0.0",
|
|
17
|
+
"simple-git": "^3.27.0",
|
|
18
|
+
"@cmnwlth/core": "0.1.0"
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public",
|
|
22
|
+
"provenance": true
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/kristoffeys/commonwealth.git",
|
|
27
|
+
"directory": "packages/sync"
|
|
28
|
+
},
|
|
29
|
+
"homepage": "https://github.com/kristoffeys/commonwealth#readme",
|
|
30
|
+
"bugs": "https://github.com/kristoffeys/commonwealth/issues",
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsup",
|
|
33
|
+
"typecheck": "tsc --noEmit"
|
|
34
|
+
}
|
|
35
|
+
}
|