pi-config-sync 0.1.3 → 0.2.1
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/README.md +14 -4
- package/extensions/git-sync.ts +33 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,6 +36,14 @@ session start → auto-sync (rate-limited, default every 5 min across session
|
|
|
36
36
|
session shutdown → best-effort commit + push (next start reconciles the rest)
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
+
### Machine-local settings
|
|
40
|
+
|
|
41
|
+
`settings.json` uses a git clean/smudge filter: portable settings are committed, while each machine retains its own selected top-level values. By default this is `lastChangelogVersion`; machine values stay in your live settings file (mirrored to `.git-sync/settings.machine.json`) and are absent only from committed blobs. On an existing repository, the first sync after upgrading creates a one-time commit that strips those keys from the committed blob and normalizes JSON formatting — the live settings file is unchanged.
|
|
42
|
+
|
|
43
|
+
The filter is fail-open: a checkout on a machine without pi-config-sync still works, but its machine-local values are not stripped until the package runs again. A newly linked machine gets its sidecar as pi writes its local settings.
|
|
44
|
+
|
|
45
|
+
The filter script runs under the Node.js that runs pi. When pi ships as a single bundled executable (for example through mise), that executable cannot run the script, so the package uses the first `node` found on `PATH` instead and falls back to a disabled filter with a warning. Set `nodePath` in `git-sync.jsonc` to pin a specific Node.js binary; the git filter configuration is corrected on the next sync.
|
|
46
|
+
|
|
39
47
|
Commits look like `pi config: auto-sync from <hostname>`. Concurrent pi sessions coordinate through a pid-liveness lock, subagent child processes never sync, and a diverged repo aborts the rebase and asks you to resolve manually — nothing is ever forced.
|
|
40
48
|
|
|
41
49
|
## Commands
|
|
@@ -57,13 +65,13 @@ This package uses an **allowlist**, not a broad config-directory upload.
|
|
|
57
65
|
|
|
58
66
|
| Path | Contents |
|
|
59
67
|
| --- | --- |
|
|
60
|
-
| `settings.json` | Model defaults, theme, installed package list |
|
|
68
|
+
| `settings.json` | Model defaults, theme, installed package list — committed with machine-local keys stripped |
|
|
61
69
|
| `AGENTS.md` | Your global agent instructions |
|
|
62
70
|
| `extensions/`, `chains/`, `prompts/`, `themes/`, `skills/` | Your custom resources |
|
|
63
71
|
| `.gitignore`, `git-sync.jsonc` | The sync policy itself |
|
|
64
72
|
| `extraPaths` entries | Anything safe you add explicitly |
|
|
65
73
|
|
|
66
|
-
Nothing outside the allowlist ever syncs — new files are ignored by default.
|
|
74
|
+
Nothing outside the allowlist ever syncs — new files are ignored by default. Subdirectories of allowed directories sync at any depth, with two exceptions that sync and `/gitsync status` warn about: a directory that is itself a git repository (a cloned extension) is skipped, so remove its inner `.git` to sync its files; and a path whose name matches the denylist below (such as `extensions/token-counter/`) is skipped, so rename it.
|
|
67
75
|
|
|
68
76
|
### What never syncs
|
|
69
77
|
|
|
@@ -87,11 +95,13 @@ Create `~/.pi/agent/git-sync.jsonc`:
|
|
|
87
95
|
"autoSyncIntervalMinutes": 5,
|
|
88
96
|
"includeHostname": true,
|
|
89
97
|
"extraPaths": ["my-safe-directory"],
|
|
90
|
-
"warnOnPublicRemote": true
|
|
98
|
+
"warnOnPublicRemote": true,
|
|
99
|
+
"machineLocalSettings": ["lastChangelogVersion"],
|
|
100
|
+
"nodePath": "/usr/local/bin/node"
|
|
91
101
|
}
|
|
92
102
|
```
|
|
93
103
|
|
|
94
|
-
Unsafe extra paths (secrets, cache names, absolute paths, or `..`) are rejected. Set `includeHostname` to `false` to omit the machine hostname from automatic commit messages.
|
|
104
|
+
Unsafe extra paths (secrets, cache names, absolute paths, or `..`) are rejected. Set `includeHostname` to `false` to omit the machine hostname from automatic commit messages. `machineLocalSettings` replaces the default list when set; it accepts top-level keys only, and `[]` disables stripping (the filter still normalizes committed JSON formatting). Useful candidates include `shellPath`, `externalEditor`, `npmCommand`, `sessionDir`, and `trackingId`. `nodePath` is optional and only needed when pi runs as a bundled executable and Node.js is not on `PATH`, or to pin a specific interpreter for the `settings.json` filter.
|
|
95
105
|
|
|
96
106
|
## Conflicts and uninstall
|
|
97
107
|
|
package/extensions/git-sync.ts
CHANGED
|
@@ -10,13 +10,15 @@ const STATUS_KEY = "git-sync";
|
|
|
10
10
|
const START = "# >>> pi-config-sync managed — do not edit inside this block";
|
|
11
11
|
const END = "# <<< pi-config-sync managed";
|
|
12
12
|
const LEGACY_MARKERS: Array<[string, string]> = [["# >>> pi-git-sync managed — do not edit inside this block", "# <<< pi-git-sync managed"]];
|
|
13
|
-
const DEFAULT_PATHS = [".gitignore", "settings.json", "AGENTS.md", "git-sync.jsonc", "extensions", "chains", "prompts", "themes", "skills"];
|
|
13
|
+
const DEFAULT_PATHS = [".gitignore", ".gitattributes", "settings.json", "AGENTS.md", "git-sync.jsonc", "extensions", "chains", "prompts", "themes", "skills"];
|
|
14
|
+
const DEFAULT_MACHINE_LOCAL = ["lastChangelogVersion"];
|
|
14
15
|
const IGNORE_DENY = ["auth*", "*token*", "*secret*", "*credential*", "*.env", "*.env.*", "*.local.json", "**/node_modules/", ".DS_Store"];
|
|
15
16
|
const LIKELY_SYNC_REPO_NAMES = ["pi-agent-config", "my-pi-config", "pi-config", "dotfiles-pi"];
|
|
16
17
|
|
|
17
|
-
export interface GitSyncConfig { autoSyncIntervalMinutes?: number; includeHostname?: boolean;
|
|
18
|
+
export interface GitSyncConfig { autoSyncIntervalMinutes?: number; extraPaths?: string[]; includeHostname?: boolean; machineLocalSettings?: string[]; nodePath?: string; warnOnPublicRemote?: boolean }
|
|
18
19
|
export interface GhClient { available(): Promise<boolean>; currentUser(): Promise<string>; repoExists(id: string): Promise<boolean>; isPrivate(id: string): Promise<boolean | undefined>; createPrivateRepo(id: string): Promise<void>; remoteUrl(id: string): string }
|
|
19
|
-
export interface Deps { dir?: string; gh?: GhClient; notify?: (message: string, level: Level) => void }
|
|
20
|
+
export interface Deps { dir?: string; gh?: GhClient; notify?: (message: string, level: Level) => void; runtime?: Runtime }
|
|
21
|
+
export interface Runtime { bundled: boolean; execPath: string; pathEnv?: string; platform?: NodeJS.Platform }
|
|
20
22
|
type Level = "info" | "warning" | "error";
|
|
21
23
|
type Ctx = ExtensionContext | ExtensionCommandContext;
|
|
22
24
|
|
|
@@ -56,15 +58,37 @@ function isSubagentChild() { return Number(process.env.PI_SUBAGENT_DEPTH ?? "0")
|
|
|
56
58
|
export function isDenied(file: string) { const parts = file.toLowerCase().replaceAll("\\", "/").split("/").filter(Boolean); return parts.some(part => ["sessions", "state", "npm", "git", "bin", ".git-sync", "node_modules"].includes(part) || part.startsWith("auth") || part.includes("token") || part.includes("secret") || part.includes("credential") || part === ".env" || part.includes(".env.") || part.endsWith(".env") || part.endsWith(".local.json")); }
|
|
57
59
|
function validExtra(entry: string) { return entry.trim() !== "" && !entry.includes("..") && !path.isAbsolute(entry) && !isDenied(entry); }
|
|
58
60
|
export function stripJsonComments(input: string) { let out = "", quote = "", escaped = false; for (let i = 0; i < input.length; i++) { const c = input[i]!, next = input[i + 1]; if (quote) { out += c; if (escaped) escaped = false; else if (c === "\\") escaped = true; else if (c === quote) quote = ""; continue; } if (c === '"' || c === "'") { quote = c; out += c; } else if (c === "/" && next === "/") { while (i < input.length && input[i] !== "\n") i++; out += "\n"; } else if (c === "/" && next === "*") { i += 2; while (i < input.length && !(input[i] === "*" && input[i + 1] === "/")) i++; i++; } else out += c; } return out; }
|
|
59
|
-
export
|
|
61
|
+
export function machineKeys(config: GitSyncConfig) { return config.machineLocalSettings ?? DEFAULT_MACHINE_LOCAL; }
|
|
62
|
+
export async function readConfig(deps?: Deps, ctx?: Ctx): Promise<GitSyncConfig> { const dir = dirOf(deps); try { const raw = JSON.parse(stripJsonComments(await fs.readFile(path.join(dir, "git-sync.jsonc"), "utf8"))) as GitSyncConfig; const extras = (raw.extraPaths ?? []).filter(validExtra); if (extras.length !== (raw.extraPaths ?? []).length) warnOnce(ctx, "git-sync: unsafe extraPaths were ignored", deps, `${dir}|extras`); let machineLocalSettings: string[] | undefined; if (Array.isArray(raw.machineLocalSettings)) { machineLocalSettings = raw.machineLocalSettings.filter((key): key is string => typeof key === "string" && key.trim() !== ""); if (machineLocalSettings.length !== raw.machineLocalSettings.length) warnOnce(ctx, "git-sync: invalid machineLocalSettings entries were ignored", deps, `${dir}|machineKeys`); } let nodePath: string | undefined; if (raw.nodePath !== undefined) { if (typeof raw.nodePath === "string" && raw.nodePath.trim() !== "") nodePath = raw.nodePath.trim(); else warnOnce(ctx, "git-sync: invalid nodePath was ignored", deps, `${dir}|nodePath`); } return { ...raw, extraPaths: extras, machineLocalSettings, nodePath }; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; warnOnce(ctx, "git-sync: invalid git-sync.jsonc; using defaults", deps, `${dir}|invalid`); return {}; } }
|
|
60
63
|
function allowRules(entry: string) { const segments = entry.replace(/\/+$/, "").split("/").filter(Boolean); const rules: string[] = []; let prefix = ""; for (let i = 0; i < segments.length; i++) { prefix = prefix ? `${prefix}/${segments[i]}` : segments[i]!; if (i < segments.length - 1) rules.push(`!${prefix}/`); else rules.push(`!${prefix}`, `!${prefix}/`, `!${prefix}/**`); } return rules; }
|
|
61
64
|
export async function ensureIgnoreRules(dir = dirOf(), config: GitSyncConfig = {}) { const file = path.join(dir, ".gitignore"); let existing = ""; try { existing = await fs.readFile(file, "utf8"); } catch {} const paths = [...DEFAULT_PATHS, ...(config.extraPaths ?? []).filter(validExtra)]; const lines = [START, "*", ...paths.flatMap(allowRules), "# hard denylist — re-ignored even inside allowed dirs", ...IGNORE_DENY, END]; const block = lines.join("\n"); let base = existing, replaced = false; for (const [start, end] of [[START, END] as [string, string], ...LEGACY_MARKERS]) { const re = new RegExp(`${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}\\n?`); if (re.test(base)) { base = base.replace(re, ""); replaced = true; } } await fs.mkdir(dir, { recursive: true }); await fs.writeFile(file, (replaced ? base : base.replace(/\s*$/, "\n")) + block + "\n"); }
|
|
62
65
|
export async function ensureInfoExclude(dir = dirOf()) { const file = path.join(dir, ".git", "info", "exclude"); await fs.mkdir(path.dirname(file), { recursive: true }); let current = ""; try { current = await fs.readFile(file, "utf8"); } catch {} const missing = IGNORE_DENY.filter(rule => !current.split("\n").includes(rule)); if (missing.length) await fs.writeFile(file, current.replace(/\s*$/, "\n") + missing.join("\n") + "\n"); }
|
|
63
66
|
function escapeRegExp(text: string) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
|
|
64
|
-
async function
|
|
67
|
+
export async function ensureAttributes(dir = dirOf()) { const file = path.join(dir, ".gitattributes"); let current = ""; try { current = await fs.readFile(file, "utf8"); } catch {} const line = "settings.json filter=pi-config-sync"; if (!current.split(/\r?\n/).includes(line)) await fs.writeFile(file, `${current.replace(/\s*$/, "")}\n${line}\n`.replace(/^\n/, "")); }
|
|
68
|
+
function filterSource(keys: string[]) { return `import fs from "node:fs";
|
|
69
|
+
const keys=${JSON.stringify(keys)};
|
|
70
|
+
const chunks=[]; for await (const chunk of process.stdin) chunks.push(chunk); const raw=Buffer.concat(chunks);
|
|
71
|
+
try { const value=JSON.parse(raw.toString("utf8")); if (!value || Array.isArray(value) || typeof value !== "object") throw new Error("not object"); if (process.argv[2] === "clean") { for (const key of keys) delete value[key]; process.stdout.write(JSON.stringify(value, null, 2)+"\\n"); } else if (process.argv[2] === "smudge") { const sidecar=JSON.parse(fs.readFileSync(new URL("settings.machine.json", import.meta.url), "utf8")); if (!sidecar || Array.isArray(sidecar) || typeof sidecar !== "object") throw new Error("bad sidecar"); process.stdout.write(JSON.stringify({...value, ...sidecar}, null, 2)+"\\n"); } else process.stdout.write(raw); } catch { process.stdout.write(raw); }
|
|
72
|
+
`; }
|
|
73
|
+
/** pi shipped as a single executable (Node SEA or compiled Bun binary): process.execPath is pi itself and cannot run the filter script. */
|
|
74
|
+
async function detectRuntime(): Promise<Runtime> { const execPath = process.execPath; if (process.versions.bun) return { bundled: !/^bun/i.test(path.basename(execPath)), execPath }; try { return { bundled: (await import("node:sea")).isSea(), execPath }; } catch { return { bundled: false, execPath }; } }
|
|
75
|
+
export async function findOnPath(name: string, pathEnv = process.env.PATH ?? "", platform = process.platform) { const names = platform === "win32" ? [`${name}.exe`, `${name}.cmd`, name] : [name]; for (const directory of pathEnv.split(path.delimiter).filter(Boolean)) for (const candidate of names) { const full = path.join(directory, candidate); try { await fs.access(full, fs.constants.X_OK); return full; } catch {} } return undefined; }
|
|
76
|
+
export async function filterInterpreter(config: GitSyncConfig, runtime: Runtime, ctx?: Ctx, deps?: Deps) { if (config.nodePath) return config.nodePath; if (!runtime.bundled) return runtime.execPath; const found = await findOnPath("node", runtime.pathEnv, runtime.platform); if (found) return found; warnOnce(ctx, "git-sync: pi runs as a bundled executable and no node was found on PATH; settings.json filter is disabled until nodePath is set in git-sync.jsonc", deps, "nodePath"); return "node"; }
|
|
77
|
+
async function gitConfigValue(key: string, dir: string) { try { return (await git(["config", "--get", key], dir)).stdout.trim(); } catch { return undefined; } }
|
|
78
|
+
export async function ensureFilter(dir = dirOf(), config: GitSyncConfig = {}, ctx?: Ctx, deps?: Deps) { if (!(await hasDotGit(dir))) return; await fs.mkdir(stateDir(dir), { recursive: true }); const script = path.join(stateDir(dir), "filter.mjs"), source = filterSource(machineKeys(config)); try { if (await fs.readFile(script, "utf8") !== source) await fs.writeFile(script, source); } catch { await fs.writeFile(script, source); } const interpreter = await filterInterpreter(config, deps?.runtime ?? await detectRuntime(), ctx, deps); const quoted = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; const values: Record<string, string> = { "filter.pi-config-sync.clean": `${quoted(interpreter)} ${quoted(script)} clean`, "filter.pi-config-sync.smudge": `${quoted(interpreter)} ${quoted(script)} smudge`, "filter.pi-config-sync.required": "false" }; let configured = false; for (const [key, value] of Object.entries(values)) if (await gitConfigValue(key, dir) !== value) { await git(["config", key, value], dir); configured = true; } if (configured) try { await git(["add", "--renormalize", "settings.json"], dir); } catch {} }
|
|
79
|
+
export async function refreshMachineSidecar(dir = dirOf(), config: GitSyncConfig = {}) { try { const settings = JSON.parse(await fs.readFile(path.join(dir, "settings.json"), "utf8")) as Record<string, unknown>; if (!settings || Array.isArray(settings) || typeof settings !== "object") return; const sidecar = Object.fromEntries(machineKeys(config).filter(key => Object.hasOwn(settings, key)).map(key => [key, settings[key]])); const output = JSON.stringify(sidecar, null, 2)+"\n", file = path.join(stateDir(dir), "settings.machine.json"); await fs.mkdir(stateDir(dir), { recursive: true }); try { if (await fs.readFile(file, "utf8") === output) return; } catch {} await fs.writeFile(file, output); } catch {} }
|
|
80
|
+
async function prepareCommit(deps?: Deps, ctx?: Ctx) { const config = await readConfig(deps, ctx), dir = dirOf(deps); await ensureIgnoreRules(dir, config); await ensureInfoExclude(dir); await ensureAttributes(dir); await ensureFilter(dir, config, ctx, deps); await refreshMachineSidecar(dir, config); return config; }
|
|
65
81
|
export async function stagedSecretFiles(dir = dirOf()) { const { stdout } = await git(["diff", "--cached", "--name-only", "-z"], dir); return stdout.split("\0").filter(Boolean).filter(isDenied); }
|
|
82
|
+
function allowedRoots(config: GitSyncConfig) { return new Set([...DEFAULT_PATHS, ...(config.extraPaths ?? []).filter(validExtra)].map(entry => entry.split("/").filter(Boolean)[0]!)); }
|
|
83
|
+
function inAllowedRoot(file: string, roots: Set<string>) { const parts = file.split("/").filter(Boolean); return parts.length >= 2 && roots.has(parts[0]!) && !parts.includes("node_modules") && !parts.includes(".DS_Store"); }
|
|
84
|
+
async function statusEntries(dir: string, args: string[]) { return (await git(["status", "--porcelain", "-z", ...args], dir)).stdout.split("\0").filter(Boolean).map(entry => ({ code: entry.slice(0, 2), file: entry.slice(3) })); }
|
|
85
|
+
/** Untracked directories inside allowed roots that are git repositories themselves. They are excluded from staging: a gitlink pointer is useless on other machines, and one without commits makes git add fail. */
|
|
86
|
+
async function untrackedNestedRepos(dir: string, roots: Set<string>) { const found: string[] = []; try { for (const { code, file } of await statusEntries(dir, ["--untracked-files=all"])) if (code === "??" && file.endsWith("/") && inAllowedRoot(file, roots)) { try { await fs.access(path.join(dir, file, ".git")); found.push(file.replace(/\/$/, "")); } catch {} } } catch {} return found; }
|
|
87
|
+
/** Allowlisted content that will not sync: nested repositories (skipped, or a legacy pointer) and names caught by the secret denylist. */
|
|
88
|
+
export async function syncGaps(dir = dirOf(), config: GitSyncConfig = {}) { const roots = allowedRoots(config), nested = new Set(await untrackedNestedRepos(dir, roots)), denied: string[] = []; try { for (const entry of (await git(["ls-files", "-s", "-z"], dir)).stdout.split("\0").filter(Boolean)) { const [meta, file] = entry.split("\t"); if (meta?.startsWith("160000") && file) nested.add(file); } } catch {} try { for (const { code, file } of await statusEntries(dir, ["--ignored"])) if (code === "!!" && inAllowedRoot(file, roots) && isDenied(file)) denied.push(file); } catch {} return { denied, nested: [...nested].sort() }; }
|
|
89
|
+
function gapMessages(gaps: { denied: string[]; nested: string[] }) { const lines: string[] = []; if (gaps.nested.length) lines.push(`nested git repositories are skipped: ${gaps.nested.join(", ")}. Remove the inner .git directory to sync them.`); if (gaps.denied.length) lines.push(`allowlisted paths skipped because their name looks sensitive: ${gaps.denied.join(", ")}. Rename them to sync.`); return lines; }
|
|
66
90
|
export async function trackedSecretFiles(dir = dirOf()) { try { const { stdout } = await git(["ls-files", "-z"], dir); return stdout.split("\0").filter(Boolean).filter(isDenied); } catch { return []; } }
|
|
67
|
-
export async function commitLocalChanges(deps?: Deps, commitMessage?: string, ctx?: Ctx) { const dir = dirOf(deps); await prepareCommit(deps, ctx); const status = (await git(["status", "--porcelain"], dir)).stdout.trim(); if (!status) return false; await git(["add", "-A"], dir); const bad = await stagedSecretFiles(dir); if (bad.length) { await git(["reset"], dir); throw new Error(`REFUSED to commit sensitive paths: ${bad.join(", ")}. Remove with git rm --cached <file>.`); } const config = await readConfig(deps, ctx); const suffix = config.includeHostname === false ? "" : ` from ${os.hostname()}`; await git(["commit", "-m", commitMessage ?? `pi config: auto-sync${suffix}`], dir); return true; }
|
|
91
|
+
export async function commitLocalChanges(deps?: Deps, commitMessage?: string, ctx?: Ctx) { const dir = dirOf(deps); await prepareCommit(deps, ctx); const status = (await git(["status", "--porcelain"], dir)).stdout.trim(); if (!status) return false; const skipped = await untrackedNestedRepos(dir, allowedRoots(await readConfig(deps, ctx))); await git(["add", "-A", "--", ".", ...skipped.map(entry => `:(exclude)${entry}`)], dir); const bad = await stagedSecretFiles(dir); if (bad.length) { await git(["reset"], dir); throw new Error(`REFUSED to commit sensitive paths: ${bad.join(", ")}. Remove with git rm --cached <file>.`); } if (!(await git(["diff", "--cached", "--name-only"], dir)).stdout.trim()) return false; const config = await readConfig(deps, ctx); const suffix = config.includeHostname === false ? "" : ` from ${os.hostname()}`; await git(["commit", "-m", commitMessage ?? `pi config: auto-sync${suffix}`], dir); return true; }
|
|
68
92
|
async function hasDotGit(dir: string) { try { await fs.access(path.join(dir, ".git")); return true; } catch { return false; } }
|
|
69
93
|
async function hasCommits(dir: string) { try { await git(["rev-parse", "HEAD"], dir); return true; } catch { return false; } }
|
|
70
94
|
async function isSyncableRepo(dir = dirOf()) { if (!(await hasDotGit(dir))) return false; try { const { stdout } = await git(["remote"], dir); return stdout.split("\n").includes("origin"); } catch { return false; } }
|
|
@@ -74,7 +98,7 @@ async function fetchOrigin(dir: string) { try { await git(["fetch", "origin"], d
|
|
|
74
98
|
async function integrate(upstream: string, dir: string) { try { await git(["merge", "--ff-only", upstream], dir); return true; } catch {} try { await git(["rebase", upstream], dir); return true; } catch { try { await git(["rebase", "--abort"], dir); } catch {} return false; } }
|
|
75
99
|
async function push(first: boolean, dir: string) { try { await git(first ? ["push", "-u", "origin", "HEAD"] : ["push"], dir, 15_000); return true; } catch { return false; } }
|
|
76
100
|
async function bestEffortPush(deps?: Deps) { const dir = dirOf(deps); const upstream = await upstreamRef(dir); if (!upstream) return push(true, dir); const { ahead, behind } = await counts(upstream, dir); return ahead > 0 && behind === 0 ? push(false, dir) : false; }
|
|
77
|
-
export async function runSync(ctx: Ctx | undefined, options: { auto: boolean; push: boolean; skipPull?: boolean }, deps?: Deps) { const dir = dirOf(deps); if (!(await isSyncableRepo(dir))) { if (!options.auto) notify(ctx, `git-sync: no git repo with an 'origin' remote in ${dir}. Run /gitsync init.`, "warning", deps); return; } if (ctx?.hasUI) ctx.ui.setStatus(STATUS_KEY, "syncing"); try { await prepareCommit(deps, ctx); const tracked = await trackedSecretFiles(dir); if (tracked.length) notify(ctx, `git-sync: tracked sensitive files: ${tracked.join(", ")}. Remove with git rm --cached <file>.`, "warning", deps); const changed: string[] = []; if (await commitLocalChanges(deps, undefined, ctx)) changed.push("committed local changes"); if (!options.skipPull) { if (!(await fetchOrigin(dir))) { if (!options.auto) notify(ctx, "git-sync: fetch failed; skipped pull/push.", "warning", deps); return; } const upstream = await upstreamRef(dir); if (upstream && (await counts(upstream, dir)).behind > 0) { if (!(await integrate(upstream, dir))) throw new Error(`local and remote diverged with conflicts; rebase aborted in ${dir}`); changed.push("pulled updates"); } } if (options.push) { const upstream = await upstreamRef(dir); if (!upstream || (await counts(upstream, dir)).ahead > 0) { if (await push(!upstream, dir)) changed.push("pushed"); } } if (changed.some(x => x.startsWith("pulled"))) notify(ctx, `git-sync: ${changed.join(", ")}. Run /reload to apply pulled config.`, "info", deps); else if (!options.auto) notify(ctx, changed.length ? `git-sync: ${changed.join(", ")}.` : "git-sync: already up to date.", "info", deps); } finally { if (ctx?.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined); } }
|
|
101
|
+
export async function runSync(ctx: Ctx | undefined, options: { auto: boolean; push: boolean; skipPull?: boolean }, deps?: Deps) { const dir = dirOf(deps); if (!(await isSyncableRepo(dir))) { if (!options.auto) notify(ctx, `git-sync: no git repo with an 'origin' remote in ${dir}. Run /gitsync init.`, "warning", deps); return; } if (ctx?.hasUI) ctx.ui.setStatus(STATUS_KEY, "syncing"); try { await prepareCommit(deps, ctx); const tracked = await trackedSecretFiles(dir); if (tracked.length) notify(ctx, `git-sync: tracked sensitive files: ${tracked.join(", ")}. Remove with git rm --cached <file>.`, "warning", deps); const changed: string[] = []; if (await commitLocalChanges(deps, undefined, ctx)) changed.push("committed local changes"); for (const line of gapMessages(await syncGaps(dir, await readConfig(deps, ctx)))) warnOnce(ctx, `git-sync: ${line}`, deps, `${dir}|${line}`); if (!options.skipPull) { if (!(await fetchOrigin(dir))) { if (!options.auto) notify(ctx, "git-sync: fetch failed; skipped pull/push.", "warning", deps); return; } const upstream = await upstreamRef(dir); if (upstream && (await counts(upstream, dir)).behind > 0) { if (!(await integrate(upstream, dir))) throw new Error(`local and remote diverged with conflicts; rebase aborted in ${dir}`); changed.push("pulled updates"); } } if (options.push) { const upstream = await upstreamRef(dir); if (!upstream || (await counts(upstream, dir)).ahead > 0) { if (await push(!upstream, dir)) changed.push("pushed"); } } if (changed.some(x => x.startsWith("pulled"))) notify(ctx, `git-sync: ${changed.join(", ")}. Run /reload to apply pulled config.`, "info", deps); else if (!options.auto) notify(ctx, changed.length ? `git-sync: ${changed.join(", ")}.` : "git-sync: already up to date.", "info", deps); } finally { if (ctx?.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined); } }
|
|
78
102
|
|
|
79
103
|
export function parseRepoReference(input: string, fallbackOwner: string) { const raw = input.trim().replace(/\.git$/i, ""); if (!raw) return undefined; const ssh = raw.match(/^git@github\.com:([^/\s]+)\/([^/\s]+)$/i); if (ssh) return { owner: ssh[1]!, name: ssh[2]! }; try { const url = new URL(raw); if (["github.com", "www.github.com"].includes(url.hostname) && url.pathname.split("/").filter(Boolean).length === 2) { const [owner, name] = url.pathname.split("/").filter(Boolean); return { owner: owner!, name: name!.replace(/\.git$/i, "") }; } } catch {} const bits = raw.split("/").filter(Boolean); if (bits.length === 1) return { owner: fallbackOwner, name: bits[0]! }; if (bits.length === 2 && !raw.includes(":")) return { owner: bits[0]!, name: bits[1]! }; return undefined; }
|
|
80
104
|
function remoteFromArg(arg: string, fallback: string) { if (/^(https?|ssh):\/\//.test(arg) || /^git@/.test(arg) || arg.startsWith("/") || arg.startsWith(".")) return arg; const ref = parseRepoReference(arg, fallback); return ref ? `https://github.com/${ref.owner}/${ref.name}.git` : undefined; }
|
|
@@ -86,8 +110,8 @@ async function warnPublic(ctx: Ctx | undefined, deps?: Deps) { const dir = dirOf
|
|
|
86
110
|
export async function runInit(arg: string, ctx?: Ctx, deps?: Deps) { const dir = dirOf(deps); await fs.mkdir(dir, { recursive: true }); if (await hasOrigin(dir)) throw new Error("already initialized; use /gitsync sync"); const config = await readConfig(deps, ctx); await ensureIgnoreRules(dir, config); await initRepo(dir); await ensureInfoExclude(dir); const tracked = await trackedSecretFiles(dir); if (tracked.length) throw new Error(`tracked sensitive files: ${tracked.join(", ")}. Remove with git rm --cached <file>.`); await commitLocalChanges(deps, "pi config: initial sync setup", ctx); let remote = remoteFromArg(arg, ""); if (!remote) { const gh = deps?.gh ?? defaultGh; if (!(await gh.available())) { notify(ctx, "git-sync: initial commit created. Create a private repo, then run /gitsync init <url>.", "warning", deps); return; } const owner = await gh.currentUser(); const ref = parseRepoReference(arg || "pi-agent-config", owner); if (!ref) throw new Error(`invalid repository reference: ${arg}`); const id = `${ref.owner}/${ref.name}`; if (await gh.repoExists(id)) throw new Error("repository already exists; use /gitsync link instead"); await gh.createPrivateRepo(id); remote = gh.remoteUrl(id); } await addRemote(remote, dir); if (!(await push(true, dir))) throw new Error("initial push failed"); await warnPublic(ctx, deps); notify(ctx, "git-sync: initialized and pushed private config repo.", "info", deps); }
|
|
87
111
|
async function defaultBranch(dir: string) { try { const { stdout } = await git(["ls-remote", "--symref", "origin", "HEAD"], dir); const found = stdout.match(/ref: refs\/heads\/([^\s]+)\s+HEAD/); return found?.[1] ?? "main"; } catch { return "main"; } }
|
|
88
112
|
async function backupConflicts(dir: string, branch: string) { const { stdout } = await git(["ls-tree", "-r", "--name-only", "-z", `origin/${branch}`], dir); const backups: string[] = []; for (const relative of stdout.split("\0").filter(Boolean)) { const target = path.join(dir, relative); try { await fs.lstat(target); } catch { continue; } const local = await fs.readFile(target).catch(() => undefined); const remote = await gitRaw(["show", `origin/${branch}:${relative}`], dir).then(x => x.stdout).catch(() => undefined); if (local && remote && !local.equals(remote)) { await fs.rename(target, `${target}.local-backup`); backups.push(relative); } } return backups; }
|
|
89
|
-
export async function runLink(arg: string, ctx?: Ctx, deps?: Deps) { const dir = dirOf(deps); if (await hasOrigin(dir)) throw new Error("already linked; use /gitsync sync"); const gh = deps?.gh ?? defaultGh; let remote = remoteFromArg(arg, ""); if (!remote) { if (!(await gh.available())) { notify(ctx, "git-sync: provide a repo URL, or install and authenticate gh.", "warning", deps); return; } const owner = await gh.currentUser(); for (const name of LIKELY_SYNC_REPO_NAMES) if (await gh.repoExists(`${owner}/${name}`)) { remote = gh.remoteUrl(`${owner}/${name}`); break; } if (!remote) throw new Error("no sync repository found; provide its URL"); } await fs.mkdir(dir, { recursive: true }); if ((await hasDotGit(dir)) && (await hasCommits(dir))) throw new Error(`existing git history in ${dir} has no 'origin' remote; push or back it up (or remove ${path.join(dir, ".git")}) before linking`); await initRepo(dir); await ensureIgnoreRules(dir, await
|
|
90
|
-
async function showStatus(ctx: ExtensionCommandContext, deps?: Deps) { const dir = dirOf(deps); if (!(await isSyncableRepo(dir))) { notify(ctx, `git-sync: ${dir} is not initialized. Run /gitsync init.`, "warning", deps); return; } const branch = (await git(["rev-parse", "--abbrev-ref", "HEAD"], dir)).stdout.trim(); const dirty = (await git(["status", "--porcelain"], dir)).stdout.trim(); const bad = await trackedSecretFiles(dir); notify(ctx, `repo: ${dir}\nbranch: ${branch}\nuncommitted changes: ${dirty ? "yes" : "none"}${bad.length ? `\nWARNING tracked sensitive files: ${bad.join(", ")}` : ""}`, bad.length ? "warning" : "info", deps); await warnPublic(ctx, deps); }
|
|
113
|
+
export async function runLink(arg: string, ctx?: Ctx, deps?: Deps) { const dir = dirOf(deps); if (await hasOrigin(dir)) throw new Error("already linked; use /gitsync sync"); const gh = deps?.gh ?? defaultGh; let remote = remoteFromArg(arg, ""); if (!remote) { if (!(await gh.available())) { notify(ctx, "git-sync: provide a repo URL, or install and authenticate gh.", "warning", deps); return; } const owner = await gh.currentUser(); for (const name of LIKELY_SYNC_REPO_NAMES) if (await gh.repoExists(`${owner}/${name}`)) { remote = gh.remoteUrl(`${owner}/${name}`); break; } if (!remote) throw new Error("no sync repository found; provide its URL"); } await fs.mkdir(dir, { recursive: true }); if ((await hasDotGit(dir)) && (await hasCommits(dir))) throw new Error(`existing git history in ${dir} has no 'origin' remote; push or back it up (or remove ${path.join(dir, ".git")}) before linking`); const config = await readConfig(deps, ctx); await initRepo(dir); await ensureIgnoreRules(dir, config); await ensureInfoExclude(dir); await ensureAttributes(dir); await ensureFilter(dir, config, ctx, deps); await refreshMachineSidecar(dir, config); await addRemote(remote, dir); await git(["fetch", "origin"], dir); const branch = await defaultBranch(dir); const backups = await backupConflicts(dir, branch); try { await git(["checkout", "-B", branch, `origin/${branch}`], dir); } catch (error) { const output = message(error); const refused = output.match(/would be overwritten by checkout:\n([\s\S]*?)Please move or remove/)?.[1]?.split("\n").map(line => line.trim()).filter(Boolean) ?? []; for (const relative of refused) { if (isDenied(relative)) continue; const target = path.join(dir, relative); try { await fs.rename(target, `${target}.local-backup`); backups.push(relative); } catch {} } if (refused.length) { try { await git(["checkout", "-B", branch, `origin/${branch}`], dir); } catch (retry) { throw new Error(`${message(retry)}\nResolve manually in ${dir}`); } } else throw new Error(`${output}\nResolve manually in ${dir}`); } const tracked = await trackedSecretFiles(dir); if (tracked.length) notify(ctx, `git-sync: remote tracks sensitive files: ${tracked.join(", ")}. Remove with git rm --cached <file>.`, "warning", deps); await warnPublic(ctx, deps); notify(ctx, `git-sync: linked — run /reload to apply pulled config.${backups.length ? ` Backed up: ${backups.join(", ")}.` : ""}`, "info", deps); }
|
|
114
|
+
async function showStatus(ctx: ExtensionCommandContext, deps?: Deps) { const dir = dirOf(deps); if (!(await isSyncableRepo(dir))) { notify(ctx, `git-sync: ${dir} is not initialized. Run /gitsync init.`, "warning", deps); return; } const branch = (await git(["rev-parse", "--abbrev-ref", "HEAD"], dir)).stdout.trim(); const dirty = (await git(["status", "--porcelain"], dir)).stdout.trim(); const bad = await trackedSecretFiles(dir), gaps = gapMessages(await syncGaps(dir, await readConfig(deps, ctx))); notify(ctx, `repo: ${dir}\nbranch: ${branch}\nuncommitted changes: ${dirty ? "yes" : "none"}${bad.length ? `\nWARNING tracked sensitive files: ${bad.join(", ")}` : ""}${gaps.map(line => `\nWARNING ${line}`).join("")}`, bad.length || gaps.length ? "warning" : "info", deps); await warnPublic(ctx, deps); }
|
|
91
115
|
async function readState(dir: string) { try { return JSON.parse(await fs.readFile(statePath(dir), "utf8")) as { lastAutoSyncAt?: string }; } catch { return {}; } }
|
|
92
116
|
async function writeState(state: { lastAutoSyncAt: string }, dir = dirOf()) { await fs.mkdir(stateDir(dir), { recursive: true }); await fs.writeFile(statePath(dir), JSON.stringify(state)); }
|
|
93
117
|
export async function shouldAutoSync(deps?: Deps) { const dir = dirOf(deps); if (isSubagentChild() || !(await isSyncableRepo(dir))) return false; const state = await readState(dir); if (!state.lastAutoSyncAt) return true; const config = await readConfig(deps); return Date.now() - Date.parse(state.lastAutoSyncAt) >= (config.autoSyncIntervalMinutes ?? 5) * 60_000; }
|