@netnodeag/kraftwerk 0.101.0 → 0.103.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 (49) hide show
  1. package/README.md +60 -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 +7 -0
  8. package/dist/core/git.d.ts +36 -2
  9. package/dist/core/git.js +226 -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/api/git.d.ts +0 -6
  14. package/dist/server/api/git.js +4 -25
  15. package/dist/server/cloud-events.d.ts +8 -0
  16. package/dist/server/cloud-events.js +199 -0
  17. package/dist/server/cloud.d.ts +15 -0
  18. package/dist/server/cloud.js +77 -2
  19. package/dist/server/join.d.ts +6 -2
  20. package/dist/server/join.js +15 -4
  21. package/dist/server/relay.js +5 -0
  22. package/dist/server/sandbox.d.ts +9 -0
  23. package/dist/server/sandbox.js +48 -0
  24. package/dist/server/server.js +5 -3
  25. package/dist/server/sync-setup.d.ts +3 -2
  26. package/dist/server/sync-setup.js +6 -3
  27. package/dist/server/users.d.ts +11 -0
  28. package/dist/server/users.js +68 -18
  29. package/dist/server/workspace-cloud.d.ts +3 -1
  30. package/dist/server/workspace-cloud.js +18 -8
  31. package/package.json +1 -1
  32. package/web/dist/assets/{dist-BgG4OIU9.js → dist-B09k-Kwi.js} +1 -1
  33. package/web/dist/assets/{dist-Db9KgP0W.js → dist-BG9MPqC7.js} +1 -1
  34. package/web/dist/assets/{dist-Bi5Y6JmO.js → dist-BbST9sxK.js} +1 -1
  35. package/web/dist/assets/{dist-CiGlBloC.js → dist-BrXAphjl.js} +1 -1
  36. package/web/dist/assets/{dist-Bd_SvBeU.js → dist-C0Ulmjwh.js} +1 -1
  37. package/web/dist/assets/{dist-DTxqCKQj.js → dist-C8wsDqpL.js} +1 -1
  38. package/web/dist/assets/{dist-Cfj7O2BI.js → dist-CJk4RtqY.js} +1 -1
  39. package/web/dist/assets/{dist-DXGv3DRS.js → dist-CfSpo_bP.js} +1 -1
  40. package/web/dist/assets/dist-DMU8iY9H.js +1 -0
  41. package/web/dist/assets/{dist-Cq4ezkbk.js → dist-Dv55aORJ.js} +1 -1
  42. package/web/dist/assets/{dist-Co1Cz1EB.js → dist-QQHKzUGH.js} +1 -1
  43. package/web/dist/assets/{editor-CH-WK0Ag.js → editor-Co8xGDnf.js} +3 -3
  44. package/web/dist/assets/index-CepQsH8H.js +488 -0
  45. package/web/dist/assets/index-DJGLnVQY.css +2 -0
  46. package/web/dist/index.html +2 -2
  47. package/web/dist/assets/dist-DeUP_9vJ.js +0 -1
  48. package/web/dist/assets/index-ClVr51ut.css +0 -2
  49. package/web/dist/assets/index-CnwVoHX3.js +0 -488
package/README.md CHANGED
@@ -555,13 +555,39 @@ 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
562
566
  workspace just opens it. `POST /api/cloud/join {link, cwd, dir?}` on the
563
567
  daemon does the work.
564
568
 
569
+ #### Run in the cloud: a sandbox on kraftwerk cloud
570
+
571
+ A workspace can also run on kraftwerk cloud itself: *Run in the cloud →
572
+ Launch* on its page there. The cloud starts a sandbox (a container with
573
+ kraftwerk's daemon), and that daemon does the same `kraftwerk join` as a
574
+ laptop would. Afterwards it is one more machine of the workspace: kraftwerk
575
+ sync, remote boards, and agents working cloud board tasks while no laptop
576
+ is on.
577
+
578
+ - **Reaching it.** People open its UI on an origin of its own
579
+ (`https://<id>.run.…`), which the cloud forwards to the daemon.
580
+ - **Sandbox mode.** The cloud sets `KRAFTWERK_PUBLIC_ORIGIN` to that
581
+ origin, and the daemon then runs in sandbox mode (`server/sandbox.ts`):
582
+ - Everyone coming in from outside signs in with their cloud account,
583
+ whatever `users:` says, browser or not. The sign-in returns to the
584
+ public origin, starting at the cloud as the browser reaches it
585
+ (`KRAFTWERK_PUBLIC_CLOUD_URL`, set when the sandbox reaches the cloud at
586
+ another address).
587
+ - A Host without a workspace in it reaches the sandbox's one workspace.
588
+ - Only what runs inside the sandbox on loopback (its agents' CLI) is the
589
+ machine's own shell.
590
+
565
591
  ### kraftwerk sync: the workspace's files in the cloud
566
592
 
567
593
  In cloud mode a workspace's history can live in its own repository in
@@ -573,12 +599,33 @@ to a config), so there is no token to paste and no credential helper.
573
599
  Workspaces made on the platform start with it. For one you started locally,
574
600
  switch it to cloud, then on the **Git** page click *set up kraftwerk sync*
575
601
  (`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
602
+ `autosync: sync` every 60 seconds, the remote, a first commit, a push.
603
+
604
+ `autosync: sync` is the simple sync: every interval kraftwerk commits what
605
+ changed under the synced paths (as the account the machine is linked to),
606
+ takes the others' commits in and pushes — nobody commits, pulls or merges by
607
+ hand. When two people changed the same file at once, the version that
608
+ reached the cloud first stays, and the other lands beside it as
609
+ `name.konflikt-<handle>.ext`, committed too, so nothing is lost. The Git page
610
+ lists those copies on every machine until someone deletes them:
611
+
612
+ ```yaml
613
+ git:
614
+ autosync: sync # off | pull | push | sync
615
+ interval: 60
616
+ ```
617
+
618
+ A remote of your own
577
619
  (GitHub, GitLab, a server in-house) is expert mode: kraftwerk never replaces
578
620
  it, and the Git page says which of the two a workspace uses
579
621
  (*managed by kraftwerk* or *own git provider · expert mode*) and shows the
580
622
  remote's address.
581
623
 
624
+ A workspace deleted on kraftwerk cloud (by its owner or an admin) stays on
625
+ your machine with all its files: the mode chip says *cloud · deleted*, and
626
+ switching it to local keeps you working. Switching it to cloud again gives it
627
+ a fresh id — the old one is never used again.
628
+
582
629
  ### This machine in the kraftwerk cloud
583
630
 
584
631
  The kraftwerk cloud is the `~/.kraftwerk` registry made reachable over the
@@ -1269,6 +1316,17 @@ the model via ACP session options and the thinking budget via
1269
1316
  are created and edited in the UI, or by editing the files, since the
1270
1317
  definition is read fresh for each new session.
1271
1318
 
1319
+
1320
+ **Told at once.** A task on a cloud board handed to you by someone else
1321
+ lands in the bell of the workspace on your machines — and as a browser
1322
+ notification and on a paired phone — within a fraction of a second: the
1323
+ cloud pokes the machine over its event stream (`/api/machines/stream`, held
1324
+ by every daemon connected to the cloud, remote access or not), the daemon
1325
+ fetches what waits and acknowledges it; a poke missed while offline comes
1326
+ with the next heartbeat. A task for an agent in a work column wakes that
1327
+ agent on the machine that has it, as a local board does — one machine
1328
+ claims it, so clones never both start. The agent works it with
1329
+ `npx kraftwerk tasks … --board @<board>`.
1272
1330
  ### Repositories
1273
1331
 
1274
1332
  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.`;
@@ -68,6 +68,8 @@ export interface MachineWorkspace {
68
68
  name: string;
69
69
  slug: string;
70
70
  root?: string;
71
+ /** Who hosts its git remote: kraftwerk sync, an own provider ("custom"), or none yet. */
72
+ git?: "kraftwerk" | "custom" | "none";
71
73
  }
72
74
  export interface Credentials {
73
75
  id: string;
@@ -82,6 +84,8 @@ export interface RegisterResponse {
82
84
  /** The claiming account's uuid and handle (clouds before 0.97 send neither). */
83
85
  accountId?: string | null;
84
86
  accountHandle?: string | null;
87
+ /** Reported ws_ ids deleted in the cloud (clouds before 0.102 send none). */
88
+ deletedWorkspaces?: string[];
85
89
  }
86
90
  export interface HeartbeatResponse {
87
91
  ok: boolean;
@@ -90,6 +94,9 @@ export interface HeartbeatResponse {
90
94
  accountId?: string | null;
91
95
  accountHandle?: string | null;
92
96
  claimCode: string | null;
97
+ deletedWorkspaces?: string[];
98
+ /** Events waiting at /api/machines/events (clouds before 0.102 send none). */
99
+ events?: number;
93
100
  }
94
101
  /** A person the cloud vouches for: the account's uuid (the same on every machine), email and handle. */
95
102
  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;
@@ -107,6 +128,8 @@ export declare function remoteAuthEnv(base?: NodeJS.ProcessEnv): NodeJS.ProcessE
107
128
  export declare const literal: (p: string) => string;
108
129
  /** Repo root for a directory, or null when it is not inside a git repo. */
109
130
  export declare function repoRootFor(dir: string): Promise<string | null>;
131
+ /** The workspace's remote URL (its git block's remote), credentials cut out; undefined without git, a repo or that remote. */
132
+ export declare function gitRemoteUrl(): Promise<string | undefined>;
110
133
  /** Label for a porcelain code, using whichever half is set. */
111
134
  export declare function label(code: string): string;
112
135
  /** Parse `git status --porcelain=v1 -z`, which NUL-separates and doubles up on renames and copies. */
@@ -145,6 +168,10 @@ export declare function gitCommit(paths: string[], message: string): Promise<{
145
168
  error?: string;
146
169
  committed?: number;
147
170
  }>;
171
+ export declare function setSyncAuthor(fn: () => {
172
+ name: string;
173
+ email: string;
174
+ } | null): void;
148
175
  export declare function gitFetch(): Promise<{
149
176
  ok: boolean;
150
177
  error?: string;
@@ -169,3 +196,10 @@ export declare function gitPush(): Promise<{
169
196
  export declare function startGitSync(): void;
170
197
  /** Stop the current workspace's background sync (the workspace closes). A tick in flight finishes, then stops. */
171
198
  export declare function stopGitSync(): void;
199
+ /** `knowledge/a.konflikt-ben-2.md` → { path: knowledge/a.md, by: ben }, or null when it is not a copy. */
200
+ export declare function parseConflictCopy(copy: string): {
201
+ path: string;
202
+ by: string;
203
+ } | null;
204
+ /** `notes/preise.md` → `notes/preise.konflikt-anna.md`, numbered while taken. */
205
+ 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
@@ -212,6 +219,14 @@ async function openRepo() {
212
219
  return { cfg, error: `${project.root} is not inside a git repository.` };
213
220
  return { repo: { cfg, project, repoRoot } };
214
221
  }
222
+ /** The workspace's remote URL (its git block's remote), credentials cut out; undefined without git, a repo or that remote. */
223
+ export async function gitRemoteUrl() {
224
+ const { repo } = await openRepo();
225
+ if (!repo)
226
+ return undefined;
227
+ const r = await git(["remote", "get-url", repo.cfg.remote], repo.repoRoot);
228
+ return r.ok && r.stdout.trim() ? withoutCredentials(r.stdout.trim()) : undefined;
229
+ }
215
230
  /**
216
231
  * The checked-out branch, or why it cannot be synced: a detached HEAD, or a
217
232
  * configured branch that is not the one checked out. Without the second
@@ -374,6 +389,7 @@ const gitState = perWorkspace(() => ({
374
389
  lastPull: undefined,
375
390
  lastPush: undefined,
376
391
  lastError: undefined,
392
+ lastAutoCommit: undefined,
377
393
  timer: null,
378
394
  ticking: false,
379
395
  lastRun: 0,
@@ -455,6 +471,7 @@ export async function gitStatus(fresh = false) {
455
471
  lastPull: gitState().lastPull,
456
472
  lastPush: gitState().lastPush,
457
473
  lastError: gitState().lastError,
474
+ ...(gitState().lastAutoCommit ? { lastAutoCommit: gitState().lastAutoCommit } : {}),
458
475
  };
459
476
  // A failed status (a stale index.lock, a timeout on a huge untracked tree)
460
477
  // must not read as "workspace clean": with no file list the commit endpoint
@@ -477,12 +494,14 @@ export async function gitStatus(fresh = false) {
477
494
  const scopeError = scope.wholeRepo
478
495
  ? "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
496
  : undefined;
497
+ const conflicts = repo.cfg.autosync === "sync" ? await conflictCopies(repoRoot) : [];
480
498
  const value = {
481
499
  ...base,
482
500
  error: head.error ?? scopeError,
483
501
  files: [...syncable, ...blocked.slice(0, MAX_BLOCKED)],
484
502
  blockedHidden: blockedHidden || undefined,
485
503
  scope: scope.include,
504
+ ...(conflicts.length ? { conflicts } : {}),
486
505
  };
487
506
  // A commit that finished while this status was running already emptied
488
507
  // the cache; caching the pre-commit list on top of that would show the
@@ -541,7 +560,29 @@ export function capDiff(diff) {
541
560
  export function gitCommit(paths, message) {
542
561
  return serial(() => commitNow(paths, message));
543
562
  }
544
- async function commitNow(paths, message) {
563
+ /**
564
+ * Who a commit is by. A commit by hand is git's own user (its config); one
565
+ * that kraftwerk makes by itself (`autosync: sync`) is by the account this
566
+ * machine is linked to, when the daemon knows one (setSyncAuthor) — else
567
+ * git's user. With no git user configured at all, the machine's identity
568
+ * stands in, so a commit never fails on "Please tell me who you are".
569
+ */
570
+ let syncAuthor = () => null;
571
+ export function setSyncAuthor(fn) {
572
+ syncAuthor = fn;
573
+ }
574
+ async function authorEnv(repoRoot, who) {
575
+ const pick = who === "sync" ? syncAuthor() : null;
576
+ if (pick)
577
+ return { GIT_AUTHOR_NAME: pick.name, GIT_AUTHOR_EMAIL: pick.email, GIT_COMMITTER_NAME: pick.name, GIT_COMMITTER_EMAIL: pick.email };
578
+ if ((await git(["config", "user.email"], repoRoot)).stdout.trim())
579
+ return {};
580
+ const id = await readIdentity().catch(() => null);
581
+ const name = id?.handle || "kraftwerk";
582
+ const email = `${name}@${(id?.machine || "kraftwerk").replace(/[^A-Za-z0-9.-]+/g, "-")}.kraftwerk`;
583
+ return { GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_NAME: name, GIT_COMMITTER_EMAIL: email };
584
+ }
585
+ async function commitNow(paths, message, author = "git") {
545
586
  const { repo, error } = await openRepo();
546
587
  if (!repo)
547
588
  return { ok: false, error };
@@ -583,7 +624,7 @@ async function commitNow(paths, message) {
583
624
  return { ok: false, error: add.stderr || "git add failed" };
584
625
  }
585
626
  }
586
- const commit = await git(["commit", "-m", text, "--", ...specs], repoRoot);
627
+ const commit = await git(["commit", "-m", text, "--", ...specs], repoRoot, LOCAL_TIMEOUT, await authorEnv(repoRoot, author));
587
628
  if (!commit.ok) {
588
629
  let error = commit.stderr || commit.stdout.trim() || "git commit failed";
589
630
  if (ours.length) {
@@ -600,8 +641,8 @@ async function commitNow(paths, message) {
600
641
  return { ok: false, error };
601
642
  }
602
643
  touched();
603
- // With `autosync: push` a commit should not sit here until the next interval.
604
- if (repo.cfg.autosync === "push")
644
+ // With `autosync: push` or `sync` a commit should not sit here until the next interval.
645
+ if (author === "git" && (repo.cfg.autosync === "push" || repo.cfg.autosync === "sync"))
605
646
  syncSoon();
606
647
  return { ok: true, committed: paths.length };
607
648
  }
@@ -765,6 +806,10 @@ async function tick() {
765
806
  }
766
807
  }
767
808
  async function sync(repo) {
809
+ if (repo.cfg.autosync === "sync") {
810
+ await syncNow(repo);
811
+ return;
812
+ }
768
813
  const fetched = await gitFetch();
769
814
  if (!fetched.ok || repo.cfg.autosync === "off")
770
815
  return;
@@ -792,3 +837,178 @@ async function sync(repo) {
792
837
  return;
793
838
  await gitPush();
794
839
  }
840
+ /* ---------- autosync: sync ---------- */
841
+ /** How many conflict copies the status lists. */
842
+ const MAX_CONFLICTS = 20;
843
+ const COPY_MARK = ".konflikt-";
844
+ /** `knowledge/a.konflikt-ben-2.md` → { path: knowledge/a.md, by: ben }, or null when it is not a copy. */
845
+ export function parseConflictCopy(copy) {
846
+ const slash = copy.lastIndexOf("/") + 1;
847
+ const name = copy.slice(slash);
848
+ const i = name.lastIndexOf(COPY_MARK);
849
+ if (i <= 0)
850
+ return null;
851
+ const rest = name.slice(i + COPY_MARK.length);
852
+ const dot = rest.indexOf(".");
853
+ const tag = dot >= 0 ? rest.slice(0, dot) : rest;
854
+ if (!/^[a-z0-9_-]+$/.test(tag))
855
+ return null;
856
+ return { path: copy.slice(0, slash) + name.slice(0, i) + (dot >= 0 ? rest.slice(dot) : ""), by: tag.replace(/-\d+$/, "") };
857
+ }
858
+ /** The conflict copies in the work tree, newest first (their files' times). */
859
+ async function conflictCopies(repoRoot) {
860
+ const r = await git(["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", `*${COPY_MARK}*`], repoRoot);
861
+ if (!r.ok)
862
+ return [];
863
+ const out = [];
864
+ for (const copy of r.stdout.split("\0").filter(Boolean)) {
865
+ const parsed = parseConflictCopy(copy);
866
+ if (!parsed)
867
+ continue;
868
+ let at = "";
869
+ try {
870
+ at = statSync(path.join(repoRoot, copy)).mtime.toISOString();
871
+ }
872
+ catch {
873
+ continue; // deleted, not committed yet
874
+ }
875
+ out.push({ path: parsed.path, copy, by: parsed.by, at });
876
+ }
877
+ return out.sort((a, b) => b.at.localeCompare(a.at)).slice(0, MAX_CONFLICTS);
878
+ }
879
+ /** `notes/preise.md` → `notes/preise.konflikt-anna.md`, numbered while taken. */
880
+ export function conflictPath(file, handle, taken) {
881
+ const dir = file.includes("/") ? file.slice(0, file.lastIndexOf("/") + 1) : "";
882
+ const name = file.slice(dir.length);
883
+ const dot = name.lastIndexOf(".");
884
+ const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];
885
+ const tag = (handle || "lokal").toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "lokal";
886
+ for (let n = 1;; n++) {
887
+ const p = `${dir}${stem}.konflikt-${tag}${n > 1 ? `-${n}` : ""}${ext}`;
888
+ if (!taken(p))
889
+ return p;
890
+ }
891
+ }
892
+ /** A blob of `rev` written to a file in the work tree, bytes as they are. */
893
+ function blobToFile(repoRoot, rev, file) {
894
+ return new Promise((resolve) => {
895
+ const child = spawn("git", ["cat-file", "blob", rev], { cwd: repoRoot, env: gitEnv() });
896
+ const out = createWriteStream(path.join(repoRoot, file));
897
+ child.stdout.pipe(out);
898
+ child.once("error", () => resolve(false));
899
+ child.once("close", (code) => out.end(() => resolve(code === 0)));
900
+ });
901
+ }
902
+ const lines = (r) => (r.ok ? r.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : []);
903
+ /**
904
+ * One round of kraftwerk sync: commit what changed under the synced roots,
905
+ * fetch, take the remote's commits (fast-forward, or a merge where the
906
+ * remote wins and our side of every file both changed is kept beside it),
907
+ * push. Each step queues with the others (serial), so a click on the git
908
+ * screen never meets a half-done round.
909
+ */
910
+ async function syncNow(repo) {
911
+ const st0 = await gitStatus(true);
912
+ if (st0.error || !st0.repoRoot)
913
+ return;
914
+ const changed = (st0.files ?? []).filter((f) => f.syncable).map((f) => f.path);
915
+ if (changed.length) {
916
+ const id = await readIdentity().catch(() => null);
917
+ const shown = changed.length <= 3 ? changed.join(", ") : `${changed.slice(0, 3).join(", ")} and ${changed.length - 3} more`;
918
+ const msg = `kraftwerk sync: ${shown}${id ? ` (${id.handle}@${id.machine})` : ""}`;
919
+ const c = await serial(() => commitNow(changed, msg, "sync"));
920
+ if (c.ok)
921
+ gitState().lastAutoCommit = new Date().toISOString();
922
+ else
923
+ gitState().lastError = c.error;
924
+ }
925
+ if (!(await gitFetch()).ok)
926
+ return;
927
+ const st = await gitStatus(true);
928
+ if (st.error || !st.repoRoot)
929
+ return;
930
+ if (st.upstream && st.behind) {
931
+ const merged = st.ahead ? await serial(() => mergeTheirs(repo, st.upstream)) : await gitPull();
932
+ if (!merged.ok)
933
+ return;
934
+ }
935
+ const after = await gitStatus(true);
936
+ if (after.error)
937
+ return;
938
+ if (!after.upstream || after.ahead)
939
+ await gitPush();
940
+ }
941
+ /**
942
+ * Merge the remote's branch, the remote winning: `-X theirs` settles the
943
+ * hunks both sides touched, and what that cannot (one side deleted, the other
944
+ * changed) takes the remote's side by hand. Then every file both sides
945
+ * changed whose result is not our version gets our version beside it, as a
946
+ * second commit. Only the remote's history is taken as it is; ours is kept
947
+ * in full — in history, and in the copies.
948
+ */
949
+ async function mergeTheirs(repo, upstream) {
950
+ const { repoRoot } = repo;
951
+ const fail = (error) => {
952
+ gitState().lastError = error;
953
+ touched();
954
+ return { ok: false, error };
955
+ };
956
+ const ours = (await git(["rev-parse", "HEAD"], repoRoot)).stdout.trim();
957
+ const base = (await git(["merge-base", "HEAD", upstream], repoRoot)).stdout.trim();
958
+ if (!ours || !base)
959
+ return fail("kraftwerk sync: the local and remote histories share nothing — merge them in a terminal once");
960
+ const mine = new Set(lines(await git(["diff", "--name-only", "--no-renames", base, ours], repoRoot)));
961
+ const both = lines(await git(["diff", "--name-only", "--no-renames", base, upstream], repoRoot)).filter((p) => mine.has(p));
962
+ const env = await authorEnv(repoRoot, "sync");
963
+ const msg = "kraftwerk sync: the remote's changes taken in (where both changed a file, the remote's version wins)";
964
+ const m = await git(["merge", "--no-edit", "--no-ff", "-X", "theirs", "-m", msg, upstream], repoRoot, NET_TIMEOUT, env);
965
+ if (!m.ok) {
966
+ const unmerged = lines(await git(["diff", "--name-only", "--diff-filter=U"], repoRoot));
967
+ if (unmerged.length === 0) {
968
+ await git(["merge", "--abort"], repoRoot);
969
+ return fail(`kraftwerk sync could not merge: ${m.stderr || m.stdout.trim() || "unknown error"}`);
970
+ }
971
+ for (const p of unmerged) {
972
+ const stages = lines(await git(["ls-files", "-u", "--", literal(p)], repoRoot)).map((l) => l.split(/\s+/)[2]);
973
+ const r = stages.includes("3")
974
+ ? await git(["checkout", "--theirs", "--", literal(p)], repoRoot).then(() => git(["add", "--", literal(p)], repoRoot))
975
+ : await git(["rm", "-q", "--", literal(p)], repoRoot);
976
+ if (!r.ok) {
977
+ await git(["merge", "--abort"], repoRoot);
978
+ return fail(`kraftwerk sync could not settle ${p}: ${r.stderr}`);
979
+ }
980
+ }
981
+ const done = await git(["commit", "--no-edit", "-m", msg], repoRoot, LOCAL_TIMEOUT, env);
982
+ if (!done.ok) {
983
+ await git(["merge", "--abort"], repoRoot);
984
+ return fail(`kraftwerk sync could not finish the merge: ${done.stderr || done.stdout.trim()}`);
985
+ }
986
+ }
987
+ // Our side of each file both changed, where the result is not it — named after the account when the daemon knows it.
988
+ const id = await readIdentity().catch(() => null);
989
+ const who = syncAuthor()?.name || id?.handle || "";
990
+ const kept = [];
991
+ const at = new Date().toISOString();
992
+ for (const p of both) {
993
+ const oursBlob = (await git(["rev-parse", "--verify", "-q", `${ours}:${p}`], repoRoot)).stdout.trim();
994
+ if (!oursBlob)
995
+ continue; // we deleted it: nothing of ours to keep
996
+ const now = (await git(["rev-parse", "--verify", "-q", `HEAD:${p}`], repoRoot)).stdout.trim();
997
+ if (now === oursBlob)
998
+ continue;
999
+ const copy = conflictPath(p, who, (c) => existsSync(path.join(repoRoot, c)));
1000
+ if (!(await blobToFile(repoRoot, oursBlob, copy)))
1001
+ continue;
1002
+ if ((await git(["add", "--", literal(copy)], repoRoot)).ok)
1003
+ kept.push({ path: p, copy, by: who, at });
1004
+ }
1005
+ if (kept.length) {
1006
+ 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);
1007
+ if (!c.ok)
1008
+ return fail(`kraftwerk sync kept copies but could not commit them: ${c.stderr || c.stdout.trim()}`);
1009
+ }
1010
+ gitState().lastPull = at;
1011
+ gitState().lastError = undefined;
1012
+ touched();
1013
+ return { ok: true };
1014
+ }
@@ -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
  }