@cybedefend/vibedefend 1.8.1 → 1.8.3

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 (40) hide show
  1. package/README.md +50 -1
  2. package/dist/auth/auth-store.js +53 -24
  3. package/dist/auth/auth-store.js.map +1 -1
  4. package/dist/auth/auth.js +30 -7
  5. package/dist/auth/auth.js.map +1 -1
  6. package/dist/auth/refresh-lock.js +139 -0
  7. package/dist/auth/refresh-lock.js.map +1 -0
  8. package/dist/config.js +1 -1
  9. package/dist/config.js.map +1 -1
  10. package/dist/diagnostics.js +0 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/hook-runner.js +556 -503
  13. package/dist/hooks/runtime/fetch-rules.js +1 -3
  14. package/dist/hooks/runtime/fetch-rules.js.map +1 -1
  15. package/dist/hooks/runtime/resolve.js +25 -243
  16. package/dist/hooks/runtime/resolve.js.map +1 -1
  17. package/dist/hooks/runtime/session-review.js +53 -27
  18. package/dist/hooks/runtime/session-review.js.map +1 -1
  19. package/dist/hooks/runtime/session-start.js +17 -5
  20. package/dist/hooks/runtime/session-start.js.map +1 -1
  21. package/dist/hooks/runtime/sign-in-notice.js +44 -0
  22. package/dist/hooks/runtime/sign-in-notice.js.map +1 -0
  23. package/dist/hooks/runtime/user-prompt-submit.js +3 -5
  24. package/dist/hooks/runtime/user-prompt-submit.js.map +1 -1
  25. package/dist/index.js +6 -7
  26. package/dist/index.js.map +1 -1
  27. package/dist/install.js +2 -6
  28. package/dist/install.js.map +1 -1
  29. package/dist/login.js +2 -3
  30. package/dist/login.js.map +1 -1
  31. package/dist/logout.js +2 -6
  32. package/dist/logout.js.map +1 -1
  33. package/dist/prompts.js +1 -1
  34. package/dist/scan-diff.js +526 -0
  35. package/dist/scan-diff.js.map +1 -0
  36. package/dist/update-check-gate.js +17 -0
  37. package/dist/update-check-gate.js.map +1 -0
  38. package/dist/zip.js +95 -0
  39. package/dist/zip.js.map +1 -0
  40. package/package.json +3 -3
@@ -5156,9 +5156,7 @@ function extractToolInputShape(input2, client) {
5156
5156
  }
5157
5157
 
5158
5158
  // src/hooks/runtime/resolve.ts
5159
- import { execFileSync as execFileSync2 } from "node:child_process";
5160
- import { createHash } from "node:crypto";
5161
- import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
5159
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
5162
5160
 
5163
5161
  // src/auth/auth-store.ts
5164
5162
  import { execFileSync } from "node:child_process";
@@ -5192,11 +5190,13 @@ function storeAuth(mcpName, auth) {
5192
5190
  storeFileFallback(mcpName, auth);
5193
5191
  }
5194
5192
  function loadAuth(mcpName) {
5195
- let blob = null;
5196
- if (process.platform === "darwin") {
5197
- blob = readMacOSKeychain(mcpName);
5198
- }
5199
- if (!blob) blob = readFileFallback(mcpName);
5193
+ const fromFile = parseBundle(readFileFallback(mcpName));
5194
+ if (process.platform !== "darwin") return fromFile;
5195
+ const fromKeychain = parseBundle(readMacOSKeychain(mcpName));
5196
+ if (!fromKeychain) return fromFile;
5197
+ return fromFile && isSameSignIn(fromFile, fromKeychain) && fromFile.expiresAt > fromKeychain.expiresAt ? fromFile : fromKeychain;
5198
+ }
5199
+ function parseBundle(blob) {
5200
5200
  if (!blob) return null;
5201
5201
  try {
5202
5202
  const parsed = JSON.parse(blob);
@@ -5208,6 +5208,9 @@ function loadAuth(mcpName) {
5208
5208
  return null;
5209
5209
  }
5210
5210
  }
5211
+ function isSameSignIn(a, b) {
5212
+ return a.logtoEndpoint === b.logtoEndpoint && a.cliAppId === b.cliAppId && a.logtoResource === b.logtoResource;
5213
+ }
5211
5214
  function clearAuth(mcpName) {
5212
5215
  if (process.platform === "darwin") {
5213
5216
  try {
@@ -5228,24 +5231,11 @@ function clearAuth(mcpName) {
5228
5231
  removeFileFallback(mcpName);
5229
5232
  }
5230
5233
  function storeMacOSKeychain(mcpName, blob) {
5231
- try {
5232
- execFileSync(
5233
- "security",
5234
- [
5235
- "delete-generic-password",
5236
- "-s",
5237
- KEYCHAIN_SERVICE,
5238
- "-a",
5239
- accountFor(mcpName)
5240
- ],
5241
- { stdio: "ignore" }
5242
- );
5243
- } catch {
5244
- }
5245
5234
  execFileSync(
5246
5235
  "security",
5247
5236
  [
5248
5237
  "add-generic-password",
5238
+ "-U",
5249
5239
  "-s",
5250
5240
  KEYCHAIN_SERVICE,
5251
5241
  "-a",
@@ -5253,7 +5243,10 @@ function storeMacOSKeychain(mcpName, blob) {
5253
5243
  "-w",
5254
5244
  blob
5255
5245
  ],
5256
- { stdio: "ignore" }
5246
+ // A keychain whose dialog nobody answers hangs every client. Logto has
5247
+ // already consumed the previous refresh token: past this, the renewed
5248
+ // bundle goes to the file rather than wait with the hook.
5249
+ { stdio: "ignore", timeout: 3e3 }
5257
5250
  );
5258
5251
  }
5259
5252
  function readMacOSKeychain(mcpName) {
@@ -5348,6 +5341,110 @@ function removeFileFallback(mcpName, replacedBy) {
5348
5341
  }
5349
5342
  }
5350
5343
 
5344
+ // src/auth/refresh-lock.ts
5345
+ import { createHash, randomUUID } from "node:crypto";
5346
+ import {
5347
+ closeSync,
5348
+ mkdirSync as mkdirSync2,
5349
+ openSync,
5350
+ readFileSync as readFileSync2,
5351
+ statSync,
5352
+ unlinkSync,
5353
+ writeSync
5354
+ } from "node:fs";
5355
+ import { homedir as homedir3 } from "node:os";
5356
+ import { dirname, join as join2 } from "node:path";
5357
+ var WAIT_MS = 5e3;
5358
+ var POLL_MS = 50;
5359
+ var STALE_AFTER_MS = 3e4;
5360
+ var RefreshLockBusyError = class extends Error {
5361
+ constructor() {
5362
+ super("Another process is refreshing the token.");
5363
+ this.name = "RefreshLockBusyError";
5364
+ }
5365
+ };
5366
+ function refreshLockPath(mcpName) {
5367
+ const digest = createHash("sha256").update(mcpName).digest("hex").slice(0, 16);
5368
+ return join2(homedir3(), ".cybedefend", `refresh-${digest}.lock`);
5369
+ }
5370
+ async function withRefreshLock(mcpName, body, options = {}) {
5371
+ const path = refreshLockPath(mcpName);
5372
+ const deadline = Date.now() + (options.waitMs ?? WAIT_MS);
5373
+ for (; ; ) {
5374
+ const attempt = tryAcquire(path);
5375
+ if (attempt === "unavailable") return body();
5376
+ if (attempt !== "held") {
5377
+ try {
5378
+ return await body();
5379
+ } finally {
5380
+ release(path, attempt);
5381
+ }
5382
+ }
5383
+ if (isAbandoned(path)) {
5384
+ removeQuietly(path);
5385
+ continue;
5386
+ }
5387
+ if (Date.now() >= deadline) throw new RefreshLockBusyError();
5388
+ await new Promise((resolve2) => setTimeout(resolve2, options.pollMs ?? POLL_MS));
5389
+ }
5390
+ }
5391
+ function tryAcquire(path) {
5392
+ let handle;
5393
+ try {
5394
+ mkdirSync2(dirname(path), { recursive: true });
5395
+ } catch {
5396
+ return "unavailable";
5397
+ }
5398
+ try {
5399
+ handle = openSync(path, "wx", 384);
5400
+ } catch (e) {
5401
+ return e.code === "EEXIST" ? "held" : "unavailable";
5402
+ }
5403
+ const token = randomUUID();
5404
+ try {
5405
+ writeSync(handle, JSON.stringify({ pid: process.pid, token }));
5406
+ } catch {
5407
+ } finally {
5408
+ closeSync(handle);
5409
+ }
5410
+ return token;
5411
+ }
5412
+ function isAbandoned(path) {
5413
+ let age;
5414
+ try {
5415
+ age = Date.now() - statSync(path).mtimeMs;
5416
+ } catch {
5417
+ return false;
5418
+ }
5419
+ if (age >= STALE_AFTER_MS) return true;
5420
+ const pid = holder(path)?.pid;
5421
+ return typeof pid === "number" && !isAlive(pid);
5422
+ }
5423
+ function holder(path) {
5424
+ try {
5425
+ return JSON.parse(readFileSync2(path, "utf8"));
5426
+ } catch {
5427
+ return null;
5428
+ }
5429
+ }
5430
+ function isAlive(pid) {
5431
+ try {
5432
+ process.kill(pid, 0);
5433
+ return true;
5434
+ } catch (e) {
5435
+ return e.code !== "ESRCH";
5436
+ }
5437
+ }
5438
+ function release(path, token) {
5439
+ if (holder(path)?.token === token) removeQuietly(path);
5440
+ }
5441
+ function removeQuietly(path) {
5442
+ try {
5443
+ unlinkSync(path);
5444
+ } catch {
5445
+ }
5446
+ }
5447
+
5351
5448
  // src/auth/token-exchange.ts
5352
5449
  var RefreshTokenInvalidError = class extends Error {
5353
5450
  constructor(msg) {
@@ -5406,12 +5503,28 @@ async function getValidAccessToken(mcpName) {
5406
5503
  );
5407
5504
  }
5408
5505
  if (!inFlightRefresh) {
5409
- inFlightRefresh = doRefresh(mcpName, stored).finally(() => {
5506
+ inFlightRefresh = refreshUnderLock(mcpName).finally(() => {
5410
5507
  inFlightRefresh = null;
5411
5508
  });
5412
5509
  }
5413
5510
  return await inFlightRefresh;
5414
5511
  }
5512
+ function hasUsableStoredAuth(mcpName, now = Date.now()) {
5513
+ const stored = loadAuth(mcpName);
5514
+ if (!stored) return false;
5515
+ if (stored.refreshToken) return true;
5516
+ return typeof stored.expiresAt === "number" && stored.expiresAt > now;
5517
+ }
5518
+ function refreshUnderLock(mcpName) {
5519
+ return withRefreshLock(mcpName, async () => {
5520
+ const current = loadAuth(mcpName);
5521
+ if (!current) {
5522
+ throw new LoginRequiredError("No stored credentials. Run `vibedefend login`.");
5523
+ }
5524
+ if (Date.now() < current.expiresAt) return current.accessToken;
5525
+ return doRefresh(mcpName, current);
5526
+ });
5527
+ }
5415
5528
  async function doRefresh(mcpName, stored) {
5416
5529
  if (!stored.refreshToken) {
5417
5530
  throw new LoginRequiredError("No refresh_token available; re-login required.");
@@ -5436,6 +5549,11 @@ async function doRefresh(mcpName, stored) {
5436
5549
  return updated.accessToken;
5437
5550
  } catch (e) {
5438
5551
  if (e instanceof RefreshTokenInvalidError) {
5552
+ const latest = loadAuth(mcpName);
5553
+ if (latest && latest.refreshToken !== stored.refreshToken) {
5554
+ if (Date.now() < latest.expiresAt) return latest.accessToken;
5555
+ throw e;
5556
+ }
5439
5557
  clearAuth(mcpName);
5440
5558
  throw new LoginRequiredError(
5441
5559
  "Your session has expired. Run `vibedefend login` to re-authenticate."
@@ -5550,13 +5668,13 @@ async function resolveProjectByRepository(apiBase, token, q, deps = {}) {
5550
5668
  }
5551
5669
 
5552
5670
  // src/hooks/runtime/repo-link-cache.ts
5553
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
5554
- import { dirname as dirname2 } from "node:path";
5671
+ import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
5672
+ import { dirname as dirname3 } from "node:path";
5555
5673
 
5556
5674
  // src/utils.ts
5557
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
5558
- import { dirname, join as join2 } from "node:path";
5559
- import { homedir as homedir3, platform } from "node:os";
5675
+ import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
5676
+ import { dirname as dirname2, join as join3 } from "node:path";
5677
+ import { homedir as homedir4, platform } from "node:os";
5560
5678
 
5561
5679
  // node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/index.mjs
5562
5680
  var FORCE_COLOR;
@@ -5659,11 +5777,11 @@ function init(open2, close) {
5659
5777
 
5660
5778
  // src/utils.ts
5661
5779
  function home(...parts) {
5662
- return join2(homedir3(), ...parts);
5780
+ return join3(homedir4(), ...parts);
5663
5781
  }
5664
5782
  function ensureDirFor(filePath) {
5665
- const dir = dirname(filePath);
5666
- if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
5783
+ const dir = dirname2(filePath);
5784
+ if (!existsSync2(dir)) mkdirSync3(dir, { recursive: true });
5667
5785
  }
5668
5786
 
5669
5787
  // src/hooks/runtime/repo-link-cache.ts
@@ -5679,7 +5797,7 @@ function readRepoLinkCache(deps = {}) {
5679
5797
  const p = pathOf(deps);
5680
5798
  if (!existsSync3(p)) return {};
5681
5799
  try {
5682
- const raw = readFileSync3(p, "utf8");
5800
+ const raw = readFileSync4(p, "utf8");
5683
5801
  if (!raw.trim()) return {};
5684
5802
  const parsed = JSON.parse(raw);
5685
5803
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
@@ -5725,25 +5843,25 @@ function writeCachedRepoLink(key, entry, deps = {}) {
5725
5843
  resolvedAt: now()
5726
5844
  };
5727
5845
  const p = pathOf(deps);
5728
- const dir = dirname2(p);
5729
- if (!existsSync3(dir)) mkdirSync3(dir, { recursive: true });
5846
+ const dir = dirname3(p);
5847
+ if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
5730
5848
  writeFileSync3(p, JSON.stringify(map2, null, 2) + "\n");
5731
5849
  } catch {
5732
5850
  }
5733
5851
  }
5734
5852
 
5735
5853
  // src/hooks/runtime/config.ts
5736
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
5737
- import { homedir as homedir4 } from "node:os";
5738
- import { join as join3 } from "node:path";
5854
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
5855
+ import { homedir as homedir5 } from "node:os";
5856
+ import { join as join4 } from "node:path";
5739
5857
  function runtimeConfigPath() {
5740
- return join3(homedir4(), ".cybedefend", "runtime-config.json");
5858
+ return join4(homedir5(), ".cybedefend", "runtime-config.json");
5741
5859
  }
5742
5860
  function loadRuntimeConfig(path) {
5743
5861
  const p = path ?? runtimeConfigPath();
5744
5862
  if (!existsSync4(p)) return null;
5745
5863
  try {
5746
- const raw = readFileSync4(p, "utf8");
5864
+ const raw = readFileSync5(p, "utf8");
5747
5865
  return JSON.parse(raw);
5748
5866
  } catch {
5749
5867
  return null;
@@ -5765,9 +5883,9 @@ async function readStdinJson() {
5765
5883
  }
5766
5884
 
5767
5885
  // src/hooks/runtime/trusted-api-base.ts
5768
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
5769
- import { homedir as homedir5 } from "node:os";
5770
- import { join as join4 } from "node:path";
5886
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
5887
+ import { homedir as homedir6 } from "node:os";
5888
+ import { join as join5 } from "node:path";
5771
5889
 
5772
5890
  // src/config.ts
5773
5891
  var REGIONS = [
@@ -5795,7 +5913,7 @@ var REGIONS = [
5795
5913
 
5796
5914
  // src/hooks/runtime/trusted-api-base.ts
5797
5915
  function userRegionsPath() {
5798
- return join4(homedir5(), ".cybedefend", "regions.json");
5916
+ return join5(homedir6(), ".cybedefend", "regions.json");
5799
5917
  }
5800
5918
  function normalizeOrigin(candidate) {
5801
5919
  if (typeof candidate !== "string") return null;
@@ -5814,7 +5932,7 @@ function normalizeOrigin(candidate) {
5814
5932
  function readUserRegionApiBases(path) {
5815
5933
  try {
5816
5934
  if (!existsSync5(path)) return [];
5817
- const parsed = JSON.parse(readFileSync5(path, "utf8"));
5935
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
5818
5936
  if (!Array.isArray(parsed)) return [];
5819
5937
  return parsed.map(
5820
5938
  (entry) => entry && typeof entry === "object" ? entry.apiBase : null
@@ -5883,7 +6001,7 @@ function resolveProjectId(cwd = process.cwd(), deps = {}) {
5883
6001
  const configPath = `${cwd}/.cybedefend/config.json`;
5884
6002
  if (existsSync6(configPath)) {
5885
6003
  try {
5886
- const raw = readFileSync6(configPath, "utf8");
6004
+ const raw = readFileSync7(configPath, "utf8");
5887
6005
  const cfg = JSON.parse(raw);
5888
6006
  return {
5889
6007
  projectId: cfg.projectId ?? null,
@@ -5898,119 +6016,9 @@ function resolveToken(mcpName, opts = {}) {
5898
6016
  const envToken = process.env.CYBEDEFEND_TOKEN;
5899
6017
  if (envToken && envToken.length > 0) return envToken;
5900
6018
  const stored = (opts.loadStoredAuth ?? loadAuth)(mcpName);
5901
- if (stored && (opts.now ?? Date.now)() < stored.expiresAt) {
5902
- return stored.accessToken;
5903
- }
5904
- const platform2 = opts.platform ?? process.platform;
5905
- const readKeychain = opts.readKeychain ?? readMacOSKeychain2;
5906
- if (platform2 === "darwin") {
5907
- const now = (opts.now ?? Date.now)();
5908
- return resolveTokenMacOS(mcpName, opts.mcpUrl, readKeychain, now) ?? resolveTokenCodexMacOS(mcpName, opts.mcpUrl, readKeychain, now);
5909
- }
5910
- if (platform2 === "linux") return resolveTokenLinux(mcpName);
5911
- return null;
5912
- }
5913
- function codexCredentialAccount(mcpName, mcpUrl) {
5914
- const digest = createHash("sha256").update(JSON.stringify({ type: "http", url: mcpUrl, headers: {} })).digest("hex");
5915
- return `${mcpName}|${digest.slice(0, 16)}`;
5916
- }
5917
- function isExpired(expiresAt, now) {
5918
- if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= 0) {
5919
- return false;
5920
- }
5921
- const expiresAtMs = expiresAt < 1e11 ? expiresAt * 1e3 : expiresAt;
5922
- return now >= expiresAtMs;
5923
- }
5924
- function readMacOSKeychain2(service, account) {
5925
- try {
5926
- const blob = execFileSync2(
5927
- "security",
5928
- [
5929
- "find-generic-password",
5930
- "-s",
5931
- service,
5932
- ...account === void 0 ? [] : ["-a", account],
5933
- "-w"
5934
- ],
5935
- {
5936
- encoding: "utf8",
5937
- stdio: ["ignore", "pipe", "ignore"],
5938
- timeout: 2e3
5939
- }
5940
- ).trim();
5941
- return blob.length > 0 ? blob : null;
5942
- } catch {
5943
- return null;
5944
- }
5945
- }
5946
- function resolveTokenMacOS(mcpName, mcpUrl, readKeychain, now) {
5947
- const blob = readKeychain("Claude Code-credentials");
5948
- if (!blob) return null;
5949
- try {
5950
- const data = JSON.parse(blob);
5951
- const oauth = data.mcpOAuth ?? {};
5952
- for (const entry of Object.values(oauth)) {
5953
- if (entry?.serverName !== mcpName || !entry.accessToken) continue;
5954
- if (mcpUrl && typeof entry.serverUrl === "string" && entry.serverUrl !== mcpUrl) {
5955
- continue;
5956
- }
5957
- if (isExpired(entry.expiresAt, now)) {
5958
- continue;
5959
- }
5960
- return entry.accessToken;
5961
- }
5962
- } catch {
5963
- return blob || null;
5964
- }
5965
- return null;
5966
- }
5967
- function resolveTokenCodexMacOS(mcpName, mcpUrl, readKeychain, now) {
5968
- const accounts = mcpUrl ? [codexCredentialAccount(mcpName, mcpUrl), mcpName] : [mcpName];
5969
- for (const account of accounts) {
5970
- const blob = readKeychain("Codex MCP Credentials", account);
5971
- if (!blob) continue;
5972
- const token = parseCodexCredential(blob, now);
5973
- if (token) return token;
5974
- }
5975
- return null;
6019
+ return stored && (opts.now ?? Date.now)() < stored.expiresAt ? stored.accessToken : null;
5976
6020
  }
5977
- function parseCodexCredential(blob, now) {
5978
- try {
5979
- const data = JSON.parse(blob);
5980
- if (isExpired(data.expires_at ?? data.expiresAt, now)) return null;
5981
- return data.token_response?.access_token ?? data.access_token ?? data.accessToken ?? data.token ?? null;
5982
- } catch {
5983
- return blob || null;
5984
- }
5985
- }
5986
- function resolveTokenLinux(mcpName) {
5987
- try {
5988
- const token = execFileSync2(
5989
- "secret-tool",
5990
- ["lookup", "service", "Claude-Code", "account", mcpName],
5991
- {
5992
- encoding: "utf8",
5993
- stdio: ["ignore", "pipe", "ignore"],
5994
- timeout: 2e3
5995
- }
5996
- ).trim();
5997
- return token.length > 0 ? token : null;
5998
- } catch {
5999
- return null;
6000
- }
6001
- }
6002
- function isExpiredJwt(token) {
6003
- const payload = token.split(".")[1];
6004
- if (!payload) return false;
6005
- try {
6006
- const json2 = Buffer.from(payload, "base64url").toString("utf8");
6007
- const exp = JSON.parse(json2).exp;
6008
- return typeof exp === "number" && exp * 1e3 <= Date.now();
6009
- } catch {
6010
- return false;
6011
- }
6012
- }
6013
- async function resolveTokenWithRefresh(mcpName, deps = {}, opts = {}) {
6021
+ async function resolveTokenWithRefresh(mcpName, deps = {}) {
6014
6022
  const getValidAccessTokenFn = deps.getValidAccessToken ?? getValidAccessToken;
6015
6023
  const resolveTokenFn = deps.resolveTokenFn ?? resolveToken;
6016
6024
  const envToken = process.env.CYBEDEFEND_TOKEN;
@@ -6019,19 +6027,9 @@ async function resolveTokenWithRefresh(mcpName, deps = {}, opts = {}) {
6019
6027
  const token = await getValidAccessTokenFn(mcpName);
6020
6028
  if (token) return token;
6021
6029
  } catch (e) {
6022
- if (e instanceof LoginRequiredError) {
6023
- return resolveTokenFn(mcpName, opts);
6024
- }
6025
- }
6026
- const legacy = resolveTokenFn(mcpName, opts);
6027
- if (legacy && isExpiredJwt(legacy)) {
6028
- process.stderr.write(
6029
- `[vibedefend] the stored credential for "${mcpName}" has expired and cannot be refreshed (no refresh token in the legacy store). Run \`vibedefend login\`.
6030
- `
6031
- );
6032
- return null;
6030
+ if (e instanceof LoginRequiredError) return null;
6033
6031
  }
6034
- return legacy;
6032
+ return resolveTokenFn(mcpName);
6035
6033
  }
6036
6034
  var RESOLVE_API_TIMEOUT_MS = 4e3;
6037
6035
  function resolveActivationMode(config2) {
@@ -6100,9 +6098,9 @@ async function resolveProjectIdWithApi(cwd = process.cwd(), deps = {}) {
6100
6098
  }
6101
6099
 
6102
6100
  // src/hooks/runtime/usage-block.ts
6103
- import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "node:fs";
6104
- import { homedir as homedir6 } from "node:os";
6105
- import { dirname as dirname3, join as join5 } from "node:path";
6101
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "node:fs";
6102
+ import { homedir as homedir7 } from "node:os";
6103
+ import { dirname as dirname4, join as join6 } from "node:path";
6106
6104
  var BLOCKED_CODE = "VIBEDEFEND_BLOCKED";
6107
6105
  var USAGE_WARNING_HEADER = "x-vibedefend-usage-warning";
6108
6106
  var UNITS = ["injection", "judgment", "diff_scan"];
@@ -6199,8 +6197,8 @@ function blockKey(block) {
6199
6197
  }
6200
6198
  var NOTICES_CAP = 300;
6201
6199
  function defaultUsageNoticesFile() {
6202
- const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join5(homedir6(), ".cybedefend");
6203
- return join5(dir, "usage-notices-sessions.json");
6200
+ const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join6(homedir7(), ".cybedefend");
6201
+ return join6(dir, "usage-notices-sessions.json");
6204
6202
  }
6205
6203
  function makeUsageNotifier(opts = {}) {
6206
6204
  const file2 = opts.file ?? defaultUsageNoticesFile();
@@ -6213,7 +6211,7 @@ function makeUsageNotifier(opts = {}) {
6213
6211
  function load2() {
6214
6212
  try {
6215
6213
  if (!existsSync7(file2)) return [];
6216
- const data = JSON.parse(readFileSync7(file2, "utf8"));
6214
+ const data = JSON.parse(readFileSync8(file2, "utf8"));
6217
6215
  return Array.isArray(data.seen) ? data.seen.filter((s) => typeof s === "string") : [];
6218
6216
  } catch {
6219
6217
  return [];
@@ -6225,7 +6223,7 @@ function makeUsageNotifier(opts = {}) {
6225
6223
  const seen = load2();
6226
6224
  if (seen.includes(marker)) return null;
6227
6225
  try {
6228
- mkdirSync4(dirname3(file2), { recursive: true });
6226
+ mkdirSync5(dirname4(file2), { recursive: true });
6229
6227
  writeFileSync4(
6230
6228
  file2,
6231
6229
  JSON.stringify({ seen: [...seen, marker].slice(-NOTICES_CAP) }),
@@ -6359,13 +6357,13 @@ async function fetchProposalsCount(opts) {
6359
6357
  }
6360
6358
 
6361
6359
  // src/hooks/runtime/session-activation.ts
6362
- import { existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "node:fs";
6363
- import { homedir as homedir7 } from "node:os";
6364
- import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6, resolve as resolvePath2 } from "node:path";
6360
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
6361
+ import { homedir as homedir8 } from "node:os";
6362
+ import { dirname as dirname5, isAbsolute as isAbsolute2, join as join7, resolve as resolvePath2 } from "node:path";
6365
6363
  import { fileURLToPath } from "node:url";
6366
6364
 
6367
6365
  // src/hooks/runtime/emit.ts
6368
- import { writeSync } from "node:fs";
6366
+ import { writeSync as writeSync2 } from "node:fs";
6369
6367
  var ENVELOPE_CLIENTS = {
6370
6368
  SessionStart: /* @__PURE__ */ new Set(["codex"]),
6371
6369
  PreToolUse: /* @__PURE__ */ new Set(["claude-code", "codex", "vscode"]),
@@ -6391,7 +6389,7 @@ function writeStdoutSync(text) {
6391
6389
  while (offset < buf.length) {
6392
6390
  let written = 0;
6393
6391
  try {
6394
- written = writeSync(1, buf, offset, buf.length - offset);
6392
+ written = writeSync2(1, buf, offset, buf.length - offset);
6395
6393
  } catch (e) {
6396
6394
  if (e?.code !== "EAGAIN") return;
6397
6395
  }
@@ -6529,14 +6527,14 @@ function isSettledReason(reason) {
6529
6527
  }
6530
6528
  var SESSIONS_CAP = 200;
6531
6529
  function defaultStoreFile() {
6532
- const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join6(homedir7(), ".cybedefend");
6533
- return join6(dir, "inactive-sessions.json");
6530
+ const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join7(homedir8(), ".cybedefend");
6531
+ return join7(dir, "inactive-sessions.json");
6534
6532
  }
6535
6533
  function defaultInactiveSessionStore(file2 = defaultStoreFile(), now = Date.now) {
6536
6534
  function load2() {
6537
6535
  if (!existsSync8(file2)) return {};
6538
6536
  try {
6539
- const parsed = JSON.parse(readFileSync8(file2, "utf8"));
6537
+ const parsed = JSON.parse(readFileSync9(file2, "utf8"));
6540
6538
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
6541
6539
  } catch {
6542
6540
  return {};
@@ -6544,7 +6542,7 @@ function defaultInactiveSessionStore(file2 = defaultStoreFile(), now = Date.now)
6544
6542
  }
6545
6543
  function save(map2) {
6546
6544
  try {
6547
- mkdirSync5(dirname4(file2), { recursive: true });
6545
+ mkdirSync6(dirname5(file2), { recursive: true });
6548
6546
  writeFileSync5(file2, JSON.stringify(map2) + "\n", "utf8");
6549
6547
  } catch {
6550
6548
  }
@@ -6661,13 +6659,13 @@ function composeInactiveNotice(reason, repository, client) {
6661
6659
  }
6662
6660
 
6663
6661
  // src/hooks/runtime/work-dir.ts
6664
- import { existsSync as existsSync9, realpathSync, statSync } from "node:fs";
6665
- import { dirname as dirname5, isAbsolute as isAbsolute3, join as join7, resolve } from "node:path";
6662
+ import { existsSync as existsSync9, realpathSync, statSync as statSync2 } from "node:fs";
6663
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join8, resolve } from "node:path";
6666
6664
  function findRepoRoot(dir) {
6667
6665
  let current = resolve(dir);
6668
6666
  for (; ; ) {
6669
- if (existsSync9(join7(current, ".git"))) return current;
6670
- const parent = dirname5(current);
6667
+ if (existsSync9(join8(current, ".git"))) return current;
6668
+ const parent = dirname6(current);
6671
6669
  if (parent === current) return null;
6672
6670
  current = parent;
6673
6671
  }
@@ -6676,10 +6674,10 @@ function nearestExistingDir(path) {
6676
6674
  let current = resolve(path);
6677
6675
  for (; ; ) {
6678
6676
  try {
6679
- if (statSync(current).isDirectory()) return current;
6677
+ if (statSync2(current).isDirectory()) return current;
6680
6678
  } catch {
6681
6679
  }
6682
- const parent = dirname5(current);
6680
+ const parent = dirname6(current);
6683
6681
  if (parent === current) return current;
6684
6682
  current = parent;
6685
6683
  }
@@ -6694,7 +6692,7 @@ function realPath(p) {
6694
6692
  function projectDirForFile(file2, workDir) {
6695
6693
  if (file2.length === 0 || file2.includes("$")) return workDir;
6696
6694
  const absolute = isAbsolute3(file2) ? file2 : resolve(workDir, file2);
6697
- const fileRoot = findRepoRoot(nearestExistingDir(dirname5(absolute)));
6695
+ const fileRoot = findRepoRoot(nearestExistingDir(dirname6(absolute)));
6698
6696
  if (fileRoot === null) return workDir;
6699
6697
  const workRoot = findRepoRoot(nearestExistingDir(workDir));
6700
6698
  if (workRoot !== null && realPath(workRoot) === realPath(fileRoot)) {
@@ -6706,23 +6704,23 @@ function projectDirForFile(file2, workDir) {
6706
6704
  // src/hooks/runtime/antigravity-session.ts
6707
6705
  import {
6708
6706
  appendFileSync,
6709
- closeSync,
6707
+ closeSync as closeSync2,
6710
6708
  constants,
6711
6709
  lstatSync,
6712
- mkdirSync as mkdirSync6,
6713
- openSync,
6710
+ mkdirSync as mkdirSync7,
6711
+ openSync as openSync2,
6714
6712
  readdirSync,
6715
- readFileSync as readFileSync9,
6713
+ readFileSync as readFileSync10,
6716
6714
  renameSync,
6717
6715
  rmSync,
6718
- unlinkSync,
6716
+ unlinkSync as unlinkSync2,
6719
6717
  utimesSync,
6720
6718
  writeFileSync as writeFileSync6,
6721
- writeSync as writeSync2
6719
+ writeSync as writeSync3
6722
6720
  } from "node:fs";
6723
6721
  import { createHash as createHash2, randomBytes } from "node:crypto";
6724
- import { homedir as homedir8 } from "node:os";
6725
- import { join as join8 } from "node:path";
6722
+ import { homedir as homedir9 } from "node:os";
6723
+ import { join as join9 } from "node:path";
6726
6724
  var MAX_STASHED_CONTEXTS = 20;
6727
6725
  var DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
6728
6726
  var STASH_NAME_RE = /^\d+-[0-9a-f]{8}\.md$/;
@@ -6734,10 +6732,10 @@ function conversationKey(raw) {
6734
6732
  return createHash2("sha256").update(id).digest("hex").slice(0, 32);
6735
6733
  }
6736
6734
  function antigravityStateDir() {
6737
- return join8(homedir8(), ".cybedefend", "antigravity");
6735
+ return join9(homedir9(), ".cybedefend", "antigravity");
6738
6736
  }
6739
6737
  function keyDir(key, dir) {
6740
- return join8(dir, key);
6738
+ return join9(dir, key);
6741
6739
  }
6742
6740
  function isFinalStashName(name) {
6743
6741
  return STASH_NAME_RE.test(name);
@@ -6759,15 +6757,15 @@ function isUnsafeFilePath(path) {
6759
6757
  var NOFOLLOW_SUPPORTED = typeof constants.O_NOFOLLOW === "number";
6760
6758
  function appendLedgerLine(path, line) {
6761
6759
  if (NOFOLLOW_SUPPORTED) {
6762
- const fd = openSync(
6760
+ const fd = openSync2(
6763
6761
  path,
6764
6762
  constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW,
6765
6763
  FILE_MODE
6766
6764
  );
6767
6765
  try {
6768
- writeSync2(fd, line, null, "utf8");
6766
+ writeSync3(fd, line, null, "utf8");
6769
6767
  } finally {
6770
- closeSync(fd);
6768
+ closeSync2(fd);
6771
6769
  }
6772
6770
  return;
6773
6771
  }
@@ -6776,15 +6774,15 @@ function appendLedgerLine(path, line) {
6776
6774
  }
6777
6775
  function writeMarkerFile(path, content) {
6778
6776
  if (NOFOLLOW_SUPPORTED) {
6779
- const fd = openSync(
6777
+ const fd = openSync2(
6780
6778
  path,
6781
6779
  constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
6782
6780
  FILE_MODE
6783
6781
  );
6784
6782
  try {
6785
- writeSync2(fd, content, null, "utf8");
6783
+ writeSync3(fd, content, null, "utf8");
6786
6784
  } finally {
6787
- closeSync(fd);
6785
+ closeSync2(fd);
6788
6786
  }
6789
6787
  return;
6790
6788
  }
@@ -6793,7 +6791,7 @@ function writeMarkerFile(path, content) {
6793
6791
  }
6794
6792
  function ensureRealDir(path) {
6795
6793
  if (isUnsafePath(path)) return false;
6796
- mkdirSync6(path, { recursive: true, mode: DIR_MODE });
6794
+ mkdirSync7(path, { recursive: true, mode: DIR_MODE });
6797
6795
  return true;
6798
6796
  }
6799
6797
  function ensureLiveKeyDir(key, dir, now) {
@@ -6812,12 +6810,12 @@ function stashContext(key, body, dir = antigravityStateDir()) {
6812
6810
  const now = Date.now();
6813
6811
  const kd = ensureLiveKeyDir(key, dir, now);
6814
6812
  if (!kd) return;
6815
- const contextDir = join8(kd, "context");
6813
+ const contextDir = join9(kd, "context");
6816
6814
  if (!ensureRealDir(contextDir)) return;
6817
6815
  const suffix = randomBytes(4).toString("hex");
6818
- tmpPath = join8(contextDir, `.${now}-${suffix}.tmp`);
6816
+ tmpPath = join9(contextDir, `.${now}-${suffix}.tmp`);
6819
6817
  writeFileSync6(tmpPath, body, { mode: FILE_MODE, flag: "wx" });
6820
- const finalPath = join8(contextDir, `${now}-${suffix}.md`);
6818
+ const finalPath = join9(contextDir, `${now}-${suffix}.md`);
6821
6819
  renameSync(tmpPath, finalPath);
6822
6820
  tmpPath = void 0;
6823
6821
  const kept = readdirSync(contextDir).filter(isFinalStashName).sort();
@@ -6825,7 +6823,7 @@ function stashContext(key, body, dir = antigravityStateDir()) {
6825
6823
  if (excess > 0) {
6826
6824
  for (const stale of kept.slice(0, excess)) {
6827
6825
  try {
6828
- unlinkSync(join8(contextDir, stale));
6826
+ unlinkSync2(join9(contextDir, stale));
6829
6827
  } catch {
6830
6828
  }
6831
6829
  }
@@ -6833,7 +6831,7 @@ function stashContext(key, body, dir = antigravityStateDir()) {
6833
6831
  } catch {
6834
6832
  if (tmpPath) {
6835
6833
  try {
6836
- unlinkSync(tmpPath);
6834
+ unlinkSync2(tmpPath);
6837
6835
  } catch {
6838
6836
  }
6839
6837
  }
@@ -6843,15 +6841,15 @@ function drainContext(key, dir = antigravityStateDir()) {
6843
6841
  try {
6844
6842
  const kd = keyDir(key, dir);
6845
6843
  if (isUnsafePath(kd)) return [];
6846
- const contextDir = join8(kd, "context");
6844
+ const contextDir = join9(kd, "context");
6847
6845
  if (isUnsafePath(contextDir)) return [];
6848
6846
  const entries = readdirSync(contextDir).filter(isFinalStashName).sort();
6849
6847
  const seen = /* @__PURE__ */ new Set();
6850
6848
  const bodies = [];
6851
6849
  for (const name of entries) {
6852
- const filePath = join8(contextDir, name);
6850
+ const filePath = join9(contextDir, name);
6853
6851
  try {
6854
- const body = readFileSync9(filePath, "utf8");
6852
+ const body = readFileSync10(filePath, "utf8");
6855
6853
  if (!seen.has(body)) {
6856
6854
  seen.add(body);
6857
6855
  bodies.push(body);
@@ -6859,7 +6857,7 @@ function drainContext(key, dir = antigravityStateDir()) {
6859
6857
  } catch {
6860
6858
  }
6861
6859
  try {
6862
- unlinkSync(filePath);
6860
+ unlinkSync2(filePath);
6863
6861
  } catch {
6864
6862
  }
6865
6863
  }
@@ -6873,7 +6871,7 @@ function recordEdit(key, file2, dir = antigravityStateDir()) {
6873
6871
  const now = Date.now();
6874
6872
  const kd = ensureLiveKeyDir(key, dir, now);
6875
6873
  if (!kd) return;
6876
- appendLedgerLine(join8(kd, "edits.jsonl"), JSON.stringify({ f: file2 }) + "\n");
6874
+ appendLedgerLine(join9(kd, "edits.jsonl"), JSON.stringify({ f: file2 }) + "\n");
6877
6875
  } catch {
6878
6876
  }
6879
6877
  }
@@ -6881,9 +6879,9 @@ function readEdits(key, dir = antigravityStateDir()) {
6881
6879
  try {
6882
6880
  const kd = keyDir(key, dir);
6883
6881
  if (isUnsafePath(kd)) return { count: 0, files: [] };
6884
- const editsPath = join8(kd, "edits.jsonl");
6882
+ const editsPath = join9(kd, "edits.jsonl");
6885
6883
  if (isUnsafeFilePath(editsPath)) return { count: 0, files: [] };
6886
- const content = readFileSync9(editsPath, "utf8");
6884
+ const content = readFileSync10(editsPath, "utf8");
6887
6885
  let count = 0;
6888
6886
  const files = [];
6889
6887
  const seen = /* @__PURE__ */ new Set();
@@ -6913,7 +6911,7 @@ function markReviewed(key, dir = antigravityStateDir()) {
6913
6911
  const now = Date.now();
6914
6912
  const kd = ensureLiveKeyDir(key, dir, now);
6915
6913
  if (!kd) return;
6916
- writeMarkerFile(join8(kd, "reviewed"), String(now));
6914
+ writeMarkerFile(join9(kd, "reviewed"), String(now));
6917
6915
  } catch {
6918
6916
  }
6919
6917
  }
@@ -6921,7 +6919,7 @@ function isReviewed(key, dir = antigravityStateDir()) {
6921
6919
  try {
6922
6920
  const kd = keyDir(key, dir);
6923
6921
  if (isUnsafePath(kd)) return false;
6924
- return lstatSync(join8(kd, "reviewed")).isFile();
6922
+ return lstatSync(join9(kd, "reviewed")).isFile();
6925
6923
  } catch {
6926
6924
  return false;
6927
6925
  }
@@ -6930,7 +6928,7 @@ function pruneStale(dir = antigravityStateDir(), now = Date.now(), maxAgeMs = DE
6930
6928
  try {
6931
6929
  const entries = readdirSync(dir);
6932
6930
  for (const name of entries) {
6933
- const entryPath = join8(dir, name);
6931
+ const entryPath = join9(dir, name);
6934
6932
  try {
6935
6933
  const { mtimeMs } = lstatSync(entryPath);
6936
6934
  if (now - mtimeMs > maxAgeMs) {
@@ -6995,9 +6993,7 @@ async function fetchRulesHook(deps = {}) {
6995
6993
  const { projectId, apiBase: configApiBase } = resolution;
6996
6994
  if (!projectId) return;
6997
6995
  const apiBase = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
6998
- const token = resolveTok(config2.region.mcpName, {
6999
- mcpUrl: config2.region.mcpUrl
7000
- });
6996
+ const token = resolveTok(config2.region.mcpName);
7001
6997
  if (!token) return;
7002
6998
  const intent = buildIntent(event);
7003
6999
  const fileLabel = files.join(", ");
@@ -7104,6 +7100,15 @@ function composeSecurityBody(markdown, total, filePath) {
7104
7100
  ].join("\n");
7105
7101
  }
7106
7102
 
7103
+ // src/hooks/runtime/sign-in-notice.ts
7104
+ import { homedir as homedir11 } from "node:os";
7105
+ import { join as join11 } from "node:path";
7106
+
7107
+ // src/hooks/runtime/user-prompt-submit.ts
7108
+ import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "node:fs";
7109
+ import { homedir as homedir10 } from "node:os";
7110
+ import { join as join10 } from "node:path";
7111
+
7107
7112
  // src/hooks/runtime/proposal-mode.ts
7108
7113
  var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
7109
7114
  var FALSY = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
@@ -7128,11 +7133,144 @@ var DIRECT_PROPOSE_DIRECTIVES = {
7128
7133
  "non-blocking": `**Non-blocking mode is ON** (autonomous agent \u2014 nobody is in the chat to answer). Do NOT ask the user (no AskUserQuestion). If \u2014 and ONLY if \u2014 one durable, reusable gap stands out, call ${REPORT_MISSING_CALL} directly for that single rule. It lands as a pending proposal that a human accepts or rejects in the CybeDefend dashboard. Otherwise propose nothing.`
7129
7134
  };
7130
7135
 
7136
+ // src/hooks/runtime/user-prompt-submit.ts
7137
+ var SESSIONS_CAP2 = 100;
7138
+ function defaultSessionsFile() {
7139
+ const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join10(homedir10(), ".cybedefend");
7140
+ return join10(dir, "user-prompt-seen-sessions.json");
7141
+ }
7142
+ function defaultSessionTracker(file2 = defaultSessionsFile()) {
7143
+ function load2() {
7144
+ if (!existsSync10(file2)) return [];
7145
+ try {
7146
+ const raw = readFileSync11(file2, "utf8");
7147
+ const data = JSON.parse(raw);
7148
+ if (!Array.isArray(data.sessions)) return [];
7149
+ return data.sessions.filter((s) => typeof s === "string");
7150
+ } catch {
7151
+ return [];
7152
+ }
7153
+ }
7154
+ return {
7155
+ hasSeen(sessionId) {
7156
+ return load2().includes(sessionId);
7157
+ },
7158
+ async markSeen(sessionId) {
7159
+ const existing = load2();
7160
+ if (existing.includes(sessionId)) return;
7161
+ const next = [...existing, sessionId].slice(-SESSIONS_CAP2);
7162
+ try {
7163
+ mkdirSync8(join10(file2, ".."), { recursive: true });
7164
+ writeFileSync7(file2, JSON.stringify({ sessions: next }), "utf8");
7165
+ } catch {
7166
+ }
7167
+ }
7168
+ };
7169
+ }
7170
+ async function userPromptSubmitHook(deps = {}) {
7171
+ const readStdin = deps.readStdin ?? readStdinJson;
7172
+ const loadConfig = deps.loadConfig ?? loadRuntimeConfig;
7173
+ const resolveProject = deps.resolveProject ?? resolveProjectIdWithApi;
7174
+ const resolveTok = deps.resolveTokenFn ?? resolveToken;
7175
+ const fetchProposals = deps.fetchProposalsFn ?? fetchProposalsCount;
7176
+ const emitFn = deps.emitFn ?? emit;
7177
+ const sessionTracker = deps.sessionTracker ?? defaultSessionTracker();
7178
+ const stdin = await readStdin();
7179
+ const event = sniff(stdin);
7180
+ const sessionId = typeof stdin.session_id === "string" && stdin.session_id.length > 0 ? stdin.session_id : null;
7181
+ if (sessionId !== null && sessionTracker.hasSeen(sessionId)) {
7182
+ return;
7183
+ }
7184
+ const config2 = loadConfig();
7185
+ if (!config2) return;
7186
+ const folder = sessionFolderOf(stdin, event.client);
7187
+ if (isSessionInactive(stdin, { store: deps.sessionStore, cwd: folder })) return;
7188
+ const { projectId, apiBase: configApiBase } = await resolveProject(folder);
7189
+ if (!projectId) return;
7190
+ const apiBase = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
7191
+ const token = resolveTok(config2.region.mcpName);
7192
+ let total = null;
7193
+ if (token) {
7194
+ const result = await fetchProposals({ apiBase, projectId, token });
7195
+ if (result) total = result.total;
7196
+ }
7197
+ const lines = [
7198
+ "## \u26A0\uFE0F CybeDefend doctrine \u2014 execute BEFORE answering this prompt",
7199
+ "",
7200
+ `**Project**: \`${projectId}\``,
7201
+ "",
7202
+ "### Step 0 \u2014 Proposal inbox"
7203
+ ];
7204
+ const nonBlocking = isNonBlockingMode(config2);
7205
+ if (nonBlocking) {
7206
+ lines.push(
7207
+ `- CybeDefend: ${total === null ? "proposal inbox not checked" : `**${total}** pending proposals`} \u2014 no action required.`,
7208
+ `- ${NON_BLOCKING_INBOX_DIRECTIVE}`
7209
+ );
7210
+ } else if (total === null) {
7211
+ lines.push(
7212
+ "- CybeDefend: could not fetch proposal-inbox status (token / API unreachable).",
7213
+ '- Call `cybe_rules_list_proposals(projectId, status="proposed")` yourself to verify, then handle each surfaced proposal via AskUserQuestion (Accept / Reject / Skip / Tell me more) before continuing.'
7214
+ );
7215
+ } else if (total > 0) {
7216
+ lines.push(
7217
+ `- CybeDefend: **${total}** pending proposals.`,
7218
+ '- Call `cybe_rules_list_proposals(projectId, status="proposed")` and surface each via AskUserQuestion (Accept / Reject / Skip / Tell me more) BEFORE responding to this prompt.'
7219
+ );
7220
+ } else {
7221
+ lines.push(
7222
+ "- CybeDefend: **0** pending proposals.",
7223
+ '- You MUST still acknowledge step 0 in your reply ("No pending business-rule proposals."). Silently skipping this step is a doctrine violation observed in earlier sessions.'
7224
+ );
7225
+ }
7226
+ lines.push(
7227
+ "",
7228
+ "### Step 1 \u2014 Rules fetch (before any code edit)",
7229
+ "- Even if you plan to brainstorm / explore / ask clarifying questions first, call BOTH:",
7230
+ ' - `cybe_rules_fetch(projectId, files=[...], intent="<1-2 sentence narrative>")` for business rules',
7231
+ ' - `cybe_secrules_fetch(projectId, files=[...], intent="...", languages=[...])` for security rules',
7232
+ '- Use a rich `intent` \u2014 the retrieval is 60% graph + 40% vector, so a generic placeholder like "Editing file" returns nothing useful.',
7233
+ "- The PreToolUse hook fires automatically as a backstop on Edit/Write/MultiEdit, but your explicit call with a narrative intent gets better matches.",
7234
+ "",
7235
+ "### Order",
7236
+ nonBlocking ? "1. Step 0 needs no action (non-blocking mode)." : "1. Satisfy step 0 (acknowledge / handle the inbox).",
7237
+ "2. Satisfy step 1 (fetch rules with a narrative intent) once you know which files you will touch.",
7238
+ "3. THEN proceed with whatever skill / brainstorm / implementation flow fits the task.",
7239
+ ""
7240
+ );
7241
+ emitFn(lines.join("\n"), event.client);
7242
+ if (sessionId !== null) {
7243
+ try {
7244
+ await sessionTracker.markSeen(sessionId);
7245
+ } catch {
7246
+ }
7247
+ }
7248
+ }
7249
+
7250
+ // src/hooks/runtime/sign-in-notice.ts
7251
+ var SIGN_IN_NOTICE = "\u{1F6E1}\uFE0F CybeDefend found no sign-in: Action Guards may not be enforced, and no rules reach your agent. Run `vibedefend login`.";
7252
+ function noticeSessionsFile() {
7253
+ const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join11(homedir11(), ".cybedefend");
7254
+ return join11(dir, "sign-in-notice-sessions.json");
7255
+ }
7256
+ async function claimSignInNotice(mcpName, sessionId, deps = {}) {
7257
+ if (!sessionId) return false;
7258
+ try {
7259
+ const sessions = defaultSessionTracker(noticeSessionsFile());
7260
+ if (sessions.hasSeen(sessionId)) return false;
7261
+ if ((deps.hasUsableSignIn ?? hasUsableStoredAuth)(mcpName)) return false;
7262
+ await sessions.markSeen(sessionId);
7263
+ return true;
7264
+ } catch {
7265
+ return false;
7266
+ }
7267
+ }
7268
+
7131
7269
  // src/hooks/runtime/self-update-check.ts
7132
7270
  import { spawn } from "node:child_process";
7133
- import { existsSync as existsSync11, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "node:fs";
7134
- import { homedir as homedir9 } from "node:os";
7135
- import { join as join9 } from "node:path";
7271
+ import { existsSync as existsSync12, readFileSync as readFileSync12, rmSync as rmSync2, writeFileSync as writeFileSync8 } from "node:fs";
7272
+ import { homedir as homedir12 } from "node:os";
7273
+ import { join as join12 } from "node:path";
7136
7274
 
7137
7275
  // src/hooks/runtime/semver.ts
7138
7276
  function parseVersion(input2) {
@@ -7160,7 +7298,7 @@ function isNewer(latest, current) {
7160
7298
 
7161
7299
  // src/self-update.ts
7162
7300
  import { fileURLToPath as fileURLToPath2 } from "node:url";
7163
- import { existsSync as existsSync10, realpathSync as realpathSync2 } from "node:fs";
7301
+ import { existsSync as existsSync11, realpathSync as realpathSync2 } from "node:fs";
7164
7302
  var GLOBAL_MODES = /* @__PURE__ */ new Set([
7165
7303
  "npm-global",
7166
7304
  "pnpm-global",
@@ -7188,7 +7326,7 @@ function detectInstallMode(scriptPath) {
7188
7326
  }
7189
7327
  function resolveScriptPath() {
7190
7328
  const fromArgv = process.argv[1];
7191
- if (fromArgv && existsSync10(fromArgv)) {
7329
+ if (fromArgv && existsSync11(fromArgv)) {
7192
7330
  try {
7193
7331
  return realpathSync2(fromArgv);
7194
7332
  } catch {
@@ -7210,9 +7348,9 @@ function isValidRegistryVersion(value) {
7210
7348
  }
7211
7349
  async function selfUpdateCheck(deps) {
7212
7350
  const now = deps.now ?? (() => Date.now());
7213
- const dir = deps.cybeDir ?? join9(process.env.CYBEDEFEND_HOME ?? homedir9(), ".cybedefend");
7214
- const throttlePath = join9(dir, "update-check.json");
7215
- const logPath = join9(dir, "last-update.log");
7351
+ const dir = deps.cybeDir ?? join12(process.env.CYBEDEFEND_HOME ?? homedir12(), ".cybedefend");
7352
+ const throttlePath = join12(dir, "update-check.json");
7353
+ const logPath = join12(dir, "last-update.log");
7216
7354
  const installMode = deps.installMode ?? (deps.runnerSource ? detectInstallMode(deps.runnerSource) : detectInstallMode(resolveScriptPath()));
7217
7355
  const priorFailure = takeUpdateLogNotice(logPath);
7218
7356
  const throttle = readThrottle(throttlePath);
@@ -7245,8 +7383,8 @@ function applyOrNotify(deps, installMode, latest, logPath) {
7245
7383
  }
7246
7384
  function readThrottle(path) {
7247
7385
  try {
7248
- if (!existsSync11(path)) return null;
7249
- const data = JSON.parse(readFileSync10(path, "utf8"));
7386
+ if (!existsSync12(path)) return null;
7387
+ const data = JSON.parse(readFileSync12(path, "utf8"));
7250
7388
  if (typeof data.lastCheckedAt !== "number") return null;
7251
7389
  return { lastCheckedAt: data.lastCheckedAt };
7252
7390
  } catch {
@@ -7256,16 +7394,16 @@ function readThrottle(path) {
7256
7394
  function writeThrottle(path, throttle) {
7257
7395
  try {
7258
7396
  ensureDirFor(path);
7259
- writeFileSync7(path, JSON.stringify(throttle) + "\n");
7397
+ writeFileSync8(path, JSON.stringify(throttle) + "\n");
7260
7398
  } catch {
7261
7399
  }
7262
7400
  }
7263
7401
  function takeUpdateLogNotice(logPath) {
7264
7402
  try {
7265
- if (!existsSync11(logPath)) return null;
7403
+ if (!existsSync12(logPath)) return null;
7266
7404
  let parsed = {};
7267
7405
  try {
7268
- parsed = JSON.parse(readFileSync10(logPath, "utf8"));
7406
+ parsed = JSON.parse(readFileSync12(logPath, "utf8"));
7269
7407
  } catch {
7270
7408
  parsed = {};
7271
7409
  }
@@ -7340,18 +7478,18 @@ function pmCommand(mode, spec) {
7340
7478
 
7341
7479
  // src/hooks/runtime/hook-refresh-trigger.ts
7342
7480
  import { spawn as spawn2 } from "node:child_process";
7343
- import { existsSync as existsSync12, readFileSync as readFileSync11, writeFileSync as writeFileSync8 } from "node:fs";
7344
- import { homedir as homedir10 } from "node:os";
7345
- import { dirname as dirname6, join as join10 } from "node:path";
7481
+ import { existsSync as existsSync13, readFileSync as readFileSync13, writeFileSync as writeFileSync9 } from "node:fs";
7482
+ import { homedir as homedir13 } from "node:os";
7483
+ import { dirname as dirname7, join as join13 } from "node:path";
7346
7484
  function maybeRefreshStaleWiring(deps) {
7347
7485
  try {
7348
7486
  const { config: config2, runnerVersion } = deps;
7349
7487
  if (!config2.runnerSource || config2.installedVersion === runnerVersion) {
7350
7488
  return false;
7351
7489
  }
7352
- const cliEntry = join10(dirname6(dirname6(config2.runnerSource)), "bin", "vibedefend.js");
7353
- if (!(deps.exists ?? existsSync12)(cliEntry)) return false;
7354
- const markerPath = deps.markerPath ?? join10(process.env.CYBEDEFEND_HOME ?? homedir10(), ".cybedefend", "hook-refresh.json");
7490
+ const cliEntry = join13(dirname7(dirname7(config2.runnerSource)), "bin", "vibedefend.js");
7491
+ if (!(deps.exists ?? existsSync13)(cliEntry)) return false;
7492
+ const markerPath = deps.markerPath ?? join13(process.env.CYBEDEFEND_HOME ?? homedir13(), ".cybedefend", "hook-refresh.json");
7355
7493
  if (readMarkerVersion(markerPath) === runnerVersion) return false;
7356
7494
  (deps.spawnRefresh ?? defaultSpawnRefresh)(cliEntry);
7357
7495
  writeMarker(markerPath, runnerVersion);
@@ -7362,8 +7500,8 @@ function maybeRefreshStaleWiring(deps) {
7362
7500
  }
7363
7501
  function readMarkerVersion(path) {
7364
7502
  try {
7365
- if (!existsSync12(path)) return null;
7366
- const data = JSON.parse(readFileSync11(path, "utf8"));
7503
+ if (!existsSync13(path)) return null;
7504
+ const data = JSON.parse(readFileSync13(path, "utf8"));
7367
7505
  return typeof data.version === "string" ? data.version : null;
7368
7506
  } catch {
7369
7507
  return null;
@@ -7372,7 +7510,7 @@ function readMarkerVersion(path) {
7372
7510
  function writeMarker(path, version2) {
7373
7511
  try {
7374
7512
  ensureDirFor(path);
7375
- writeFileSync8(path, JSON.stringify({ version: version2, spawnedAt: Date.now() }) + "\n");
7513
+ writeFileSync9(path, JSON.stringify({ version: version2, spawnedAt: Date.now() }) + "\n");
7376
7514
  } catch {
7377
7515
  }
7378
7516
  }
@@ -7386,18 +7524,18 @@ function defaultSpawnRefresh(cliEntry) {
7386
7524
  }
7387
7525
 
7388
7526
  // src/version.ts
7389
- import { readFileSync as readFileSync12 } from "node:fs";
7527
+ import { readFileSync as readFileSync14 } from "node:fs";
7390
7528
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7391
- import { dirname as dirname7, join as join11 } from "node:path";
7529
+ import { dirname as dirname8, join as join14 } from "node:path";
7392
7530
  var PKG_NAME = "@cybedefend/vibedefend";
7393
7531
  function defaultPkgPath() {
7394
- return join11(dirname7(fileURLToPath3(import.meta.url)), "..", "package.json");
7532
+ return join14(dirname8(fileURLToPath3(import.meta.url)), "..", "package.json");
7395
7533
  }
7396
7534
  function readPackageMeta(opts = {}) {
7397
7535
  if (typeof opts.bakedVersion === "string" && opts.bakedVersion.length > 0) {
7398
7536
  return { name: PKG_NAME, version: opts.bakedVersion };
7399
7537
  }
7400
- const readFile = opts.readFile ?? ((p) => readFileSync12(p, "utf8"));
7538
+ const readFile = opts.readFile ?? ((p) => readFileSync14(p, "utf8"));
7401
7539
  const pkgPath = opts.pkgPath ?? defaultPkgPath();
7402
7540
  try {
7403
7541
  return JSON.parse(readFile(pkgPath));
@@ -7406,7 +7544,7 @@ function readPackageMeta(opts = {}) {
7406
7544
  }
7407
7545
  }
7408
7546
  var pkg = readPackageMeta({
7409
- bakedVersion: true ? "1.8.1" : void 0
7547
+ bakedVersion: true ? "1.8.3" : void 0
7410
7548
  });
7411
7549
 
7412
7550
  // src/hooks/runtime/session-start.ts
@@ -7462,9 +7600,7 @@ async function sessionStartHook(deps = {}) {
7462
7600
  );
7463
7601
  return;
7464
7602
  }
7465
- const token = resolveTok(config2.region.mcpName, {
7466
- mcpUrl: config2.region.mcpUrl
7467
- });
7603
+ const token = resolveTok(config2.region.mcpName);
7468
7604
  let total = null;
7469
7605
  if (token) {
7470
7606
  const result = await fetchProposals({ apiBase, projectId, token });
@@ -7544,27 +7680,41 @@ async function sessionStartHook(deps = {}) {
7544
7680
  if (notice) lines.push("", notice);
7545
7681
  } catch {
7546
7682
  }
7547
- emitFn(lines.join("\n") + "\n", event.client);
7683
+ const body = lines.join("\n") + "\n";
7684
+ const claimNotice = deps.claimSignInNoticeFn ?? claimSignInNotice;
7685
+ if (!token && await claimNotice(config2.region.mcpName, sessionId)) {
7686
+ emitNoticeFn(
7687
+ {
7688
+ userMessage: SIGN_IN_NOTICE,
7689
+ modelContext: body + (SYSTEM_MESSAGE_CLIENTS.has(event.client) ? "\n- **No sign-in**: the user has been told to run `vibedefend login`; do not repeat it.\n" : `
7690
+ - **No sign-in**: Tell the user once, in one short line: ${SIGN_IN_NOTICE}
7691
+ `)
7692
+ },
7693
+ event.client
7694
+ );
7695
+ return;
7696
+ }
7697
+ emitFn(body, event.client);
7548
7698
  }
7549
7699
 
7550
7700
  // src/hooks/runtime/session-review.ts
7551
- import { existsSync as existsSync14, readFileSync as readFileSync14 } from "node:fs";
7701
+ import { existsSync as existsSync15, readFileSync as readFileSync16 } from "node:fs";
7552
7702
 
7553
7703
  // src/hooks/runtime/review-sessions.ts
7554
- import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync13, writeFileSync as writeFileSync9 } from "node:fs";
7555
- import { homedir as homedir11 } from "node:os";
7556
- import { dirname as dirname8, join as join12 } from "node:path";
7557
- var SESSIONS_CAP2 = 200;
7704
+ import { existsSync as existsSync14, mkdirSync as mkdirSync9, readFileSync as readFileSync15, writeFileSync as writeFileSync10 } from "node:fs";
7705
+ import { homedir as homedir14 } from "node:os";
7706
+ import { dirname as dirname9, join as join15 } from "node:path";
7707
+ var SESSIONS_CAP3 = 200;
7558
7708
  function defaultStoreFile2() {
7559
- const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join12(homedir11(), ".cybedefend");
7560
- return join12(dir, "review-sessions.json");
7709
+ const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join15(homedir14(), ".cybedefend");
7710
+ return join15(dir, "review-sessions.json");
7561
7711
  }
7562
7712
  var isCount = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0;
7563
7713
  function defaultReviewSessionStore(file2 = defaultStoreFile2(), now = Date.now) {
7564
7714
  function load2() {
7565
- if (!existsSync13(file2)) return {};
7715
+ if (!existsSync14(file2)) return {};
7566
7716
  try {
7567
- const parsed = JSON.parse(readFileSync13(file2, "utf8"));
7717
+ const parsed = JSON.parse(readFileSync15(file2, "utf8"));
7568
7718
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
7569
7719
  } catch {
7570
7720
  return {};
@@ -7572,8 +7722,8 @@ function defaultReviewSessionStore(file2 = defaultStoreFile2(), now = Date.now)
7572
7722
  }
7573
7723
  function save(map2) {
7574
7724
  try {
7575
- mkdirSync7(dirname8(file2), { recursive: true });
7576
- writeFileSync9(file2, JSON.stringify(map2) + "\n", "utf8");
7725
+ mkdirSync9(dirname9(file2), { recursive: true });
7726
+ writeFileSync10(file2, JSON.stringify(map2) + "\n", "utf8");
7577
7727
  } catch {
7578
7728
  }
7579
7729
  }
@@ -7588,9 +7738,9 @@ function defaultReviewSessionStore(file2 = defaultStoreFile2(), now = Date.now)
7588
7738
  const map2 = load2();
7589
7739
  map2[sessionId] = { ...record2, at: now() };
7590
7740
  const entries = Object.entries(map2);
7591
- if (entries.length > SESSIONS_CAP2) {
7741
+ if (entries.length > SESSIONS_CAP3) {
7592
7742
  entries.sort(([, a], [, b]) => (a.at ?? 0) - (b.at ?? 0));
7593
- save(Object.fromEntries(entries.slice(-SESSIONS_CAP2)));
7743
+ save(Object.fromEntries(entries.slice(-SESSIONS_CAP3)));
7594
7744
  return;
7595
7745
  }
7596
7746
  save(map2);
@@ -7702,10 +7852,11 @@ async function sessionReviewHook(deps = {}) {
7702
7852
  const withDiffScan2 = config2.hooks.enableDiffScan !== false;
7703
7853
  if (withDiffScan2) {
7704
7854
  body2 += "\n" + composeDiffScanBody(
7705
- files.slice(0, CHANGED_FILES_MAX).map((f) => relativizePath(f, folder2))
7855
+ files.slice(0, CHANGED_FILES_MAX).map((f) => relativizePath(f, folder2)),
7856
+ "antigravity"
7706
7857
  );
7707
7858
  }
7708
- emitFn(body2, "antigravity", composeStopReason(withDiffScan2, proposalMode2));
7859
+ emitFn(body2, "antigravity", composeStopReason(withDiffScan2, proposalMode2, "antigravity"));
7709
7860
  markReviewed(key, stateDir);
7710
7861
  return;
7711
7862
  }
@@ -7751,9 +7902,9 @@ async function sessionReviewHook(deps = {}) {
7751
7902
  const withDiffScan = config2.hooks.enableDiffScan !== false;
7752
7903
  if (withDiffScan) {
7753
7904
  const unreviewed = eventsAfterEdits(transcript, reviewed);
7754
- body += "\n" + composeDiffScanBody(extractChangedFiles(unreviewed, void 0, folder));
7905
+ body += "\n" + composeDiffScanBody(extractChangedFiles(unreviewed, void 0, folder), event.client);
7755
7906
  }
7756
- emitFn(body, event.client, composeStopReason(withDiffScan, proposalMode));
7907
+ emitFn(body, event.client, composeStopReason(withDiffScan, proposalMode, event.client));
7757
7908
  if (!dryRun) remember(total);
7758
7909
  }
7759
7910
  function loadTranscript(stdin, readFile) {
@@ -7783,9 +7934,9 @@ function loadTranscript(stdin, readFile) {
7783
7934
  return out;
7784
7935
  }
7785
7936
  function defaultReadTranscript(path) {
7786
- if (!existsSync14(path)) return null;
7937
+ if (!existsSync15(path)) return null;
7787
7938
  try {
7788
- return readFileSync14(path, "utf8");
7939
+ return readFileSync16(path, "utf8");
7789
7940
  } catch {
7790
7941
  return null;
7791
7942
  }
@@ -7953,7 +8104,10 @@ function composeReviewBody(editCount, client, userPrompt, proposalMode) {
7953
8104
  ""
7954
8105
  ].join("\n");
7955
8106
  }
7956
- function composeDiffScanBody(changedFiles) {
8107
+ function scanDiffCommand(client) {
8108
+ return client === "unknown" ? "vibedefend scan-diff <paths...>" : `vibedefend scan-diff --agent ${client} <paths...>`;
8109
+ }
8110
+ function composeDiffScanBody(changedFiles, client) {
7957
8111
  const total = changedFiles.length;
7958
8112
  const shown = changedFiles.slice(0, CHANGED_FILES_DISPLAY);
7959
8113
  const heading = total > CHANGED_FILES_DISPLAY ? `**Changed files this session (showing first ${CHANGED_FILES_DISPLAY} of ${total}):**` : `**Changed files this session (${total}):**`;
@@ -7962,8 +8116,8 @@ function composeDiffScanBody(changedFiles) {
7962
8116
  ...shown.map((f) => `- \`${f}\``),
7963
8117
  "(If you changed other files not listed above, include them too.)"
7964
8118
  ] : [
7965
- "Use the repo-relative paths of every file you created or edited this",
7966
- "session as the `paths`."
8119
+ "Use the paths of every file you created or edited this session as the",
8120
+ "`paths` (relative to your current folder, or absolute)."
7967
8121
  ];
7968
8122
  return [
7969
8123
  "## \u{1F50D} CybeDefend pre-commit diff scan",
@@ -7974,21 +8128,29 @@ function composeDiffScanBody(changedFiles) {
7974
8128
  ...fileLines,
7975
8129
  "",
7976
8130
  "### Required next-turn action",
7977
- "1. Call `cybe_scan_diff(projectId, { paths })` with those repo-relative",
7978
- " PATHS (paths only \u2014 NOT the file contents). It returns",
7979
- " `{ scanId, uploadUrl, expiresAt }`.",
7980
- "2. Build a ZIP of those exact files (full current content, repo-relative",
7981
- " entry names \u2014 e.g. `zip -q diff.zip <paths>`) and upload it with an HTTP",
7982
- " PUT to `uploadUrl` (header `Content-Type: application/zip`) BEFORE",
7983
- ' `expiresAt` (e.g. `curl -X PUT -H "Content-Type: application/zip"',
7984
- ' --data-binary @diff.zip "<uploadUrl>"`). The contents go straight to the',
7985
- " bucket, never through the MCP tool.",
7986
- "3. Poll `cybe_scan_status(projectId, scanId)` until it is completed, then",
8131
+ `1. Run \`${scanDiffCommand(client)}\` from the session folder, with`,
8132
+ " those paths as arguments: they are relative to the session folder, and",
8133
+ " the command reads a relative path from the folder it runs in",
8134
+ " (absolute paths work too; quote any path with spaces). It finds the project",
8135
+ " (`.cybedefend/config.json`, else the git `origin`), asks CybeDefend for",
8136
+ " the scan, zips and uploads the files itself, and prints the `scanId`",
8137
+ " (`--json` prints `{ projectId, scanId, scanners, expiresAt, files }`).",
8138
+ " If it says no scanner applies, there is nothing to scan: stop here.",
8139
+ "2. Poll `cybe_scan_status(projectId, scanId)` until it is completed, then",
7987
8140
  " read `cybe_scan_findings(projectId, scanId)`.",
7988
- "4. Fix or justify every finding. For a confident false positive, add a",
8141
+ "3. Fix or justify every finding. For a confident false positive, add a",
7989
8142
  " `// cybedefend-ignore: <reason>` comment on the offending line so it",
7990
8143
  " stays silenced on the full scan too.",
7991
8144
  "",
8145
+ "Fallback, ONLY if the `vibedefend` command is not available: call",
8146
+ "`cybe_scan_diff(projectId, { paths })` (paths only, not the contents); it",
8147
+ "returns `{ scanId, uploadUrl, uploadHeaders, expiresAt }`. Build a ZIP of",
8148
+ "those files (entry names: the same paths) and upload it with an HTTP PUT",
8149
+ "to that `uploadUrl` before `expiresAt`, sending every header of",
8150
+ "`uploadHeaders` (only `Content-Type: application/zip` when there is none),",
8151
+ "then continue at step 2. Only ever upload to the `uploadUrl` that",
8152
+ "`cybe_scan_diff` just returned.",
8153
+ "",
7992
8154
  "This diff scan is best-effort \u2014 it COMPLEMENTS, never replaces, the full",
7993
8155
  "scan (secrets are head-only; cross-file SAST context may be missing). Caps:",
7994
8156
  "300 files / 1 MB per file / 3 MB total \u2014 over the cap the scan fails, so run",
@@ -7996,8 +8158,8 @@ function composeDiffScanBody(changedFiles) {
7996
8158
  ""
7997
8159
  ].join("\n");
7998
8160
  }
7999
- function composeStopReason(withDiffScan, proposalMode) {
8000
- const scan = withDiffScan ? " Then run a pre-commit `cybe_scan_diff` on the files you changed (poll `cybe_scan_status`, read `cybe_scan_findings`) and fix or justify each finding." : "";
8161
+ function composeStopReason(withDiffScan, proposalMode, client) {
8162
+ const scan = withDiffScan ? ` Then run a pre-commit diff scan of the files you changed: \`${scanDiffCommand(client)}\` (paths relative to your current folder, or absolute; it uploads the files and prints a scanId), poll \`cybe_scan_status\`, read \`cybe_scan_findings\`, and fix or justify each finding. Only if the \`vibedefend\` command is not available, use \`cybe_scan_diff\` instead.` : "";
8001
8163
  const directPropose = "If \u2014 and only if \u2014 one durable rule is missing, propose that single rule directly with `cybe_rules_report_missing` (`confirmed_by_user: true`). ";
8002
8164
  const propose = {
8003
8165
  // Ask only when the analysis found a rule: asking "propose a rule?" with
@@ -8052,125 +8214,6 @@ async function preCompactHook(deps = {}) {
8052
8214
  emitFn(body, event.client);
8053
8215
  }
8054
8216
 
8055
- // src/hooks/runtime/user-prompt-submit.ts
8056
- import { existsSync as existsSync15, mkdirSync as mkdirSync8, readFileSync as readFileSync15, writeFileSync as writeFileSync10 } from "node:fs";
8057
- import { homedir as homedir12 } from "node:os";
8058
- import { join as join13 } from "node:path";
8059
- var SESSIONS_CAP3 = 100;
8060
- function defaultSessionsFile() {
8061
- const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join13(homedir12(), ".cybedefend");
8062
- return join13(dir, "user-prompt-seen-sessions.json");
8063
- }
8064
- function defaultSessionTracker(file2 = defaultSessionsFile()) {
8065
- function load2() {
8066
- if (!existsSync15(file2)) return [];
8067
- try {
8068
- const raw = readFileSync15(file2, "utf8");
8069
- const data = JSON.parse(raw);
8070
- if (!Array.isArray(data.sessions)) return [];
8071
- return data.sessions.filter((s) => typeof s === "string");
8072
- } catch {
8073
- return [];
8074
- }
8075
- }
8076
- return {
8077
- hasSeen(sessionId) {
8078
- return load2().includes(sessionId);
8079
- },
8080
- async markSeen(sessionId) {
8081
- const existing = load2();
8082
- if (existing.includes(sessionId)) return;
8083
- const next = [...existing, sessionId].slice(-SESSIONS_CAP3);
8084
- try {
8085
- mkdirSync8(join13(file2, ".."), { recursive: true });
8086
- writeFileSync10(file2, JSON.stringify({ sessions: next }), "utf8");
8087
- } catch {
8088
- }
8089
- }
8090
- };
8091
- }
8092
- async function userPromptSubmitHook(deps = {}) {
8093
- const readStdin = deps.readStdin ?? readStdinJson;
8094
- const loadConfig = deps.loadConfig ?? loadRuntimeConfig;
8095
- const resolveProject = deps.resolveProject ?? resolveProjectIdWithApi;
8096
- const resolveTok = deps.resolveTokenFn ?? resolveToken;
8097
- const fetchProposals = deps.fetchProposalsFn ?? fetchProposalsCount;
8098
- const emitFn = deps.emitFn ?? emit;
8099
- const sessionTracker = deps.sessionTracker ?? defaultSessionTracker();
8100
- const stdin = await readStdin();
8101
- const event = sniff(stdin);
8102
- const sessionId = typeof stdin.session_id === "string" && stdin.session_id.length > 0 ? stdin.session_id : null;
8103
- if (sessionId !== null && sessionTracker.hasSeen(sessionId)) {
8104
- return;
8105
- }
8106
- const config2 = loadConfig();
8107
- if (!config2) return;
8108
- const folder = sessionFolderOf(stdin, event.client);
8109
- if (isSessionInactive(stdin, { store: deps.sessionStore, cwd: folder })) return;
8110
- const { projectId, apiBase: configApiBase } = await resolveProject(folder);
8111
- if (!projectId) return;
8112
- const apiBase = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
8113
- const token = resolveTok(config2.region.mcpName, {
8114
- mcpUrl: config2.region.mcpUrl
8115
- });
8116
- let total = null;
8117
- if (token) {
8118
- const result = await fetchProposals({ apiBase, projectId, token });
8119
- if (result) total = result.total;
8120
- }
8121
- const lines = [
8122
- "## \u26A0\uFE0F CybeDefend doctrine \u2014 execute BEFORE answering this prompt",
8123
- "",
8124
- `**Project**: \`${projectId}\``,
8125
- "",
8126
- "### Step 0 \u2014 Proposal inbox"
8127
- ];
8128
- const nonBlocking = isNonBlockingMode(config2);
8129
- if (nonBlocking) {
8130
- lines.push(
8131
- `- CybeDefend: ${total === null ? "proposal inbox not checked" : `**${total}** pending proposals`} \u2014 no action required.`,
8132
- `- ${NON_BLOCKING_INBOX_DIRECTIVE}`
8133
- );
8134
- } else if (total === null) {
8135
- lines.push(
8136
- "- CybeDefend: could not fetch proposal-inbox status (token / API unreachable).",
8137
- '- Call `cybe_rules_list_proposals(projectId, status="proposed")` yourself to verify, then handle each surfaced proposal via AskUserQuestion (Accept / Reject / Skip / Tell me more) before continuing.'
8138
- );
8139
- } else if (total > 0) {
8140
- lines.push(
8141
- `- CybeDefend: **${total}** pending proposals.`,
8142
- '- Call `cybe_rules_list_proposals(projectId, status="proposed")` and surface each via AskUserQuestion (Accept / Reject / Skip / Tell me more) BEFORE responding to this prompt.'
8143
- );
8144
- } else {
8145
- lines.push(
8146
- "- CybeDefend: **0** pending proposals.",
8147
- '- You MUST still acknowledge step 0 in your reply ("No pending business-rule proposals."). Silently skipping this step is a doctrine violation observed in earlier sessions.'
8148
- );
8149
- }
8150
- lines.push(
8151
- "",
8152
- "### Step 1 \u2014 Rules fetch (before any code edit)",
8153
- "- Even if you plan to brainstorm / explore / ask clarifying questions first, call BOTH:",
8154
- ' - `cybe_rules_fetch(projectId, files=[...], intent="<1-2 sentence narrative>")` for business rules',
8155
- ' - `cybe_secrules_fetch(projectId, files=[...], intent="...", languages=[...])` for security rules',
8156
- '- Use a rich `intent` \u2014 the retrieval is 60% graph + 40% vector, so a generic placeholder like "Editing file" returns nothing useful.',
8157
- "- The PreToolUse hook fires automatically as a backstop on Edit/Write/MultiEdit, but your explicit call with a narrative intent gets better matches.",
8158
- "",
8159
- "### Order",
8160
- nonBlocking ? "1. Step 0 needs no action (non-blocking mode)." : "1. Satisfy step 0 (acknowledge / handle the inbox).",
8161
- "2. Satisfy step 1 (fetch rules with a narrative intent) once you know which files you will touch.",
8162
- "3. THEN proceed with whatever skill / brainstorm / implementation flow fits the task.",
8163
- ""
8164
- );
8165
- emitFn(lines.join("\n"), event.client);
8166
- if (sessionId !== null) {
8167
- try {
8168
- await sessionTracker.markSeen(sessionId);
8169
- } catch {
8170
- }
8171
- }
8172
- }
8173
-
8174
8217
  // src/hooks/runtime/pre-invocation.ts
8175
8218
  var STASH_SEPARATOR = "\n\n---\n\n";
8176
8219
  async function preInvocationHook(deps = {}) {
@@ -11645,15 +11688,15 @@ function resolveCandidatePaths(rawPath, opts) {
11645
11688
  // src/hooks/runtime/session-writes.ts
11646
11689
  import {
11647
11690
  existsSync as existsSync17,
11648
- mkdirSync as mkdirSync9,
11649
- readFileSync as readFileSync17,
11691
+ mkdirSync as mkdirSync10,
11692
+ readFileSync as readFileSync18,
11650
11693
  renameSync as renameSync2,
11651
11694
  rmdirSync,
11652
- statSync as statSync3,
11695
+ statSync as statSync4,
11653
11696
  writeFileSync as writeFileSync11
11654
11697
  } from "node:fs";
11655
- import { homedir as homedir13 } from "node:os";
11656
- import { join as join14, posix } from "node:path";
11698
+ import { homedir as homedir15 } from "node:os";
11699
+ import { join as join16, posix } from "node:path";
11657
11700
  var DEFAULT_MAX_PATHS = 500;
11658
11701
  var DEFAULT_SESSION_WRITES_TTL_MS = 4 * 60 * 60 * 1e3;
11659
11702
  var SESSION_WRITES_FILE = "guards-session-writes.json";
@@ -11667,11 +11710,11 @@ function withLock(lockDir, fn) {
11667
11710
  let held = false;
11668
11711
  while (!held) {
11669
11712
  try {
11670
- mkdirSync9(lockDir);
11713
+ mkdirSync10(lockDir);
11671
11714
  held = true;
11672
11715
  } catch {
11673
11716
  try {
11674
- if (Date.now() - statSync3(lockDir).mtimeMs > LOCK_STALE_MS) {
11717
+ if (Date.now() - statSync4(lockDir).mtimeMs > LOCK_STALE_MS) {
11675
11718
  rmdirSync(lockDir);
11676
11719
  continue;
11677
11720
  }
@@ -11694,7 +11737,7 @@ function withLock(lockDir, fn) {
11694
11737
  }
11695
11738
  }
11696
11739
  function defaultDir() {
11697
- return process.env.CYBEDEFEND_BASELINE_DIR ?? join14(homedir13(), ".cybedefend");
11740
+ return process.env.CYBEDEFEND_BASELINE_DIR ?? join16(homedir15(), ".cybedefend");
11698
11741
  }
11699
11742
  function normalizePath(p) {
11700
11743
  if (typeof p !== "string") return "";
@@ -11729,14 +11772,14 @@ function coerce(raw) {
11729
11772
  }
11730
11773
  function makeSessionWritesStore(opts = {}) {
11731
11774
  const dir = opts.dir ?? defaultDir();
11732
- const file2 = join14(dir, SESSION_WRITES_FILE);
11775
+ const file2 = join16(dir, SESSION_WRITES_FILE);
11733
11776
  const now = opts.now ?? (() => Date.now());
11734
11777
  const maxPaths = typeof opts.maxPaths === "number" && opts.maxPaths > 0 ? Math.floor(opts.maxPaths) : DEFAULT_MAX_PATHS;
11735
11778
  const ttlMs = typeof opts.ttlMs === "number" && opts.ttlMs > 0 ? opts.ttlMs : DEFAULT_SESSION_WRITES_TTL_MS;
11736
11779
  function readAll() {
11737
11780
  if (!existsSync17(file2)) return {};
11738
11781
  try {
11739
- return coerce(JSON.parse(readFileSync17(file2, "utf8")));
11782
+ return coerce(JSON.parse(readFileSync18(file2, "utf8")));
11740
11783
  } catch {
11741
11784
  return {};
11742
11785
  }
@@ -11751,7 +11794,7 @@ function makeSessionWritesStore(opts = {}) {
11751
11794
  }
11752
11795
  function writeAll(all) {
11753
11796
  try {
11754
- if (!existsSync17(dir)) mkdirSync9(dir, { recursive: true });
11797
+ if (!existsSync17(dir)) mkdirSync10(dir, { recursive: true });
11755
11798
  const tmp = `${file2}.${process.pid}.tmp`;
11756
11799
  writeFileSync11(tmp, JSON.stringify(all), "utf8");
11757
11800
  renameSync2(tmp, file2);
@@ -11764,7 +11807,7 @@ function makeSessionWritesStore(opts = {}) {
11764
11807
  const usable = paths.filter(isUsable);
11765
11808
  if (usable.length === 0) return;
11766
11809
  try {
11767
- if (!existsSync17(dir)) mkdirSync9(dir, { recursive: true });
11810
+ if (!existsSync17(dir)) mkdirSync10(dir, { recursive: true });
11768
11811
  withLock(`${file2}.lock`, () => {
11769
11812
  const t = now();
11770
11813
  const all = pruneExpired(readAll(), t);
@@ -12080,10 +12123,10 @@ function nearMiss(req, rule) {
12080
12123
  import { isAbsolute as isAbsolute6, resolve as resolvePath4 } from "node:path";
12081
12124
 
12082
12125
  // src/hooks/runtime/guard-rules-cache.ts
12083
- import { readFileSync as readFileSync18, writeFileSync as writeFileSync12, existsSync as existsSync18, mkdirSync as mkdirSync10 } from "node:fs";
12084
- import { dirname as dirname9 } from "node:path";
12085
- import { homedir as homedir14 } from "node:os";
12086
- import { join as join15 } from "node:path";
12126
+ import { readFileSync as readFileSync19, writeFileSync as writeFileSync12, existsSync as existsSync18, mkdirSync as mkdirSync11 } from "node:fs";
12127
+ import { dirname as dirname10 } from "node:path";
12128
+ import { homedir as homedir16 } from "node:os";
12129
+ import { join as join17 } from "node:path";
12087
12130
 
12088
12131
  // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/external.js
12089
12132
  var external_exports = {};
@@ -31920,8 +31963,8 @@ function tokenFingerprint(token) {
31920
31963
  }
31921
31964
 
31922
31965
  // src/hooks/runtime/guard-rules-cache.ts
31923
- var DEFAULT_CACHE_FILE = join15(
31924
- homedir14(),
31966
+ var DEFAULT_CACHE_FILE = join17(
31967
+ homedir16(),
31925
31968
  ".cybedefend",
31926
31969
  "guards-cache.json"
31927
31970
  );
@@ -31996,7 +32039,7 @@ function reportDroppedRules(dropped) {
31996
32039
  }
31997
32040
  function makeGuardRulesCache(opts) {
31998
32041
  const cacheFile = opts.cacheFile ?? DEFAULT_CACHE_FILE;
31999
- const failuresFile = opts.failuresFile ?? join15(dirname9(cacheFile), "guards-cache-failures.json");
32042
+ const failuresFile = opts.failuresFile ?? join17(dirname10(cacheFile), "guards-cache-failures.json");
32000
32043
  const staleSec = opts.staleSec ?? DEFAULT_STALE_SEC;
32001
32044
  const fetchFn = opts.fetchFn;
32002
32045
  const clock = opts.now ?? Date.now;
@@ -32101,7 +32144,7 @@ function makeGuardRulesCache(opts) {
32101
32144
  function readCache(projectId) {
32102
32145
  if (!existsSync18(cacheFile)) return null;
32103
32146
  try {
32104
- const raw = readFileSync18(cacheFile, "utf8");
32147
+ const raw = readFileSync19(cacheFile, "utf8");
32105
32148
  const data = JSON.parse(raw);
32106
32149
  if (data.projectId !== projectId) return null;
32107
32150
  return data;
@@ -32112,7 +32155,7 @@ function makeGuardRulesCache(opts) {
32112
32155
  function readFailures() {
32113
32156
  try {
32114
32157
  if (!existsSync18(failuresFile)) return {};
32115
- const parsed = JSON.parse(readFileSync18(failuresFile, "utf8"));
32158
+ const parsed = JSON.parse(readFileSync19(failuresFile, "utf8"));
32116
32159
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
32117
32160
  return {};
32118
32161
  }
@@ -32152,9 +32195,9 @@ function makeGuardRulesCache(opts) {
32152
32195
  return { refreshIfStale };
32153
32196
  }
32154
32197
  function ensureDirFor2(filePath) {
32155
- const dir = dirname9(filePath);
32198
+ const dir = dirname10(filePath);
32156
32199
  if (!existsSync18(dir)) {
32157
- mkdirSync10(dir, { recursive: true });
32200
+ mkdirSync11(dir, { recursive: true });
32158
32201
  }
32159
32202
  }
32160
32203
  var DEFAULT_TIMEOUT_MS2 = 8e3;
@@ -32294,11 +32337,11 @@ function detectPromptInjection(text) {
32294
32337
  }
32295
32338
 
32296
32339
  // src/hooks/runtime/judge-cache.ts
32297
- import { readFileSync as readFileSync19, writeFileSync as writeFileSync13, existsSync as existsSync19, mkdirSync as mkdirSync11 } from "node:fs";
32298
- import { dirname as dirname10, join as join16 } from "node:path";
32299
- import { homedir as homedir15 } from "node:os";
32300
- var DEFAULT_JUDGE_CACHE_FILE = join16(
32301
- homedir15(),
32340
+ import { readFileSync as readFileSync20, writeFileSync as writeFileSync13, existsSync as existsSync19, mkdirSync as mkdirSync12 } from "node:fs";
32341
+ import { dirname as dirname11, join as join18 } from "node:path";
32342
+ import { homedir as homedir17 } from "node:os";
32343
+ var DEFAULT_JUDGE_CACHE_FILE = join18(
32344
+ homedir17(),
32302
32345
  ".cybedefend",
32303
32346
  "guards-judge-cache.json"
32304
32347
  );
@@ -32311,7 +32354,7 @@ function makeJudgeCache(opts = {}) {
32311
32354
  function readAll() {
32312
32355
  if (!existsSync19(cacheFile)) return {};
32313
32356
  try {
32314
- return JSON.parse(readFileSync19(cacheFile, "utf8"));
32357
+ return JSON.parse(readFileSync20(cacheFile, "utf8"));
32315
32358
  } catch {
32316
32359
  return {};
32317
32360
  }
@@ -32342,36 +32385,36 @@ function makeJudgeCache(opts = {}) {
32342
32385
  return { get, set: set2 };
32343
32386
  }
32344
32387
  function ensureDirFor3(filePath) {
32345
- const dir = dirname10(filePath);
32388
+ const dir = dirname11(filePath);
32346
32389
  if (!existsSync19(dir)) {
32347
- mkdirSync11(dir, { recursive: true });
32390
+ mkdirSync12(dir, { recursive: true });
32348
32391
  }
32349
32392
  }
32350
32393
 
32351
32394
  // src/hooks/runtime/guard-check.ts
32352
32395
  import { spawn as spawn3 } from "node:child_process";
32353
- import { homedir as homedir18 } from "node:os";
32354
- import { join as join19 } from "node:path";
32396
+ import { homedir as homedir20 } from "node:os";
32397
+ import { join as join21 } from "node:path";
32355
32398
 
32356
32399
  // src/hooks/runtime/guard-violations-buffer.ts
32357
32400
  import {
32358
32401
  appendFileSync as appendFileSync2,
32359
- closeSync as closeSync3,
32402
+ closeSync as closeSync4,
32360
32403
  existsSync as existsSync20,
32361
- openSync as openSync3,
32362
- readFileSync as readFileSync20,
32404
+ openSync as openSync4,
32405
+ readFileSync as readFileSync21,
32363
32406
  writeFileSync as writeFileSync14,
32364
- writeSync as writeSync3,
32365
- mkdirSync as mkdirSync12,
32407
+ writeSync as writeSync4,
32408
+ mkdirSync as mkdirSync13,
32366
32409
  rmSync as rmSync3,
32367
- statSync as statSync4,
32410
+ statSync as statSync5,
32368
32411
  utimesSync as utimesSync2
32369
32412
  } from "node:fs";
32370
- import { dirname as dirname11 } from "node:path";
32371
- import { homedir as homedir16 } from "node:os";
32372
- import { join as join17 } from "node:path";
32373
- var DEFAULT_BUFFER_FILE = join17(
32374
- homedir16(),
32413
+ import { dirname as dirname12 } from "node:path";
32414
+ import { homedir as homedir18 } from "node:os";
32415
+ import { join as join19 } from "node:path";
32416
+ var DEFAULT_BUFFER_FILE = join19(
32417
+ homedir18(),
32375
32418
  ".cybedefend",
32376
32419
  "guards-violations-buffer.jsonl"
32377
32420
  );
@@ -32382,8 +32425,8 @@ var MAX_RECORD_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
32382
32425
  var FLUSH_LOCK_STALE_MS = 6e4;
32383
32426
  function makeViolationsBuffer(opts = {}) {
32384
32427
  const bufferFile = opts.bufferFile ?? DEFAULT_BUFFER_FILE;
32385
- const holdsFile = opts.holdsFile ?? join17(dirname11(bufferFile), "guards-violations-holds.json");
32386
- const lockFile = opts.lockFile ?? join17(dirname11(bufferFile), "guards-violations-flush.lock");
32428
+ const holdsFile = opts.holdsFile ?? join19(dirname12(bufferFile), "guards-violations-holds.json");
32429
+ const lockFile = opts.lockFile ?? join19(dirname12(bufferFile), "guards-violations-flush.lock");
32387
32430
  const now = opts.now ?? Date.now;
32388
32431
  function bufferViolation2(ctx, v) {
32389
32432
  const record2 = {
@@ -32497,7 +32540,7 @@ function makeViolationsBuffer(opts = {}) {
32497
32540
  }
32498
32541
  function readBuffer() {
32499
32542
  try {
32500
- const raw = readFileSync20(bufferFile);
32543
+ const raw = readFileSync21(bufferFile);
32501
32544
  return { content: raw.toString("utf8"), bytes: raw.length };
32502
32545
  } catch {
32503
32546
  return null;
@@ -32505,7 +32548,7 @@ function makeViolationsBuffer(opts = {}) {
32505
32548
  }
32506
32549
  function appendedSince(bytes) {
32507
32550
  try {
32508
- const raw = readFileSync20(bufferFile);
32551
+ const raw = readFileSync21(bufferFile);
32509
32552
  return raw.length > bytes ? raw.subarray(bytes).toString("utf8") : "";
32510
32553
  } catch {
32511
32554
  return "";
@@ -32519,11 +32562,11 @@ function makeViolationsBuffer(opts = {}) {
32519
32562
  }
32520
32563
  for (let attempt = 0; attempt < 2; attempt++) {
32521
32564
  try {
32522
- const fd = openSync3(lockFile, "wx");
32565
+ const fd = openSync4(lockFile, "wx");
32523
32566
  try {
32524
- writeSync3(fd, String(process.pid));
32567
+ writeSync4(fd, String(process.pid));
32525
32568
  } finally {
32526
- closeSync3(fd);
32569
+ closeSync4(fd);
32527
32570
  }
32528
32571
  return true;
32529
32572
  } catch (e) {
@@ -32540,7 +32583,7 @@ function makeViolationsBuffer(opts = {}) {
32540
32583
  }
32541
32584
  function lockIsStale() {
32542
32585
  try {
32543
- return Date.now() - statSync4(lockFile).mtimeMs > FLUSH_LOCK_STALE_MS;
32586
+ return Date.now() - statSync5(lockFile).mtimeMs > FLUSH_LOCK_STALE_MS;
32544
32587
  } catch {
32545
32588
  return true;
32546
32589
  }
@@ -32567,7 +32610,7 @@ function makeViolationsBuffer(opts = {}) {
32567
32610
  function readHolds() {
32568
32611
  try {
32569
32612
  if (!existsSync20(holdsFile)) return {};
32570
- const parsed = JSON.parse(readFileSync20(holdsFile, "utf8"));
32613
+ const parsed = JSON.parse(readFileSync21(holdsFile, "utf8"));
32571
32614
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
32572
32615
  return {};
32573
32616
  }
@@ -32627,9 +32670,9 @@ function capRecords(records, now) {
32627
32670
  return dated.slice(-MAX_BUFFERED_RECORDS).map(({ record: record2 }) => record2);
32628
32671
  }
32629
32672
  function ensureDirFor4(filePath) {
32630
- const dir = dirname11(filePath);
32673
+ const dir = dirname12(filePath);
32631
32674
  if (!existsSync20(dir)) {
32632
- mkdirSync12(dir, { recursive: true });
32675
+ mkdirSync13(dir, { recursive: true });
32633
32676
  }
32634
32677
  }
32635
32678
  var _defaultBuffer = makeViolationsBuffer();
@@ -32638,9 +32681,9 @@ var flushViolations = _defaultBuffer.flushViolations.bind(_defaultBuffer);
32638
32681
  var liftViolationHolds = _defaultBuffer.liftHolds.bind(_defaultBuffer);
32639
32682
 
32640
32683
  // src/hooks/runtime/unmapped-tools.ts
32641
- import { existsSync as existsSync21, mkdirSync as mkdirSync13, readFileSync as readFileSync21, writeFileSync as writeFileSync15 } from "node:fs";
32642
- import { dirname as dirname12, join as join18 } from "node:path";
32643
- import { homedir as homedir17 } from "node:os";
32684
+ import { existsSync as existsSync21, mkdirSync as mkdirSync14, readFileSync as readFileSync22, writeFileSync as writeFileSync15 } from "node:fs";
32685
+ import { dirname as dirname13, join as join20 } from "node:path";
32686
+ import { homedir as homedir19 } from "node:os";
32644
32687
  var TARGETLESS_TOOL_RE = /^(?:ToolSearch|TodoRead|TodoWrite|Task|Agent|AskUserQuestion|Skill|SlashCommand|EnterPlanMode|ExitPlanMode|EnterWorktree|ExitWorktree|BashOutput|KillShell|KillBash|Monitor|ListMcpResourcesTool|ReadMcpResourceTool|ReadMcpResourceDirTool|ScheduleWakeup|PushNotification|CronCreate|CronDelete|CronList|SendMessage|ListAgents|TaskOutput|TaskStop|ReportFindings|Workflow)$/;
32645
32688
  var OWN_MCP_TOOL_RE = /^mcp__cybedefend(?:-[A-Za-z0-9_-]+)?__/;
32646
32689
  function isTargetlessTool(tool) {
@@ -32652,13 +32695,13 @@ function strictUnmappedPolicy() {
32652
32695
  }
32653
32696
  var MAX_TOOLS = 200;
32654
32697
  function defaultUnmappedToolsFile() {
32655
- const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join18(homedir17(), ".cybedefend");
32656
- return join18(dir, "guards-unmapped-tools.json");
32698
+ const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join20(homedir19(), ".cybedefend");
32699
+ return join20(dir, "guards-unmapped-tools.json");
32657
32700
  }
32658
32701
  function load(file2) {
32659
32702
  try {
32660
32703
  if (!existsSync21(file2)) return { tools: {} };
32661
- const parsed = JSON.parse(readFileSync21(file2, "utf8"));
32704
+ const parsed = JSON.parse(readFileSync22(file2, "utf8"));
32662
32705
  if (!parsed || typeof parsed !== "object" || typeof parsed.tools !== "object" || !parsed.tools) {
32663
32706
  return { tools: {} };
32664
32707
  }
@@ -32682,7 +32725,7 @@ function makeUnmappedToolTelemetry(file2 = defaultUnmappedToolsFile()) {
32682
32725
  if (names.length > MAX_TOOLS) {
32683
32726
  names.sort((a, b) => data.tools[a].lastSeen.localeCompare(data.tools[b].lastSeen)).slice(0, names.length - MAX_TOOLS).forEach((n) => delete data.tools[n]);
32684
32727
  }
32685
- mkdirSync13(dirname12(file2), { recursive: true });
32728
+ mkdirSync14(dirname13(file2), { recursive: true });
32686
32729
  writeFileSync15(file2, JSON.stringify(data, null, 2) + "\n", "utf8");
32687
32730
  } catch {
32688
32731
  }
@@ -32748,11 +32791,11 @@ function appendDebugLog(entry) {
32748
32791
  try {
32749
32792
  const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "";
32750
32793
  if (!homeDir) return;
32751
- const { mkdirSync: mkdirSync14, appendFileSync: appendFileSync3 } = __require("node:fs");
32752
- const { join: join20 } = __require("node:path");
32753
- const dir = join20(homeDir, ".cybedefend");
32754
- mkdirSync14(dir, { recursive: true });
32755
- appendFileSync3(join20(dir, "hook-debug.log"), entry + "\n", "utf8");
32794
+ const { mkdirSync: mkdirSync15, appendFileSync: appendFileSync3 } = __require("node:fs");
32795
+ const { join: join22 } = __require("node:path");
32796
+ const dir = join22(homeDir, ".cybedefend");
32797
+ mkdirSync15(dir, { recursive: true });
32798
+ appendFileSync3(join22(dir, "hook-debug.log"), entry + "\n", "utf8");
32756
32799
  } catch {
32757
32800
  }
32758
32801
  }
@@ -33311,7 +33354,7 @@ async function runCatchJudgeStep(args) {
33311
33354
  message
33312
33355
  };
33313
33356
  }
33314
- function emitUnverifiedBanner(reason, client) {
33357
+ function emitUnverifiedBanner(reason, client, userNotice) {
33315
33358
  const banner = [
33316
33359
  "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
33317
33360
  "\u2588 VibeDefend Action Guards \u2014 UNVERIFIED \u2588",
@@ -33329,16 +33372,24 @@ function emitUnverifiedBanner(reason, client) {
33329
33372
  ].join("\n") + "\n";
33330
33373
  process.stderr.write(banner);
33331
33374
  const isCodex = typeof process.env.CODEX_SANDBOX !== "undefined" || typeof process.env.CODEX_AGENT !== "undefined";
33332
- if (isCodex && client !== "antigravity") {
33333
- try {
33334
- const ctx = JSON.stringify({
33375
+ const withContext = isCodex && client !== "antigravity";
33376
+ if (!withContext && !userNotice) return;
33377
+ try {
33378
+ const ctx = JSON.stringify({
33379
+ ...userNotice ? { systemMessage: userNotice } : {},
33380
+ ...withContext ? {
33335
33381
  additionalContext: `VibeDefend Action Guards UNVERIFIED \u2014 ${reason} Tool call allowed WITHOUT enforcement. Run \`vibedefend login\` to restore protection.`
33336
- });
33337
- process.stdout.write(ctx + "\n");
33338
- } catch {
33339
- }
33382
+ } : {}
33383
+ });
33384
+ process.stdout.write(ctx + "\n");
33385
+ } catch {
33340
33386
  }
33341
33387
  }
33388
+ async function claimUserNotice(mcpName, envelope, client) {
33389
+ if (!SYSTEM_MESSAGE_CLIENTS.has(client)) return void 0;
33390
+ return await claimSignInNotice(mcpName, sessionIdOf3(envelope, client)) ? SIGN_IN_NOTICE : void 0;
33391
+ }
33392
+ var agentMessageWritten = false;
33342
33393
  function sessionIdOf3(envelope, client) {
33343
33394
  if (typeof envelope.session_id === "string") return envelope.session_id;
33344
33395
  if (typeof envelope.sessionId === "string") return envelope.sessionId;
@@ -33619,23 +33670,24 @@ function emitAgentMessage(verdict, message, client) {
33619
33670
  // Codex
33620
33671
  additionalContext: fullMessage
33621
33672
  };
33673
+ agentMessageWritten = true;
33622
33674
  process.stdout.write(JSON.stringify(payload) + "\n");
33623
33675
  } catch {
33624
33676
  }
33625
33677
  }
33626
33678
  function makeProductionJudgeDeps() {
33627
33679
  const cache = makeJudgeCache();
33628
- const warnDir = process.env.CYBEDEFEND_BASELINE_DIR ?? join19(homedir18(), ".cybedefend");
33680
+ const warnDir = process.env.CYBEDEFEND_BASELINE_DIR ?? join21(homedir20(), ".cybedefend");
33629
33681
  const scriptCache = makeJudgeCache({
33630
- cacheFile: join19(warnDir, "guards-judge-script-cache.json"),
33682
+ cacheFile: join21(warnDir, "guards-judge-script-cache.json"),
33631
33683
  ttlMs: SCRIPT_VERDICT_TTL_MS,
33632
33684
  maxEntries: SCRIPT_VERDICT_MAX_ENTRIES
33633
33685
  });
33634
33686
  const warnTracker = defaultSessionTracker(
33635
- join19(warnDir, "guards-judge-warned-sessions.json")
33687
+ join21(warnDir, "guards-judge-warned-sessions.json")
33636
33688
  );
33637
33689
  const blockedTracker = defaultSessionTracker(
33638
- join19(warnDir, "guards-judge-blocked-sessions.json")
33690
+ join21(warnDir, "guards-judge-blocked-sessions.json")
33639
33691
  );
33640
33692
  return {
33641
33693
  usage: {
@@ -33663,8 +33715,8 @@ function makeProductionJudgeDeps() {
33663
33715
  }
33664
33716
  function makeProductionUnmappedDeps() {
33665
33717
  const telemetry = makeUnmappedToolTelemetry();
33666
- const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join19(homedir18(), ".cybedefend");
33667
- const tracker = defaultSessionTracker(join19(dir, "guards-unmapped-notified.json"));
33718
+ const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join21(homedir20(), ".cybedefend");
33719
+ const tracker = defaultSessionTracker(join21(dir, "guards-unmapped-notified.json"));
33668
33720
  return {
33669
33721
  record: telemetry.record,
33670
33722
  noticeOnce: (sessionId, tool) => {
@@ -33692,6 +33744,7 @@ function makeSessionWritesPort(sessionId) {
33692
33744
  }
33693
33745
  async function runPreToolUseGuard() {
33694
33746
  try {
33747
+ agentMessageWritten = false;
33695
33748
  const envelope = await readStdinJson();
33696
33749
  const config2 = loadRuntimeConfig();
33697
33750
  if (!config2) return 0;
@@ -33703,11 +33756,7 @@ async function runPreToolUseGuard() {
33703
33756
  );
33704
33757
  if (!projectId) return 0;
33705
33758
  const apiBaseResolved = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
33706
- const token = await resolveTokenWithRefresh(
33707
- config2.region.mcpName,
33708
- {},
33709
- { mcpUrl: config2.region.mcpUrl }
33710
- );
33759
+ const token = await resolveTokenWithRefresh(config2.region.mcpName);
33711
33760
  const cache = makeGuardRulesCache({
33712
33761
  fetchFn: (ctx) => fetchEffectiveRulesFromGateway(ctx)
33713
33762
  });
@@ -33717,9 +33766,11 @@ async function runPreToolUseGuard() {
33717
33766
  apiBaseResolved
33718
33767
  });
33719
33768
  if (!token && rulesOutcome.kind === "unavailable") {
33769
+ const client = sniffCaller(envelope).client;
33720
33770
  emitUnverifiedBanner(
33721
33771
  "Not authenticated \u2014 run `vibedefend login` to restore Action Guards.",
33722
- sniffCaller(envelope).client
33772
+ client,
33773
+ await claimUserNotice(config2.region.mcpName, envelope, client)
33723
33774
  );
33724
33775
  return 0;
33725
33776
  }
@@ -33763,6 +33814,10 @@ async function runPreToolUseGuard() {
33763
33814
  usageNotifier: makeUsageNotifier({ write: () => void 0 })
33764
33815
  });
33765
33816
  if (token) scheduleViolationsFlush({ buffer, token, apiBaseResolved });
33817
+ if (!token && exitCode === 0 && !agentMessageWritten) {
33818
+ const notice = await claimUserNotice(config2.region.mcpName, envelope, sniffCaller(envelope).client);
33819
+ if (notice) process.stdout.write(JSON.stringify({ systemMessage: notice }) + "\n");
33820
+ }
33766
33821
  return exitCode;
33767
33822
  } catch {
33768
33823
  return 0;
@@ -33794,9 +33849,7 @@ async function runViolationsFlush(deps = {}) {
33794
33849
  try {
33795
33850
  const config2 = (deps.loadConfig ?? loadRuntimeConfig)();
33796
33851
  if (!config2) return;
33797
- const token = (deps.resolveTokenFn ?? resolveToken)(config2.region.mcpName, {
33798
- mcpUrl: config2.region.mcpUrl
33799
- });
33852
+ const token = (deps.resolveTokenFn ?? resolveToken)(config2.region.mcpName);
33800
33853
  if (!token) return;
33801
33854
  const apiBaseResolved = process.env.CYBEDEFEND_API_BASE ?? config2.region.apiBase;
33802
33855
  await (deps.buffer ?? makeViolationsBuffer()).flushViolations(