robisie 0.2.2 → 0.3.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.
@@ -13832,6 +13832,9 @@ var init_types = __esm({
13832
13832
  // src/lib/db/schema.ts
13833
13833
  var schema_exports = {};
13834
13834
  __export2(schema_exports, {
13835
+ cliInstallations: () => cliInstallations,
13836
+ cliKeyPairs: () => cliKeyPairs,
13837
+ deviceAuthorizations: () => deviceAuthorizations,
13835
13838
  emailFailures: () => emailFailures,
13836
13839
  gdprAuditLog: () => gdprAuditLog,
13837
13840
  jobs: () => jobs,
@@ -13858,7 +13861,7 @@ __export2(schema_exports, {
13858
13861
  userProfiles: () => userProfiles,
13859
13862
  users: () => users
13860
13863
  });
13861
- var users, jobs, plugins, userPlugins, monitoredChannels, subscriptions, products, userProfiles, emailFailures, gdprAuditLog, storageCleanupQueue, bytea, tsvector, memoryDocuments, memoryChunks, plannerProjects, plannerReviewPolicies, plannerTracks, plannerTasks, stripeEvents, userMcpKeys, plannerWebhookSubscriptions, plannerTaskStatusEvents, plannerLimitEvents, mcpRateLimitWindows, licenseUsageReadings, licenseUsageAlerts;
13864
+ var users, jobs, plugins, userPlugins, monitoredChannels, subscriptions, products, userProfiles, emailFailures, gdprAuditLog, storageCleanupQueue, bytea, tsvector, memoryDocuments, memoryChunks, plannerProjects, plannerReviewPolicies, plannerTracks, plannerTasks, stripeEvents, userMcpKeys, cliInstallations, deviceAuthorizations, cliKeyPairs, plannerWebhookSubscriptions, plannerTaskStatusEvents, plannerLimitEvents, mcpRateLimitWindows, licenseUsageReadings, licenseUsageAlerts;
13862
13865
  var init_schema2 = __esm({
13863
13866
  "src/lib/db/schema.ts"() {
13864
13867
  "use strict";
@@ -14332,6 +14335,51 @@ var init_schema2 = __esm({
14332
14335
  index("idx_user_mcp_keys_user").on(table.userId)
14333
14336
  ]
14334
14337
  );
14338
+ cliInstallations = pgTable("cli_installations", {
14339
+ id: uuid("id").primaryKey().defaultRandom(),
14340
+ userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
14341
+ displayName: text("display_name"),
14342
+ createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).notNull().defaultNow(),
14343
+ revokedAt: timestamp("revoked_at", { withTimezone: true, mode: "date" })
14344
+ }, (table) => [index("idx_cli_installations_user").on(table.userId)]);
14345
+ deviceAuthorizations = pgTable("device_authorizations", {
14346
+ id: uuid("id").primaryKey().defaultRandom(),
14347
+ deviceCodeHash: text("device_code_hash").notNull().unique(),
14348
+ userCodeHash: text("user_code_hash").notNull().unique(),
14349
+ clientId: text("client_id").notNull(),
14350
+ scope: text("scope").notNull(),
14351
+ installationHint: uuid("installation_hint"),
14352
+ displayName: text("display_name"),
14353
+ state: text("state", { enum: ["pending", "approved", "denied", "consumed", "expired"] }).notNull().default("pending"),
14354
+ ownerUserId: text("owner_user_id").references(() => users.id, { onDelete: "cascade" }),
14355
+ installationId: uuid("installation_id").references(() => cliInstallations.id, { onDelete: "cascade" }),
14356
+ approvedSessionId: text("approved_session_id"),
14357
+ reauthAt: timestamp("reauth_at", { withTimezone: true, mode: "date" }),
14358
+ intervalS: integer("interval_s").notNull().default(5),
14359
+ lastPolledAt: timestamp("last_polled_at", { withTimezone: true, mode: "date" }),
14360
+ pollCount: integer("poll_count").notNull().default(0),
14361
+ createdIpHash: text("created_ip_hash").notNull(),
14362
+ createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).notNull().defaultNow(),
14363
+ expiresAt: timestamp("expires_at", { withTimezone: true, mode: "date" }).notNull().default(sql`now() + interval '600 seconds'`),
14364
+ decidedAt: timestamp("decided_at", { withTimezone: true, mode: "date" }),
14365
+ consumedAt: timestamp("consumed_at", { withTimezone: true, mode: "date" })
14366
+ }, (table) => [
14367
+ index("idx_device_authorizations_active_ip").on(table.createdIpHash, table.expiresAt).where(sql`${table.state} = 'pending'`),
14368
+ index("idx_device_authorizations_owner").on(table.ownerUserId)
14369
+ ]);
14370
+ cliKeyPairs = pgTable("cli_key_pairs", {
14371
+ pairId: uuid("pair_id").primaryKey(),
14372
+ installationId: uuid("installation_id").notNull().references(() => cliInstallations.id, { onDelete: "cascade" }),
14373
+ userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
14374
+ workerKeyId: uuid("worker_key_id").notNull().unique().references(() => userMcpKeys.id, { onDelete: "cascade" }),
14375
+ reviewKeyId: uuid("review_key_id").notNull().unique().references(() => userMcpKeys.id, { onDelete: "cascade" }),
14376
+ issuedAt: timestamp("issued_at", { withTimezone: true, mode: "date" }).notNull().defaultNow(),
14377
+ confirmedAt: timestamp("confirmed_at", { withTimezone: true, mode: "date" }),
14378
+ revokedAt: timestamp("revoked_at", { withTimezone: true, mode: "date" })
14379
+ }, (table) => [
14380
+ index("idx_cli_key_pairs_installation").on(table.installationId),
14381
+ index("idx_cli_key_pairs_user").on(table.userId)
14382
+ ]);
14335
14383
  plannerWebhookSubscriptions = pgTable(
14336
14384
  "planner_webhook_subscriptions",
14337
14385
  {
@@ -37577,7 +37625,7 @@ var init_constants = __esm({
37577
37625
  "packages/client/src/constants.ts"() {
37578
37626
  "use strict";
37579
37627
  PACKAGE_NAME = "robisie";
37580
- PACKAGE_VERSION = "0.2.2";
37628
+ PACKAGE_VERSION = "0.3.0";
37581
37629
  SUPPORTED_CONTRACT_MAJOR = 1;
37582
37630
  DEFAULT_ORIGIN = "https://robisie.app";
37583
37631
  MCP_SERVER_NAME = "robisie";
@@ -53343,7 +53391,7 @@ function finishTickState(state, outcome, tick, at3, facts = {}) {
53343
53391
  const reason = observed ? `runtime=failed outcome=${outcome} loaded=${facts.observedLoaded ?? "UNKNOWN"} tick=${tick}` : `outcome=failed tick=${tick}`;
53344
53392
  return { ...state, confirmed: void 0, breaker: { ...state.confirmed, at: at3, reason } };
53345
53393
  }
53346
- function readLoadedSha(repo, git2 = defaultGit) {
53394
+ function readLoadedSha(repo, git2 = quietGit) {
53347
53395
  try {
53348
53396
  const head = git2(["rev-parse", "HEAD"], repo);
53349
53397
  const dirty = git2(["status", "--porcelain", "-z", "--", ":(glob)maszynista/*.ts", "services", "src/lib"], repo);
@@ -53355,9 +53403,15 @@ function readLoadedSha(repo, git2 = defaultGit) {
53355
53403
  function mainRefLockRace(error48) {
53356
53404
  return [record6(error48).stderr, error48 instanceof Error ? error48.message : String(error48)].some((diagnostic) => typeof diagnostic === "string" && diagnostic.includes("cannot lock ref 'refs/remotes/origin/main'"));
53357
53405
  }
53358
- function defaultGit(args, cwd = process.cwd(), timeoutMs = 6e4) {
53406
+ function runGit(args, cwd = process.cwd(), timeoutMs = 6e4, quiet = false) {
53359
53407
  try {
53360
- const output = (0, import_node_child_process4.execFileSync)("git", args, { cwd, encoding: "utf8", timeout: timeoutMs, maxBuffer: 20 * 1024 * 1024 });
53408
+ const output = (0, import_node_child_process4.execFileSync)("git", args, {
53409
+ cwd,
53410
+ encoding: "utf8",
53411
+ timeout: timeoutMs,
53412
+ maxBuffer: 20 * 1024 * 1024,
53413
+ stdio: quiet ? ["ignore", "pipe", "ignore"] : void 0
53414
+ });
53361
53415
  return args.includes("-z") ? output : output.trim();
53362
53416
  } catch (error48) {
53363
53417
  throw Object.assign(
@@ -54079,7 +54133,7 @@ async function runHostActivation(input, deps = {}) {
54079
54133
  deps.log?.(`ff ${head.slice(0, 8)}\u2192${target.slice(0, 8)} ${label2} brud=${porcelainPaths(porcelain).length} zachowany`);
54080
54134
  return endRefusal({ code: "activate", target });
54081
54135
  }
54082
- var import_node_child_process4, import_node_crypto6, import_node_fs11, import_node_path13, STATE_FILE, MODE_FILE, BREAKER_WINDOW_TICKS, SMOKE_TIMEOUT_MS, ACTIVATION_RESERVE_MS, loadableExtensions, dependencyKeys;
54136
+ var import_node_child_process4, import_node_crypto6, import_node_fs11, import_node_path13, STATE_FILE, MODE_FILE, BREAKER_WINDOW_TICKS, SMOKE_TIMEOUT_MS, ACTIVATION_RESERVE_MS, loadableExtensions, dependencyKeys, defaultGit, quietGit;
54083
54137
  var init_host_activation = __esm({
54084
54138
  "maszynista/host-activation.ts"() {
54085
54139
  "use strict";
@@ -54096,6 +54150,8 @@ var init_host_activation = __esm({
54096
54150
  ACTIVATION_RESERVE_MS = 15e4;
54097
54151
  loadableExtensions = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".mjs", ".cjs", ".json"]);
54098
54152
  dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "overrides", "resolutions"];
54153
+ defaultGit = (args, cwd, timeoutMs) => runGit(args, cwd, timeoutMs);
54154
+ quietGit = (args, cwd, timeoutMs) => runGit(args, cwd, timeoutMs, true);
54099
54155
  }
54100
54156
  });
54101
54157
 
@@ -76326,7 +76382,7 @@ function callLocalReceiver(input, dir) {
76326
76382
  "--disable-web-search",
76327
76383
  "--verbatim",
76328
76384
  "--reasoning-effort",
76329
- "none"
76385
+ "low"
76330
76386
  ];
76331
76387
  const result = (0, import_node_child_process7.spawnSync)("grok", args, { cwd: dir, env: localReceiverEnv(), encoding: "utf8", timeout: 18e4, maxBuffer: 256 * 1024 });
76332
76388
  if (result.error || result.status !== 0) throw result.error ?? new Error(`Grok exit=${result.status}`);
@@ -76335,7 +76391,7 @@ function callLocalReceiver(input, dir) {
76335
76391
  return { output: envelope.structuredOutput ?? null, invocation: {
76336
76392
  provider: "xai",
76337
76393
  actualModel: models[0],
76338
- effort: "none",
76394
+ effort: "low",
76339
76395
  exit: result.status,
76340
76396
  startedAt,
76341
76397
  finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -77319,7 +77375,7 @@ function completion(dir, claim, response, timestamp3, stop = "") {
77319
77375
  reason = `U\u017Cycia ${p.events.length}/${p.contract.min}; termin ${p.contract.deadline}; wyzwalacz: nowe zdarzenie lub deadline`;
77320
77376
  } else {
77321
77377
  const raw = record10(response), invocation = record10(raw.invocation), model = text6.parse(invocation.actualModel);
77322
- if (invocation.provider !== "xai" || !/^grok-/.test(model) || invocation.exit !== 0 || invocation.effort !== "none" || !(0, import_node_util6.isDeepStrictEqual)(Object.keys(record10(invocation.modelUsage)), [model]) || !at2.safeParse(invocation.startedAt).success || !at2.safeParse(invocation.finishedAt).success || !Array.isArray(invocation.command)) throw new Error("Brak rzeczywistego wywo\u0142ania Groka");
77378
+ if (invocation.provider !== "xai" || !/^grok-/.test(model) || invocation.exit !== 0 || invocation.effort !== "none" && invocation.effort !== "low" || !(0, import_node_util6.isDeepStrictEqual)(Object.keys(record10(invocation.modelUsage)), [model]) || !at2.safeParse(invocation.startedAt).success || !at2.safeParse(invocation.finishedAt).success || !Array.isArray(invocation.command)) throw new Error("Brak rzeczywistego wywo\u0142ania Groka");
77323
77379
  const results = validateLocalReceiver(raw.output, input);
77324
77380
  if (results.some((r) => r.verdict !== "PASS")) throw new Error(results.map((r) => `${r.index}: ${r.verdict}: ${r.reason}`).join("; "));
77325
77381
  const used = new Set(results.flatMap((r) => r.eventIds)), events = p.events.filter((e) => used.has(e.id));
@@ -78094,7 +78150,7 @@ var init_git_commit = __esm({
78094
78150
  });
78095
78151
 
78096
78152
  // packages/client/src/delivery-local.ts
78097
- function runGit(repo, args, input) {
78153
+ function runGit2(repo, args, input) {
78098
78154
  let options2;
78099
78155
  try {
78100
78156
  options2 = args[0] === "notes" && args.includes("add") ? gitCommitOptions(args, repo) : { args, env: process.env };
@@ -78116,12 +78172,12 @@ function gitText(run) {
78116
78172
  return (run.error?.message ?? (run.stderr.trim() || run.stdout.trim())).slice(0, OUTPUT_LIMIT);
78117
78173
  }
78118
78174
  function resolveCommit(repo, spec) {
78119
- const run = runGit(repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${spec}^{commit}`]);
78175
+ const run = runGit2(repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${spec}^{commit}`]);
78120
78176
  const sha5 = run.stdout.trim();
78121
78177
  return run.status === 0 && SHA_RE.test(sha5) ? sha5 : void 0;
78122
78178
  }
78123
78179
  function isAncestor2(repo, ancestor3, descendant) {
78124
- const run = runGit(repo, ["merge-base", "--is-ancestor", ancestor3, descendant]);
78180
+ const run = runGit2(repo, ["merge-base", "--is-ancestor", ancestor3, descendant]);
78125
78181
  if (run.status === 0) return true;
78126
78182
  if (run.status === 1) return false;
78127
78183
  return run;
@@ -78135,7 +78191,7 @@ function canonical2(value) {
78135
78191
  }
78136
78192
  function prepare(repo, input) {
78137
78193
  const target = typeof input?.target === "string" ? input.target : "";
78138
- const branch = runGit(repo, ["check-ref-format", "--branch", target]);
78194
+ const branch = runGit2(repo, ["check-ref-format", "--branch", target]);
78139
78195
  if (!target || target.startsWith("-") || branch.status !== 0 || branch.stdout.trim() !== target) {
78140
78196
  return { ok: false, reason: "invalid-target", message: `Nieprawid\u0142owa nazwa ga\u0142\u0119zi celu: ${JSON.stringify(target)}` };
78141
78197
  }
@@ -78148,7 +78204,7 @@ function prepare(repo, input) {
78148
78204
  }
78149
78205
  const taskSha = resolveCommit(repo, requested);
78150
78206
  if (taskSha !== requested) return { ok: false, reason: "invalid-task", message: `Commit zadania ${requested} nie istnieje w repozytorium.` };
78151
- const merge3 = runGit(repo, ["merge-tree", "--write-tree", "--name-only", "--no-messages", targetSha2, taskSha]);
78207
+ const merge3 = runGit2(repo, ["merge-tree", "--write-tree", "--name-only", "--no-messages", targetSha2, taskSha]);
78152
78208
  const lines2 = merge3.stdout.split("\n").filter(Boolean);
78153
78209
  const tree = lines2[0] ?? "";
78154
78210
  if (merge3.status === 1 && SHA_RE.test(tree)) {
@@ -78181,7 +78237,7 @@ function check4(repo, prepared, commands, options2 = {}) {
78181
78237
  return { ok: false, reason: "error", message: `Nie uda\u0142o si\u0119 utworzy\u0107 katalogu tymczasowego: ${error48 instanceof Error ? error48.message : String(error48)}`, results };
78182
78238
  }
78183
78239
  const worktree = (0, import_node_path28.join)(tmp, "wt");
78184
- const add2 = runGit(repo, ["worktree", "add", "--detach", "--quiet", worktree, prepared.taskSha]);
78240
+ const add2 = runGit2(repo, ["worktree", "add", "--detach", "--quiet", worktree, prepared.taskSha]);
78185
78241
  if (add2.status !== 0 || add2.error) {
78186
78242
  const outcome2 = { ok: false, reason: "error", message: `git worktree add nie powiod\u0142o si\u0119: ${gitText(add2)}`, results };
78187
78243
  return withCleanup(outcome2, removeWorktree(repo, tmp, worktree, false), tmp, worktree);
@@ -78197,14 +78253,14 @@ function check4(repo, prepared, commands, options2 = {}) {
78197
78253
  }
78198
78254
  function removeWorktree(repo, tmp, worktree, added) {
78199
78255
  const failed2 = [];
78200
- const remove = runGit(repo, ["worktree", "remove", "--force", worktree]);
78256
+ const remove = runGit2(repo, ["worktree", "remove", "--force", worktree]);
78201
78257
  if (added && (remove.status !== 0 || remove.error)) failed2.push({ step: "worktree-remove", message: gitText(remove) || `status=${remove.status}` });
78202
78258
  try {
78203
78259
  (0, import_node_fs25.rmSync)(tmp, { recursive: true, force: true });
78204
78260
  } catch (error48) {
78205
78261
  failed2.push({ step: "rm-tmp", message: error48 instanceof Error ? error48.message : String(error48) });
78206
78262
  }
78207
- const prune = runGit(repo, ["worktree", "prune"]);
78263
+ const prune = runGit2(repo, ["worktree", "prune"]);
78208
78264
  if (prune.status !== 0 || prune.error) failed2.push({ step: "worktree-prune", message: gitText(prune) || `status=${prune.status}` });
78209
78265
  return failed2;
78210
78266
  }
@@ -78237,7 +78293,7 @@ function runChecks(cwd, commands, timeoutMs, results) {
78237
78293
  return { ok: true, results };
78238
78294
  }
78239
78295
  function checkedOutIn(repo, ref) {
78240
- const list2 = runGit(repo, ["worktree", "list", "--porcelain", "-z"]);
78296
+ const list2 = runGit2(repo, ["worktree", "list", "--porcelain", "-z"]);
78241
78297
  if (list2.status !== 0) return list2;
78242
78298
  let path34;
78243
78299
  for (const field of list2.stdout.split("\0")) {
@@ -78261,7 +78317,7 @@ function deliver(repo, prepared) {
78261
78317
  if (!forward || prepared.mode !== "fast-forward") {
78262
78318
  return { ok: false, reason: "not-fast-forward", message: `Odmowa: ${taskSha} nie jest fast-forwardem ${prepared.target} (${targetSha2}). Zaktualizuj ga\u0142\u0105\u017A zadania o cel i powt\xF3rz.` };
78263
78319
  }
78264
- const symbolic = runGit(repo, ["symbolic-ref", "-q", ref]);
78320
+ const symbolic = runGit2(repo, ["symbolic-ref", "-q", ref]);
78265
78321
  if (symbolic.status === 0 && !symbolic.error) {
78266
78322
  return { ok: false, reason: "target-is-symbolic-ref", message: `Odmowa: ${prepared.target} jest aliasem (symbolic ref) do ${symbolic.stdout.trim()}; dostarcz do ga\u0142\u0119zi docelowej wprost.` };
78267
78323
  }
@@ -78273,7 +78329,7 @@ function deliver(repo, prepared) {
78273
78329
  if (before !== targetSha2) {
78274
78330
  return { ok: false, reason: "target-moved", message: `Odmowa: ${prepared.target} przesun\u0105\u0142 si\u0119 z ${targetSha2} na ${before ?? "(brak)"} po prepare; nic nie zmieniono.` };
78275
78331
  }
78276
- const merge3 = runGit(worktree, ["-c", `core.hooksPath=${import_node_os6.devNull}`, "merge", "--ff-only", "--no-autostash", "--no-overwrite-ignore", taskSha]);
78332
+ const merge3 = runGit2(worktree, ["-c", `core.hooksPath=${import_node_os6.devNull}`, "merge", "--ff-only", "--no-autostash", "--no-overwrite-ignore", taskSha]);
78277
78333
  const after2 = resolveCommit(repo, ref);
78278
78334
  if (after2 === taskSha) return { ok: true, moved: true, ref, from: targetSha2, to: taskSha };
78279
78335
  if (after2 === targetSha2) {
@@ -78283,7 +78339,7 @@ Od\u0142\xF3\u017C zmiany (git stash) albo cofnij je i pon\xF3w dostaw\u0119.` }
78283
78339
  }
78284
78340
  return { ok: false, reason: "target-moved", message: `Odmowa: ${prepared.target} po pr\xF3bie FF wskazuje ${after2 ?? "(brak)"} zamiast ${taskSha}; sprawd\u017A stan repozytorium.` };
78285
78341
  }
78286
- const update = runGit(repo, ["update-ref", "--no-deref", "-m", `robisie: dostawa local-ff ${taskSha}`, ref, taskSha, targetSha2]);
78342
+ const update = runGit2(repo, ["update-ref", "--no-deref", "-m", `robisie: dostawa local-ff ${taskSha}`, ref, taskSha, targetSha2]);
78287
78343
  if (update.status !== 0) {
78288
78344
  const now = resolveCommit(repo, ref);
78289
78345
  if (now !== targetSha2) {
@@ -78305,24 +78361,24 @@ function attachEvidence(repo, sha5, kind, evidence2) {
78305
78361
  }
78306
78362
  if (line2 === void 0) return { ok: false, reason: "error", message: "Dow\xF3d nie jest serializowalny do JSON." };
78307
78363
  const ref = `refs/notes/robisie/${kind}`;
78308
- const strategy = runGit(repo, ["config", `notes.robisie/${kind}.mergeStrategy`, "cat_sort_uniq"]);
78364
+ const strategy = runGit2(repo, ["config", `notes.robisie/${kind}.mergeStrategy`, "cat_sort_uniq"]);
78309
78365
  if (strategy.status !== 0) return { ok: false, reason: "error", message: `Ustawienie notes mergeStrategy nie powiod\u0142o si\u0119: ${gitText(strategy)}` };
78310
78366
  const existing = readEvidenceLines(repo, kind, sha5);
78311
78367
  if (!Array.isArray(existing)) return existing;
78312
78368
  if (existing.includes(line2)) return { ok: true, ref, sha: sha5, written: false };
78313
78369
  const body = [.../* @__PURE__ */ new Set([...existing, line2])].sort().join("\n") + "\n";
78314
- const write = runGit(repo, ["notes", `--ref=${ref}`, "add", "-f", "-F", "-", sha5], body);
78370
+ const write = runGit2(repo, ["notes", `--ref=${ref}`, "add", "-f", "-F", "-", sha5], body);
78315
78371
  if (write.status !== 0) return { ok: false, reason: "error", message: `git notes add nie powiod\u0142o si\u0119: ${gitText(write)}` };
78316
78372
  return { ok: true, ref, sha: sha5, written: true };
78317
78373
  }
78318
78374
  function readEvidenceLines(repo, kind, sha5) {
78319
78375
  const ref = `refs/notes/robisie/${kind}`;
78320
- const exists2 = runGit(repo, ["rev-parse", "--verify", "--quiet", ref]);
78376
+ const exists2 = runGit2(repo, ["rev-parse", "--verify", "--quiet", ref]);
78321
78377
  if (exists2.status === 1 && !exists2.error && !exists2.stderr.trim()) return [];
78322
78378
  if (exists2.status !== 0 || exists2.error) {
78323
78379
  return { ok: false, reason: "evidence-read-failed", message: `Odczyt ${ref} nie powi\xF3d\u0142 si\u0119: ${gitText(exists2) || `status=${exists2.status}`}` };
78324
78380
  }
78325
- const show = runGit(repo, ["notes", `--ref=${ref}`, "show", sha5]);
78381
+ const show = runGit2(repo, ["notes", `--ref=${ref}`, "show", sha5]);
78326
78382
  if (show.status === 0 && !show.error) return show.stdout.split("\n").filter(Boolean);
78327
78383
  if (show.status === 1 && !show.error && /^error: no note found for object [0-9a-f]+\.?$/.test(show.stderr.trim())) return [];
78328
78384
  return { ok: false, reason: "evidence-read-failed", message: `git notes show nie powiod\u0142o si\u0119: ${gitText(show) || `status=${show.status}`}` };
@@ -99,36 +99,26 @@ export function inputDirectory(config) {
99
99
  /** Reject links along the write path; do not change modes on user-owned directories. */
100
100
  function checkDirectory(directory, writing, configPath) {
101
101
  try {
102
- const parent = dirname(directory);
103
- if (parent !== directory)
104
- checkDirectory(parent, false, configPath);
102
+ let existing = directory;
105
103
  let stat;
106
- try {
107
- stat = lstatSync(directory);
108
- }
109
- catch (error) {
110
- if (!missing(error))
111
- throw error;
112
- if (!writing)
113
- return;
114
- let existing = parent;
115
- while (true) {
116
- try {
117
- lstatSync(existing);
118
- break;
119
- }
120
- catch (cause) {
121
- if (!missing(cause))
122
- throw cause;
123
- existing = dirname(existing);
124
- }
104
+ while (true) {
105
+ try {
106
+ stat = lstatSync(existing);
107
+ break;
108
+ }
109
+ catch (error) {
110
+ if (!missing(error) || dirname(existing) === existing)
111
+ throw error;
112
+ existing = dirname(existing);
125
113
  }
126
- accessSync(existing, constants.W_OK | constants.X_OK);
127
- return;
128
114
  }
129
- if (!stat.isDirectory() || stat.isSymbolicLink())
115
+ // inputDirectory canonicalizes stateDir; a changed realpath here means a link in the write path.
116
+ if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(existing) !== existing)
130
117
  throw problem(directory, configPath);
131
- accessSync(directory, constants.R_OK | constants.X_OK | (writing ? constants.W_OK : 0));
118
+ if (existing === directory)
119
+ accessSync(directory, constants.R_OK | constants.X_OK | (writing ? constants.W_OK : 0));
120
+ else if (writing)
121
+ accessSync(existing, constants.W_OK | constants.X_OK);
132
122
  }
133
123
  catch (error) {
134
124
  if (error instanceof RobisieError)
@@ -0,0 +1,29 @@
1
+ import { type Ctx } from "./context.js";
2
+ import { type LoginIo, type PairCopies } from "./device-login.js";
3
+ /** Replaceable like commands.ts `loginIo`: tests swap the clock and sleep, never the protocol. */
4
+ export declare const loginRuntime: {
5
+ io: Partial<LoginIo>;
6
+ };
7
+ /**
8
+ * J5 copies of A: the header in `~/.claude.json` (only where init installed it and it is still there) and the
9
+ * manifest login fields. `restore` writes back exactly the captured state and throws when the read-back differs.
10
+ */
11
+ export declare function pairCopies(ctx: Ctx): PairCopies;
12
+ /** `npx robisie login`; the manifest's installation_id is only a claim the server checks (§5.2). */
13
+ export declare function login(ctx: Ctx, options: {
14
+ wait: boolean;
15
+ timeoutSeconds?: number;
16
+ }): Promise<0 | 1 | 2>;
17
+ /** init without any key and without a terminal pairs instead of stopping at „Brak klucza” (§7.6). */
18
+ export declare function initNeedsLogin(ctx: Ctx, keyStdin: boolean): boolean;
19
+ /**
20
+ * Takes the installation lock, finishes an interrupted pair journal, and for a login installation hands the
21
+ * command A and B from the files instead of the environment (§7.3, §7.6). Installations never paired by
22
+ * login have no mutex file: creating one here would turn doctor into a writer of manual installations.
23
+ */
24
+ export declare function openInstallation(ctx: Ctx, command: "init" | "doctor" | "factory run"): Promise<{
25
+ ctx: Ctx;
26
+ release: (() => void) | null;
27
+ }>;
28
+ /** Releases the lock after the command; a failure is reported, the command's own result stands. */
29
+ export declare function closeInstallation(ctx: Ctx, release: () => void): void;
package/dist/login.js ADDED
@@ -0,0 +1,153 @@
1
+ import { existsSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { agentPaths, planAgent } from "./agents.js";
5
+ import { KEY_ENV, KEY_PATTERN } from "./constants.js";
6
+ import { RobisieError } from "./context.js";
7
+ import { acquireInstallationLock, deviceLogin, resumePairJournal } from "./device-login.js";
8
+ import { applyOp, capture } from "./fsops.js";
9
+ import { clientPaths, readKey, readManifest, refuseSymlink, writeManifest, writePrivate } from "./manifest.js";
10
+ /**
11
+ * CLI side of `npx robisie login` (CONTRACT.md §7.3 J5, §7.6): the copies of A outside the key files, the
12
+ * installation lock with journal recovery for init/doctor/factory run, and which keys those commands use.
13
+ */
14
+ const REVIEW_KEY_ENV = "ROBISIE_REVIEW_KEY";
15
+ /** Replaceable like commands.ts `loginIo`: tests swap the clock and sleep, never the protocol. */
16
+ export const loginRuntime = { io: {} };
17
+ function isRecord(value) {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+ /** The `~/.claude.json` entry init writes; Codex and OpenCode read A from ENV and keep no copy. */
21
+ function claudeOp(ctx, key) {
22
+ const [op] = planAgent(ctx, "claude", [], key);
23
+ if (!op || op.kind !== "json")
24
+ throw new Error("Plan instalacji Claude Code nie ma wpisu MCP.");
25
+ return op;
26
+ }
27
+ function recorded(manifest, op) {
28
+ return manifest?.entries.find((entry) => entry.kind === "json" && entry.path === op.path && isDeepStrictEqual(entry.keyPath, [...op.keyPath]));
29
+ }
30
+ function jsonValue(op) {
31
+ const bytes = capture(op.path).bytes;
32
+ if (bytes === null)
33
+ return null;
34
+ let cursor = JSON.parse(bytes.toString("utf8"));
35
+ for (const key of op.keyPath)
36
+ cursor = isRecord(cursor) && Object.hasOwn(cursor, key) ? cursor[key] : null;
37
+ return cursor ?? null;
38
+ }
39
+ /**
40
+ * J5 copies of A: the header in `~/.claude.json` (only where init installed it and it is still there) and the
41
+ * manifest login fields. `restore` writes back exactly the captured state and throws when the read-back differs.
42
+ */
43
+ export function pairCopies(ctx) {
44
+ const paths = clientPaths(agentPaths(ctx).clientDir);
45
+ const manifestText = () => {
46
+ refuseSymlink(paths.manifest);
47
+ return capture(paths.manifest).bytes?.toString("utf8") ?? null;
48
+ };
49
+ return {
50
+ capture: () => {
51
+ const op = claudeOp(ctx, "");
52
+ const state = { manifest: manifestText(), claude: null };
53
+ if (recorded(readManifest(paths.manifest), op))
54
+ state.claude = jsonValue(op);
55
+ return state;
56
+ },
57
+ apply: ({ key, installationId, pairId }) => {
58
+ const manifest = readManifest(paths.manifest);
59
+ const op = claudeOp(ctx, key);
60
+ const entries = [...(manifest?.entries ?? [])];
61
+ const prior = recorded(manifest, op);
62
+ if (prior && jsonValue(op) !== null)
63
+ entries[entries.indexOf(prior)] = Object.assign({}, prior, applyOp(op, prior, { backupDir: paths.backups }).entry);
64
+ writeManifest(paths.dir, {
65
+ agents: manifest?.agents ?? [], roleProviders: manifest?.roleProviders ?? null, entries,
66
+ installation_id: installationId, pair_id: pairId, credentialSource: "login",
67
+ });
68
+ },
69
+ restore: (captured) => {
70
+ // A journal written without copies never had them applied.
71
+ if (captured === null)
72
+ return;
73
+ const unknownState = new Error("Dziennik ma nieznany zapis kopii klucza A.");
74
+ if (!isRecord(captured) || !("claude" in captured))
75
+ throw unknownState;
76
+ const { manifest, claude } = captured;
77
+ if (manifest !== null && typeof manifest !== "string")
78
+ throw unknownState;
79
+ const op = claudeOp(ctx, "");
80
+ if (claude !== null)
81
+ applyOp({ ...op, value: claude }, recorded(readManifest(paths.manifest), op), { backupDir: paths.backups });
82
+ if (manifest === null) {
83
+ refuseSymlink(paths.manifest);
84
+ rmSync(paths.manifest, { force: true });
85
+ }
86
+ else
87
+ writePrivate(paths.dir, paths.manifest, manifest);
88
+ if (manifestText() !== manifest || (claude !== null && !isDeepStrictEqual(jsonValue(op), claude))) {
89
+ throw new Error("Odczyt kontrolny kopii klucza A nie zgadza się z dziennikiem.");
90
+ }
91
+ },
92
+ };
93
+ }
94
+ /** `npx robisie login`; the manifest's installation_id is only a claim the server checks (§5.2). */
95
+ export async function login(ctx, options) {
96
+ const installationHint = readManifest(clientPaths(agentPaths(ctx).clientDir).manifest)?.installation_id ?? null;
97
+ return deviceLogin(ctx, { ...options, installationHint, copies: pairCopies(ctx), io: loginRuntime.io });
98
+ }
99
+ /** init without any key and without a terminal pairs instead of stopping at „Brak klucza” (§7.6). */
100
+ export function initNeedsLogin(ctx, keyStdin) {
101
+ if (keyStdin || ctx.askSecret !== null || ctx.env[KEY_ENV]?.trim())
102
+ return false;
103
+ const dir = agentPaths(ctx).clientDir;
104
+ return !(readManifest(clientPaths(dir).manifest) && readKey(dir));
105
+ }
106
+ /**
107
+ * Takes the installation lock, finishes an interrupted pair journal, and for a login installation hands the
108
+ * command A and B from the files instead of the environment (§7.3, §7.6). Installations never paired by
109
+ * login have no mutex file: creating one here would turn doctor into a writer of manual installations.
110
+ */
111
+ export async function openInstallation(ctx, command) {
112
+ const dir = agentPaths(ctx).clientDir;
113
+ if (!existsSync(join(dir, "robisie.lock.sqlite")) && !existsSync(join(dir, "pair-journal.json")))
114
+ return { ctx, release: null };
115
+ const release = acquireInstallationLock(dir, command);
116
+ try {
117
+ await resumePairJournal(ctx, dir, pairCopies(ctx));
118
+ if (readManifest(clientPaths(dir).manifest)?.credentialSource !== "login")
119
+ return { ctx, release };
120
+ const key = readKey(dir);
121
+ const reviewKey = readKey(dir, "review-key");
122
+ if (!key || !reviewKey || !KEY_PATTERN.test(key) || !KEY_PATTERN.test(reviewKey)) {
123
+ throw new RobisieError("Klucze A i B tej instalacji są niekompletne albo uszkodzone.", "Uruchom `npx robisie login`.");
124
+ }
125
+ for (const [name, value] of [[KEY_ENV, key], [REVIEW_KEY_ENV, reviewKey]]) {
126
+ const stale = ctx.env[name]?.trim();
127
+ if (stale && stale !== value)
128
+ ctx.err(`Stara wartość ${name} w środowisku jest ignorowana — otwórz nowy terminal.`);
129
+ }
130
+ return { ctx: { ...ctx, env: { ...ctx.env, [KEY_ENV]: key, [REVIEW_KEY_ENV]: reviewKey } }, release };
131
+ }
132
+ catch (error) {
133
+ try {
134
+ release();
135
+ }
136
+ catch {
137
+ // The SQLite handle closes with the process; the first error is the one to act on.
138
+ }
139
+ throw error;
140
+ }
141
+ }
142
+ /** Releases the lock after the command; a failure is reported, the command's own result stands. */
143
+ export function closeInstallation(ctx, release) {
144
+ try {
145
+ release();
146
+ }
147
+ catch (error) {
148
+ if (!(error instanceof RobisieError))
149
+ throw error;
150
+ ctx.err(`✗ ${error.message}`);
151
+ ctx.err(`Następny krok: ${error.nextStep}`);
152
+ }
153
+ }
@@ -12,7 +12,13 @@ export interface Manifest {
12
12
  entries: Entry[];
13
13
  /** Kept raw so doctor and uninstall can still inspect entries when the map is damaged. */
14
14
  roleProviders?: unknown;
15
+ /** Set by `npx robisie login` (CONTRACT §7.3 J5, §7.6): A and B then come from the key files, never from ENV. */
16
+ installation_id?: string;
17
+ pair_id?: string;
18
+ credentialSource?: "login";
15
19
  }
20
+ /** The login fields a rewrite of the manifest must carry forward. */
21
+ export declare function loginFields(manifest: Manifest | null): Pick<Manifest, "installation_id" | "pair_id" | "credentialSource">;
16
22
  export declare const ROLE_IDS: readonly ["ceo", "builder", "quality"];
17
23
  export type RoleProviders = Record<RoleKind, AgentId>;
18
24
  export declare const ROLE_STEP = "U\u017Cyj pe\u0142nej jednolitej mapy: `npx robisie init --agent codex --role ceo=codex --role builder=codex --role quality=codex` (role: ceo, builder, quality; dostawcy: claude, codex, opencode).";
package/dist/manifest.js CHANGED
@@ -5,6 +5,12 @@ import { PACKAGE_VERSION } from "./constants.js";
5
5
  import { RobisieError, errorMessage, shellQuote } from "./context.js";
6
6
  import { isAgentId } from "./agents.js";
7
7
  import { freeCopyPath } from "./fsops.js";
8
+ /** The login fields a rewrite of the manifest must carry forward. */
9
+ export function loginFields(manifest) {
10
+ return manifest?.credentialSource === "login"
11
+ ? { installation_id: manifest.installation_id, pair_id: manifest.pair_id, credentialSource: "login" }
12
+ : {};
13
+ }
8
14
  export const ROLE_IDS = ["ceo", "builder", "quality"];
9
15
  export const ROLE_STEP = "Użyj pełnej jednolitej mapy: `npx robisie init --agent codex --role ceo=codex --role builder=codex --role quality=codex` (role: ceo, builder, quality; dostawcy: claude, codex, opencode).";
10
16
  /** Legacy single-provider installs have one unambiguous assignment; explicit null stays null. */
@@ -173,6 +179,9 @@ export function readManifest(path) {
173
179
  throw new Error("brak pól");
174
180
  const manifest = { packageVersion: String(parsed.packageVersion ?? "?"), agents: parsed.agents, entries: parsed.entries };
175
181
  manifest.roleProviders = Object.hasOwn(parsed, "roleProviders") ? parsed.roleProviders : roleProviders(manifest);
182
+ if (parsed.credentialSource === "login" && typeof parsed.installation_id === "string" && typeof parsed.pair_id === "string") {
183
+ Object.assign(manifest, { installation_id: parsed.installation_id, pair_id: parsed.pair_id, credentialSource: "login" });
184
+ }
176
185
  return manifest;
177
186
  }
178
187
  catch {
package/dist/roles.d.ts CHANGED
@@ -17,7 +17,7 @@ export interface Role {
17
17
  export declare function rolesDir(): string;
18
18
  export declare function parseRole(file: Role["file"], text: string): Role;
19
19
  export declare function loadRoles(dir?: string): Role[];
20
- export declare const MANAGED_LINE = "<!-- robisie:managed 0.2.2 \u2014 plik zarz\u0105dzany przez `npx robisie`; `npx robisie uninstall` go usunie -->";
20
+ export declare const MANAGED_LINE = "<!-- robisie:managed 0.3.0 \u2014 plik zarz\u0105dzany przez `npx robisie`; `npx robisie uninstall` go usunie -->";
21
21
  export type AgentFlavor = "claude" | "codex" | "opencode";
22
22
  /** How the operator starts the Builder for one card in its own session (the card id is not a secret). */
23
23
  export declare function builderStartCommand(flavor: AgentFlavor, codexRolePath?: string): string;
package/docs/README.en.md CHANGED
@@ -1,4 +1,4 @@
1
- # robisie — from account to accepted card (package 0.2.2)
1
+ # robisie — from account to accepted card (package 0.3.0)
2
2
 
3
3
  In the project directory with its engine configuration, run `npx robisie init`, then `npx robisie doctor`: init prepares the project goal and tester protection list, and doctor checks both inputs.
4
4
 
@@ -57,6 +57,16 @@ Every doctor result includes `! Polityka enforced: NIE SPRAWDZONO — klient nie
57
57
 
58
58
  Polish CLI messages: `Brak klucza odbioru ROBISIE_REVIEW_KEY.` — Missing acceptance key ROBISIE_REVIEW_KEY.; `Klucz odbioru B jest tym samym tokenem co klucz A.` — Acceptance key B is the same token as key A.; `ROBISIE_REVIEW_KEY ma niepoprawny format.` — ROBISIE_REVIEW_KEY has an invalid format.; `Nie potwierdzono dostępu B do tablicy.` — Board access with key B could not be confirmed.; `Klucz B uwierzytelnia odczyt projektów.` — Key B authenticates project reads.
59
59
 
60
+ ### Sign in with a code: npx robisie login
61
+
62
+ Instead of copying keys from Connect you can pair the installation with one command in the installation directory: `npx robisie login`. It prints a code and a link to https://robisie.app/dashboard/connect/device. You or your agent, signed in to this account in the browser, compare the code with the terminal, confirm the sign-in again and approve both keys at once: A (worker) and B (owner_validator — full permissions, including deletion). The server always issues the A+B pair. The keys go straight into the installation's `key` and `review-key` files (0600, directory 0700): they never pass through the screen, the clipboard, chat or command history.
63
+
64
+ Exit code 0 means the pair is saved and confirmed. Exit code 2 means the pairing is waiting for approval — you are not signed in yet; resume it with the same `npx robisie login` before the code expires (10 minutes). Exit code 1 is an error with one next step. `npx robisie login --no-wait` only prints the code and link; `--timeout` sets how many seconds to wait (default 540). Without keys, without a terminal and without `--key-stdin`, init starts with this sign-in itself.
65
+
66
+ After sign-in, init, doctor and `npx robisie factory run` take A and B from the installation files. An old ROBISIE_KEY or ROBISIE_REVIEW_KEY value in the environment is then ignored with a warning that never prints the value — open a new terminal. Doctor does not require ROBISIE_REVIEW_KEY in the environment of such an installation. One robisie command runs at a time: a second one refuses with „Inna operacja robisie trwa” (another robisie operation is running). An interrupted pair write (for example a full disk) is finished by the next command; until then no command uses the keys in the files. Installations with keys pasted from Connect keep working as before.
67
+
68
+ The tester release is a single trust zone: on this computer the agent executing tasks technically also has access to the acceptance key (B). Run only agents you trust as yourself on it.
69
+
60
70
  <!-- sekcja: instalacja -->
61
71
  <a id="instalacja"></a>
62
72
  ## Install from npm
@@ -257,6 +267,13 @@ In other CEO sessions, including Codex, moving to delivered requires independent
257
267
 
258
268
  The project owner can use Dashboard → Planer → card → Etap → “Zrobione” to move `delivered` to `done`, including when the agent uses a `worker` key. For the first card described here, the server does not enforce stored acceptance or evidence before a change to `done`: the dashboard lets the owner select “Zrobione” even without them. Do this only after checking and explicitly accepting the result. The dashboard cannot edit `details`; review and evidence are recorded through the supported board tool flow. This guide alone does not prove a customer has completed that flow.
259
269
 
270
+ ### Blocked card: retry or abandon
271
+
272
+ A card in the “Blocked” stage waits for the owner's decision. The scope protection is intentional: the worker key A cannot close the card — setting `done` with key A is refused with 403. `done` is reserved for accepting a result with evidence, not for releasing scope. Do not broaden key A or change roles to bypass the refusal.
273
+
274
+ - **Retry:** open the Planner in the Dashboard (`https://robisie.app/dashboard/plugins/planer`) (“Projects” section), choose a project and card, then select “Ready” (`ready`) under “Stage”. The card returns to the agent's queue.
275
+ - **Abandon:** in the same card window, click “Delete”; at “Are you sure you want to delete this?” choose “Yes, delete”. **Deletion is irreversible — it cannot be undone.** The `masz-<first 8 characters of the card id>` branch with the agent's work remains in the repository.
276
+
260
277
  <!-- sekcja: aktualizacja -->
261
278
  ## Update and private backup
262
279
 
@@ -446,12 +463,12 @@ Without an installation, begin with the account and Connect → init; repeating
446
463
  CLI messages remain in Polish. Match the message, then follow the English explanation:
447
464
 
448
465
  - **brak-klucza** — `Brak klucza robisie.`
449
- No key: generate one in Connect and supply it to init.
466
+ No key: generate one in Connect and supply it to init, or pair the installation: `npx robisie login`.
450
467
  - **odrzucony-klucz** — `Serwer robisie odrzucił klucz (nieważny albo unieważniony).`
451
468
  Generate a new worker key; in zsh/bash run `unset ROBISIE_KEY`, then init with the hidden prompt.
452
469
  - **brak-odczytu** — `Ten klucz nie ma uprawnień do odczytu tablicy (np. rola seeder).`
453
470
  Select worker in Connect; `unset ROBISIE_KEY`, then init with the hidden prompt.
454
- - **major** — `Wersja kontraktu serwera (2.0.0) nie pasuje do paczki robisie 0.2.2 (obsługuje 1.x).`
471
+ - **major** — `Wersja kontraktu serwera (2.0.0) nie pasuje do paczki robisie 0.3.0 (obsługuje 1.x).`
455
472
  Example of a MAJOR mismatch: install a release compatible with the server contract.
456
473
  - **brak-env** — `Zmienna ROBISIE_KEY nie jest ustawiona — role i agenci jej potrzebują.`
457
474
  Check profile support; with --no-shell/another shell load the key file into the session environment as shown in init, then doctor.