pi-config-sync 0.2.1 → 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 CHANGED
@@ -80,9 +80,12 @@ Nothing outside the allowlist ever syncs — new files are ignored by default. S
80
80
  | `auth*` (`auth.json`) | API keys and OAuth tokens |
81
81
  | `*token*`, `*secret*`, `*credential*`, `*.env*`, `*.local.json` | Anything named like a secret |
82
82
  | `sessions/`, `state/`, `.git-sync/` | Local history and machine state |
83
+ | `logs/` at any depth | Runtime logs, including permission audit/debug logs; retained locally |
83
84
  | `npm/`, `git/`, `bin/`, `node_modules` | Installed packages — pi reinstalls them from `settings.json` |
84
85
 
85
- The policy is enforced four ways — a managed allowlist `.gitignore`, `.git/info/exclude`, a post-stage hard guard that resets and aborts any commit staging a denied path, and a tracked-file scan warning — so it holds even against `git add -f`. It never force-pushes.
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.
86
89
 
87
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.
88
91
 
@@ -12,7 +12,8 @@ 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 IGNORE_DENY = ["auth*", "*token*", "*secret*", "*credential*", "*.env", "*.env.*", "*.local.json", "**/node_modules/", ".DS_Store"];
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
19
  export interface GitSyncConfig { autoSyncIntervalMinutes?: number; extraPaths?: string[]; includeHostname?: boolean; machineLocalSettings?: string[]; nodePath?: string; warnOnPublicRemote?: boolean }
@@ -55,7 +56,7 @@ function statePath(dir: string) { return path.join(stateDir(dir), "state.json");
55
56
  function lockPath(dir: string) { return path.join(stateDir(dir), "lock"); }
56
57
  function isSubagentChild() { return Number(process.env.PI_SUBAGENT_DEPTH ?? "0") > 0; }
57
58
 
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")); }
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")); }
59
60
  function validExtra(entry: string) { return entry.trim() !== "" && !entry.includes("..") && !path.isAbsolute(entry) && !isDenied(entry); }
60
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; }
61
62
  export function machineKeys(config: GitSyncConfig) { return config.machineLocalSettings ?? DEFAULT_MACHINE_LOCAL; }
@@ -78,9 +79,9 @@ async function gitConfigValue(key: string, dir: string) { try { return (await gi
78
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 {} }
79
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 {} }
80
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; }
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
+ 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); }
82
83
  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
+ 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"); }
84
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) })); }
85
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. */
86
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; }
@@ -96,7 +97,17 @@ async function upstreamRef(dir: string) { try { return (await git(["rev-parse",
96
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) }; }
97
98
  async function fetchOrigin(dir: string) { try { await git(["fetch", "origin"], dir); return true; } catch { return false; } }
98
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; } }
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; } }
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; } }
100
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; }
101
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); } }
102
113
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-config-sync",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/diogovdias/pi-config-sync.git"