@netnodeag/kraftwerk 0.101.0 → 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 (44) hide show
  1. package/README.md +38 -2
  2. package/dist/cli/join.js +4 -2
  3. package/dist/config.d.ts +2 -2
  4. package/dist/config.js +3 -3
  5. package/dist/core/boards.d.ts +3 -0
  6. package/dist/core/boards.js +16 -2
  7. package/dist/core/cloud.d.ts +5 -0
  8. package/dist/core/git.d.ts +34 -2
  9. package/dist/core/git.js +218 -6
  10. package/dist/core/notifications.d.ts +3 -2
  11. package/dist/core/settings.d.ts +1 -1
  12. package/dist/core/settings.js +2 -2
  13. package/dist/server/cloud-events.d.ts +8 -0
  14. package/dist/server/cloud-events.js +199 -0
  15. package/dist/server/cloud.d.ts +8 -0
  16. package/dist/server/cloud.js +41 -1
  17. package/dist/server/join.d.ts +6 -2
  18. package/dist/server/join.js +13 -4
  19. package/dist/server/relay.js +5 -0
  20. package/dist/server/sync-setup.d.ts +3 -2
  21. package/dist/server/sync-setup.js +6 -3
  22. package/dist/server/users.d.ts +11 -0
  23. package/dist/server/users.js +63 -15
  24. package/dist/server/workspace-cloud.d.ts +3 -1
  25. package/dist/server/workspace-cloud.js +18 -8
  26. package/package.json +1 -1
  27. package/web/dist/assets/{dist-BgG4OIU9.js → dist-B09k-Kwi.js} +1 -1
  28. package/web/dist/assets/{dist-Db9KgP0W.js → dist-BG9MPqC7.js} +1 -1
  29. package/web/dist/assets/{dist-Bi5Y6JmO.js → dist-BbST9sxK.js} +1 -1
  30. package/web/dist/assets/{dist-CiGlBloC.js → dist-BrXAphjl.js} +1 -1
  31. package/web/dist/assets/{dist-Bd_SvBeU.js → dist-C0Ulmjwh.js} +1 -1
  32. package/web/dist/assets/{dist-DTxqCKQj.js → dist-C8wsDqpL.js} +1 -1
  33. package/web/dist/assets/{dist-Cfj7O2BI.js → dist-CJk4RtqY.js} +1 -1
  34. package/web/dist/assets/{dist-DXGv3DRS.js → dist-CfSpo_bP.js} +1 -1
  35. package/web/dist/assets/dist-DMU8iY9H.js +1 -0
  36. package/web/dist/assets/{dist-Cq4ezkbk.js → dist-Dv55aORJ.js} +1 -1
  37. package/web/dist/assets/{dist-Co1Cz1EB.js → dist-QQHKzUGH.js} +1 -1
  38. package/web/dist/assets/{editor-CH-WK0Ag.js → editor-Co8xGDnf.js} +3 -3
  39. package/web/dist/assets/index-CepQsH8H.js +488 -0
  40. package/web/dist/assets/index-DJGLnVQY.css +2 -0
  41. package/web/dist/index.html +2 -2
  42. package/web/dist/assets/dist-DeUP_9vJ.js +0 -1
  43. package/web/dist/assets/index-ClVr51ut.css +0 -2
  44. package/web/dist/assets/index-CnwVoHX3.js +0 -488
package/README.md CHANGED
@@ -555,7 +555,11 @@ It installs kraftwerk for good (the daemon then runs from that install), starts
555
555
  the daemon if it does not run, links this machine to your account
556
556
  (no claim code), clones the workspace from kraftwerk sync into `./<its name>`
557
557
  (or `kraftwerk join <link> <folder>`) and opens it in the browser — already
558
- in cloud mode. An invite works the same way: the person accepts it in the
558
+ in cloud mode and signed in: the link proved the account, so the daemon hands
559
+ the browser a one-time sign-in (`/auth/handoff`, five minutes, single use)
560
+ instead of a second round through the cloud. A workspace whose repository is
561
+ still empty (begun locally, kraftwerk sync not set up there yet) is refused
562
+ with what to do, and nothing is made locally. An invite works the same way: the person accepts it in the
559
563
  browser (signing up on the way), and the page shows the same command. A
560
564
  workspace's page in the cloud gives you a fresh command for each further
561
565
  machine (*Install on a machine*). Running it again on a folder that holds the
@@ -573,12 +577,33 @@ to a config), so there is no token to paste and no credential helper.
573
577
  Workspaces made on the platform start with it. For one you started locally,
574
578
  switch it to cloud, then on the **Git** page click *set up kraftwerk sync*
575
579
  (`POST /api/git/sync-setup`): a repository if there is none, `git:` on with
576
- `autosync: push`, the remote, a first commit, a push. A remote of your own
580
+ `autosync: sync` every 60 seconds, the remote, a first commit, a push.
581
+
582
+ `autosync: sync` is the simple sync: every interval kraftwerk commits what
583
+ changed under the synced paths (as the account the machine is linked to),
584
+ takes the others' commits in and pushes — nobody commits, pulls or merges by
585
+ hand. When two people changed the same file at once, the version that
586
+ reached the cloud first stays, and the other lands beside it as
587
+ `name.konflikt-<handle>.ext`, committed too, so nothing is lost. The Git page
588
+ lists those copies on every machine until someone deletes them:
589
+
590
+ ```yaml
591
+ git:
592
+ autosync: sync # off | pull | push | sync
593
+ interval: 60
594
+ ```
595
+
596
+ A remote of your own
577
597
  (GitHub, GitLab, a server in-house) is expert mode: kraftwerk never replaces
578
598
  it, and the Git page says which of the two a workspace uses
579
599
  (*managed by kraftwerk* or *own git provider · expert mode*) and shows the
580
600
  remote's address.
581
601
 
602
+ A workspace deleted on kraftwerk cloud (by its owner or an admin) stays on
603
+ your machine with all its files: the mode chip says *cloud · deleted*, and
604
+ switching it to local keeps you working. Switching it to cloud again gives it
605
+ a fresh id — the old one is never used again.
606
+
582
607
  ### This machine in the kraftwerk cloud
583
608
 
584
609
  The kraftwerk cloud is the `~/.kraftwerk` registry made reachable over the
@@ -1269,6 +1294,17 @@ the model via ACP session options and the thinking budget via
1269
1294
  are created and edited in the UI, or by editing the files, since the
1270
1295
  definition is read fresh for each new session.
1271
1296
 
1297
+
1298
+ **Told at once.** A task on a cloud board handed to you by someone else
1299
+ lands in the bell of the workspace on your machines — and as a browser
1300
+ notification and on a paired phone — within a fraction of a second: the
1301
+ cloud pokes the machine over its event stream (`/api/machines/stream`, held
1302
+ by every daemon connected to the cloud, remote access or not), the daemon
1303
+ fetches what waits and acknowledges it; a poke missed while offline comes
1304
+ with the next heartbeat. A task for an agent in a work column wakes that
1305
+ agent on the machine that has it, as a local board does — one machine
1306
+ claims it, so clones never both start. The agent works it with
1307
+ `npx kraftwerk tasks … --board @<board>`.
1272
1308
  ### Repositories
1273
1309
 
1274
1310
  Turn on `repos:` in `kraftwerk.yml` (or the checkbox in settings) and the
package/dist/cli/join.js CHANGED
@@ -42,9 +42,11 @@ export function registerJoinCommand(program) {
42
42
  console.log(`${chalk.green("✔")} ${chalk.bold(data.workspace.name)} ${chalk.dim(`(${data.workspace.id}, ${data.role})`)} is on this machine`);
43
43
  console.log(` ${chalk.dim("folder")} ${tildify(data.root)}${data.cloned ? "" : chalk.dim(" (was already here)")}`);
44
44
  console.log(` ${chalk.dim("account")} ${data.account} — this machine is linked to it`);
45
- console.log(` ${chalk.dim("sync")} kraftwerk sync: what you commit goes to the cloud, the others' changes come in`);
45
+ console.log(` ${chalk.dim("sync")} kraftwerk sync: what changes here goes to the cloud every minute, the others' changes come in`);
46
46
  console.log(` ${chalk.dim("open")} ${chalk.cyan(data.workspace.url)}`);
47
47
  if (opts.open)
48
- openBrowser(data.workspace.url);
48
+ openBrowser(data.signin ?? data.workspace.url);
49
+ else if (data.signin)
50
+ console.log(` ${chalk.dim("sign in")} ${data.signin} ${chalk.dim("(once, within 5 minutes)")}`);
49
51
  });
50
52
  }
package/dist/config.d.ts CHANGED
@@ -27,7 +27,7 @@
27
27
  * git: # workspace git sync (absent = off, bare key = on with defaults)
28
28
  * remote: origin
29
29
  * interval: 300 # seconds between background fetches
30
- * autosync: pull # off | pull | push (push = pull, then push what is committed)
30
+ * autosync: pull # off | pull | push | sync (push = pull, then push what is committed; sync = commit what changed too)
31
31
  * repos: # git repositories the agents work on (absent = off, bare key = on)
32
32
  * root: kraftwerk-data/repos # where clones land, relative to the file. Default: repos
33
33
  * vibeables: # small apps built live in a chat, rendered in the inspector (absent = off, bare key = on)
@@ -69,7 +69,7 @@ export interface GitConfig {
69
69
  /** Seconds between background fetches. 0 disables the timer. Default: 300. */
70
70
  interval?: number;
71
71
  /** off = fetch only. pull = also fast-forward when behind and clean. push = pull, and push commits that are ahead. Default: pull. */
72
- autosync?: "off" | "pull" | "push";
72
+ autosync?: "off" | "pull" | "push" | "sync";
73
73
  }
74
74
  /**
75
75
  * Repositories: git clones the agents work on, kept under one root inside
package/dist/config.js CHANGED
@@ -33,7 +33,7 @@ import { readParsed } from "./core/file-cache.js";
33
33
  * git: # workspace git sync (absent = off, bare key = on with defaults)
34
34
  * remote: origin
35
35
  * interval: 300 # seconds between background fetches
36
- * autosync: pull # off | pull | push (push = pull, then push what is committed)
36
+ * autosync: pull # off | pull | push | sync (push = pull, then push what is committed; sync = commit what changed too)
37
37
  * repos: # git repositories the agents work on (absent = off, bare key = on)
38
38
  * root: kraftwerk-data/repos # where clones land, relative to the file. Default: repos
39
39
  * vibeables: # small apps built live in a chat, rendered in the inspector (absent = off, bare key = on)
@@ -480,8 +480,8 @@ function validateGit(configPath, value) {
480
480
  if (g.interval !== undefined && (typeof g.interval !== "number" || !Number.isInteger(g.interval) || g.interval < 0)) {
481
481
  throw new Error(`${file}: git.interval must be a whole number of seconds (0 disables the timer)`);
482
482
  }
483
- if (g.autosync !== undefined && g.autosync !== "off" && g.autosync !== "pull" && g.autosync !== "push") {
484
- throw new Error(`${file}: git.autosync must be "off", "pull" or "push"`);
483
+ if (g.autosync !== undefined && g.autosync !== "off" && g.autosync !== "pull" && g.autosync !== "push" && g.autosync !== "sync") {
484
+ throw new Error(`${file}: git.autosync must be "off", "pull", "push" or "sync"`);
485
485
  }
486
486
  }
487
487
  /**
@@ -251,6 +251,8 @@ export interface TaskEvent {
251
251
  message?: string;
252
252
  }
253
253
  export declare const EVENTS_FILE = "boards/events.jsonl";
254
+ /** Append an event for the server on this machine (board-wake.ts reads the file). Local run-state: never in git. Cloud tasks come in through server/cloud-events.ts. */
255
+ export declare function emitTaskEvent(ev: TaskEvent): Promise<void>;
254
256
  export declare function createTask(ref: BoardRef, input: TaskInput & {
255
257
  actor?: string;
256
258
  message?: string;
@@ -303,4 +305,5 @@ export interface LinkingTask {
303
305
  }
304
306
  /** Every task whose refs name the token (presentation:town-hall), across the workspace's boards. */
305
307
  export declare function tasksReferencing(token: string): Promise<LinkingTask[]>;
308
+ export declare function setCloudTaskContext(fn: (reference: string) => Promise<string>): void;
306
309
  export declare function taskContext(reference: string): Promise<string>;
@@ -702,8 +702,8 @@ export async function appendTaskLog(ref, idOrNumber, entry, actor) {
702
702
  return (await getTask(ref, t.slug));
703
703
  }
704
704
  export const EVENTS_FILE = "boards/events.jsonl";
705
- /** Append an event for the server on this machine (board-wake.ts reads the file). Local run-state: never in git. */
706
- async function emitTaskEvent(ev) {
705
+ /** Append an event for the server on this machine (board-wake.ts reads the file). Local run-state: never in git. Cloud tasks come in through server/cloud-events.ts. */
706
+ export async function emitTaskEvent(ev) {
707
707
  const file = path.join(getOutputDir(), EVENTS_FILE);
708
708
  await fs.mkdir(path.dirname(file), { recursive: true });
709
709
  await fs.appendFile(file, `${JSON.stringify(ev)}\n`);
@@ -1026,7 +1026,21 @@ export async function tasksReferencing(token) {
1026
1026
  }
1027
1027
  return out;
1028
1028
  }
1029
+ /**
1030
+ * The context block of a cloud-board task (`@board/3`): the server provides it
1031
+ * (server/cloud-events.ts), core cannot reach the cloud. Unset, such a task
1032
+ * says where to look.
1033
+ */
1034
+ let cloudTaskContext = null;
1035
+ export function setCloudTaskContext(fn) {
1036
+ cloudTaskContext = fn;
1037
+ }
1029
1038
  export async function taskContext(reference) {
1039
+ if (reference.startsWith("@")) {
1040
+ return cloudTaskContext
1041
+ ? cloudTaskContext(reference)
1042
+ : `You were opened for task ${reference} on a cloud board. Read it with \`npx kraftwerk tasks show ${reference.split("/")[1]} --board ${reference.split("/")[0]}\`.`;
1043
+ }
1030
1044
  const t = await findTask(reference);
1031
1045
  if (!t)
1032
1046
  return `You were opened for task ${reference}, but it does not exist any more (removed, or its board is gone). Tell the user.`;
@@ -82,6 +82,8 @@ export interface RegisterResponse {
82
82
  /** The claiming account's uuid and handle (clouds before 0.97 send neither). */
83
83
  accountId?: string | null;
84
84
  accountHandle?: string | null;
85
+ /** Reported ws_ ids deleted in the cloud (clouds before 0.102 send none). */
86
+ deletedWorkspaces?: string[];
85
87
  }
86
88
  export interface HeartbeatResponse {
87
89
  ok: boolean;
@@ -90,6 +92,9 @@ export interface HeartbeatResponse {
90
92
  accountId?: string | null;
91
93
  accountHandle?: string | null;
92
94
  claimCode: string | null;
95
+ deletedWorkspaces?: string[];
96
+ /** Events waiting at /api/machines/events (clouds before 0.102 send none). */
97
+ events?: number;
93
98
  }
94
99
  /** A person the cloud vouches for: the account's uuid (the same on every machine), email and handle. */
95
100
  export interface CloudUser {
@@ -21,7 +21,13 @@
21
21
  * pushes commits that already exist to a branch that already tracks its
22
22
  * upstream. It never creates a commit, never publishes a new branch and
23
23
  * never forces.
24
- * - A diverged branch is reported, never merged or rebased from here.
24
+ * - A diverged branch is reported, never merged or rebased from here —
25
+ * except with `autosync: sync` (kraftwerk sync's default): there the timer
26
+ * also commits what changed under the synced roots, and a diverged branch
27
+ * is merged with the rule "the cloud wins": where both sides changed a
28
+ * file, the remote's version stays and this machine's lands beside it as
29
+ * `name.konflikt-<handle>.ext`, committed too, so nothing is lost and
30
+ * nobody has to resolve anything in a terminal (see syncNow).
25
31
  *
26
32
  * Every git call passes an argument array, so nothing reaches a shell, and
27
33
  * every call is async with a timeout: git runs inside the single-threaded
@@ -33,7 +39,7 @@
33
39
  /** Paths whose content is never shown or synced, whichever repo they sit in. */
34
40
  export declare const DENY: RegExp[];
35
41
  /** off = fetch only. pull = also fast-forward. push = fast-forward, then push what is ahead. */
36
- export type Autosync = "off" | "pull" | "push";
42
+ export type Autosync = "off" | "pull" | "push" | "sync";
37
43
  export interface GitFile {
38
44
  /** Path relative to the repo root, which is what git speaks. */
39
45
  path: string;
@@ -79,6 +85,21 @@ export interface GitStatus {
79
85
  /** The last push that worked, by hand or in the background. */
80
86
  lastPush?: string;
81
87
  lastError?: string;
88
+ /** The last commit `autosync: sync` made by itself. */
89
+ lastAutoCommit?: string;
90
+ /**
91
+ * Copies `autosync: sync` kept beside the remote's version (on this machine
92
+ * or any other), read from the files themselves: they stay listed until
93
+ * someone deletes the copy. Newest first.
94
+ */
95
+ conflicts?: SyncConflict[];
96
+ }
97
+ /** One file both sides changed: the remote's version is at `path`, the other side's at `copy`, kept for `by`. */
98
+ export interface SyncConflict {
99
+ path: string;
100
+ copy: string;
101
+ by: string;
102
+ at: string;
82
103
  }
83
104
  export interface GitDiff {
84
105
  diff: string;
@@ -145,6 +166,10 @@ export declare function gitCommit(paths: string[], message: string): Promise<{
145
166
  error?: string;
146
167
  committed?: number;
147
168
  }>;
169
+ export declare function setSyncAuthor(fn: () => {
170
+ name: string;
171
+ email: string;
172
+ } | null): void;
148
173
  export declare function gitFetch(): Promise<{
149
174
  ok: boolean;
150
175
  error?: string;
@@ -169,3 +194,10 @@ export declare function gitPush(): Promise<{
169
194
  export declare function startGitSync(): void;
170
195
  /** Stop the current workspace's background sync (the workspace closes). A tick in flight finishes, then stops. */
171
196
  export declare function stopGitSync(): void;
197
+ /** `knowledge/a.konflikt-ben-2.md` → { path: knowledge/a.md, by: ben }, or null when it is not a copy. */
198
+ export declare function parseConflictCopy(copy: string): {
199
+ path: string;
200
+ by: string;
201
+ } | null;
202
+ /** `notes/preise.md` → `notes/preise.konflikt-anna.md`, numbered while taken. */
203
+ export declare function conflictPath(file: string, handle: string, taken: (p: string) => boolean): string;
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
@@ -374,6 +381,7 @@ const gitState = perWorkspace(() => ({
374
381
  lastPull: undefined,
375
382
  lastPush: undefined,
376
383
  lastError: undefined,
384
+ lastAutoCommit: undefined,
377
385
  timer: null,
378
386
  ticking: false,
379
387
  lastRun: 0,
@@ -455,6 +463,7 @@ export async function gitStatus(fresh = false) {
455
463
  lastPull: gitState().lastPull,
456
464
  lastPush: gitState().lastPush,
457
465
  lastError: gitState().lastError,
466
+ ...(gitState().lastAutoCommit ? { lastAutoCommit: gitState().lastAutoCommit } : {}),
458
467
  };
459
468
  // A failed status (a stale index.lock, a timeout on a huge untracked tree)
460
469
  // must not read as "workspace clean": with no file list the commit endpoint
@@ -477,12 +486,14 @@ export async function gitStatus(fresh = false) {
477
486
  const scopeError = scope.wholeRepo
478
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."
479
488
  : undefined;
489
+ const conflicts = repo.cfg.autosync === "sync" ? await conflictCopies(repoRoot) : [];
480
490
  const value = {
481
491
  ...base,
482
492
  error: head.error ?? scopeError,
483
493
  files: [...syncable, ...blocked.slice(0, MAX_BLOCKED)],
484
494
  blockedHidden: blockedHidden || undefined,
485
495
  scope: scope.include,
496
+ ...(conflicts.length ? { conflicts } : {}),
486
497
  };
487
498
  // A commit that finished while this status was running already emptied
488
499
  // the cache; caching the pre-commit list on top of that would show the
@@ -541,7 +552,29 @@ export function capDiff(diff) {
541
552
  export function gitCommit(paths, message) {
542
553
  return serial(() => commitNow(paths, message));
543
554
  }
544
- 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") {
545
578
  const { repo, error } = await openRepo();
546
579
  if (!repo)
547
580
  return { ok: false, error };
@@ -583,7 +616,7 @@ async function commitNow(paths, message) {
583
616
  return { ok: false, error: add.stderr || "git add failed" };
584
617
  }
585
618
  }
586
- 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));
587
620
  if (!commit.ok) {
588
621
  let error = commit.stderr || commit.stdout.trim() || "git commit failed";
589
622
  if (ours.length) {
@@ -600,8 +633,8 @@ async function commitNow(paths, message) {
600
633
  return { ok: false, error };
601
634
  }
602
635
  touched();
603
- // With `autosync: push` a commit should not sit here until the next interval.
604
- 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"))
605
638
  syncSoon();
606
639
  return { ok: true, committed: paths.length };
607
640
  }
@@ -765,6 +798,10 @@ async function tick() {
765
798
  }
766
799
  }
767
800
  async function sync(repo) {
801
+ if (repo.cfg.autosync === "sync") {
802
+ await syncNow(repo);
803
+ return;
804
+ }
768
805
  const fetched = await gitFetch();
769
806
  if (!fetched.ok || repo.cfg.autosync === "off")
770
807
  return;
@@ -792,3 +829,178 @@ async function sync(repo) {
792
829
  return;
793
830
  await gitPush();
794
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
  }
@@ -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;