pi-config-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 +21 -0
- package/README.md +76 -0
- package/extensions/git-sync.ts +94 -0
- package/package.json +16 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Diogo Dias
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# pi-config-sync
|
|
2
|
+
|
|
3
|
+
Securely sync your `~/.pi/agent` configuration across machines through a git remote.
|
|
4
|
+
It is a [pi package](https://pi.dev/packages) and keeps the repository **in place** so its history stays transparent.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pi install npm:pi-config-sync
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Quickstart
|
|
13
|
+
|
|
14
|
+
On the first machine, run `/gitsync init`. With authenticated GitHub CLI (`gh auth login`), it detects your account, creates a private `pi-agent-config` repository, commits the allowed configuration, and pushes it.
|
|
15
|
+
|
|
16
|
+
Without `gh`, first create a private remote yourself, then run:
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
/gitsync init git@github.com:you/pi-agent-config.git
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
On each additional machine, run `/gitsync link` (with `gh`) or `/gitsync link <remote-url>`. It fetches the remote configuration. A differing local allowed file is moved to `<file>.local-backup`; it is never deleted, and linking refuses to touch a directory that already has its own git history. Run `/reload` afterwards; local-only allowed files are committed and pushed by the next sync.
|
|
23
|
+
|
|
24
|
+
## Commands
|
|
25
|
+
|
|
26
|
+
| Command | Description |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| `/gitsync init [name\|owner/name\|url]` | Create and connect the first-machine repository |
|
|
29
|
+
| `/gitsync link [name\|owner/name\|url]` | Connect another machine |
|
|
30
|
+
| `/gitsync status` | Show repository and tracked-secret status |
|
|
31
|
+
| `/gitsync sync` | Commit, fetch/rebase, and push |
|
|
32
|
+
| `/gitsync push` | Commit and push without pulling |
|
|
33
|
+
| `/gitsync pull` | Fetch and integrate remote changes |
|
|
34
|
+
|
|
35
|
+
## Security model
|
|
36
|
+
|
|
37
|
+
This package uses an **allowlist**, not a broad config-directory upload. By default it syncs `.gitignore`, `settings.json`, `AGENTS.md`, `git-sync.jsonc`, and `extensions/`, `chains/`, `prompts/`, `themes/`, and `skills/`. You can add safe paths explicitly.
|
|
38
|
+
|
|
39
|
+
It never stages auth files, token/secret/credential-named files, `.env` files, sessions, state, package/cache directories, or `node_modules`. That policy is enforced four ways: a managed allowlist `.gitignore`, `.git/info/exclude`, a post-stage hard guard that resets and aborts any bad staging, and a tracked-file scan warning. It never force-pushes.
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
## Configuration
|
|
44
|
+
|
|
45
|
+
Create `~/.pi/agent/git-sync.jsonc`:
|
|
46
|
+
|
|
47
|
+
```jsonc
|
|
48
|
+
{
|
|
49
|
+
"autoSyncIntervalMinutes": 5,
|
|
50
|
+
"includeHostname": true,
|
|
51
|
+
"extraPaths": ["my-safe-directory"],
|
|
52
|
+
"warnOnPublicRemote": true
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Unsafe extra paths (secrets, cache names, absolute paths, or `..`) are rejected. Set `includeHostname` to `false` to omit the machine hostname from automatic commit messages.
|
|
57
|
+
|
|
58
|
+
## Conflicts and uninstall
|
|
59
|
+
|
|
60
|
+
On a sync conflict, rebase is aborted and the repository is left untouched for manual resolution:
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
cd ~/.pi/agent
|
|
64
|
+
git status
|
|
65
|
+
git pull --rebase
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Remove the package with `pi remove npm:pi-config-sync`. Your local repository and remote remain until you delete them yourself.
|
|
69
|
+
|
|
70
|
+
If migrating from a hand-rolled `extensions/git-sync.ts`, delete that file first to avoid duplicate `/gitsync` registration.
|
|
71
|
+
|
|
72
|
+
Onboarding flow inspired by [opencode-synced](https://github.com/iHildy/opencode-synced).
|
|
73
|
+
|
|
74
|
+
## Releases
|
|
75
|
+
|
|
76
|
+
Tags matching `v*` publish via the included provenance-enabled GitHub Action after an `NPM_TOKEN` secret is configured.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
|
|
8
|
+
const exec = promisify(execFile);
|
|
9
|
+
const STATUS_KEY = "git-sync";
|
|
10
|
+
const START = "# >>> pi-config-sync managed — do not edit inside this block";
|
|
11
|
+
const END = "# <<< pi-config-sync managed";
|
|
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"];
|
|
14
|
+
const IGNORE_DENY = ["auth*", "*token*", "*secret*", "*credential*", "*.env", "*.env.*", "*.local.json", "**/node_modules/", ".DS_Store"];
|
|
15
|
+
const LIKELY_SYNC_REPO_NAMES = ["pi-agent-config", "my-pi-config", "pi-config", "dotfiles-pi"];
|
|
16
|
+
|
|
17
|
+
export interface GitSyncConfig { autoSyncIntervalMinutes?: number; includeHostname?: boolean; extraPaths?: string[]; warnOnPublicRemote?: boolean }
|
|
18
|
+
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
|
+
type Level = "info" | "warning" | "error";
|
|
21
|
+
type Ctx = ExtensionContext | ExtensionCommandContext;
|
|
22
|
+
|
|
23
|
+
export default function gitSync(pi: ExtensionAPI) {
|
|
24
|
+
pi.registerCommand("gitsync", { description: "Securely sync pi config (init, link, status, sync, push, pull)", getArgumentCompletions: prefix => {
|
|
25
|
+
const entries = ["init", "link", "status", "sync", "push", "pull"].map(value => ({ value, label: value })).filter(x => x.value.startsWith(prefix.trim()));
|
|
26
|
+
return entries.length ? entries : null;
|
|
27
|
+
}, handler: async (args, ctx) => {
|
|
28
|
+
const [command = "status", ...rest] = args.trim().split(/\s+/); const arg = rest.join(" ");
|
|
29
|
+
try { await withLock(ctx, async () => {
|
|
30
|
+
if (command === "init") return runInit(arg, ctx);
|
|
31
|
+
if (command === "link") return runLink(arg, ctx);
|
|
32
|
+
if (command === "status") return showStatus(ctx);
|
|
33
|
+
if (command === "sync") return runSync(ctx, { auto: false, push: true });
|
|
34
|
+
if (command === "push") return runSync(ctx, { auto: false, push: true, skipPull: true });
|
|
35
|
+
if (command === "pull") return runSync(ctx, { auto: false, push: false });
|
|
36
|
+
throw new Error("Unknown command. Usage: /gitsync [init|link|status|sync|push|pull]");
|
|
37
|
+
}); } catch (error) { notify(ctx, `git-sync: ${message(error)}`, "error"); }
|
|
38
|
+
} });
|
|
39
|
+
pi.on("session_start", async (_event, ctx) => { if (await shouldAutoSync()) try { await withLock(ctx, async () => { await writeState({ lastAutoSyncAt: new Date().toISOString() }); await runSync(ctx, { auto: true, push: true }); }); } catch (error) { notify(ctx, `git-sync skipped: ${message(error)}`, "warning"); } });
|
|
40
|
+
pi.on("session_shutdown", async (event, ctx) => { const reason = typeof event === "object" && event ? (event as { reason?: string }).reason : undefined; if (reason === "reload" || isSubagentChild() || !(await isSyncableRepo())) return; try { await withLock(ctx, async () => { await prepareCommit(undefined, ctx); await commitLocalChanges(undefined, undefined, ctx); await bestEffortPush(); }); } catch {} });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function dirOf(deps?: Deps) { const value = deps?.dir ?? process.env.PI_CODING_AGENT_DIR?.trim(); return !value ? path.join(os.homedir(), ".pi", "agent") : value === "~" || value.startsWith("~/") ? path.join(os.homedir(), value.slice(2)) : path.resolve(value); }
|
|
44
|
+
function gitEnv(dir: string) { return { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_CEILING_DIRECTORIES: path.dirname(dir) }; }
|
|
45
|
+
function git(args: string[], dir: string, timeout = 10_000) { return exec("git", args, { cwd: dir, timeout, maxBuffer: 16 * 1024 * 1024, env: gitEnv(dir) }); }
|
|
46
|
+
function gitRaw(args: string[], dir: string) { return exec("git", args, { cwd: dir, timeout: 10_000, maxBuffer: 64 * 1024 * 1024, encoding: "buffer", env: gitEnv(dir) }) as unknown as Promise<{ stdout: Buffer; stderr: Buffer }>; }
|
|
47
|
+
function notify(ctx: Ctx | undefined, text: string, level: Level, deps?: Deps) { if (deps?.notify) deps.notify(text, level); else if (ctx?.hasUI) ctx.ui.notify(text, level); }
|
|
48
|
+
const warnedOnce = new Set<string>();
|
|
49
|
+
function warnOnce(ctx: Ctx | undefined, text: string, deps: Deps | undefined, key = text) { if (warnedOnce.has(key) || !(deps?.notify || ctx?.hasUI)) return; warnedOnce.add(key); notify(ctx, text, "warning", deps); }
|
|
50
|
+
function message(error: unknown) { return error instanceof Error ? error.message : String(error); }
|
|
51
|
+
function stateDir(dir: string) { return path.join(dir, ".git-sync"); }
|
|
52
|
+
function statePath(dir: string) { return path.join(stateDir(dir), "state.json"); }
|
|
53
|
+
function lockPath(dir: string) { return path.join(stateDir(dir), "lock"); }
|
|
54
|
+
function isSubagentChild() { return Number(process.env.PI_SUBAGENT_DEPTH ?? "0") > 0; }
|
|
55
|
+
|
|
56
|
+
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
|
+
function validExtra(entry: string) { return entry.trim() !== "" && !entry.includes("..") && !path.isAbsolute(entry) && !isDenied(entry); }
|
|
58
|
+
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 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`); return { ...raw, extraPaths: extras }; } 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
|
+
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
|
+
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
|
+
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
|
+
function escapeRegExp(text: string) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
|
|
64
|
+
async function prepareCommit(deps?: Deps, ctx?: Ctx) { const config = await readConfig(deps, ctx); await ensureIgnoreRules(dirOf(deps), config); await ensureInfoExclude(dirOf(deps)); return config; }
|
|
65
|
+
export async function stagedSecretFiles(dir = dirOf()) { const { stdout } = await git(["diff", "--cached", "--name-only", "-z"], dir); return stdout.split("\0").filter(Boolean).filter(isDenied); }
|
|
66
|
+
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; }
|
|
68
|
+
async function hasDotGit(dir: string) { try { await fs.access(path.join(dir, ".git")); return true; } catch { return false; } }
|
|
69
|
+
async function hasCommits(dir: string) { try { await git(["rev-parse", "HEAD"], dir); return true; } catch { return false; } }
|
|
70
|
+
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; } }
|
|
71
|
+
async function upstreamRef(dir: string) { try { return (await git(["rev-parse", "--abbrev-ref", "@{u}"], dir)).stdout.trim(); } catch { return undefined; } }
|
|
72
|
+
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) }; }
|
|
73
|
+
async function fetchOrigin(dir: string) { try { await git(["fetch", "origin"], dir); return true; } catch { return false; } }
|
|
74
|
+
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
|
+
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
|
+
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); } }
|
|
78
|
+
|
|
79
|
+
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
|
+
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; }
|
|
81
|
+
const defaultGh: GhClient = { async available() { try { await exec("gh", ["auth", "status"], { timeout: 5000 }); return true; } catch { return false; } }, async currentUser() { return (await exec("gh", ["api", "user", "--jq", ".login"])).stdout.trim(); }, async repoExists(id) { try { await exec("gh", ["repo", "view", id, "--json", "name"]); return true; } catch { return false; } }, async isPrivate(id) { try { const { stdout } = await exec("gh", ["repo", "view", id, "--json", "isPrivate"]); return (JSON.parse(stdout) as { isPrivate: boolean }).isPrivate; } catch { return undefined; } }, async createPrivateRepo(id) { await exec("gh", ["repo", "create", id, "--private"], { timeout: 15_000 }); }, remoteUrl(id) { return `https://github.com/${id}.git`; } };
|
|
82
|
+
async function addRemote(url: string, dir: string) { await git(["remote", "add", "origin", url], dir); }
|
|
83
|
+
async function hasOrigin(dir: string) { return isSyncableRepo(dir); }
|
|
84
|
+
async function initRepo(dir: string) { if (!(await hasDotGit(dir))) await git(["init", "-b", "main"], dir); }
|
|
85
|
+
async function warnPublic(ctx: Ctx | undefined, deps?: Deps) { const dir = dirOf(deps), config = await readConfig(deps, ctx); if (config.warnOnPublicRemote === false) return; const gh = deps?.gh ?? defaultGh; if (!(await gh.available())) return; try { const remote = (await git(["remote", "get-url", "origin"], dir)).stdout.trim(); const ref = parseRepoReference(remote, ""); if (ref && await gh.isPrivate(`${ref.owner}/${ref.name}`) === false) notify(ctx, "git-sync: remote is PUBLIC — pi-config-sync never syncs secrets, but review what you allowlist; silence with warnOnPublicRemote: false in git-sync.jsonc", "warning", deps); } catch {} }
|
|
86
|
+
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
|
+
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
|
+
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 readConfig(deps, ctx)); await ensureInfoExclude(dir); 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); }
|
|
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); }
|
|
91
|
+
async function readState(dir: string) { try { return JSON.parse(await fs.readFile(statePath(dir), "utf8")) as { lastAutoSyncAt?: string }; } catch { return {}; } }
|
|
92
|
+
async function writeState(state: { lastAutoSyncAt: string }, dir = dirOf()) { await fs.mkdir(stateDir(dir), { recursive: true }); await fs.writeFile(statePath(dir), JSON.stringify(state)); }
|
|
93
|
+
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; }
|
|
94
|
+
export async function withLock<T>(ctx: Ctx | undefined, fn: () => Promise<T>, deps?: Deps): Promise<T | undefined> { const dir = dirOf(deps); await fs.mkdir(stateDir(dir), { recursive: true }); try { const handle = await fs.open(lockPath(dir), "wx"); await handle.writeFile(JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() })); await handle.close(); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; try { const lock = JSON.parse(await fs.readFile(lockPath(dir), "utf8")) as { pid: number; startedAt: string }; if (Number.isInteger(lock.pid) && lock.pid > 0) { process.kill(lock.pid, 0); if (Date.now() - Date.parse(lock.startedAt) < 600_000) return undefined; } } catch {} await fs.rm(lockPath(dir), { force: true }); return withLock(ctx, fn, deps); } try { return await fn(); } finally { await fs.rm(lockPath(dir), { force: true }); } }
|
package/package.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-config-sync",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"repository": { "type": "git", "url": "git+https://github.com/diogovdias/pi-config-sync.git" },
|
|
5
|
+
"description": "Sync your ~/.pi/agent config across machines through a private git repo — with hard guards that keep secrets out.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "Diogo Dias",
|
|
9
|
+
"keywords": ["pi-package"],
|
|
10
|
+
"files": ["extensions"],
|
|
11
|
+
"pi": { "extensions": ["./extensions"] },
|
|
12
|
+
"peerDependencies": { "@earendil-works/pi-coding-agent": "*" },
|
|
13
|
+
"devDependencies": { "typescript": "^5", "@types/node": "^24", "@earendil-works/pi-coding-agent": "*" },
|
|
14
|
+
"scripts": { "typecheck": "tsc --noEmit", "test": "node --test test/*.test.ts", "check": "npm run typecheck && npm test" },
|
|
15
|
+
"engines": { "node": ">=23" }
|
|
16
|
+
}
|