public-ai-sync 0.0.0-stage → 0.0.7

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
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # public-ai-sync
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ NPM **dev dependency** that installs this pack's AI environment into a consuming repo: rules, skills, agent files, Claude hooks, scripts (lint, guard, privacy, git hooks), and code-quality runners.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install --save-dev public-ai-sync
9
+ ```
10
+
11
+ `postinstall` and `prepare` fetch the source, replace the target folder, link boot paths at the consumer root, rewrite the managed `.gitignore` block, install git hooks when the consumer is a git repo, and add `public-ai:*` npm scripts.
12
+
13
+ Default target: `.public-ai/`
14
+ Default source: `https://github.com/CodyTVWeber/Public-AI`
15
+ Default paths: `rules`, `skills`, `AI-setup`, `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, `PRIVACY.md`, `.claude`, `.func-size`, `.mr-size`, `scripts`
16
+
17
+ ## What install does
18
+
19
+ 1. Copy the default paths into the target folder (atomic replace: staging, then swap)
20
+ 2. Create relative symlinks at the consumer root so `$CLAUDE_PROJECT_DIR` hooks resolve. `.claude`, `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, `PRIVACY.md`, `rules`, `skills`, `AI-setup`, `.func-size`, and `.mr-size` link as a whole when those names are free. `scripts/` stays a real directory; each child (`lint`, `guard`, `check-privacy.sh`, `install-hooks.sh`, `tests`, …) is linked. An existing non-link file is left in place
21
+ 3. Gitignore the target and every link this package created
22
+ 4. Run `scripts/install-hooks.sh` when that script is present. A consumer that is not a git repo, or that already has a foreign hook plus a `.bak`, does not fail the install
23
+ 5. Add `public-ai:*` npm scripts when those names are free: `public-ai:sync` (manual re-run), `public-ai:lint-docs`, `public-ai:lint-explainer`, `public-ai:lint`, `public-ai:check-languages`, `public-ai:check-copies`, `public-ai:check-duplicates`, `public-ai:check-skill-catalog`, `public-ai:check-1k-cross`, `public-ai:verdict-parse`, `public-ai:code-quality`, `public-ai:privacy`, and `public-ai:install-hooks`. Consumer `postinstall` and `prepare` scripts are not added
24
+
25
+ ## Config
26
+
27
+ Consumer `package.json`:
28
+
29
+ ```json
30
+ {
31
+ "publicAiSync": {
32
+ "source": "https://github.com/CodyTVWeber/Public-AI",
33
+ "ref": "main",
34
+ "target": ".public-ai",
35
+ "paths": ["rules", "skills", "AGENTS.md"]
36
+ }
37
+ }
38
+ ```
39
+
40
+ Env (wins over `package.json`): `PUBLIC_AI_SYNC_SOURCE`, `PUBLIC_AI_SYNC_REF`, `PUBLIC_AI_SYNC_TARGET`, `PUBLIC_AI_SYNC_PATHS` (comma list), `PUBLIC_AI_SYNC_ROOT`, `PUBLIC_AI_SYNC_SKIP=1`.
41
+
42
+ `source` is a git URL or a local directory. Omit `paths` to take the full default list. A supplied env or `publicAiSync.paths` list is used even when every entry canonicalizes away; an empty list then fails at materialize instead of installing the defaults.
43
+
44
+ ## Gitignore
45
+
46
+ The package ships `gitignore.snippet`. `npx public-ai-sync ignore` rewrites the managed block between `# public-ai-sync` and `# end public-ai-sync` from the target path. A full sync rewrites that block from the target and the links this run kept. Lines after the end marker stay. Root names are anchored (`/AGENTS.md`). Owned links and files are listed without a trailing slash so Git ignores the symlink itself, not only a real directory.
47
+
48
+ ## Failures
49
+
50
+ A missing network, a failed clone, or an empty source exits non-zero and leaves the previous target folder in place.
51
+
52
+ ## Manual run
53
+
54
+ ```sh
55
+ npx public-ai-sync
56
+ npx public-ai-sync ignore
57
+ npx public-ai-sync lint-docs
58
+ npx public-ai-sync lint-explainer
59
+ npx public-ai-sync lint
60
+ npx public-ai-sync check-languages
61
+ npx public-ai-sync check-copies
62
+ npx public-ai-sync check-duplicates
63
+ npx public-ai-sync check-skill-catalog
64
+ npx public-ai-sync check-1k-cross
65
+ npx public-ai-sync verdict-parse
66
+ npx public-ai-sync code-quality
67
+ npx public-ai-sync privacy
68
+ npx public-ai-sync install-hooks
69
+ ```
package/bin/sync.mjs ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { printFail } from "../lib/errors.mjs";
3
+ import { run } from "../lib/run.mjs";
4
+
5
+ try {
6
+ process.exit(run(process.argv.slice(2)));
7
+ } catch (err) {
8
+ process.exit(printFail(err));
9
+ }
@@ -0,0 +1,3 @@
1
+ # public-ai-sync
2
+ /.public-ai/
3
+ # end public-ai-sync
package/lib/config.mjs ADDED
@@ -0,0 +1,118 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, join, posix } from "node:path";
3
+
4
+ export const DEFAULT_SOURCE = "https://github.com/CodyTVWeber/Public-AI";
5
+ export const DEFAULT_TARGET = ".public-ai";
6
+ export const DEFAULT_REF = "main";
7
+ export const DEFAULT_PATHS = [
8
+ "rules",
9
+ "skills",
10
+ "AI-setup",
11
+ "AGENTS.md",
12
+ "CLAUDE.md",
13
+ "GEMINI.md",
14
+ "PRIVACY.md",
15
+ ".claude",
16
+ ".func-size",
17
+ ".mr-size",
18
+ "scripts",
19
+ ];
20
+ export const FIELD = "publicAiSync";
21
+ export const PKG_NAME = "public-ai-sync";
22
+
23
+ export function loadConfig(env = process.env) {
24
+ const root = consumerRoot(env);
25
+ const pkg = readPkg(join(root, "package.json"));
26
+ const field = objectField(pkg[FIELD]);
27
+ const source = env.PUBLIC_AI_SYNC_SOURCE || field.source || DEFAULT_SOURCE;
28
+ const targetRel = canonicalRel(env.PUBLIC_AI_SYNC_TARGET || field.target || DEFAULT_TARGET)
29
+ || DEFAULT_TARGET;
30
+ return {
31
+ skip: envFlag(env.PUBLIC_AI_SYNC_SKIP) || skipSelf(root, pkg),
32
+ root,
33
+ source: resolveSource(root, source),
34
+ ref: env.PUBLIC_AI_SYNC_REF || field.ref || DEFAULT_REF,
35
+ paths: listedPaths(env, field),
36
+ targetRel,
37
+ target: join(root, targetRel),
38
+ };
39
+ }
40
+
41
+ export function consumerRoot(env = process.env) {
42
+ return env.PUBLIC_AI_SYNC_ROOT || env.INIT_CWD || env.npm_config_local_prefix || process.cwd();
43
+ }
44
+
45
+ export function canonicalRel(rel) {
46
+ return collapseRel(rel);
47
+ }
48
+
49
+ function listedPaths(env, field) {
50
+ const fromEnv = splitRaw(env.PUBLIC_AI_SYNC_PATHS);
51
+ if (fromEnv) return uniqueRels(fromEnv);
52
+ const fromField = arrayPaths(field.paths);
53
+ if (fromField) return uniqueRels(fromField);
54
+ return DEFAULT_PATHS;
55
+ }
56
+
57
+ function splitRaw(raw) {
58
+ if (raw == null || raw === "") return null;
59
+ return raw.split(",").map((item) => item.trim()).filter(Boolean);
60
+ }
61
+
62
+ function arrayPaths(value) {
63
+ return Array.isArray(value) ? value.map(String) : null;
64
+ }
65
+
66
+ function uniqueRels(items) {
67
+ const out = [];
68
+ for (const item of items) addUniqueRel(out, item);
69
+ return out;
70
+ }
71
+
72
+ function addUniqueRel(out, item) {
73
+ const rel = collapseRel(item);
74
+ if (!rel || out.includes(rel)) return;
75
+ out.push(rel);
76
+ }
77
+
78
+ function collapseRel(rel) {
79
+ const raw = String(rel).trim().replaceAll("\\", "/");
80
+ if (!raw || posix.isAbsolute(raw)) return "";
81
+ const collapsed = posix.normalize(raw).replace(/\/$/, "");
82
+ if (!collapsed || collapsed === ".") return "";
83
+ if (collapsed === ".." || collapsed.startsWith("../")) return "";
84
+ return collapsed;
85
+ }
86
+
87
+ function readPkg(path) {
88
+ try {
89
+ return JSON.parse(readFileSync(path, "utf8"));
90
+ } catch (err) {
91
+ return missingPkg(err);
92
+ }
93
+ }
94
+
95
+ function missingPkg(_err) {
96
+ return {};
97
+ }
98
+
99
+ function objectField(value) {
100
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
101
+ return {};
102
+ }
103
+
104
+ function envFlag(value) {
105
+ if (value == null || value === "") return false;
106
+ const normalized = String(value).toLowerCase();
107
+ return normalized === "1" || normalized === "true" || normalized === "yes";
108
+ }
109
+
110
+ function skipSelf(root, pkg) {
111
+ if (pkg?.name === PKG_NAME) return true;
112
+ return existsSync(join(root, "packages", PKG_NAME, "package.json")) && !pkg?.[FIELD];
113
+ }
114
+
115
+ function resolveSource(root, source) {
116
+ if (/^[a-z]+:\/\//i.test(source) || source.startsWith("git@")) return source;
117
+ return isAbsolute(source) ? source : join(root, source);
118
+ }
package/lib/errors.mjs ADDED
@@ -0,0 +1,14 @@
1
+ export class SyncError extends Error {
2
+ constructor(message, code = 1) {
3
+ super(message);
4
+ this.name = "SyncError";
5
+ this.code = code;
6
+ }
7
+ }
8
+
9
+ export function printFail(err) {
10
+ const raw = err && err.message ? err.message : "failed";
11
+ const line = raw.startsWith("public-ai-sync:") ? raw : `public-ai-sync: ${raw}`;
12
+ process.stderr.write(`${line}\n`);
13
+ return err instanceof SyncError ? err.code : 1;
14
+ }
@@ -0,0 +1,63 @@
1
+ import { cpSync, existsSync, mkdirSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+ import { SyncError } from "./errors.mjs";
5
+ import { listFiles, rmIfExists } from "./fs-util.mjs";
6
+
7
+ const CLONE_DEPTH = "1";
8
+
9
+ export function materializeSource(job) {
10
+ rmIfExists(job.staging);
11
+ mkdirSync(job.staging, { recursive: true });
12
+ fillStaging(job);
13
+ assertNonEmpty(job.staging);
14
+ }
15
+
16
+ function fillStaging(job) {
17
+ if (isLocalDir(job.cfg.source)) {
18
+ copyListedPaths({ from: job.cfg.source, to: job.staging, paths: job.cfg.paths });
19
+ return;
20
+ }
21
+ rmIfExists(job.gitDir);
22
+ cloneGit({ source: job.cfg.source, ref: job.cfg.ref, dest: job.gitDir });
23
+ copyListedPaths({ from: job.gitDir, to: job.staging, paths: job.cfg.paths });
24
+ }
25
+
26
+ function isLocalDir(source) {
27
+ try {
28
+ return existsSync(source) && statSync(source).isDirectory();
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ function cloneGit(spec) {
35
+ const result = spawnSync(
36
+ "git",
37
+ ["clone", "--depth", CLONE_DEPTH, "--branch", spec.ref, "--", spec.source, spec.dest],
38
+ { encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
39
+ );
40
+ if (result.status !== 0) throw new SyncError(cloneMessage(result, spec.source));
41
+ }
42
+
43
+ function cloneMessage(result, source) {
44
+ const detail = (result.stderr || result.stdout || "git clone failed").trim().split("\n")[0];
45
+ return `public-ai-sync: failed to fetch ${source}: ${detail}`;
46
+ }
47
+
48
+ function copyListedPaths(spec) {
49
+ mkdirSync(spec.to, { recursive: true });
50
+ for (const rel of spec.paths) copyOnePath({ from: spec.from, to: spec.to, rel });
51
+ }
52
+
53
+ function copyOnePath(spec) {
54
+ const src = join(spec.from, spec.rel);
55
+ if (!existsSync(src)) return;
56
+ cpSync(src, join(spec.to, spec.rel), { recursive: true });
57
+ }
58
+
59
+ function assertNonEmpty(dir) {
60
+ if (listFiles(dir).length === 0) {
61
+ throw new SyncError("public-ai-sync: source has no files in the configured paths; left the target folder unchanged");
62
+ }
63
+ }
@@ -0,0 +1,22 @@
1
+ import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ export function rmIfExists(path) {
5
+ if (existsSync(path)) rmSync(path, { recursive: true, force: true });
6
+ }
7
+
8
+ export function listFiles(dir) {
9
+ if (!existsSync(dir)) return [];
10
+ const out = [];
11
+ walkFiles({ root: dir, rel: "", out });
12
+ return out;
13
+ }
14
+
15
+ function walkFiles(state) {
16
+ const here = state.rel ? join(state.root, state.rel) : state.root;
17
+ for (const name of readdirSync(here)) {
18
+ const child = state.rel ? join(state.rel, name) : name;
19
+ if (statSync(join(state.root, child)).isDirectory()) walkFiles({ ...state, rel: child });
20
+ else state.out.push(child);
21
+ }
22
+ }
@@ -0,0 +1,99 @@
1
+ import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { canonicalRel } from "./config.mjs";
4
+
5
+ const MARKER = "# public-ai-sync";
6
+ const END_MARKER = "# end public-ai-sync";
7
+
8
+ export function ensureGitignore(root, rels) {
9
+ const file = join(root, ".gitignore");
10
+ const prev = existsSync(file) ? readFileSync(file, "utf8") : "";
11
+ const next = withManagedBlock(prev, ignoreLines(root, rels));
12
+ if (next === prev) return false;
13
+ writeFileSync(file, next);
14
+ return true;
15
+ }
16
+
17
+ export function ignoreLine(root, rel) {
18
+ return formatIgnoreLine(root, rel);
19
+ }
20
+
21
+ function ignoreLines(root, rels) {
22
+ const lines = [];
23
+ for (const rel of rels) addIgnoreLine(lines, formatIgnoreLine(root, rel));
24
+ return lines;
25
+ }
26
+
27
+ function addIgnoreLine(lines, line) {
28
+ if (lines.includes(line)) return;
29
+ lines.push(line);
30
+ }
31
+
32
+ function withManagedBlock(prev, managed) {
33
+ const { prefix, suffix } = splitManaged(prev);
34
+ const body = managed.length ? `${managed.join("\n")}\n` : "";
35
+ return `${formatPrefix(prefix)}${MARKER}\n${body}${END_MARKER}\n${formatSuffix(suffix)}`;
36
+ }
37
+
38
+ function splitManaged(text) {
39
+ const lines = text.split(/\r?\n/);
40
+ const start = lines.findIndex((row) => row.trim() === MARKER);
41
+ if (start < 0) return { prefix: text, suffix: "" };
42
+ return {
43
+ prefix: lines.slice(0, start).join("\n"),
44
+ suffix: suffixFrom(lines, start),
45
+ };
46
+ }
47
+
48
+ function suffixFrom(lines, start) {
49
+ const end = lines.findIndex((row, i) => i > start && row.trim() === END_MARKER);
50
+ if (end < 0) return suffixAfter(lines, start + 1);
51
+ return lines.slice(end + 1).join("\n");
52
+ }
53
+
54
+ function suffixAfter(lines, start) {
55
+ let end = start;
56
+ while (end < lines.length && isManagedRow(lines[end])) end += 1;
57
+ return lines.slice(end).join("\n");
58
+ }
59
+
60
+ function isManagedRow(row) {
61
+ const trimmed = row.trim();
62
+ return trimmed !== "" && !trimmed.startsWith("#");
63
+ }
64
+
65
+ function formatPrefix(prefix) {
66
+ if (!prefix) return "";
67
+ return prefix.endsWith("\n") ? prefix : `${prefix}\n`;
68
+ }
69
+
70
+ function formatSuffix(suffix) {
71
+ if (!suffix) return "";
72
+ return suffix.endsWith("\n") ? suffix : `${suffix}\n`;
73
+ }
74
+
75
+ function formatIgnoreLine(root, rel) {
76
+ const normalized = canonicalRel(rel) || slashRel(rel);
77
+ const body = bareIgnore(join(root, normalized)) ? normalized : `${normalized}/`;
78
+ return `/${body.replace(/^\//, "")}`;
79
+ }
80
+
81
+ function slashRel(rel) {
82
+ return String(rel).replaceAll("\\", "/").replace(/\/$/, "");
83
+ }
84
+
85
+ function bareIgnore(path) {
86
+ try {
87
+ return linkOrFile(lstatSync(path));
88
+ } catch (err) {
89
+ return missingPath(err);
90
+ }
91
+ }
92
+
93
+ function linkOrFile(stat) {
94
+ return stat.isSymbolicLink() || stat.isFile();
95
+ }
96
+
97
+ function missingPath(_err) {
98
+ return false;
99
+ }
package/lib/prune.mjs ADDED
@@ -0,0 +1,181 @@
1
+ import {
2
+ existsSync,
3
+ lstatSync,
4
+ readdirSync,
5
+ readFileSync,
6
+ readlinkSync,
7
+ unlinkSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
11
+ import { DEFAULT_PATHS, canonicalRel } from "./config.mjs";
12
+
13
+ export const MERGE_TOP = "scripts";
14
+ const SKIP_NAMES = new Set(["node_modules", ".git", ".public-ai"]);
15
+ const WIRED_NAME = ".wired";
16
+
17
+ export function pruneMissingChildren(job) {
18
+ for (const name of readdirSync(job.destDir)) {
19
+ if (existsSync(join(job.srcDir, name))) continue;
20
+ dropOwnedTree(join(job.destDir, name), job.targetRoot);
21
+ }
22
+ }
23
+
24
+ export function dropOwnedTree(dest, targetRoot) {
25
+ if (ourLink(dest, targetRoot)) {
26
+ unlinkSync(dest);
27
+ return;
28
+ }
29
+ if (!realDir(dest) || skipName(basename(dest))) return;
30
+ for (const name of readdirSync(dest)) dropOwnedChild({ dest, name, targetRoot });
31
+ }
32
+
33
+ export function pruneStaleOwned(job) {
34
+ const keptSet = new Set(job.kept.map(normalizeRel));
35
+ for (const rel of staleCandidates(job)) {
36
+ if (keptSet.has(normalizeRel(rel))) continue;
37
+ dropStaleLink(join(job.cfg.root, rel), job.cfg.target);
38
+ }
39
+ }
40
+
41
+ export function readWired(target) {
42
+ try {
43
+ return parseWired(readFileSync(join(target, WIRED_NAME), "utf8"));
44
+ } catch (err) {
45
+ return missingWired(err);
46
+ }
47
+ }
48
+
49
+ export function writeWired(target, rels) {
50
+ const lines = uniqueWired(rels);
51
+ const body = lines.length ? `${lines.join("\n")}\n` : "";
52
+ writeFileSync(join(target, WIRED_NAME), body);
53
+ }
54
+
55
+ export function isOurLink(dest, targetRoot) {
56
+ return ourLink(dest, targetRoot);
57
+ }
58
+
59
+ export function isRealDir(path) {
60
+ return realDir(path);
61
+ }
62
+
63
+ export function hasLstat(path) {
64
+ return lstatExists(path);
65
+ }
66
+
67
+ function dropOwnedChild(job) {
68
+ if (skipName(job.name)) return;
69
+ dropStaleLink(join(job.dest, job.name), job.targetRoot);
70
+ }
71
+
72
+ function staleCandidates(job) {
73
+ return uniqueWired(candidateRels(job));
74
+ }
75
+
76
+ function candidateRels(job) {
77
+ return [
78
+ ...DEFAULT_PATHS,
79
+ ...job.cfg.paths,
80
+ ...rootLinkRels(job.cfg),
81
+ ...scriptOwnedRels(job.cfg.root),
82
+ ...(job.previous || []),
83
+ ];
84
+ }
85
+
86
+ function parseWired(text) {
87
+ return uniqueWired(text.split(/\r?\n/).map((row) => row.trim()).filter(Boolean));
88
+ }
89
+
90
+ function uniqueWired(rels) {
91
+ const state = { seen: new Set(), out: [] };
92
+ for (const rel of rels) addSeenRel(state, rel);
93
+ return state.out;
94
+ }
95
+
96
+ function missingWired(_err) {
97
+ return [];
98
+ }
99
+
100
+ function rootLinkRels(cfg) {
101
+ if (!realDir(cfg.root)) return [];
102
+ return readdirSync(cfg.root).flatMap((name) => ownedRootRel(cfg, name));
103
+ }
104
+
105
+ function ownedRootRel(cfg, name) {
106
+ if (skipName(name)) return [];
107
+ if (!ourLink(join(cfg.root, name), cfg.target)) return [];
108
+ return [name];
109
+ }
110
+
111
+ function scriptOwnedRels(root) {
112
+ const dir = join(root, MERGE_TOP);
113
+ if (!realDir(dir)) return [];
114
+ return readdirSync(dir).flatMap((name) => nestedScriptRels(root, name));
115
+ }
116
+
117
+ function nestedScriptRels(root, name) {
118
+ if (skipName(name)) return [];
119
+ const rel = join(MERGE_TOP, name);
120
+ const dest = join(root, rel);
121
+ if (!realDir(dest)) return [rel];
122
+ return [rel, ...readdirSync(dest).flatMap((child) => nestedChildRel(rel, child))];
123
+ }
124
+
125
+ function nestedChildRel(parent, name) {
126
+ if (skipName(name)) return [];
127
+ return [join(parent, name)];
128
+ }
129
+
130
+ function addSeenRel(state, rel) {
131
+ const key = normalizeRel(rel);
132
+ if (!key || state.seen.has(key)) return;
133
+ state.seen.add(key);
134
+ state.out.push(key);
135
+ }
136
+
137
+ function dropStaleLink(dest, targetRoot) {
138
+ if (ourLink(dest, targetRoot)) unlinkSync(dest);
139
+ }
140
+
141
+ function skipName(name) {
142
+ return SKIP_NAMES.has(name);
143
+ }
144
+
145
+ function normalizeRel(rel) {
146
+ return canonicalRel(rel) || String(rel).replaceAll("\\", "/");
147
+ }
148
+
149
+ function ourLink(dest, targetRoot) {
150
+ try {
151
+ return linkResolvesInto(dest, targetRoot);
152
+ } catch (err) {
153
+ return missingPath(err);
154
+ }
155
+ }
156
+
157
+ function realDir(path) {
158
+ try {
159
+ return lstatSync(path).isDirectory();
160
+ } catch (err) {
161
+ return missingPath(err);
162
+ }
163
+ }
164
+
165
+ function lstatExists(path) {
166
+ try {
167
+ return Boolean(lstatSync(path));
168
+ } catch (err) {
169
+ return missingPath(err);
170
+ }
171
+ }
172
+
173
+ function linkResolvesInto(dest, targetRoot) {
174
+ if (!lstatSync(dest).isSymbolicLink()) return false;
175
+ const rel = relative(resolve(targetRoot), resolve(dirname(dest), readlinkSync(dest)));
176
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
177
+ }
178
+
179
+ function missingPath(_err) {
180
+ return false;
181
+ }
@@ -0,0 +1,28 @@
1
+ import { cpSync, existsSync, mkdirSync, renameSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { rmIfExists } from "./fs-util.mjs";
4
+
5
+ export function replaceTarget(staging, target) {
6
+ const next = `${target}.next`;
7
+ const prev = `${target}.prev`;
8
+ rmIfExists(next);
9
+ rmIfExists(prev);
10
+ mkdirSync(dirname(target), { recursive: true });
11
+ cpSync(staging, next, { recursive: true });
12
+ if (existsSync(target)) renameSync(target, prev);
13
+ swapNext({ next, prev, target });
14
+ rmIfExists(prev);
15
+ }
16
+
17
+ function swapNext(paths) {
18
+ try {
19
+ renameSync(paths.next, paths.target);
20
+ } catch (err) {
21
+ restorePrev(paths);
22
+ throw err;
23
+ }
24
+ }
25
+
26
+ function restorePrev(paths) {
27
+ if (existsSync(paths.prev) && !existsSync(paths.target)) renameSync(paths.prev, paths.target);
28
+ }
package/lib/run.mjs ADDED
@@ -0,0 +1,65 @@
1
+ import { existsSync, mkdtempSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { loadConfig } from "./config.mjs";
6
+ import { materializeSource } from "./fetch-source.mjs";
7
+ import { ensureGitignore } from "./gitignore.mjs";
8
+ import { replaceTarget } from "./replace-target.mjs";
9
+ import { rmIfExists } from "./fs-util.mjs";
10
+ import { TOOLS, runTool } from "./tools.mjs";
11
+ import { readWired } from "./prune.mjs";
12
+ import { wireConsumer } from "./wire.mjs";
13
+
14
+ export function run(argv, env = process.env) {
15
+ const cfg = loadConfig(env);
16
+ if (argv[0] === "ignore") return ignoreOnly(cfg);
17
+ if (TOOLS[argv[0]]) return runTool({ cfg, flag: argv[0], args: argv.slice(1) });
18
+ return sync(cfg);
19
+ }
20
+
21
+ export function sync(cfg) {
22
+ if (cfg.skip) {
23
+ process.stderr.write("public-ai-sync: skip\n");
24
+ return 0;
25
+ }
26
+ const work = mkdtempSync(join(tmpdir(), "public-ai-sync-"));
27
+ return runSync(cfg, work);
28
+ }
29
+
30
+ function ignoreOnly(cfg) {
31
+ if (!cfg.skip) ensureGitignore(cfg.root, [cfg.targetRel]);
32
+ return 0;
33
+ }
34
+
35
+ function runSync(cfg, work) {
36
+ try {
37
+ fillThenSwap(cfg, work);
38
+ return 0;
39
+ } finally {
40
+ rmIfExists(work);
41
+ }
42
+ }
43
+
44
+ function fillThenSwap(cfg, work) {
45
+ const staging = join(work, "staging");
46
+ materializeSource({ cfg, staging, gitDir: join(work, "git") });
47
+ const previous = readWired(cfg.target);
48
+ replaceTarget(staging, cfg.target);
49
+ const links = wireConsumer(cfg, previous);
50
+ ensureGitignore(cfg.root, [cfg.targetRel, ...links]);
51
+ installGitHooks(cfg.root);
52
+ }
53
+
54
+ function installGitHooks(root) {
55
+ const script = join(root, "scripts", "install-hooks.sh");
56
+ if (!existsSync(script)) return;
57
+ const result = spawnSync("bash", [script], { cwd: root, encoding: "utf8" });
58
+ if (result.status === 0) return;
59
+ process.stderr.write(`public-ai-sync: git hooks not installed (${exitLabel(result)})\n`);
60
+ }
61
+
62
+ function exitLabel(result) {
63
+ if (result.status == null) return result.error?.message || "failed";
64
+ return `exit ${result.status}`;
65
+ }
package/lib/tools.mjs ADDED
@@ -0,0 +1,48 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+ import { SyncError } from "./errors.mjs";
5
+
6
+ const NPM_PREFIX = "public-ai:";
7
+ const SYNC_BIN = "public-ai-sync";
8
+
9
+ export const TOOLS = {
10
+ "lint-docs": "scripts/lint/lint-docs.sh",
11
+ "lint-explainer": "scripts/lint/lint-explainer.sh",
12
+ lint: "scripts/lint/lint-clean-code.sh",
13
+ "check-languages": "scripts/lint/check-languages.sh",
14
+ "check-copies": "scripts/lint/check-copies.sh",
15
+ "check-duplicates": "scripts/lint/check-duplicates.sh",
16
+ "check-skill-catalog": "scripts/lint/check-skill-catalog.sh",
17
+ "check-1k-cross": "scripts/lint/check-1k-cross.sh",
18
+ "verdict-parse": "scripts/lint/verdict-parse.sh",
19
+ "code-quality": "skills/setup-repo/assets/scripts/code-quality-check.sh",
20
+ privacy: "scripts/check-privacy.sh",
21
+ "install-hooks": "scripts/install-hooks.sh",
22
+ };
23
+
24
+ export function npmScripts() {
25
+ const scripts = { [`${NPM_PREFIX}sync`]: SYNC_BIN };
26
+ for (const [flag, rel] of Object.entries(TOOLS)) {
27
+ scripts[`${NPM_PREFIX}${flag}`] = `bash ${rel}`;
28
+ }
29
+ return scripts;
30
+ }
31
+
32
+ export function runTool(job) {
33
+ const rel = TOOLS[job.flag];
34
+ const script = join(job.cfg.root, rel);
35
+ if (!existsSync(script)) {
36
+ throw new SyncError(`public-ai-sync: ${rel} is not installed; run with no arguments first`);
37
+ }
38
+ return exitStatus(spawnSync("bash", [script, ...job.args], {
39
+ cwd: job.cfg.root,
40
+ stdio: "inherit",
41
+ }));
42
+ }
43
+
44
+ function exitStatus(result) {
45
+ if (result.status === 0) return 0;
46
+ if (result.status == null) return 1;
47
+ return result.status;
48
+ }
@@ -0,0 +1,9 @@
1
+ const PART_COUNT = 3;
2
+
3
+ export function nextPatch(version) {
4
+ const parts = String(version).split(".");
5
+ if (parts.length !== PART_COUNT || parts.some((part) => !/^\d+$/.test(part))) {
6
+ throw new Error("public-ai-sync: package version is not major.minor.patch");
7
+ }
8
+ return `${parts[0]}.${parts[1]}.${Number(parts[2]) + 1}`;
9
+ }
package/lib/wire.mjs ADDED
@@ -0,0 +1,137 @@
1
+ import {
2
+ mkdirSync,
3
+ readdirSync,
4
+ readFileSync,
5
+ symlinkSync,
6
+ unlinkSync,
7
+ writeFileSync,
8
+ } from "node:fs";
9
+ import { dirname, join, relative } from "node:path";
10
+ import { npmScripts } from "./tools.mjs";
11
+ import {
12
+ MERGE_TOP,
13
+ dropOwnedTree,
14
+ hasLstat,
15
+ isOurLink,
16
+ isRealDir,
17
+ pruneMissingChildren,
18
+ pruneStaleOwned,
19
+ writeWired,
20
+ } from "./prune.mjs";
21
+
22
+ const JSON_INDENT = 2;
23
+
24
+ export function wireConsumer(cfg, previous = []) {
25
+ const links = cfg.paths.flatMap((rel) => wirePath({ cfg, rel }));
26
+ pruneStaleOwned({ cfg, kept: links, previous });
27
+ writeWired(cfg.target, links);
28
+ injectNpmScripts(cfg.root);
29
+ return links;
30
+ }
31
+
32
+ function wirePath(job) {
33
+ const src = join(job.cfg.target, job.rel);
34
+ if (!hasLstat(src)) {
35
+ dropOwnedTree(join(job.cfg.root, job.rel), job.cfg.target);
36
+ return [];
37
+ }
38
+ if (job.rel === MERGE_TOP) return mergeDir(job);
39
+ return placeLink(job, src);
40
+ }
41
+
42
+ function mergeDir(job) {
43
+ const srcDir = join(job.cfg.target, job.rel);
44
+ const destDir = join(job.cfg.root, job.rel);
45
+ prepareMergeDest(destDir, job.cfg.target);
46
+ if (!isRealDir(destDir)) return [];
47
+ return linkChildren({ cfg: job.cfg, rel: job.rel, srcDir, destDir });
48
+ }
49
+
50
+ function prepareMergeDest(destDir, targetRoot) {
51
+ if (isOurLink(destDir, targetRoot)) unlinkSync(destDir);
52
+ if (!hasLstat(destDir)) mkdirSync(destDir, { recursive: true });
53
+ }
54
+
55
+ function placeLink(job, src) {
56
+ const dest = join(job.cfg.root, job.rel);
57
+ if (hasLstat(dest)) return refreshOrSkip({ job, src, dest });
58
+ makeLink(dest, src);
59
+ return [job.rel];
60
+ }
61
+
62
+ function refreshOrSkip(state) {
63
+ if (isOurLink(state.dest, state.job.cfg.target)) {
64
+ unlinkSync(state.dest);
65
+ makeLink(state.dest, state.src);
66
+ return [state.job.rel];
67
+ }
68
+ if (!canMerge(state)) return [];
69
+ return linkChildren({
70
+ cfg: state.job.cfg,
71
+ rel: state.job.rel,
72
+ srcDir: state.src,
73
+ destDir: state.dest,
74
+ });
75
+ }
76
+
77
+ function canMerge(state) {
78
+ return underScripts(state.job.rel) && isRealDir(state.dest) && isRealDir(state.src);
79
+ }
80
+
81
+ function underScripts(rel) {
82
+ return rel === MERGE_TOP || rel.startsWith(`${MERGE_TOP}/`);
83
+ }
84
+
85
+ function linkChildren(state) {
86
+ pruneMissingChildren({
87
+ destDir: state.destDir,
88
+ srcDir: state.srcDir,
89
+ targetRoot: state.cfg.target,
90
+ });
91
+ return readdirSync(state.srcDir).flatMap((name) =>
92
+ wirePath({ cfg: state.cfg, rel: join(state.rel, name) }),
93
+ );
94
+ }
95
+
96
+ function makeLink(dest, src) {
97
+ mkdirSync(dirname(dest), { recursive: true });
98
+ symlinkSync(relative(dirname(dest), src), dest);
99
+ }
100
+
101
+ function injectNpmScripts(root) {
102
+ const file = join(root, "package.json");
103
+ const pkg = readJsonOrNull(file);
104
+ if (!pkg) return false;
105
+ const next = nextScripts(pkg.scripts);
106
+ if (!next) return false;
107
+ pkg.scripts = next;
108
+ writeFileSync(file, `${JSON.stringify(pkg, null, JSON_INDENT)}\n`);
109
+ return true;
110
+ }
111
+
112
+ function nextScripts(current) {
113
+ const scripts = isPlainObject(current) ? { ...current } : {};
114
+ let changed = false;
115
+ for (const [name, cmd] of Object.entries(npmScripts())) {
116
+ if (scripts[name]) continue;
117
+ scripts[name] = cmd;
118
+ changed = true;
119
+ }
120
+ return changed ? scripts : null;
121
+ }
122
+
123
+ function isPlainObject(value) {
124
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
125
+ }
126
+
127
+ function readJsonOrNull(file) {
128
+ try {
129
+ return JSON.parse(readFileSync(file, "utf8"));
130
+ } catch (err) {
131
+ return invalidJson(err);
132
+ }
133
+ }
134
+
135
+ function invalidJson(_err) {
136
+ return null;
137
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "public-ai-sync",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.7",
4
+ "description": "Dev dependency that installs the public AI environment into a consuming repo on install",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/CodyTVWeber/Public-AI",
10
+ "directory": "packages/public-ai-sync"
11
+ },
12
+ "bin": {
13
+ "public-ai-sync": "./bin/sync.mjs"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "lib",
18
+ "gitignore.snippet",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "postinstall": "node bin/sync.mjs",
23
+ "prepare": "node bin/sync.mjs"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ }
28
+ }