pi-config-sync 0.2.0 → 0.3.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/README.md +10 -4
- package/extensions/git-sync.ts +37 -13
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -42,6 +42,8 @@ session shutdown → best-effort commit + push (next start reconciles the rest)
|
|
|
42
42
|
|
|
43
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
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
|
+
|
|
45
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.
|
|
46
48
|
|
|
47
49
|
## Commands
|
|
@@ -69,7 +71,7 @@ This package uses an **allowlist**, not a broad config-directory upload.
|
|
|
69
71
|
| `.gitignore`, `git-sync.jsonc` | The sync policy itself |
|
|
70
72
|
| `extraPaths` entries | Anything safe you add explicitly |
|
|
71
73
|
|
|
72
|
-
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.
|
|
73
75
|
|
|
74
76
|
### What never syncs
|
|
75
77
|
|
|
@@ -78,9 +80,12 @@ Nothing outside the allowlist ever syncs — new files are ignored by default.
|
|
|
78
80
|
| `auth*` (`auth.json`) | API keys and OAuth tokens |
|
|
79
81
|
| `*token*`, `*secret*`, `*credential*`, `*.env*`, `*.local.json` | Anything named like a secret |
|
|
80
82
|
| `sessions/`, `state/`, `.git-sync/` | Local history and machine state |
|
|
83
|
+
| `logs/` at any depth | Runtime logs, including permission audit/debug logs; retained locally |
|
|
81
84
|
| `npm/`, `git/`, `bin/`, `node_modules` | Installed packages — pi reinstalls them from `settings.json` |
|
|
82
85
|
|
|
83
|
-
The policy is enforced four ways — a managed allowlist `.gitignore`, `.git/info/exclude`, a post-stage hard guard that
|
|
86
|
+
The policy is enforced four ways — a managed allowlist `.gitignore`, `.git/info/exclude`, a post-stage hard guard that refuses additions or changes to denied paths, and a push guard that checks the committed tree and outgoing history — so force-staging a denied path does not bypass the commit guard. Deletions remain allowed for cleanup. It never force-pushes.
|
|
87
|
+
|
|
88
|
+
Ignore rules do not untrack existing files. Use `git rm --cached -- <path>` to stop tracking a log while retaining the local file. A later deletion does not remove that log from earlier commits: the push guard also checks commits not reachable from locally known `origin` remote-tracking refs, including on initial and shutdown pushes. Unpushed history containing denied paths must be cleaned before retrying. The package does not rewrite history or revoke exposed credentials. These are path-based checks, not a content secret scanner.
|
|
84
89
|
|
|
85
90
|
Git commands operate only on the agent directory's own repository — `GIT_CEILING_DIRECTORIES` stops git from ever discovering a parent repository (such as dotfiles in `$HOME`), and sync refuses to run until `~/.pi/agent/.git` itself exists. GitHub CLI calls are account-level (`gh api user`, `gh repo view/create`) and never modify repository contents. Use a private repository. When `gh` can identify a public GitHub remote, the package warns; it does not block because no credentials are synced.
|
|
86
91
|
|
|
@@ -94,11 +99,12 @@ Create `~/.pi/agent/git-sync.jsonc`:
|
|
|
94
99
|
"includeHostname": true,
|
|
95
100
|
"extraPaths": ["my-safe-directory"],
|
|
96
101
|
"warnOnPublicRemote": true,
|
|
97
|
-
"machineLocalSettings": ["lastChangelogVersion"]
|
|
102
|
+
"machineLocalSettings": ["lastChangelogVersion"],
|
|
103
|
+
"nodePath": "/usr/local/bin/node"
|
|
98
104
|
}
|
|
99
105
|
```
|
|
100
106
|
|
|
101
|
-
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`.
|
|
107
|
+
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.
|
|
102
108
|
|
|
103
109
|
## Conflicts and uninstall
|
|
104
110
|
|
package/extensions/git-sync.ts
CHANGED
|
@@ -12,12 +12,14 @@ 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
13
|
const DEFAULT_PATHS = [".gitignore", ".gitattributes", "settings.json", "AGENTS.md", "git-sync.jsonc", "extensions", "chains", "prompts", "themes", "skills"];
|
|
14
14
|
const DEFAULT_MACHINE_LOCAL = ["lastChangelogVersion"];
|
|
15
|
-
const
|
|
15
|
+
const RUNTIME_LOG_DIR = "logs";
|
|
16
|
+
const IGNORE_DENY = [`**/${RUNTIME_LOG_DIR}/`, "auth*", "*token*", "*secret*", "*credential*", "*.env", "*.env.*", "*.local.json", "**/node_modules/", ".DS_Store"];
|
|
16
17
|
const LIKELY_SYNC_REPO_NAMES = ["pi-agent-config", "my-pi-config", "pi-config", "dotfiles-pi"];
|
|
17
18
|
|
|
18
|
-
export interface GitSyncConfig { autoSyncIntervalMinutes?: number;
|
|
19
|
+
export interface GitSyncConfig { autoSyncIntervalMinutes?: number; extraPaths?: string[]; includeHostname?: boolean; machineLocalSettings?: string[]; nodePath?: string; warnOnPublicRemote?: boolean }
|
|
19
20
|
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 }
|
|
20
|
-
export interface Deps { dir?: string; gh?: GhClient; notify?: (message: string, level: Level) => void }
|
|
21
|
+
export interface Deps { dir?: string; gh?: GhClient; notify?: (message: string, level: Level) => void; runtime?: Runtime }
|
|
22
|
+
export interface Runtime { bundled: boolean; execPath: string; pathEnv?: string; platform?: NodeJS.Platform }
|
|
21
23
|
type Level = "info" | "warning" | "error";
|
|
22
24
|
type Ctx = ExtensionContext | ExtensionCommandContext;
|
|
23
25
|
|
|
@@ -54,11 +56,11 @@ function statePath(dir: string) { return path.join(stateDir(dir), "state.json");
|
|
|
54
56
|
function lockPath(dir: string) { return path.join(stateDir(dir), "lock"); }
|
|
55
57
|
function isSubagentChild() { return Number(process.env.PI_SUBAGENT_DEPTH ?? "0") > 0; }
|
|
56
58
|
|
|
57
|
-
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")); }
|
|
59
|
+
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", RUNTIME_LOG_DIR].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")); }
|
|
58
60
|
function validExtra(entry: string) { return entry.trim() !== "" && !entry.includes("..") && !path.isAbsolute(entry) && !isDenied(entry); }
|
|
59
61
|
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; }
|
|
60
62
|
export function machineKeys(config: GitSyncConfig) { return config.machineLocalSettings ?? DEFAULT_MACHINE_LOCAL; }
|
|
61
|
-
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`); } return { ...raw, extraPaths: extras, machineLocalSettings }; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; warnOnce(ctx, "git-sync: invalid git-sync.jsonc; using defaults", deps, `${dir}|invalid`); return {}; } }
|
|
63
|
+
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 {}; } }
|
|
62
64
|
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; }
|
|
63
65
|
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"); }
|
|
64
66
|
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"); }
|
|
@@ -69,13 +71,25 @@ const keys=${JSON.stringify(keys)};
|
|
|
69
71
|
const chunks=[]; for await (const chunk of process.stdin) chunks.push(chunk); const raw=Buffer.concat(chunks);
|
|
70
72
|
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); }
|
|
71
73
|
`; }
|
|
74
|
+
/** pi shipped as a single executable (Node SEA or compiled Bun binary): process.execPath is pi itself and cannot run the filter script. */
|
|
75
|
+
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 }; } }
|
|
76
|
+
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; }
|
|
77
|
+
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"; }
|
|
72
78
|
async function gitConfigValue(key: string, dir: string) { try { return (await git(["config", "--get", key], dir)).stdout.trim(); } catch { return undefined; } }
|
|
73
|
-
export async function ensureFilter(dir = dirOf(), config: GitSyncConfig = {}) { 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 quoted = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; const values: Record<string, string> = { "filter.pi-config-sync.clean": `${quoted(
|
|
79
|
+
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 {} }
|
|
74
80
|
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 {} }
|
|
75
|
-
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); await refreshMachineSidecar(dir, config); return config; }
|
|
76
|
-
export async function stagedSecretFiles(dir = dirOf()) { const { stdout } = await git(["diff", "--cached", "--name-only", "-z"], dir); return stdout.split("\0").filter(Boolean).filter(isDenied); }
|
|
81
|
+
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; }
|
|
82
|
+
export async function stagedSecretFiles(dir = dirOf()) { const { stdout } = await git(["diff", "--cached", "--name-only", "--diff-filter=d", "-z"], dir); return stdout.split("\0").filter(Boolean).filter(isDenied); }
|
|
83
|
+
function allowedRoots(config: GitSyncConfig) { return new Set([...DEFAULT_PATHS, ...(config.extraPaths ?? []).filter(validExtra)].map(entry => entry.split("/").filter(Boolean)[0]!)); }
|
|
84
|
+
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(RUNTIME_LOG_DIR) && !parts.includes(".DS_Store"); }
|
|
85
|
+
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) })); }
|
|
86
|
+
/** 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. */
|
|
87
|
+
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; }
|
|
88
|
+
/** Allowlisted content that will not sync: nested repositories (skipped, or a legacy pointer) and names caught by the secret denylist. */
|
|
89
|
+
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() }; }
|
|
90
|
+
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; }
|
|
77
91
|
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 []; } }
|
|
78
|
-
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; }
|
|
92
|
+
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; }
|
|
79
93
|
async function hasDotGit(dir: string) { try { await fs.access(path.join(dir, ".git")); return true; } catch { return false; } }
|
|
80
94
|
async function hasCommits(dir: string) { try { await git(["rev-parse", "HEAD"], dir); return true; } catch { return false; } }
|
|
81
95
|
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; } }
|
|
@@ -83,9 +97,19 @@ async function upstreamRef(dir: string) { try { return (await git(["rev-parse",
|
|
|
83
97
|
async function counts(upstream: string, dir: string) { const { stdout } = await git(["rev-list", "--left-right", "--count", `${upstream}...HEAD`], dir); const [behind = "0", ahead = "0"] = stdout.trim().split(/\s+/); return { behind: Number(behind), ahead: Number(ahead) }; }
|
|
84
98
|
async function fetchOrigin(dir: string) { try { await git(["fetch", "origin"], dir); return true; } catch { return false; } }
|
|
85
99
|
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; } }
|
|
86
|
-
async function
|
|
100
|
+
async function assertSafeToPush(dir: string) {
|
|
101
|
+
const tracked = (await git(["ls-tree", "-r", "--name-only", "-z", "HEAD"], dir)).stdout;
|
|
102
|
+
const denied = new Set(tracked.split("\0").filter(Boolean).filter(isDenied));
|
|
103
|
+
const commits = (await git(["rev-list", "HEAD", "--not", "--remotes=origin"], dir)).stdout.trim().split("\n").filter(Boolean);
|
|
104
|
+
for (const commit of commits) {
|
|
105
|
+
const changed = (await git(["diff-tree", "--root", "-m", "-r", "--no-commit-id", "--no-renames", "--name-only", "--diff-filter=d", "-z", commit], dir)).stdout;
|
|
106
|
+
for (const file of changed.split("\0").filter(Boolean).filter(isDenied)) denied.add(file);
|
|
107
|
+
}
|
|
108
|
+
if (denied.size) throw new Error(`REFUSED to push denied paths in the current tree or outgoing history: ${[...denied].join(", ")}. Untrack current files and remove any unpushed commits containing them before retrying; local files are not deleted.`);
|
|
109
|
+
}
|
|
110
|
+
async function push(first: boolean, dir: string) { await assertSafeToPush(dir); try { await git(first ? ["push", "-u", "origin", "HEAD"] : ["push"], dir, 15_000); return true; } catch { return false; } }
|
|
87
111
|
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; }
|
|
88
|
-
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); } }
|
|
112
|
+
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); } }
|
|
89
113
|
|
|
90
114
|
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; }
|
|
91
115
|
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; }
|
|
@@ -97,8 +121,8 @@ async function warnPublic(ctx: Ctx | undefined, deps?: Deps) { const dir = dirOf
|
|
|
97
121
|
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); }
|
|
98
122
|
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"; } }
|
|
99
123
|
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; }
|
|
100
|
-
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); 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); }
|
|
101
|
-
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); }
|
|
124
|
+
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); }
|
|
125
|
+
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); }
|
|
102
126
|
async function readState(dir: string) { try { return JSON.parse(await fs.readFile(statePath(dir), "utf8")) as { lastAutoSyncAt?: string }; } catch { return {}; } }
|
|
103
127
|
async function writeState(state: { lastAutoSyncAt: string }, dir = dirOf()) { await fs.mkdir(stateDir(dir), { recursive: true }); await fs.writeFile(statePath(dir), JSON.stringify(state)); }
|
|
104
128
|
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; }
|