@netnodeag/kraftwerk 0.100.1 → 0.102.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.
Files changed (55) hide show
  1. package/README.md +73 -0
  2. package/dist/cli/cloud.d.ts +1 -0
  3. package/dist/cli/cloud.js +1 -1
  4. package/dist/cli/join.d.ts +2 -0
  5. package/dist/cli/join.js +52 -0
  6. package/dist/cli/kraftwerk.js +3 -0
  7. package/dist/client/routes.d.ts +2 -0
  8. package/dist/client/routes.js +2 -0
  9. package/dist/config.d.ts +2 -2
  10. package/dist/config.js +3 -3
  11. package/dist/core/boards.d.ts +3 -0
  12. package/dist/core/boards.js +16 -2
  13. package/dist/core/cloud.d.ts +5 -0
  14. package/dist/core/git.d.ts +46 -2
  15. package/dist/core/git.js +251 -8
  16. package/dist/core/notifications.d.ts +3 -2
  17. package/dist/core/settings.d.ts +1 -1
  18. package/dist/core/settings.js +2 -2
  19. package/dist/server/api/cloud.d.ts +4 -0
  20. package/dist/server/api/cloud.js +14 -0
  21. package/dist/server/api/git.d.ts +13 -1
  22. package/dist/server/api/git.js +39 -1
  23. package/dist/server/api/index.d.ts +10 -1
  24. package/dist/server/cloud-events.d.ts +8 -0
  25. package/dist/server/cloud-events.js +199 -0
  26. package/dist/server/cloud.d.ts +12 -0
  27. package/dist/server/cloud.js +53 -0
  28. package/dist/server/join.d.ts +38 -0
  29. package/dist/server/join.js +111 -0
  30. package/dist/server/relay.js +5 -0
  31. package/dist/server/sync-setup.d.ts +31 -0
  32. package/dist/server/sync-setup.js +90 -0
  33. package/dist/server/users.d.ts +11 -0
  34. package/dist/server/users.js +63 -15
  35. package/dist/server/workspace-cloud.d.ts +3 -1
  36. package/dist/server/workspace-cloud.js +18 -8
  37. package/package.json +1 -1
  38. package/web/dist/assets/{dist-Dj1JIIbI.js → dist-B09k-Kwi.js} +1 -1
  39. package/web/dist/assets/{dist-DQsdt9qV.js → dist-BG9MPqC7.js} +1 -1
  40. package/web/dist/assets/{dist-DxHapyfL.js → dist-BbST9sxK.js} +1 -1
  41. package/web/dist/assets/{dist-OUSFQqAo.js → dist-BrXAphjl.js} +1 -1
  42. package/web/dist/assets/{dist-CYnkW4NZ.js → dist-C0Ulmjwh.js} +1 -1
  43. package/web/dist/assets/{dist-DmqwXVk5.js → dist-C8wsDqpL.js} +1 -1
  44. package/web/dist/assets/{dist-Dhqv4G4v.js → dist-CJk4RtqY.js} +1 -1
  45. package/web/dist/assets/{dist-BQht4Kxn.js → dist-CfSpo_bP.js} +1 -1
  46. package/web/dist/assets/dist-DMU8iY9H.js +1 -0
  47. package/web/dist/assets/{dist-C6Hh2gvr.js → dist-Dv55aORJ.js} +1 -1
  48. package/web/dist/assets/{dist-KYJrjjHE.js → dist-QQHKzUGH.js} +1 -1
  49. package/web/dist/assets/{editor-DjVpjnNv.js → editor-Co8xGDnf.js} +3 -3
  50. package/web/dist/assets/index-CepQsH8H.js +488 -0
  51. package/web/dist/assets/index-DJGLnVQY.css +2 -0
  52. package/web/dist/index.html +2 -2
  53. package/web/dist/assets/dist-CxDUjCCR.js +0 -1
  54. package/web/dist/assets/index-BV1cBJKv.js +0 -488
  55. package/web/dist/assets/index-ClVr51ut.css +0 -2
package/dist/core/git.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { spawn } from "node:child_process";
2
- import { realpathSync } from "node:fs";
2
+ import { createWriteStream, existsSync, realpathSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { boardsRootFor, presentationsRootFor, ENTITY_KINDS, entitiesRootFor, projectsRootFor, reposRootFor, resolveWorkspace, vibeablesRootFor, isSafeGitName } from "../config.js";
5
5
  import { ENV_FILE } from "../runner/docker.js";
6
6
  import { getOutputDir, workspaceRoot } from "./context.js";
7
7
  import { perWorkspace, workspaceOpen } from "./workspace.js";
8
8
  import { workspaceEnv } from "./env.js";
9
+ import { readIdentity } from "./identity.js";
9
10
  /**
10
11
  * Workspace git sync. Several people run kraftwerk against one git repo, so
11
12
  * knowledge, agents, skills, channels and workflows travel between them like
@@ -29,7 +30,13 @@ import { workspaceEnv } from "./env.js";
29
30
  * pushes commits that already exist to a branch that already tracks its
30
31
  * upstream. It never creates a commit, never publishes a new branch and
31
32
  * never forces.
32
- * - A diverged branch is reported, never merged or rebased from here.
33
+ * - A diverged branch is reported, never merged or rebased from here —
34
+ * except with `autosync: sync` (kraftwerk sync's default): there the timer
35
+ * also commits what changed under the synced roots, and a diverged branch
36
+ * is merged with the rule "the cloud wins": where both sides changed a
37
+ * file, the remote's version stays and this machine's lands beside it as
38
+ * `name.konflikt-<handle>.ext`, committed too, so nothing is lost and
39
+ * nobody has to resolve anything in a terminal (see syncNow).
33
40
  *
34
41
  * Every git call passes an argument array, so nothing reaches a shell, and
35
42
  * every call is async with a timeout: git runs inside the single-threaded
@@ -135,7 +142,31 @@ export async function sshCommandFor(repoRoot) {
135
142
  }
136
143
  /** A git call that may touch the network: longer timeout, non-interactive ssh. */
137
144
  export async function gitNet(args, repoRoot) {
138
- return git(args, repoRoot, NET_TIMEOUT, { GIT_SSH_COMMAND: await sshCommandFor(repoRoot) });
145
+ return git(args, repoRoot, NET_TIMEOUT, { GIT_SSH_COMMAND: await sshCommandFor(repoRoot), ...remoteAuthEnv() });
146
+ }
147
+ /**
148
+ * HTTP credentials git gets for some remotes, by URL prefix → header. The
149
+ * daemon sets one for kraftwerk sync (`<cloud>/git/` → the machine's key, see
150
+ * server/cloud.ts), so a workspace syncs with its cloud repo without a token
151
+ * in a remote URL or a credential helper. They go in through the
152
+ * environment as URL-scoped `http.<prefix>.extraHeader` — never written to a
153
+ * git config, and git sends them to that prefix only.
154
+ */
155
+ let remoteAuth = () => ({});
156
+ export function setRemoteAuth(fn) {
157
+ remoteAuth = fn;
158
+ }
159
+ export function remoteAuthEnv(base = process.env) {
160
+ const headers = Object.entries(remoteAuth());
161
+ if (headers.length === 0)
162
+ return {};
163
+ const start = Number(base.GIT_CONFIG_COUNT ?? 0) || 0;
164
+ const env = { GIT_CONFIG_COUNT: String(start + headers.length) };
165
+ headers.forEach(([prefix, header], i) => {
166
+ env[`GIT_CONFIG_KEY_${start + i}`] = `http.${prefix}.extraHeader`;
167
+ env[`GIT_CONFIG_VALUE_${start + i}`] = header;
168
+ });
169
+ return env;
139
170
  }
140
171
  /**
141
172
  * Remote/branch names from kraftwerk.yml become git positionals. Config
@@ -350,6 +381,7 @@ const gitState = perWorkspace(() => ({
350
381
  lastPull: undefined,
351
382
  lastPush: undefined,
352
383
  lastError: undefined,
384
+ lastAutoCommit: undefined,
353
385
  timer: null,
354
386
  ticking: false,
355
387
  lastRun: 0,
@@ -381,6 +413,10 @@ function serial(fn) {
381
413
  * of times, and the nav badge polls it from every open tab, so results are
382
414
  * cached for a beat.
383
415
  */
416
+ /** A remote URL fit to show: `https://user:secret@host/x` → `https://host/x`. */
417
+ export function withoutCredentials(url) {
418
+ return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, "$1");
419
+ }
384
420
  export async function gitStatus(fresh = false) {
385
421
  const cached = gitState().statusCache;
386
422
  if (!fresh && cached && Date.now() - cached.at < CACHE_MS)
@@ -393,12 +429,14 @@ export async function gitStatus(fresh = false) {
393
429
  if (!repo)
394
430
  return { enabled: true, error: opened.error, autosync: cfg?.autosync, interval: cfg?.interval };
395
431
  const { repoRoot } = repo;
396
- const [head, upstreamRes, status] = await Promise.all([
432
+ const [head, upstreamRes, status, urlRes] = await Promise.all([
397
433
  checkedOut(repo),
398
434
  git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], repoRoot),
399
435
  git(["status", "--porcelain=v1", "-z", "--untracked-files=all"], repoRoot),
436
+ git(["remote", "get-url", repo.cfg.remote], repoRoot),
400
437
  ]);
401
438
  const upstream = upstreamRes.ok ? upstreamRes.stdout.trim() : undefined;
439
+ const remoteUrl = urlRes.ok && urlRes.stdout.trim() ? withoutCredentials(urlRes.stdout.trim()) : undefined;
402
440
  let ahead;
403
441
  let behind;
404
442
  if (upstream) {
@@ -415,6 +453,7 @@ export async function gitStatus(fresh = false) {
415
453
  branch: head.branch,
416
454
  upstream,
417
455
  remote: cfg?.remote ?? repo.cfg.remote,
456
+ remoteUrl,
418
457
  ahead,
419
458
  behind,
420
459
  diverged: !!ahead && !!behind,
@@ -424,6 +463,7 @@ export async function gitStatus(fresh = false) {
424
463
  lastPull: gitState().lastPull,
425
464
  lastPush: gitState().lastPush,
426
465
  lastError: gitState().lastError,
466
+ ...(gitState().lastAutoCommit ? { lastAutoCommit: gitState().lastAutoCommit } : {}),
427
467
  };
428
468
  // A failed status (a stale index.lock, a timeout on a huge untracked tree)
429
469
  // must not read as "workspace clean": with no file list the commit endpoint
@@ -446,12 +486,14 @@ export async function gitStatus(fresh = false) {
446
486
  const scopeError = scope.wholeRepo
447
487
  ? "A configured root points at the repository root, which would put the whole repo in scope. Narrow workflows/knowledge/agents/skills/vibeables/projects in kraftwerk.yml."
448
488
  : undefined;
489
+ const conflicts = repo.cfg.autosync === "sync" ? await conflictCopies(repoRoot) : [];
449
490
  const value = {
450
491
  ...base,
451
492
  error: head.error ?? scopeError,
452
493
  files: [...syncable, ...blocked.slice(0, MAX_BLOCKED)],
453
494
  blockedHidden: blockedHidden || undefined,
454
495
  scope: scope.include,
496
+ ...(conflicts.length ? { conflicts } : {}),
455
497
  };
456
498
  // A commit that finished while this status was running already emptied
457
499
  // the cache; caching the pre-commit list on top of that would show the
@@ -510,7 +552,29 @@ export function capDiff(diff) {
510
552
  export function gitCommit(paths, message) {
511
553
  return serial(() => commitNow(paths, message));
512
554
  }
513
- async function commitNow(paths, message) {
555
+ /**
556
+ * Who a commit is by. A commit by hand is git's own user (its config); one
557
+ * that kraftwerk makes by itself (`autosync: sync`) is by the account this
558
+ * machine is linked to, when the daemon knows one (setSyncAuthor) — else
559
+ * git's user. With no git user configured at all, the machine's identity
560
+ * stands in, so a commit never fails on "Please tell me who you are".
561
+ */
562
+ let syncAuthor = () => null;
563
+ export function setSyncAuthor(fn) {
564
+ syncAuthor = fn;
565
+ }
566
+ async function authorEnv(repoRoot, who) {
567
+ const pick = who === "sync" ? syncAuthor() : null;
568
+ if (pick)
569
+ return { GIT_AUTHOR_NAME: pick.name, GIT_AUTHOR_EMAIL: pick.email, GIT_COMMITTER_NAME: pick.name, GIT_COMMITTER_EMAIL: pick.email };
570
+ if ((await git(["config", "user.email"], repoRoot)).stdout.trim())
571
+ return {};
572
+ const id = await readIdentity().catch(() => null);
573
+ const name = id?.handle || "kraftwerk";
574
+ const email = `${name}@${(id?.machine || "kraftwerk").replace(/[^A-Za-z0-9.-]+/g, "-")}.kraftwerk`;
575
+ return { GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_NAME: name, GIT_COMMITTER_EMAIL: email };
576
+ }
577
+ async function commitNow(paths, message, author = "git") {
514
578
  const { repo, error } = await openRepo();
515
579
  if (!repo)
516
580
  return { ok: false, error };
@@ -552,7 +616,7 @@ async function commitNow(paths, message) {
552
616
  return { ok: false, error: add.stderr || "git add failed" };
553
617
  }
554
618
  }
555
- const commit = await git(["commit", "-m", text, "--", ...specs], repoRoot);
619
+ const commit = await git(["commit", "-m", text, "--", ...specs], repoRoot, LOCAL_TIMEOUT, await authorEnv(repoRoot, author));
556
620
  if (!commit.ok) {
557
621
  let error = commit.stderr || commit.stdout.trim() || "git commit failed";
558
622
  if (ours.length) {
@@ -569,8 +633,8 @@ async function commitNow(paths, message) {
569
633
  return { ok: false, error };
570
634
  }
571
635
  touched();
572
- // With `autosync: push` a commit should not sit here until the next interval.
573
- if (repo.cfg.autosync === "push")
636
+ // With `autosync: push` or `sync` a commit should not sit here until the next interval.
637
+ if (author === "git" && (repo.cfg.autosync === "push" || repo.cfg.autosync === "sync"))
574
638
  syncSoon();
575
639
  return { ok: true, committed: paths.length };
576
640
  }
@@ -734,6 +798,10 @@ async function tick() {
734
798
  }
735
799
  }
736
800
  async function sync(repo) {
801
+ if (repo.cfg.autosync === "sync") {
802
+ await syncNow(repo);
803
+ return;
804
+ }
737
805
  const fetched = await gitFetch();
738
806
  if (!fetched.ok || repo.cfg.autosync === "off")
739
807
  return;
@@ -761,3 +829,178 @@ async function sync(repo) {
761
829
  return;
762
830
  await gitPush();
763
831
  }
832
+ /* ---------- autosync: sync ---------- */
833
+ /** How many conflict copies the status lists. */
834
+ const MAX_CONFLICTS = 20;
835
+ const COPY_MARK = ".konflikt-";
836
+ /** `knowledge/a.konflikt-ben-2.md` → { path: knowledge/a.md, by: ben }, or null when it is not a copy. */
837
+ export function parseConflictCopy(copy) {
838
+ const slash = copy.lastIndexOf("/") + 1;
839
+ const name = copy.slice(slash);
840
+ const i = name.lastIndexOf(COPY_MARK);
841
+ if (i <= 0)
842
+ return null;
843
+ const rest = name.slice(i + COPY_MARK.length);
844
+ const dot = rest.indexOf(".");
845
+ const tag = dot >= 0 ? rest.slice(0, dot) : rest;
846
+ if (!/^[a-z0-9_-]+$/.test(tag))
847
+ return null;
848
+ return { path: copy.slice(0, slash) + name.slice(0, i) + (dot >= 0 ? rest.slice(dot) : ""), by: tag.replace(/-\d+$/, "") };
849
+ }
850
+ /** The conflict copies in the work tree, newest first (their files' times). */
851
+ async function conflictCopies(repoRoot) {
852
+ const r = await git(["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", `*${COPY_MARK}*`], repoRoot);
853
+ if (!r.ok)
854
+ return [];
855
+ const out = [];
856
+ for (const copy of r.stdout.split("\0").filter(Boolean)) {
857
+ const parsed = parseConflictCopy(copy);
858
+ if (!parsed)
859
+ continue;
860
+ let at = "";
861
+ try {
862
+ at = statSync(path.join(repoRoot, copy)).mtime.toISOString();
863
+ }
864
+ catch {
865
+ continue; // deleted, not committed yet
866
+ }
867
+ out.push({ path: parsed.path, copy, by: parsed.by, at });
868
+ }
869
+ return out.sort((a, b) => b.at.localeCompare(a.at)).slice(0, MAX_CONFLICTS);
870
+ }
871
+ /** `notes/preise.md` → `notes/preise.konflikt-anna.md`, numbered while taken. */
872
+ export function conflictPath(file, handle, taken) {
873
+ const dir = file.includes("/") ? file.slice(0, file.lastIndexOf("/") + 1) : "";
874
+ const name = file.slice(dir.length);
875
+ const dot = name.lastIndexOf(".");
876
+ const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];
877
+ const tag = (handle || "lokal").toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "lokal";
878
+ for (let n = 1;; n++) {
879
+ const p = `${dir}${stem}.konflikt-${tag}${n > 1 ? `-${n}` : ""}${ext}`;
880
+ if (!taken(p))
881
+ return p;
882
+ }
883
+ }
884
+ /** A blob of `rev` written to a file in the work tree, bytes as they are. */
885
+ function blobToFile(repoRoot, rev, file) {
886
+ return new Promise((resolve) => {
887
+ const child = spawn("git", ["cat-file", "blob", rev], { cwd: repoRoot, env: gitEnv() });
888
+ const out = createWriteStream(path.join(repoRoot, file));
889
+ child.stdout.pipe(out);
890
+ child.once("error", () => resolve(false));
891
+ child.once("close", (code) => out.end(() => resolve(code === 0)));
892
+ });
893
+ }
894
+ const lines = (r) => (r.ok ? r.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : []);
895
+ /**
896
+ * One round of kraftwerk sync: commit what changed under the synced roots,
897
+ * fetch, take the remote's commits (fast-forward, or a merge where the
898
+ * remote wins and our side of every file both changed is kept beside it),
899
+ * push. Each step queues with the others (serial), so a click on the git
900
+ * screen never meets a half-done round.
901
+ */
902
+ async function syncNow(repo) {
903
+ const st0 = await gitStatus(true);
904
+ if (st0.error || !st0.repoRoot)
905
+ return;
906
+ const changed = (st0.files ?? []).filter((f) => f.syncable).map((f) => f.path);
907
+ if (changed.length) {
908
+ const id = await readIdentity().catch(() => null);
909
+ const shown = changed.length <= 3 ? changed.join(", ") : `${changed.slice(0, 3).join(", ")} and ${changed.length - 3} more`;
910
+ const msg = `kraftwerk sync: ${shown}${id ? ` (${id.handle}@${id.machine})` : ""}`;
911
+ const c = await serial(() => commitNow(changed, msg, "sync"));
912
+ if (c.ok)
913
+ gitState().lastAutoCommit = new Date().toISOString();
914
+ else
915
+ gitState().lastError = c.error;
916
+ }
917
+ if (!(await gitFetch()).ok)
918
+ return;
919
+ const st = await gitStatus(true);
920
+ if (st.error || !st.repoRoot)
921
+ return;
922
+ if (st.upstream && st.behind) {
923
+ const merged = st.ahead ? await serial(() => mergeTheirs(repo, st.upstream)) : await gitPull();
924
+ if (!merged.ok)
925
+ return;
926
+ }
927
+ const after = await gitStatus(true);
928
+ if (after.error)
929
+ return;
930
+ if (!after.upstream || after.ahead)
931
+ await gitPush();
932
+ }
933
+ /**
934
+ * Merge the remote's branch, the remote winning: `-X theirs` settles the
935
+ * hunks both sides touched, and what that cannot (one side deleted, the other
936
+ * changed) takes the remote's side by hand. Then every file both sides
937
+ * changed whose result is not our version gets our version beside it, as a
938
+ * second commit. Only the remote's history is taken as it is; ours is kept
939
+ * in full — in history, and in the copies.
940
+ */
941
+ async function mergeTheirs(repo, upstream) {
942
+ const { repoRoot } = repo;
943
+ const fail = (error) => {
944
+ gitState().lastError = error;
945
+ touched();
946
+ return { ok: false, error };
947
+ };
948
+ const ours = (await git(["rev-parse", "HEAD"], repoRoot)).stdout.trim();
949
+ const base = (await git(["merge-base", "HEAD", upstream], repoRoot)).stdout.trim();
950
+ if (!ours || !base)
951
+ return fail("kraftwerk sync: the local and remote histories share nothing — merge them in a terminal once");
952
+ const mine = new Set(lines(await git(["diff", "--name-only", "--no-renames", base, ours], repoRoot)));
953
+ const both = lines(await git(["diff", "--name-only", "--no-renames", base, upstream], repoRoot)).filter((p) => mine.has(p));
954
+ const env = await authorEnv(repoRoot, "sync");
955
+ const msg = "kraftwerk sync: the remote's changes taken in (where both changed a file, the remote's version wins)";
956
+ const m = await git(["merge", "--no-edit", "--no-ff", "-X", "theirs", "-m", msg, upstream], repoRoot, NET_TIMEOUT, env);
957
+ if (!m.ok) {
958
+ const unmerged = lines(await git(["diff", "--name-only", "--diff-filter=U"], repoRoot));
959
+ if (unmerged.length === 0) {
960
+ await git(["merge", "--abort"], repoRoot);
961
+ return fail(`kraftwerk sync could not merge: ${m.stderr || m.stdout.trim() || "unknown error"}`);
962
+ }
963
+ for (const p of unmerged) {
964
+ const stages = lines(await git(["ls-files", "-u", "--", literal(p)], repoRoot)).map((l) => l.split(/\s+/)[2]);
965
+ const r = stages.includes("3")
966
+ ? await git(["checkout", "--theirs", "--", literal(p)], repoRoot).then(() => git(["add", "--", literal(p)], repoRoot))
967
+ : await git(["rm", "-q", "--", literal(p)], repoRoot);
968
+ if (!r.ok) {
969
+ await git(["merge", "--abort"], repoRoot);
970
+ return fail(`kraftwerk sync could not settle ${p}: ${r.stderr}`);
971
+ }
972
+ }
973
+ const done = await git(["commit", "--no-edit", "-m", msg], repoRoot, LOCAL_TIMEOUT, env);
974
+ if (!done.ok) {
975
+ await git(["merge", "--abort"], repoRoot);
976
+ return fail(`kraftwerk sync could not finish the merge: ${done.stderr || done.stdout.trim()}`);
977
+ }
978
+ }
979
+ // Our side of each file both changed, where the result is not it — named after the account when the daemon knows it.
980
+ const id = await readIdentity().catch(() => null);
981
+ const who = syncAuthor()?.name || id?.handle || "";
982
+ const kept = [];
983
+ const at = new Date().toISOString();
984
+ for (const p of both) {
985
+ const oursBlob = (await git(["rev-parse", "--verify", "-q", `${ours}:${p}`], repoRoot)).stdout.trim();
986
+ if (!oursBlob)
987
+ continue; // we deleted it: nothing of ours to keep
988
+ const now = (await git(["rev-parse", "--verify", "-q", `HEAD:${p}`], repoRoot)).stdout.trim();
989
+ if (now === oursBlob)
990
+ continue;
991
+ const copy = conflictPath(p, who, (c) => existsSync(path.join(repoRoot, c)));
992
+ if (!(await blobToFile(repoRoot, oursBlob, copy)))
993
+ continue;
994
+ if ((await git(["add", "--", literal(copy)], repoRoot)).ok)
995
+ kept.push({ path: p, copy, by: who, at });
996
+ }
997
+ if (kept.length) {
998
+ const c = await git(["commit", "-m", `kraftwerk sync: kept ${who || "this machine"}'s version of ${kept.length} file${kept.length === 1 ? "" : "s"} beside the remote's`, "--", ...kept.map((k) => literal(k.copy))], repoRoot, LOCAL_TIMEOUT, env);
999
+ if (!c.ok)
1000
+ return fail(`kraftwerk sync kept copies but could not commit them: ${c.stderr || c.stdout.trim()}`);
1001
+ }
1002
+ gitState().lastPull = at;
1003
+ gitState().lastError = undefined;
1004
+ touched();
1005
+ return { ok: true };
1006
+ }
@@ -2,7 +2,8 @@ import type { ChatMeta } from "./chat/types.js";
2
2
  /**
3
3
  * Attention items: things that happened while nobody was looking and that
4
4
  * the user should see — a session waiting for a permission answer, a routine
5
- * that finished or failed, a workflow run that ended. The inspector shows
5
+ * that finished or failed, a workflow run that ended, a cloud-board task
6
+ * someone handed to the person this machine belongs to (server/cloud-events.ts). The inspector shows
6
7
  * them behind the bell in the top bar (count, list, browser notification);
7
8
  * this module is the one writer. Items are run-state, not config, so they
8
9
  * live in <output>/notifications.json (capped, newest first).
@@ -10,7 +11,7 @@ import type { ChatMeta } from "./chat/types.js";
10
11
  * Approval items carry a `key` so the same request is never listed twice
11
12
  * and disappears again the moment someone answers (dismissKey).
12
13
  */
13
- export type NotificationKind = "approval" | "routine_done" | "routine_failed" | "run_done" | "run_failed" | "task_woken" | "task_wake_failed";
14
+ export type NotificationKind = "approval" | "routine_done" | "routine_failed" | "run_done" | "run_failed" | "task_woken" | "task_wake_failed" | "task_assigned";
14
15
  /**
15
16
  * What a "diagnose" on a failure item should look at: a workflow run (chat
16
17
  * in the run folder) or a routine (its agent, and the session that failed
@@ -51,7 +51,7 @@ export interface GitSettingsInput {
51
51
  remote?: string;
52
52
  branch?: string;
53
53
  interval?: number | string;
54
- autosync?: "off" | "pull" | "push" | "";
54
+ autosync?: "off" | "pull" | "push" | "sync" | "";
55
55
  }
56
56
  export declare function getSettings(): Promise<SettingsView>;
57
57
  export declare function saveSettings(input: SaveSettingsInput): Promise<SettingsView>;
@@ -68,8 +68,8 @@ function cleanGit(value) {
68
68
  out.interval = n;
69
69
  }
70
70
  if (value.autosync !== undefined && value.autosync !== "") {
71
- if (value.autosync !== "off" && value.autosync !== "pull" && value.autosync !== "push")
72
- throw new Error('git.autosync must be "off", "pull" or "push"');
71
+ if (value.autosync !== "off" && value.autosync !== "pull" && value.autosync !== "push" && value.autosync !== "sync")
72
+ throw new Error('git.autosync must be "off", "pull", "push" or "sync"');
73
73
  if (value.autosync !== GIT_DEFAULTS.autosync)
74
74
  out.autosync = value.autosync;
75
75
  }
@@ -20,6 +20,10 @@ export declare const cloudRoutes: (import("./router.js").Route<"cloud.invite", i
20
20
  member: "member";
21
21
  owner: "owner";
22
22
  }>>;
23
+ }, z.core.$strip>> | import("./router.js").Route<"cloud.join", import("../join.js").JoinResult, "/api/cloud/join", z.ZodObject<{
24
+ link: z.ZodString;
25
+ dir: z.ZodOptional<z.ZodString>;
26
+ cwd: z.ZodString;
23
27
  }, z.core.$strip>> | import("./router.js").Route<"cloud.set", {
24
28
  daemon: boolean;
25
29
  url: string;
@@ -2,6 +2,7 @@ import * as z from "zod";
2
2
  import { writeCloudFile } from "../../core/cloud.js";
3
3
  import { applyMachineCloud, cloudStatus, createWorkspaceInvite, syncMachineCloud, unlinkMachineCloud } from "../cloud.js";
4
4
  import { currentHub } from "../hub-context.js";
5
+ import { joinWorkspace } from "../join.js";
5
6
  import { setWorkspaceCloud, workspaceCloud } from "../workspace-cloud.js";
6
7
  import { fail, route } from "./router.js";
7
8
  /**
@@ -45,6 +46,19 @@ export const cloudRoutes = [
45
46
  const { slug, root, role } = await c.body();
46
47
  return createWorkspaceInvite({ slug, root }, role);
47
48
  }),
49
+ // Start on the platform: `kraftwerk join <link>` (server/join.ts).
50
+ route({
51
+ name: "cloud.join",
52
+ method: "POST",
53
+ path: "/api/cloud/join",
54
+ summary: "bring a workspace from kraftwerk cloud onto this machine {link, dir?, cwd}: claim, clone from kraftwerk sync, open",
55
+ access: "local",
56
+ errors: 409,
57
+ body: z.object({ link: z.string().min(1, "link is required"), dir: z.string().optional(), cwd: z.string().min(1, "cwd is required") }),
58
+ }, async (c) => {
59
+ const { link, dir, cwd } = await c.body();
60
+ return joinWorkspace(link, dir, cwd);
61
+ }),
48
62
  route({ name: "cloud.unlink", method: "POST", path: "/api/cloud/unlink", summary: "release the machine from its account; the cloud hands out a fresh claim code", access: "local", errors: 400 }, async () => ({
49
63
  daemon: currentHub().daemon === true,
50
64
  ...(await unlinkMachineCloud()),
@@ -1,4 +1,11 @@
1
1
  import * as z from "zod";
2
+ import { type GitStatus } from "../../core/git.js";
3
+ /**
4
+ * Who hosts the workspace's remote: kraftwerk sync is the workspace's own
5
+ * repo in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
6
+ * machine knows it); anything else is an own git provider.
7
+ */
8
+ export declare function hostingOf(remoteUrl: string | undefined): Promise<NonNullable<GitStatus["hosting"]>>;
2
9
  /** The workspace's own git, and the repositories cloned under its repos root. */
3
10
  export declare const gitRoutes: (import("./router.js").Route<"git.commit", import("./router.js").Reply<{
4
11
  ok: boolean;
@@ -16,7 +23,12 @@ export declare const gitRoutes: (import("./router.js").Route<"git.commit", impor
16
23
  }>, "/api/git/pull", undefined> | import("./router.js").Route<"git.push", import("./router.js").Reply<{
17
24
  ok: boolean;
18
25
  error?: string;
19
- }>, "/api/git/push", undefined> | import("./router.js").Route<"git.status", import("../../core/git.js").GitStatus, "/api/git", undefined> | import("./router.js").Route<"repos.add", import("./router.js").Reply<import("../../core/repos.js").RepoInfo>, "/api/repos", z.ZodObject<{
26
+ }>, "/api/git/push", undefined> | import("./router.js").Route<"git.setupSync", import("./router.js").Reply<{
27
+ ok: boolean;
28
+ done: string[];
29
+ error?: string;
30
+ status: GitStatus;
31
+ }>, "/api/git/sync-setup", undefined> | import("./router.js").Route<"git.status", GitStatus, "/api/git", undefined> | import("./router.js").Route<"repos.add", import("./router.js").Reply<import("../../core/repos.js").RepoInfo>, "/api/repos", z.ZodObject<{
20
32
  url: z.ZodDefault<z.ZodString>;
21
33
  name: z.ZodOptional<z.ZodString>;
22
34
  branch: z.ZodOptional<z.ZodString>;
@@ -1,5 +1,9 @@
1
1
  import * as z from "zod";
2
+ import { resolveWorkspace } from "../../config.js";
3
+ import { workspaceRoot } from "../../core/context.js";
2
4
  import { gitCommit, gitDiff, gitFetch, gitPull, gitPush, gitStatus } from "../../core/git.js";
5
+ import { cloudStatus } from "../cloud.js";
6
+ import { setupSync } from "../sync-setup.js";
3
7
  import { addRepo, listRepos, openRepos, removeRepo, repoCommitDiff, repoDetail, repoDiff, updateRepo } from "../../core/repos.js";
4
8
  import { fail, reply, route, statusByMessage } from "./router.js";
5
9
  const repoErrors = statusByMessage(/^no repository/);
@@ -8,10 +12,38 @@ const conflictUnlessOk = (result) => reply(result.ok ? 200 : 409, result);
8
12
  const Commit = z.object({ paths: z.array(z.string()).default([]), message: z.string().default("") });
9
13
  /** A clone to add; url, name, branch and depth are checked by addRepo. */
10
14
  const AddRepo = z.object({ url: z.string().default(""), name: z.string().optional(), branch: z.string().optional(), depth: z.number().optional() });
15
+ /**
16
+ * Who hosts the workspace's remote: kraftwerk sync is the workspace's own
17
+ * repo in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
18
+ * machine knows it); anything else is an own git provider.
19
+ */
20
+ export async function hostingOf(remoteUrl) {
21
+ if (!remoteUrl)
22
+ return "none";
23
+ const id = (await resolveWorkspace(workspaceRoot()).catch(() => null))?.config.id;
24
+ let u;
25
+ try {
26
+ u = new URL(remoteUrl);
27
+ }
28
+ catch {
29
+ return "custom"; // scp-like ssh (git@host:path) — never kraftwerk sync
30
+ }
31
+ const cloud = cloudStatus().url;
32
+ const sameHost = !cloud || (() => { try {
33
+ return new URL(cloud).host === u.host;
34
+ }
35
+ catch {
36
+ return false;
37
+ } })();
38
+ return id && sameHost && u.pathname.replace(/\/+$/, "") === `/git/${encodeURIComponent(id)}.git` ? "kraftwerk" : "custom";
39
+ }
11
40
  /** The workspace's own git, and the repositories cloned under its repos root. */
12
41
  export const gitRoutes = [
13
42
  // The git screen polls this, so it is cached for a beat; ?fresh=1 bypasses the cache.
14
- route({ name: "git.status", method: "GET", path: "/api/git", summary: "branch, ahead/behind, changed files" }, async (c) => gitStatus(c.query.has("fresh"))),
43
+ route({ name: "git.status", method: "GET", path: "/api/git", summary: "branch, ahead/behind, changed files" }, async (c) => {
44
+ const st = await gitStatus(c.query.has("fresh"));
45
+ return st.repoRoot ? { ...st, hosting: await hostingOf(st.remoteUrl) } : st;
46
+ }),
15
47
  route({ name: "git.diff", method: "GET", path: "/api/git/diff", summary: "unified diff for one file ?path=" }, async (c) => {
16
48
  const file = c.query.get("path");
17
49
  if (!file)
@@ -24,6 +56,12 @@ export const gitRoutes = [
24
56
  const result = await gitCommit(paths, message);
25
57
  return reply(result.ok ? 200 : 409, result);
26
58
  }),
59
+ // kraftwerk sync in one go (server/sync-setup.ts); 409 while cloud mode is not there or the remote is someone else's.
60
+ route({ name: "git.setupSync", method: "POST", path: "/api/git/sync-setup", summary: "set up kraftwerk sync: repo, git block, cloud remote, first push", errors: 409 }, async () => {
61
+ const r = await setupSync();
62
+ const st = r.status.repoRoot ? { ...r.status, hosting: await hostingOf(r.status.remoteUrl) } : r.status;
63
+ return reply(r.ok ? 200 : 409, { ...r, status: st });
64
+ }),
27
65
  route({ name: "git.fetch", method: "POST", path: "/api/git/fetch", summary: "git fetch" }, async () => conflictUnlessOk(await gitFetch())),
28
66
  route({ name: "git.pull", method: "POST", path: "/api/git/pull", summary: "git pull --ff-only" }, async () => conflictUnlessOk(await gitPull())),
29
67
  route({ name: "git.push", method: "POST", path: "/api/git/push", summary: "git push" }, async () => conflictUnlessOk(await gitPush())),
@@ -351,6 +351,10 @@ export declare const routes: (Route<"agents.addJournal", {
351
351
  member: "member";
352
352
  owner: "owner";
353
353
  }>>;
354
+ }, z.core.$strip>> | Route<"cloud.join", import("../join.js").JoinResult, "/api/cloud/join", z.ZodObject<{
355
+ link: z.ZodString;
356
+ dir: z.ZodOptional<z.ZodString>;
357
+ cwd: z.ZodString;
354
358
  }, z.core.$strip>> | Route<"cloud.set", {
355
359
  daemon: boolean;
356
360
  url: string;
@@ -544,7 +548,12 @@ export declare const routes: (Route<"agents.addJournal", {
544
548
  }>, "/api/git/pull", undefined> | Route<"git.push", import("./router.js").Reply<{
545
549
  ok: boolean;
546
550
  error?: string;
547
- }>, "/api/git/push", undefined> | Route<"git.status", import("../../core/git.js").GitStatus, "/api/git", undefined> | Route<"hub.close", {
551
+ }>, "/api/git/push", undefined> | Route<"git.setupSync", import("./router.js").Reply<{
552
+ ok: boolean;
553
+ done: string[];
554
+ error?: string;
555
+ status: import("../../core/git.js").GitStatus;
556
+ }>, "/api/git/sync-setup", undefined> | Route<"git.status", import("../../core/git.js").GitStatus, "/api/git", undefined> | Route<"hub.close", {
548
557
  ok: boolean;
549
558
  }, "/api/hub/close", z.ZodObject<{
550
559
  root: z.ZodString;
@@ -0,0 +1,8 @@
1
+ /** Fetch and act on what waits; a call while one runs makes it run once more after. */
2
+ export declare function fetchCloudEvents(): Promise<void>;
3
+ /** Hold the stream while connected and claimed; drop it otherwise. */
4
+ export declare function keepEventStream(): void;
5
+ /** Whether the stream is up (tests, status). */
6
+ export declare const eventStreamOpen: () => boolean;
7
+ /** Hook in (cloud.ts startMachineCloud): the task context, the heartbeat's count, the link's changes. Not at import — the modules load each other. */
8
+ export declare function installCloudEvents(): void;