clawnify 0.21.1 → 0.22.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
@@ -111,6 +111,7 @@ clawnify ai-files install # Install rules + skills + MCP into your agen
111
111
  clawnify ai-files uninstall # Remove them
112
112
  clawnify workspace # The org's workspace repo, what maps where, how to edit locally
113
113
  clawnify workspace clone [dir] # Clone the org's Clawnify git repo (see below)
114
+ clawnify knowledge pull [dir] # Company Knowledge as markdown in knowledge/ (see below)
114
115
  ```
115
116
 
116
117
  ## Workspace repo
@@ -119,6 +120,24 @@ An org's apps and website live in one git repo: Clawnify git, or GitHub if the o
119
120
 
120
121
  `clawnify workspace clone` clones Clawnify git and sets git, in that clone only, to sign in with your Clawnify login, so `git pull` and `git push` need no token. Any member can clone; owners and admins push, and a push rebuilds only the folders it changed. CI and other tools without a login use an access token (Settings, Access tokens) as the password: `read` to clone, `write` to push.
121
122
 
123
+ The clone also gets the org's Company Knowledge on disk, so a coding agent can read it beside the code: `knowledge/` is added to `.gitignore`, pulled, and refreshed after each `git pull` by a `post-merge` hook (a pull with `--rebase` does not run it).
124
+
125
+ ## Company Knowledge on disk
126
+
127
+ ```bash
128
+ clawnify knowledge pull # published documents → knowledge/ at the workspace root
129
+ clawnify knowledge pull --files # also the original Company files, in knowledge/files/
130
+ clawnify knowledge pull --project <id> # a Project's sources → knowledge/projects/<name>/
131
+ ```
132
+
133
+ Every published document becomes a markdown file, in folders that follow its folder in Clawnify, with frontmatter carrying its `id`, `title`, `version`, `edit_revision` and `body_sha256`. The folder is a read-only copy: change documents in Clawnify, where they are reviewed and published.
134
+
135
+ - **Incremental.** Each pull lists only ids and revisions, so a document that has not changed since the last pull is neither downloaded nor written again. `.clawnify-knowledge.json` in the folder records what the pull wrote.
136
+ - **Your edits are kept.** A file changed since the last pull is left as it is and reported, never overwritten. `--strict` makes that exit non-zero.
137
+ - **Removals.** A document unpublished or deleted in Clawnify has its file removed, unless you changed that file. Files the pull did not write are never touched.
138
+ - **Never committed.** The pull refuses a folder inside a git repository that git does not ignore, or one holding committed files.
139
+ - **One org per folder.** The pull refuses a folder bound to another org: by the workspace's `clawnify.json`, a Clawnify git remote, or an earlier pull. `--org` cannot override that.
140
+
122
141
  ## Websites
123
142
 
124
143
  `clawnify init --type website` scaffolds a minimal Astro project:
@@ -658,7 +658,7 @@ async function pollUntilReady(resourceId, options = {}) {
658
658
  }
659
659
 
660
660
  // src/version.ts
661
- var VERSION = "0.21.1";
661
+ var VERSION = "0.22.0";
662
662
 
663
663
  export {
664
664
  OAUTH_CLIENT_ID,
@@ -673,6 +673,7 @@ export {
673
673
  readManifest,
674
674
  manifestKind,
675
675
  readProject,
676
+ findProjectRoot,
676
677
  saveProject,
677
678
  readWorkspaceConfig,
678
679
  findWorkspaceRoot,
@@ -6,6 +6,7 @@ import {
6
6
  VERSION,
7
7
  api,
8
8
  createArchive,
9
+ findProjectRoot,
9
10
  findWorkspaceRoot,
10
11
  generatePkce,
11
12
  getEmailFromToken,
@@ -21,7 +22,7 @@ import {
21
22
  resolveOrgContext,
22
23
  saveAuth,
23
24
  saveProject
24
- } from "./chunk-SFIKX2JT.js";
25
+ } from "./chunk-ID77VUXK.js";
25
26
 
26
27
  // src/cli.ts
27
28
  import { Command, Option } from "commander";
@@ -233,8 +234,8 @@ async function getOrCreateAnonContext(dir, name, agents) {
233
234
  saveAnon(dir, ctx);
234
235
  return { ctx, created: true };
235
236
  }
236
- async function anonPostForm(path12, formData, ctx) {
237
- return api.request("POST", path12, { formData, token: ctx.deploy_token });
237
+ async function anonPostForm(path14, formData, ctx) {
238
+ return api.request("POST", path14, { formData, token: ctx.deploy_token });
238
239
  }
239
240
  function explainAnonUnauthorized(dir) {
240
241
  clearAnon(dir);
@@ -429,11 +430,11 @@ function ask(question) {
429
430
  });
430
431
  });
431
432
  }
432
- async function postFormWithRetry(path12, formData, orgId, attempts = 3) {
433
+ async function postFormWithRetry(path14, formData, orgId, attempts = 3) {
433
434
  let lastErr;
434
435
  for (let i = 0; i < attempts; i++) {
435
436
  try {
436
- return await api.postForm(path12, formData, { orgId });
437
+ return await api.postForm(path14, formData, { orgId });
437
438
  } catch (err) {
438
439
  lastErr = err;
439
440
  if (i === attempts - 1) break;
@@ -464,7 +465,7 @@ async function uploadDeploy(archive, name, framework, orgId) {
464
465
  return { ok: false, error: err.error || res.statusText };
465
466
  }
466
467
  function gitSyncBase(dir) {
467
- const git = (...args) => {
468
+ const git2 = (...args) => {
468
469
  try {
469
470
  return execFileSync("git", ["-C", dir, ...args], {
470
471
  encoding: "utf8",
@@ -474,7 +475,7 @@ function gitSyncBase(dir) {
474
475
  return void 0;
475
476
  }
476
477
  };
477
- return git("merge-base", "HEAD", "@{upstream}") ?? git("rev-parse", "HEAD");
478
+ return git2("merge-base", "HEAD", "@{upstream}") ?? git2("rev-parse", "HEAD");
478
479
  }
479
480
  function appendSyncFields(formData, dir, force) {
480
481
  if (force) {
@@ -1632,7 +1633,7 @@ async function envUnsetCommand(key) {
1632
1633
  }
1633
1634
 
1634
1635
  // src/commands/api.ts
1635
- async function apiCommand(path12, opts) {
1636
+ async function apiCommand(path14, opts) {
1636
1637
  const method = (opts.method || (opts.data !== void 0 ? "POST" : "GET")).toUpperCase();
1637
1638
  let body;
1638
1639
  if (opts.data !== void 0) {
@@ -1643,7 +1644,7 @@ async function apiCommand(path12, opts) {
1643
1644
  process.exit(1);
1644
1645
  }
1645
1646
  }
1646
- const p = path12.startsWith("/") ? path12 : `/${path12}`;
1647
+ const p = path14.startsWith("/") ? path14 : `/${path14}`;
1647
1648
  const orgId = await resolveOrgContext({ orgFlag: opts.org });
1648
1649
  const res = await api.call(method, p, { body, orgId });
1649
1650
  const text = await res.text();
@@ -1750,9 +1751,9 @@ var DETECTORS = [
1750
1751
  { agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
1751
1752
  ];
1752
1753
  function exists(cwd, name) {
1753
- const path12 = join(cwd, name);
1754
+ const path14 = join(cwd, name);
1754
1755
  try {
1755
- statSync(path12);
1756
+ statSync(path14);
1756
1757
  return true;
1757
1758
  } catch {
1758
1759
  return false;
@@ -1776,7 +1777,7 @@ function agentByName(name) {
1776
1777
  var ALL_AGENTS = DETECTORS.map((d) => d.agent);
1777
1778
 
1778
1779
  // src/lib/skills/content.gen.ts
1779
- var CLI_VERSION = "0.21.1";
1780
+ var CLI_VERSION = "0.22.0";
1780
1781
  var BUNDLED_SKILLS = [
1781
1782
  {
1782
1783
  name: "build-a-clawnify-app",
@@ -1821,10 +1822,10 @@ var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
1821
1822
  function versionHeader(name) {
1822
1823
  return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
1823
1824
  }
1824
- function readExistingVersion(path12) {
1825
- if (!existsSync2(path12)) return null;
1825
+ function readExistingVersion(path14) {
1826
+ if (!existsSync2(path14)) return null;
1826
1827
  try {
1827
- const head = readFileSync(path12, "utf8").slice(0, 500);
1828
+ const head = readFileSync(path14, "utf8").slice(0, 500);
1828
1829
  const match = head.match(VERSION_HEADER_RE);
1829
1830
  return match ? match[2] : null;
1830
1831
  } catch {
@@ -3561,7 +3562,7 @@ async function connectionsListCommand(opts) {
3561
3562
  } else {
3562
3563
  const envWidth = Math.max(4, ...catalog.customEnv.map((e) => e.name.length));
3563
3564
  for (const e of catalog.customEnv) {
3564
- console.log(` ${e.name.padEnd(envWidth)} \u25CF set${e.hint ? ` (${e.hint})` : ""}`);
3565
+ console.log(` ${e.name.padEnd(envWidth)} \u25CF set`);
3565
3566
  }
3566
3567
  }
3567
3568
  }
@@ -3612,9 +3613,9 @@ async function connectionsConnectCommand(id, opts) {
3612
3613
  }
3613
3614
 
3614
3615
  // src/commands/workspace.ts
3615
- import fs7 from "fs";
3616
- import path10 from "path";
3617
- import { spawnSync } from "child_process";
3616
+ import fs9 from "fs";
3617
+ import path12 from "path";
3618
+ import { spawnSync as spawnSync2 } from "child_process";
3618
3619
 
3619
3620
  // src/commands/git-credential.ts
3620
3621
  var GIT_HOST = "api.clawnify.com";
@@ -3648,8 +3649,606 @@ password=${token}
3648
3649
  `);
3649
3650
  }
3650
3651
 
3652
+ // src/commands/knowledge.ts
3653
+ import fs8 from "fs";
3654
+ import path11 from "path";
3655
+
3656
+ // src/lib/knowledge-guards.ts
3657
+ import fs7 from "fs";
3658
+ import path10 from "path";
3659
+ import { spawnSync } from "child_process";
3660
+ function git(cwd, args) {
3661
+ return spawnSync("git", args, { cwd, encoding: "utf8" });
3662
+ }
3663
+ function existingAncestor(p) {
3664
+ let cur = path10.resolve(p);
3665
+ while (!fs7.existsSync(cur)) {
3666
+ const parent = path10.dirname(cur);
3667
+ if (parent === cur) break;
3668
+ cur = parent;
3669
+ }
3670
+ return cur;
3671
+ }
3672
+ function dotGitAbove(p) {
3673
+ let cur = existingAncestor(p);
3674
+ for (; ; ) {
3675
+ if (fs7.existsSync(path10.join(cur, ".git"))) return cur;
3676
+ const parent = path10.dirname(cur);
3677
+ if (parent === cur) return null;
3678
+ cur = parent;
3679
+ }
3680
+ }
3681
+ function gitToplevel(p) {
3682
+ const res = git(existingAncestor(p), ["rev-parse", "--show-toplevel"]);
3683
+ if (res.error || res.status !== 0) return null;
3684
+ return res.stdout.trim() || null;
3685
+ }
3686
+ function relativeToTop(top, p) {
3687
+ const abs = path10.resolve(p);
3688
+ const anc = existingAncestor(abs);
3689
+ const real = path10.join(fs7.realpathSync(anc), path10.relative(anc, abs));
3690
+ return path10.relative(fs7.realpathSync(top), real).split(path10.sep).join("/");
3691
+ }
3692
+ function checkGitIgnored(target) {
3693
+ const top = gitToplevel(target);
3694
+ if (!top) {
3695
+ const probe = git(existingAncestor(target), ["--version"]);
3696
+ const repo = probe.error ? dotGitAbove(target) : null;
3697
+ return repo ? { ok: false, message: `it is inside the git repository ${repo}, and git is not installed to check that it ignores the folder. Install git, then pull again.` } : { ok: true };
3698
+ }
3699
+ const rel = relativeToTop(top, target);
3700
+ if (rel === "" || rel.startsWith("..")) {
3701
+ return { ok: false, message: `${target} is the root of the git repository ${top}. Pull into a folder git ignores, such as knowledge/.` };
3702
+ }
3703
+ const tracked = git(top, ["ls-files", "--", `${rel}/`]);
3704
+ if (tracked.error || tracked.status !== 0) {
3705
+ return { ok: false, message: `Could not ask git about ${rel}/: ${tracked.error?.message ?? tracked.stderr.trim()}` };
3706
+ }
3707
+ if (tracked.stdout.trim()) {
3708
+ return {
3709
+ ok: false,
3710
+ message: `${rel}/ holds files committed to git. Knowledge is pulled, never committed.
3711
+ Take them out of git first: git rm -r --cached ${rel} && git commit -m "Stop tracking ${rel}"`
3712
+ };
3713
+ }
3714
+ const ignored = git(top, ["check-ignore", "-q", "--", `${rel}/`]);
3715
+ if (ignored.status === 0) return { ok: true };
3716
+ if (ignored.status === 1) {
3717
+ return {
3718
+ ok: false,
3719
+ message: `${rel}/ is inside the git repository ${top} and git does not ignore it, so the pulled
3720
+ documents could be committed. Add it to .gitignore first:
3721
+
3722
+ echo '${rel}/' >> ${path10.join(top, ".gitignore")}`
3723
+ };
3724
+ }
3725
+ return { ok: false, message: `Could not ask git whether ${rel}/ is ignored: ${ignored.error?.message ?? ignored.stderr.trim()}` };
3726
+ }
3727
+ var CLAWNIFY_GIT_URL = new RegExp(
3728
+ `^https://(?:[^@/]+@)?${GIT_HOST.replace(/\./g, "\\.")}/git/([0-9a-f-]{36})(?:\\.git)?/?$`,
3729
+ "i"
3730
+ );
3731
+ function orgFromGitUrl(url) {
3732
+ return CLAWNIFY_GIT_URL.exec(url.trim())?.[1]?.toLowerCase() ?? null;
3733
+ }
3734
+ function folderBindings(target) {
3735
+ const out = [];
3736
+ const ws = findWorkspaceRoot(target);
3737
+ if (ws) out.push({ source: `${path10.join(ws.dir, "clawnify.json")} (workspace.org)`, org: ws.org });
3738
+ const link = findProjectRoot(target);
3739
+ if (link?.org_id) out.push({ source: ".clawnify/project.json (clawnify link)", org: link.org_id });
3740
+ const top = gitToplevel(target);
3741
+ if (top) {
3742
+ const res = git(top, ["config", "--get-regexp", "^remote\\..*\\.url$"]);
3743
+ for (const line of res.status === 0 ? res.stdout.split("\n") : []) {
3744
+ const [key, url] = line.trim().split(/\s+/, 2);
3745
+ const org = url ? orgFromGitUrl(url) : null;
3746
+ if (key && org) out.push({ source: `git ${key.replace(/\.url$/, "")} (${url})`, org });
3747
+ }
3748
+ }
3749
+ return out;
3750
+ }
3751
+ function conflictingBindings(bindings, org) {
3752
+ return bindings.filter((b) => b.org.toLowerCase() !== org.id.toLowerCase() && b.org !== org.slug);
3753
+ }
3754
+
3755
+ // src/lib/knowledge-plan.ts
3756
+ import { createHash } from "crypto";
3757
+ var MANIFEST_FILE = ".clawnify-knowledge.json";
3758
+ var FORMAT = 1;
3759
+ function sha256(data) {
3760
+ return createHash("sha256").update(data).digest("hex");
3761
+ }
3762
+ function itemKey(item) {
3763
+ return `${item.kind}:${item.id}`;
3764
+ }
3765
+ function slugify3(text, max = 80) {
3766
+ return text.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, max).replace(/-+$/, "") || "untitled";
3767
+ }
3768
+ function slugifyFolder(folder) {
3769
+ if (!folder) return "";
3770
+ return folder.split("/").map((seg) => slugify3(seg)).filter((seg) => seg !== "untitled").join("/");
3771
+ }
3772
+ function splitFilename(name) {
3773
+ const base = name.split(/[\\/]/).pop() ?? name;
3774
+ const m = /^(.+?)\.([A-Za-z0-9]{1,10})$/.exec(base);
3775
+ if (!m) return { stem: slugify3(base), ext: "" };
3776
+ return { stem: slugify3(m[1]), ext: `.${m[2].toLowerCase()}` };
3777
+ }
3778
+ function join5(dir, name) {
3779
+ return dir ? `${dir}/${name}` : name;
3780
+ }
3781
+ function assignPaths(items, previous) {
3782
+ const prevPath = /* @__PURE__ */ new Map();
3783
+ for (const [p, e] of Object.entries(previous)) prevPath.set(itemKey(e), p);
3784
+ const plain = (it) => join5(it.dir, `${it.stem}${it.ext}`);
3785
+ const short = (it) => join5(it.dir, `${it.stem}-${it.id.slice(0, 8)}${it.ext}`);
3786
+ const out = /* @__PURE__ */ new Map();
3787
+ const taken = /* @__PURE__ */ new Set();
3788
+ for (const it of items) {
3789
+ const p = prevPath.get(itemKey(it));
3790
+ if (p && (p === plain(it) || p === short(it)) && !taken.has(p)) {
3791
+ out.set(itemKey(it), p);
3792
+ taken.add(p);
3793
+ }
3794
+ }
3795
+ const rest = items.filter((it) => !out.has(itemKey(it))).sort((a, b) => itemKey(a) < itemKey(b) ? -1 : 1);
3796
+ for (const it of rest) {
3797
+ let p = plain(it);
3798
+ if (taken.has(p)) p = short(it);
3799
+ if (taken.has(p)) p = join5(it.dir, `${it.stem}-${it.id}${it.ext}`);
3800
+ out.set(itemKey(it), p);
3801
+ taken.add(p);
3802
+ }
3803
+ return out;
3804
+ }
3805
+ function planPull(input) {
3806
+ const previous = input.manifest?.entries ?? {};
3807
+ const sameFormat = input.manifest?.format === FORMAT;
3808
+ const paths = assignPaths(input.listed, previous);
3809
+ const listedKeys = new Set(input.listed.map(itemKey));
3810
+ const claimed = new Set(paths.values());
3811
+ const actions = [];
3812
+ for (const item of input.listed) {
3813
+ const path14 = paths.get(itemKey(item));
3814
+ const entry = previous[path14];
3815
+ const local = input.local(path14);
3816
+ if (local === void 0) {
3817
+ actions.push({ type: "write", path: path14, item, guard: "absent" });
3818
+ } else if (local === "unreadable") {
3819
+ actions.push({ type: "keep", path: path14, reason: "unreadable", gone: false });
3820
+ } else if (!entry) {
3821
+ actions.push({ type: "write", path: path14, item, guard: "unowned" });
3822
+ } else {
3823
+ const current = sameFormat && entry.id === item.id && entry.kind === item.kind && entry.edit_revision === item.edit_revision;
3824
+ if (local !== entry.sha256) {
3825
+ actions.push(current ? { type: "keep", path: path14, reason: "edited", gone: false } : { type: "write", path: path14, item, guard: "edited" });
3826
+ } else {
3827
+ actions.push(current ? { type: "skip", path: path14, item } : { type: "write", path: path14, item, guard: "owned" });
3828
+ }
3829
+ }
3830
+ }
3831
+ for (const [path14, entry] of Object.entries(previous)) {
3832
+ if (claimed.has(path14)) continue;
3833
+ const local = input.local(path14);
3834
+ const because = !input.inScope(entry.kind) ? "out_of_scope" : listedKeys.has(itemKey(entry)) ? "moved" : "unlisted";
3835
+ if (local === void 0) actions.push({ type: "forget", path: path14 });
3836
+ else if (local === "unreadable") actions.push({ type: "keep", path: path14, reason: "unreadable", gone: true });
3837
+ else if (local !== entry.sha256) actions.push({ type: "keep", path: path14, reason: "edited", gone: true });
3838
+ else actions.push({ type: "remove", path: path14, entry, because });
3839
+ }
3840
+ return actions;
3841
+ }
3842
+ function renderDoc(doc, body) {
3843
+ const text = body.endsWith("\n") || body === "" ? body : `${body}
3844
+ `;
3845
+ const lines = [
3846
+ "---",
3847
+ "# A local copy pulled by `clawnify knowledge pull`. Edits here are not sent to",
3848
+ "# Clawnify, and the next pull leaves an edited file as it is. Change the",
3849
+ "# document in Clawnify instead.",
3850
+ `id: ${doc.id}`,
3851
+ `title: ${JSON.stringify(doc.title)}`
3852
+ ];
3853
+ if (doc.description) lines.push(`description: ${JSON.stringify(doc.description)}`);
3854
+ lines.push(`type: ${JSON.stringify(doc.doc_type)}`);
3855
+ lines.push(`version: ${doc.version}`);
3856
+ lines.push(`edit_revision: ${doc.edit_revision}`);
3857
+ if (doc.folder) lines.push(`folder: ${JSON.stringify(doc.folder)}`);
3858
+ if (doc.tags && doc.tags.length > 0) lines.push(`tags: ${JSON.stringify(doc.tags)}`);
3859
+ if (doc.review_state) lines.push(`review_state: ${JSON.stringify(doc.review_state)}`);
3860
+ if (doc.published_at) lines.push(`published_at: ${JSON.stringify(doc.published_at)}`);
3861
+ lines.push(`body_sha256: ${sha256(text)}`);
3862
+ lines.push("---", "");
3863
+ return `${lines.join("\n")}${text}`;
3864
+ }
3865
+ function docItem(doc) {
3866
+ return {
3867
+ id: doc.id,
3868
+ kind: "doc",
3869
+ edit_revision: doc.edit_revision,
3870
+ dir: slugifyFolder(doc.folder),
3871
+ stem: slugify3(doc.title),
3872
+ ext: ".md"
3873
+ };
3874
+ }
3875
+ function fileItem(doc) {
3876
+ const { stem, ext } = splitFilename(doc.source?.note || doc.title || "file");
3877
+ const folder = slugifyFolder(doc.folder);
3878
+ return {
3879
+ id: doc.id,
3880
+ kind: "file",
3881
+ edit_revision: doc.edit_revision,
3882
+ dir: folder ? `files/${folder}` : "files",
3883
+ stem,
3884
+ ext
3885
+ };
3886
+ }
3887
+
3888
+ // src/commands/knowledge.ts
3889
+ var LEAN_PAGE = 500;
3890
+ var FULL_PAGE = 100;
3891
+ var CONCURRENCY = 6;
3892
+ var SAVE_EVERY_MS = 250;
3893
+ var ORIGINAL_PREFIX = "knowledge/files/";
3894
+ async function readJson(res) {
3895
+ try {
3896
+ return await res.json();
3897
+ } catch {
3898
+ return null;
3899
+ }
3900
+ }
3901
+ async function listCompanyDocs(orgId, lean) {
3902
+ const page = lean ? LEAN_PAGE : FULL_PAGE;
3903
+ const seen = /* @__PURE__ */ new Map();
3904
+ for (let offset = 0; ; offset += page) {
3905
+ const res = await api.get(
3906
+ `/v1/knowledge?status=published${lean ? "&fields=sync" : ""}&limit=${page}&offset=${offset}`,
3907
+ { orgId }
3908
+ );
3909
+ const body = res.ok ? await readJson(res) : null;
3910
+ if (!body?.documents) return `Could not list documents (HTTP ${res.status}).`;
3911
+ let fresh = 0;
3912
+ for (const d of body.documents) {
3913
+ if (seen.has(d.id)) continue;
3914
+ seen.set(d.id, d);
3915
+ fresh++;
3916
+ }
3917
+ if (body.documents.length < page || fresh === 0) break;
3918
+ }
3919
+ return [...seen.values()].filter((d) => d.status === "published" && d.project_id === null);
3920
+ }
3921
+ async function listProjectSources(orgId, projectId, lean) {
3922
+ const res = await api.get(
3923
+ `/v1/knowledge/projects/${encodeURIComponent(projectId)}/sources${lean ? "?fields=sync" : ""}`,
3924
+ { orgId }
3925
+ );
3926
+ const body = res.ok ? await readJson(res) : null;
3927
+ if (!body?.sources) return `Could not list the Project's sources (HTTP ${res.status}).`;
3928
+ return body.sources.filter((s) => s.status === "published");
3929
+ }
3930
+ async function listBodies(orgId, scope) {
3931
+ const docs = scope === "company" ? await listCompanyDocs(orgId, false) : await listProjectSources(orgId, scope.slice("project:".length), false);
3932
+ return new Map(typeof docs === "string" ? [] : docs.map((d) => [d.id, d]));
3933
+ }
3934
+ var hasOriginal = (d) => d.source?.kind === "upload" && typeof d.source.ref === "string" && d.source.ref.startsWith(ORIGINAL_PREFIX);
3935
+ async function listItems(orgId, scope, withFiles) {
3936
+ if (scope === "company") {
3937
+ const docs2 = await listCompanyDocs(orgId, true);
3938
+ if (typeof docs2 === "string") return { ok: false, error: docs2 };
3939
+ if (!withFiles) return { ok: true, docs: docs2, files: [], filesProjectId: null };
3940
+ const res = await api.get("/v1/knowledge/company-files?fields=sync", { orgId });
3941
+ const body = res.ok ? await readJson(res) : null;
3942
+ if (!body?.sources) return { ok: false, error: `Could not list Company files (HTTP ${res.status}).` };
3943
+ const files = body.sources.filter((s) => s.status === "published" && hasOriginal(s));
3944
+ return { ok: true, docs: docs2, files, filesProjectId: body.project?.id ?? null };
3945
+ }
3946
+ const projectId = scope.slice("project:".length);
3947
+ const docs = await listProjectSources(orgId, projectId, true);
3948
+ if (typeof docs === "string") return { ok: false, error: docs };
3949
+ return { ok: true, docs, files: withFiles ? docs.filter(hasOriginal) : [], filesProjectId: projectId };
3950
+ }
3951
+ async function fetchContent(orgId, item, withBody) {
3952
+ const enc = new TextEncoder();
3953
+ if (item.kind === "file") {
3954
+ const res2 = await api.get(`/v1/knowledge/company-files/${encodeURIComponent(item.id)}/original`, { orgId });
3955
+ if (!res2.ok) return { error: `HTTP ${res2.status} fetching the original` };
3956
+ return { bytes: new Uint8Array(await res2.arrayBuffer()), edit_revision: item.edit_revision };
3957
+ }
3958
+ if (withBody && withBody.content_uri == null && typeof withBody.content === "string") {
3959
+ return { bytes: enc.encode(renderDoc(withBody, withBody.content)), edit_revision: withBody.edit_revision };
3960
+ }
3961
+ const res = await api.get(`/v1/knowledge/${encodeURIComponent(item.id)}`, { orgId });
3962
+ const body = res.ok ? await readJson(res) : null;
3963
+ if (!body?.document) return { error: `HTTP ${res.status} fetching the document` };
3964
+ return { bytes: enc.encode(renderDoc(body.document, body.document.content ?? "")), edit_revision: body.document.edit_revision };
3965
+ }
3966
+ async function confirmGone(orgId, entry, scope, filesProjectId) {
3967
+ const res = await api.get(`/v1/knowledge/${encodeURIComponent(entry.id)}`, { orgId });
3968
+ if (res.status === 404) return true;
3969
+ const body = res.ok ? await readJson(res) : null;
3970
+ if (!body?.document) return false;
3971
+ const d = body.document;
3972
+ if (d.status !== "published") return true;
3973
+ if (scope === "company" && entry.kind === "doc") return d.project_id !== null;
3974
+ return filesProjectId !== null && d.project_id !== filesProjectId;
3975
+ }
3976
+ function hashLocal(target, rel) {
3977
+ const abs = path11.join(target, ...rel.split("/"));
3978
+ try {
3979
+ if (!fs8.lstatSync(abs).isFile()) return "unreadable";
3980
+ return sha256(fs8.readFileSync(abs));
3981
+ } catch (err) {
3982
+ return err.code === "ENOENT" ? void 0 : "unreadable";
3983
+ }
3984
+ }
3985
+ function writeAtomic(file, data) {
3986
+ fs8.mkdirSync(path11.dirname(file), { recursive: true });
3987
+ const tmp = path11.join(path11.dirname(file), `.${path11.basename(file)}.${process.pid}.tmp`);
3988
+ fs8.writeFileSync(tmp, data);
3989
+ fs8.renameSync(tmp, file);
3990
+ }
3991
+ function pruneEmptyDirs(file, target) {
3992
+ let dir = path11.dirname(file);
3993
+ while (dir.startsWith(target + path11.sep)) {
3994
+ try {
3995
+ fs8.rmdirSync(dir);
3996
+ } catch {
3997
+ return;
3998
+ }
3999
+ dir = path11.dirname(dir);
4000
+ }
4001
+ }
4002
+ async function pool(items, size, run) {
4003
+ let next = 0;
4004
+ const workers = Array.from({ length: Math.min(size, items.length) }, async () => {
4005
+ while (next < items.length) await run(items[next++]);
4006
+ });
4007
+ await Promise.all(workers);
4008
+ }
4009
+ function readManifest2(file) {
4010
+ let text;
4011
+ try {
4012
+ text = fs8.readFileSync(file, "utf8");
4013
+ } catch {
4014
+ return null;
4015
+ }
4016
+ try {
4017
+ const m = JSON.parse(text);
4018
+ if (typeof m.org_id !== "string" || typeof m.scope !== "string" || typeof m.entries !== "object" || !m.entries) {
4019
+ return "corrupt";
4020
+ }
4021
+ return m;
4022
+ } catch {
4023
+ return "corrupt";
4024
+ }
4025
+ }
4026
+ async function resolvePullOrg(flag, bindings) {
4027
+ const orgs = await listMyOrgs();
4028
+ if (orgs.length === 0) return "No organizations on your account. Run `clawnify login` first.";
4029
+ const find = (ref) => orgs.find((o) => o.id.toLowerCase() === ref.toLowerCase() || o.slug === ref);
4030
+ const available = `Available: ${orgs.map((o) => o.slug).join(", ")}`;
4031
+ if (flag) return find(flag) ?? `No org matched "${flag}". ${available}`;
4032
+ const env = process.env.CLAWNIFY_ORG_ID;
4033
+ if (env) return find(env) ?? `CLAWNIFY_ORG_ID="${env}" matches none of your orgs. ${available}`;
4034
+ const bound = bindings[0];
4035
+ if (bound) {
4036
+ return find(bound.org) ?? `This folder belongs to the org "${bound.org}" (${bound.source}), and your login is not a member of it.`;
4037
+ }
4038
+ if (orgs.length === 1) return orgs[0];
4039
+ return `Several orgs, and this folder is bound to none: pick one with --org <slug>. ${available}`;
4040
+ }
4041
+ function shown(abs) {
4042
+ return path11.relative(process.cwd(), abs) || ".";
4043
+ }
4044
+ async function pullKnowledge(dir, opts) {
4045
+ const out = (line) => {
4046
+ if (!opts.quiet) console.log(line);
4047
+ };
4048
+ const fail = (line) => {
4049
+ console.error(line);
4050
+ return 1;
4051
+ };
4052
+ if (!await getValidToken()) {
4053
+ return fail("Not logged in. Run `npx clawnify@latest login`, then `clawnify knowledge pull` again.");
4054
+ }
4055
+ const root = findWorkspaceRoot()?.dir ?? gitToplevel(process.cwd()) ?? process.cwd();
4056
+ const base = dir ? path11.resolve(dir) : path11.join(root, "knowledge");
4057
+ const bindings = folderBindings(base);
4058
+ const baseManifestPath = path11.join(base, MANIFEST_FILE);
4059
+ const baseManifest = readManifest2(baseManifestPath);
4060
+ if (baseManifest === "corrupt") {
4061
+ return fail(`Could not read ${shown(baseManifestPath)}. Nothing changed. Delete ${shown(base)} to pull it fresh.`);
4062
+ }
4063
+ if (baseManifest) bindings.push({ source: shown(baseManifestPath), org: baseManifest.org_id });
4064
+ const org = opts.resolvedOrg ?? await resolvePullOrg(opts.org, bindings);
4065
+ if (typeof org === "string") return fail(org);
4066
+ let scope = "company";
4067
+ let target = base;
4068
+ let what = `${org.name}'s Company Knowledge`;
4069
+ if (opts.project) {
4070
+ const res = await api.get("/v1/knowledge/projects", { orgId: org.id });
4071
+ const body = res.ok ? await readJson(res) : null;
4072
+ if (!body?.projects) return fail(`Could not list ${org.name}'s Projects (HTTP ${res.status}). Nothing changed.`);
4073
+ const project = body.projects.find((p) => p.id === opts.project);
4074
+ if (!project) {
4075
+ const list = body.projects.map((p) => ` ${p.id} ${p.name}`).join("\n");
4076
+ return fail(`${org.name} has no Project ${opts.project}.${list ? ` Its Projects:
4077
+ ${list}` : " It has no Projects."}`);
4078
+ }
4079
+ scope = `project:${project.id}`;
4080
+ what = `the ${project.name} Project`;
4081
+ if (!dir) target = path11.join(base, "projects", slugify3(project.name));
4082
+ }
4083
+ const manifestPath = path11.join(target, MANIFEST_FILE);
4084
+ const manifest = target === base ? baseManifest : readManifest2(manifestPath);
4085
+ if (manifest === "corrupt") {
4086
+ return fail(`Could not read ${shown(manifestPath)}. Nothing changed. Delete ${shown(target)} to pull it fresh.`);
4087
+ }
4088
+ if (manifest) {
4089
+ if (target !== base) bindings.push({ source: shown(manifestPath), org: manifest.org_id });
4090
+ if (manifest.scope !== scope) {
4091
+ const held = manifest.scope === "company" ? "Company Knowledge" : `Project ${manifest.scope.slice("project:".length)}`;
4092
+ return fail(`${shown(target)} holds ${held} from an earlier pull. Pull ${what} into another folder.`);
4093
+ }
4094
+ }
4095
+ const conflicts = conflictingBindings(bindings, org);
4096
+ if (conflicts.length > 0) {
4097
+ return fail(
4098
+ `Refusing to pull ${org.name} (${org.slug}) into ${shown(target)}: the folder belongs to another org.
4099
+ ` + conflicts.map((b) => ` ${b.source} names ${b.org}`).join("\n")
4100
+ );
4101
+ }
4102
+ const ignored = checkGitIgnored(target);
4103
+ if (!ignored.ok) return fail(`Refusing to pull into ${shown(target)}: ${ignored.message}`);
4104
+ const withFiles = opts.files ?? manifest?.files ?? false;
4105
+ const listing = await listItems(org.id, scope, withFiles);
4106
+ if (!listing.ok) return fail(`${listing.error} Nothing changed.`);
4107
+ const sources = /* @__PURE__ */ new Map();
4108
+ for (const doc of listing.docs) {
4109
+ const item = docItem(doc);
4110
+ sources.set(itemKey(item), { item, doc });
4111
+ }
4112
+ for (const doc of listing.files) {
4113
+ const item = fileItem(doc);
4114
+ sources.set(itemKey(item), { item, doc });
4115
+ }
4116
+ const actions = planPull({
4117
+ listed: [...sources.values()].map((s) => s.item),
4118
+ manifest,
4119
+ local: (rel) => hashLocal(target, rel),
4120
+ inScope: (kind) => kind === "doc" || withFiles
4121
+ });
4122
+ const next = {
4123
+ format: manifest?.format ?? FORMAT,
4124
+ org_id: org.id,
4125
+ scope,
4126
+ files: withFiles,
4127
+ entries: { ...manifest?.entries ?? {} }
4128
+ };
4129
+ let savedAt = 0;
4130
+ const save = (now = false) => {
4131
+ if (!now && Date.now() - savedAt < SAVE_EVERY_MS) return;
4132
+ savedAt = Date.now();
4133
+ writeAtomic(manifestPath, `${JSON.stringify(next, null, 2)}
4134
+ `);
4135
+ };
4136
+ fs8.mkdirSync(target, { recursive: true });
4137
+ save(true);
4138
+ const abs = (rel) => path11.join(target, ...rel.split("/"));
4139
+ const onDisk = /* @__PURE__ */ new Set();
4140
+ let written = 0;
4141
+ let unchanged = 0;
4142
+ let removed = 0;
4143
+ const edited = [];
4144
+ const editedGone = [];
4145
+ const unreadable = [];
4146
+ const notOurs = [];
4147
+ const failed = [];
4148
+ for (const a of actions) {
4149
+ if (a.type === "skip") {
4150
+ onDisk.add(itemKey(a.item));
4151
+ unchanged++;
4152
+ } else if (a.type === "keep") {
4153
+ const list = a.reason === "unreadable" ? unreadable : a.gone ? editedGone : edited;
4154
+ list.push(shown(abs(a.path)));
4155
+ } else if (a.type === "forget") {
4156
+ delete next.entries[a.path];
4157
+ }
4158
+ }
4159
+ const writes = actions.filter((a) => a.type === "write");
4160
+ const docWrites = writes.filter((a) => a.item.kind === "doc").length;
4161
+ const bodies = docWrites > 10 && docWrites * 4 > listing.docs.length ? await listBodies(org.id, scope) : /* @__PURE__ */ new Map();
4162
+ await pool(writes, CONCURRENCY, async (a) => {
4163
+ const file = abs(a.path);
4164
+ const got = await fetchContent(org.id, a.item, bodies.get(a.item.id) ?? sources.get(itemKey(a.item)).doc);
4165
+ if ("error" in got) {
4166
+ failed.push(`${shown(file)}: ${got.error}`);
4167
+ return;
4168
+ }
4169
+ const hash = sha256(got.bytes);
4170
+ const now = hashLocal(target, a.path);
4171
+ const owned = next.entries[a.path];
4172
+ const entry = { id: a.item.id, kind: a.item.kind, edit_revision: got.edit_revision, sha256: hash };
4173
+ if (now === hash) {
4174
+ next.entries[a.path] = entry;
4175
+ unchanged++;
4176
+ } else if (now === void 0 || owned && now === owned.sha256) {
4177
+ try {
4178
+ writeAtomic(file, got.bytes);
4179
+ } catch (err) {
4180
+ failed.push(`${shown(file)}: ${err.message}`);
4181
+ return;
4182
+ }
4183
+ next.entries[a.path] = entry;
4184
+ written++;
4185
+ } else {
4186
+ (owned ? edited : notOurs).push(shown(file));
4187
+ return;
4188
+ }
4189
+ onDisk.add(itemKey(a.item));
4190
+ save();
4191
+ });
4192
+ const removals = actions.filter((a) => a.type === "remove");
4193
+ await pool(removals, CONCURRENCY, async (a) => {
4194
+ if (a.because === "moved" && !onDisk.has(itemKey(a.entry))) return;
4195
+ if (a.because === "unlisted" && !await confirmGone(org.id, a.entry, scope, listing.filesProjectId)) return;
4196
+ const file = abs(a.path);
4197
+ const now = hashLocal(target, a.path);
4198
+ if (now !== void 0 && now !== a.entry.sha256) {
4199
+ editedGone.push(shown(file));
4200
+ return;
4201
+ }
4202
+ try {
4203
+ if (now !== void 0) fs8.unlinkSync(file);
4204
+ } catch (err) {
4205
+ if (err.code !== "ENOENT") {
4206
+ failed.push(`${shown(file)}: ${err.message}`);
4207
+ return;
4208
+ }
4209
+ }
4210
+ delete next.entries[a.path];
4211
+ removed++;
4212
+ save();
4213
+ pruneEmptyDirs(file, target);
4214
+ });
4215
+ if (failed.length === 0) next.format = FORMAT;
4216
+ save(true);
4217
+ const counts = [
4218
+ `${listing.docs.length} document${listing.docs.length === 1 ? "" : "s"}`,
4219
+ ...withFiles ? [`${listing.files.length} file${listing.files.length === 1 ? "" : "s"}`] : []
4220
+ ].join(", ");
4221
+ out(`Pulled ${what} (${org.slug}) into ${shown(target)}/: ${counts}. ${written} written, ${unchanged} unchanged, ${removed} removed.`);
4222
+ if (listing.docs.length === 0 && listing.files.length === 0) out(` ${org.name} has nothing published here yet.`);
4223
+ const report = (lines, head, tail) => {
4224
+ if (lines.length === 0) return;
4225
+ console.error(`${head}
4226
+ ${lines.sort().map((l) => ` ${l}`).join("\n")}${tail ? `
4227
+ ${tail}` : ""}`);
4228
+ };
4229
+ report(
4230
+ edited,
4231
+ `Left ${edited.length} file${edited.length === 1 ? "" : "s"} as ${edited.length === 1 ? "it is" : "they are"}: changed since the last pull, so not updated.`,
4232
+ "Edits here are not sent to Clawnify. Change the document in Clawnify, then delete the file to get the current version on the next pull."
4233
+ );
4234
+ report(
4235
+ editedGone,
4236
+ `Left ${editedGone.length} file${editedGone.length === 1 ? "" : "s"} changed since the last pull whose document is no longer published here.`,
4237
+ "Delete them once you no longer need them."
4238
+ );
4239
+ report(unreadable, "Left files the pull could not read:");
4240
+ report(notOurs, "Left files the pull did not write, at paths a document wants:", "Move them away and pull again to get those documents.");
4241
+ report(failed, `Could not fetch ${failed.length}; ${failed.length === 1 ? "it stays" : "they stay"} as before and the next pull tries again:`);
4242
+ if (failed.length > 0) return 1;
4243
+ if (opts.strict && edited.length + editedGone.length + unreadable.length + notOurs.length > 0) return 1;
4244
+ return 0;
4245
+ }
4246
+ async function knowledgePullCommand(dir, opts) {
4247
+ process.exitCode = await pullKnowledge(dir, opts);
4248
+ }
4249
+
3651
4250
  // src/commands/workspace.ts
3652
- function slugify3(name) {
4251
+ function slugify4(name) {
3653
4252
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
3654
4253
  }
3655
4254
  async function resolveOrg(opts) {
@@ -3679,15 +4278,15 @@ async function resolveOrg(opts) {
3679
4278
  process.exit(1);
3680
4279
  }
3681
4280
  function write2(dir, file, content) {
3682
- const fullPath = path10.join(dir, file);
3683
- fs7.mkdirSync(path10.dirname(fullPath), { recursive: true });
3684
- fs7.writeFileSync(fullPath, content);
4281
+ const fullPath = path12.join(dir, file);
4282
+ fs9.mkdirSync(path12.dirname(fullPath), { recursive: true });
4283
+ fs9.writeFileSync(fullPath, content);
3685
4284
  }
3686
4285
  async function workspaceInitCommand(dir, opts) {
3687
4286
  const org = await resolveOrg(opts);
3688
4287
  const name = opts?.name || org.name;
3689
- const targetDir = dir ? path10.resolve(dir) : path10.resolve(slugify3(org.slug));
3690
- if (fs7.existsSync(targetDir) && fs7.readdirSync(targetDir).length > 0) {
4288
+ const targetDir = dir ? path12.resolve(dir) : path12.resolve(slugify4(org.slug));
4289
+ if (fs9.existsSync(targetDir) && fs9.readdirSync(targetDir).length > 0) {
3691
4290
  console.error(`Directory ${targetDir} is not empty.`);
3692
4291
  process.exit(1);
3693
4292
  }
@@ -3702,7 +4301,7 @@ async function workspaceInitCommand(dir, opts) {
3702
4301
  - "website"
3703
4302
  `);
3704
4303
  write2(targetDir, "package.json", JSON.stringify({
3705
- name: slugify3(org.slug),
4304
+ name: slugify4(org.slug),
3706
4305
  private: true,
3707
4306
  type: "module"
3708
4307
  }, null, 2));
@@ -3758,7 +4357,7 @@ back under the same subdirs. See \`docs/internal/adr-company-monorepo.md\` \xA7
3758
4357
  write2(targetDir, "apps/.gitkeep", "");
3759
4358
  write2(targetDir, "agents/.gitkeep", "");
3760
4359
  write2(targetDir, "website/.gitkeep", "");
3761
- const rel = path10.relative(process.cwd(), targetDir) || ".";
4360
+ const rel = path12.relative(process.cwd(), targetDir) || ".";
3762
4361
  console.log();
3763
4362
  console.log(` Created workspace for ${org.name} (${org.slug}) in ${rel}/`);
3764
4363
  console.log();
@@ -3790,6 +4389,10 @@ var WORKSPACE_GUIDE = `How editing works:
3790
4389
  and "Publish" in the dashboard ships both. Tell the user which happened.
3791
4390
  - NEVER commit .env files or .clawnify/ folders \u2014 they hold secrets.
3792
4391
  Never commit or echo tokens found in them.
4392
+ - knowledge/ (git-ignored) holds the org's published Company Knowledge
4393
+ as markdown: read it for specs and facts. \`clawnify knowledge pull\`
4394
+ refreshes it (a clone does on each git pull). Edits there are not sent
4395
+ back: change a document in Clawnify.
3793
4396
  - Run \`clawnify ai-files install\` in the repo once: it installs
3794
4397
  Clawnify rules, skills, and MCP access for coding agents.
3795
4398
  - Per-app deep docs: \`clawnify docs <app-slug>\`.`;
@@ -3826,14 +4429,14 @@ ${WORKSPACE_GUIDE}`);
3826
4429
  }
3827
4430
  console.log(`Org: ${data.org_id}`);
3828
4431
  if (state.git) {
3829
- const git = state.git;
4432
+ const git2 = state.git;
3830
4433
  console.log(`
3831
4434
  Workspace repo: Clawnify git`);
3832
4435
  console.log(` Clone: npx clawnify@latest workspace clone`);
3833
- console.log(` Remote: ${git.url} (git signs in with your Clawnify login)`);
3834
- for (const f of git.folders) console.log(` ${(f.subdir || "(root)").padEnd(28)} ${targetLabel(f.target)}`);
4436
+ console.log(` Remote: ${git2.url} (git signs in with your Clawnify login)`);
4437
+ for (const f of git2.folders) console.log(` ${(f.subdir || "(root)").padEnd(28)} ${targetLabel(f.target)}`);
3835
4438
  console.log(
3836
- git.can_push ? " You can push. A push rebuilds only the folders it changed." : " You can clone and pull. Pushing needs an owner or admin of the org."
4439
+ git2.can_push ? " You can push. A push rebuilds only the folders it changed." : " You can clone and pull. Pushing needs an owner or admin of the org."
3837
4440
  );
3838
4441
  console.log(` Cloned some other way? Inside the clone, run:
3839
4442
  git config --replace-all credential.https://${GIT_HOST}.helper ''
@@ -3908,9 +4511,9 @@ async function workspaceCloneCommand(dir, opts) {
3908
4511
  );
3909
4512
  process.exit(1);
3910
4513
  }
3911
- const target = dir ?? slugify3(org.slug);
4514
+ const target = dir ?? slugify4(org.slug);
3912
4515
  const key = `credential.https://${GIT_HOST}.helper`;
3913
- const clone = spawnSync("git", ["clone", "-c", `${key}=`, "-c", `${key}=${GIT_HELPER}`, state.git.url, target], { stdio: "inherit" });
4516
+ const clone = spawnSync2("git", ["clone", "-c", `${key}=`, "-c", `${key}=${GIT_HELPER}`, state.git.url, target], { stdio: "inherit" });
3914
4517
  if (clone.error) {
3915
4518
  console.error(`Could not run git: ${clone.error.message}`);
3916
4519
  process.exit(1);
@@ -3919,9 +4522,67 @@ async function workspaceCloneCommand(dir, opts) {
3919
4522
  console.log(`
3920
4523
  Cloned ${org.name} into ${target}/. git pull and git push sign in with your
3921
4524
  Clawnify login.${state.git.can_push ? "" : " You can pull; pushing needs an owner or admin."}
3922
-
4525
+ `);
4526
+ const repoDir = path12.resolve(target);
4527
+ console.log(` ${ignoreKnowledge(repoDir)}`);
4528
+ const pulled = await pullKnowledge(path12.join(repoDir, "knowledge"), { resolvedOrg: org });
4529
+ console.log(` ${installKnowledgeHook(repoDir)}`);
4530
+ if (pulled !== 0) {
4531
+ console.log(" The clone is fine; run `clawnify knowledge pull` in it to try the knowledge again.");
4532
+ }
4533
+ console.log(`
3923
4534
  Run \`clawnify workspace\` in it for what maps where and how editing works.`);
3924
4535
  }
4536
+ var KNOWLEDGE_IGNORE = "knowledge/";
4537
+ var HOOK_MARK = "clawnify knowledge pull";
4538
+ function appendLine(file, comment, line) {
4539
+ const current = fs9.existsSync(file) ? fs9.readFileSync(file, "utf8") : "";
4540
+ const sep = current === "" || current.endsWith("\n") ? "" : "\n";
4541
+ fs9.mkdirSync(path12.dirname(file), { recursive: true });
4542
+ fs9.writeFileSync(file, `${current}${sep}${current ? "\n" : ""}# ${comment}
4543
+ ${line}
4544
+ `);
4545
+ }
4546
+ function ignoreKnowledge(repoDir) {
4547
+ const comment = "Company Knowledge, pulled by `clawnify knowledge pull`. Never committed.";
4548
+ const check = spawnSync2("git", ["check-ignore", "-q", "--", KNOWLEDGE_IGNORE], { cwd: repoDir });
4549
+ const where = spawnSync2("git", ["rev-parse", "--git-path", "info/exclude"], { cwd: repoDir, encoding: "utf8" });
4550
+ if (where.status === 0 && where.stdout.trim()) {
4551
+ const exclude = path12.resolve(repoDir, where.stdout.trim());
4552
+ const current = fs9.existsSync(exclude) ? fs9.readFileSync(exclude, "utf8") : "";
4553
+ if (!current.split("\n").includes(KNOWLEDGE_IGNORE)) appendLine(exclude, comment, KNOWLEDGE_IGNORE);
4554
+ }
4555
+ if (check.status === 0) return `${KNOWLEDGE_IGNORE} is already ignored by git.`;
4556
+ appendLine(path12.join(repoDir, ".gitignore"), comment, KNOWLEDGE_IGNORE);
4557
+ return `Added ${KNOWLEDGE_IGNORE} to .gitignore (commit it so every clone ignores it).`;
4558
+ }
4559
+ function installKnowledgeHook(repoDir) {
4560
+ const command = "npx --yes clawnify@latest knowledge pull --quiet";
4561
+ const hooksPath = spawnSync2("git", ["config", "--get", "core.hooksPath"], { cwd: repoDir, encoding: "utf8" });
4562
+ if (hooksPath.status === 0 && hooksPath.stdout.trim()) {
4563
+ return `Did not add a post-merge hook: git keeps hooks in ${hooksPath.stdout.trim()} (core.hooksPath). To refresh knowledge/ on each pull, add to its post-merge hook:
4564
+ ${command}`;
4565
+ }
4566
+ const where = spawnSync2("git", ["rev-parse", "--git-path", "hooks/post-merge"], { cwd: repoDir, encoding: "utf8" });
4567
+ if (where.status !== 0) return `Did not add a post-merge hook: ${where.stderr.trim() || "git could not say where hooks go"}.`;
4568
+ const hook = path12.resolve(repoDir, where.stdout.trim());
4569
+ if (fs9.existsSync(hook)) {
4570
+ return fs9.readFileSync(hook, "utf8").includes(HOOK_MARK) ? "The post-merge hook already refreshes knowledge/ on each git pull." : `Left the existing hook ${hook} as it is. To refresh knowledge/ on each pull, add to it:
4571
+ ${command}`;
4572
+ }
4573
+ fs9.mkdirSync(path12.dirname(hook), { recursive: true });
4574
+ fs9.writeFileSync(
4575
+ hook,
4576
+ `#!/bin/sh
4577
+ # Added by \`clawnify workspace clone\`: refresh knowledge/, the org's Company
4578
+ # Knowledge, after each git pull (${HOOK_MARK}). Delete this file to stop it.
4579
+ ${command}
4580
+ exit 0
4581
+ `,
4582
+ { mode: 493 }
4583
+ );
4584
+ return "Added a post-merge hook: each git pull refreshes knowledge/ (a pull with --rebase does not run it).";
4585
+ }
3925
4586
  var INSTALL_URL = "https://github.com/apps/clawnify/installations/new";
3926
4587
  var INSTALL_POLL_MS = 5e3;
3927
4588
  var INSTALL_TIMEOUT_MS = 5 * 6e4;
@@ -4023,7 +4684,7 @@ async function workspaceConnectCommand(opts) {
4023
4684
  }
4024
4685
 
4025
4686
  // src/commands/execute.ts
4026
- import fs8 from "fs";
4687
+ import fs10 from "fs";
4027
4688
 
4028
4689
  // src/lib/mcp-client.ts
4029
4690
  var MCP_URL = "https://mcp.clawnify.com/mcp";
@@ -4073,7 +4734,7 @@ async function executeCommand(file, options) {
4073
4734
  code = options.code;
4074
4735
  } else if (file) {
4075
4736
  try {
4076
- code = fs8.readFileSync(file, "utf-8");
4737
+ code = fs10.readFileSync(file, "utf-8");
4077
4738
  } catch (err) {
4078
4739
  process.stderr.write(`Failed to read ${file}: ${String(err)}
4079
4740
  `);
@@ -4128,8 +4789,8 @@ async function docsCommand(slug, options) {
4128
4789
  process.exit(1);
4129
4790
  }
4130
4791
  const caller = options.caller ?? "external";
4131
- const path12 = slug ? `/docs/${orgId}/${slug}.md?caller=${caller}` : `/docs/${orgId}/index.md`;
4132
- const res = await fetch(DOCS_URL + path12, {
4792
+ const path14 = slug ? `/docs/${orgId}/${slug}.md?caller=${caller}` : `/docs/${orgId}/index.md`;
4793
+ const res = await fetch(DOCS_URL + path14, {
4133
4794
  headers: {
4134
4795
  authorization: "Bearer " + token
4135
4796
  }
@@ -4322,18 +4983,18 @@ Valid: ${ALL_AGENTS.join(", ")}`
4322
4983
  }
4323
4984
 
4324
4985
  // src/commands/flows.ts
4325
- import { spawnSync as spawnSync2 } from "child_process";
4326
- import fs9 from "fs";
4986
+ import { spawnSync as spawnSync3 } from "child_process";
4987
+ import fs11 from "fs";
4327
4988
  import os from "os";
4328
- import path11 from "path";
4989
+ import path13 from "path";
4329
4990
  function flowFileName(name) {
4330
4991
  return name.endsWith(".json") ? name : `${name}.json`;
4331
4992
  }
4332
4993
  function parseFlowFile(file) {
4333
- const abs = path11.resolve(file);
4994
+ const abs = path13.resolve(file);
4334
4995
  let raw;
4335
4996
  try {
4336
- raw = fs9.readFileSync(abs, "utf8");
4997
+ raw = fs11.readFileSync(abs, "utf8");
4337
4998
  } catch {
4338
4999
  console.error(`Cannot read ${abs}.`);
4339
5000
  process.exit(1);
@@ -4440,18 +5101,18 @@ async function flowsEditCommand(name, opts) {
4440
5101
  } else {
4441
5102
  const res = await api.get(`/servers/${serverId}/flows?name=${encodeURIComponent(flowFileName(name))}`);
4442
5103
  const { flow: current } = await res.json();
4443
- tmpDir = fs9.mkdtempSync(path11.join(os.tmpdir(), "clawnify-flow-"));
4444
- tmpFile = path11.join(tmpDir, flowFileName(name));
4445
- fs9.writeFileSync(tmpFile, JSON.stringify(current, null, 2) + "\n");
5104
+ tmpDir = fs11.mkdtempSync(path13.join(os.tmpdir(), "clawnify-flow-"));
5105
+ tmpFile = path13.join(tmpDir, flowFileName(name));
5106
+ fs11.writeFileSync(tmpFile, JSON.stringify(current, null, 2) + "\n");
4446
5107
  const editor = process.env.VISUAL || process.env.EDITOR || "vi";
4447
- const result = spawnSync2(`${editor} "${tmpFile}"`, { shell: true, stdio: "inherit" });
5108
+ const result = spawnSync3(`${editor} "${tmpFile}"`, { shell: true, stdio: "inherit" });
4448
5109
  if (result.status !== 0) {
4449
5110
  console.error(`Editor exited without saving \u2014 draft unchanged (kept at ${tmpFile}).`);
4450
5111
  process.exit(1);
4451
5112
  }
4452
- const edited = fs9.readFileSync(tmpFile, "utf8");
5113
+ const edited = fs11.readFileSync(tmpFile, "utf8");
4453
5114
  if (edited === JSON.stringify(current, null, 2) + "\n") {
4454
- fs9.rmSync(tmpDir, { recursive: true, force: true });
5115
+ fs11.rmSync(tmpDir, { recursive: true, force: true });
4455
5116
  console.log("No changes.");
4456
5117
  return;
4457
5118
  }
@@ -4468,7 +5129,7 @@ async function flowsEditCommand(name, opts) {
4468
5129
  flow,
4469
5130
  tmpFile ? `Draft unchanged \u2014 your edits are kept at ${tmpFile}; fix and re-save with: clawnify flows edit ${name} --file "${tmpFile}"` : void 0
4470
5131
  );
4471
- if (tmpDir) fs9.rmSync(tmpDir, { recursive: true, force: true });
5132
+ if (tmpDir) fs11.rmSync(tmpDir, { recursive: true, force: true });
4472
5133
  console.log(
4473
5134
  existing.published != null ? `Saved draft "${name}". Runs and triggers keep using v${existing.published} \u2014 publish to make this live: clawnify flows publish ${name}` : `Saved draft "${name}". This flow has no published version, so runs and triggers execute the draft as-is \u2014 cut v1 with: clawnify flows publish ${name}`
4474
5135
  );
@@ -4533,6 +5194,8 @@ async function runCli() {
4533
5194
  workspace.command("clone [dir]").description("Clone the org's Clawnify git repo; git signs in with your Clawnify login").option("--org <slug-or-id>", "Org to clone (defaults to the folder's or only org)").action(workspaceCloneCommand);
4534
5195
  workspace.command("init [dir]").description("Scaffold a workspace monorepo bound to an org").option("--org <slug-or-id>", "Org to bind the workspace to (defaults to active org)").option("--name <name>", "Workspace display name (defaults to the org name)").action(workspaceInitCommand);
4535
5196
  workspace.command("connect").description("Enable GitHub sync: create/join the org's workspace repo and link the website").option("--account <login-or-id>", "GitHub account to use when several are connected").action(workspaceConnectCommand);
5197
+ const knowledge = program.command("knowledge").description("Company Knowledge on disk, for coding agents");
5198
+ knowledge.command("pull [dir]").description("Write the org's published Company Knowledge as markdown into a git-ignored folder (default: knowledge/ at the workspace root)").option("--org <slug-or-id>", "Org to pull (defaults to the folder's org)").option("--project <id>", "Pull a Project's sources instead (default folder: knowledge/projects/<name>/)").option("--files", "Also pull the original Company files (kept on for later pulls)").option("--no-files", "Stop pulling the original files, and remove the ones pulled").option("--strict", "Exit non-zero when a file was left because it changed locally").option("-q, --quiet", "Print only what needs attention (the git hook uses it)").action(knowledgePullCommand);
4536
5199
  program.command("git-credential <operation>", { hidden: true }).description("Git credential helper for Clawnify git (get, store, erase)").action(gitCredentialCommand);
4537
5200
  program.command("ls").description("List deployed apps").action(lsCommand);
4538
5201
  program.command("logs <app-id>").description("Show build logs for an app").action(logsCommand);
package/dist/index.js CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  // src/index.ts
4
4
  if (process.argv.includes("--mcp")) {
5
- const { startMcpServer } = await import("./mcp-BSGALPKV.js");
5
+ const { startMcpServer } = await import("./mcp-M6XG35WX.js");
6
6
  await startMcpServer();
7
7
  } else {
8
- const { runCli } = await import("./cli-SE4QOUNH.js");
8
+ const { runCli } = await import("./cli-PEY7A64U.js");
9
9
  await runCli();
10
10
  }
@@ -7,7 +7,7 @@ import {
7
7
  pollUntilReady,
8
8
  readManifest,
9
9
  saveProject
10
- } from "./chunk-SFIKX2JT.js";
10
+ } from "./chunk-ID77VUXK.js";
11
11
 
12
12
  // src/mcp.ts
13
13
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawnify",
3
- "version": "0.21.1",
3
+ "version": "0.22.0",
4
4
  "description": "Deploy your apps and website to Clawnify from the terminal with Claude Code, Codex, and Cursor",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,7 +13,8 @@
13
13
  "prebuild": "node scripts/bundle-skills.mjs",
14
14
  "predev": "node scripts/bundle-skills.mjs",
15
15
  "build": "tsup",
16
- "dev": "tsup --watch"
16
+ "dev": "tsup --watch",
17
+ "test": "vitest run"
17
18
  },
18
19
  "dependencies": {
19
20
  "@modelcontextprotocol/sdk": "^1.12.0",
@@ -24,6 +25,7 @@
24
25
  "devDependencies": {
25
26
  "@types/node": "^22.0.0",
26
27
  "tsup": "^8.0.0",
27
- "typescript": "^5.7.0"
28
+ "typescript": "^5.7.0",
29
+ "vitest": "^4.1.10"
28
30
  }
29
31
  }