@archme/cli 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -12652,7 +12652,7 @@ async function runSandboxedJob(deps, job, opts, settle = async (o2) => o2) {
12652
12652
  const cr = cp.result;
12653
12653
  sandbox.memory_peak_bytes.clone = cr.memoryPeakBytes;
12654
12654
  for (const [k, v] of Object.entries(cr.durations_ms ?? {})) durations[`clone_${k}`] = v;
12655
- if (cr.outcome === "skip") return { kind: "skip", metrics };
12655
+ if (cr.outcome === "skip" || cr.outcome === "off_branch") return { kind: "skip", skip: cr.outcome, metrics };
12656
12656
  if (cr.outcome === "rejected") return { kind: "rejected", message: cr.error ?? "job rejected by the clone step", metrics };
12657
12657
  const scan = cr.outcome === "scan";
12658
12658
  if (cr.error || clone.exit.exitCode !== 0 || !scan && !cr.diff) {
@@ -19356,11 +19356,9 @@ function planPollTick(input) {
19356
19356
  return { kind: "idle", reason: "waiting for the initial scan to establish the diff marker" };
19357
19357
  case "up-to-date":
19358
19358
  return { kind: "idle", reason: "up to date" };
19359
+ // A reset dropped commits the board reflects: the daemon net-diffs their
19360
+ // removal and the marker moves back (`computeDiff`'s reset rule).
19359
19361
  case "upstream-behind":
19360
- return {
19361
- kind: "idle",
19362
- reason: `upstream is behind the marker (reset to ${short3(plan.tip)}); nothing to do`
19363
- };
19364
19362
  case "force-push":
19365
19363
  target = plan.tip;
19366
19364
  break;
@@ -19371,6 +19369,9 @@ function planPollTick(input) {
19371
19369
  if (!input.jobForTarget) {
19372
19370
  return { kind: "enqueue", beforeSha: marker.sha, afterSha: target };
19373
19371
  }
19372
+ if (didNotLand(input.jobForTarget, marker.sha)) {
19373
+ return { kind: "enqueue", beforeSha: marker.sha, afterSha: target, afterJobId: input.jobForTarget.id };
19374
+ }
19374
19375
  const decision = decideGate({
19375
19376
  targetSha: target,
19376
19377
  markerSha: marker.sha,
@@ -19395,6 +19396,12 @@ function planPollTick(input) {
19395
19396
  return { kind: "idle", reason: `${short3(target)}: ${decision.reason}` };
19396
19397
  }
19397
19398
  }
19399
+ function didNotLand(job, markerSha) {
19400
+ if (job.status !== "completed" || !job.id) return false;
19401
+ if (job.beforeSha && job.beforeSha !== markerSha) return true;
19402
+ const runs = job.unlandedRuns ?? 0;
19403
+ return runs > 0 && runs < MAX_UNLANDED_RUNS;
19404
+ }
19398
19405
  function haltHasCleared(halt, job, rolledUpThrough) {
19399
19406
  if (halt.haltCode !== "job-terminal" || !halt.haltSha) return false;
19400
19407
  return job?.status === "completed" || rolledUpThrough === halt.haltSha;
@@ -19407,11 +19414,13 @@ function localHaltReason(decision, job, targetSha) {
19407
19414
  function short3(sha2) {
19408
19415
  return sha2.slice(0, 7);
19409
19416
  }
19417
+ var MAX_UNLANDED_RUNS;
19410
19418
  var init_localPoll = __esm({
19411
19419
  "src/daemon/localPoll.ts"() {
19412
19420
  "use strict";
19413
19421
  init_commitAdvance();
19414
19422
  init_commitGate();
19423
+ MAX_UNLANDED_RUNS = 3;
19415
19424
  }
19416
19425
  });
19417
19426
 
@@ -19964,6 +19973,11 @@ var init_pushSubject = __esm({
19964
19973
  });
19965
19974
 
19966
19975
  // src/daemon/localPoller.ts
19976
+ function countUnlandedRuns(rows) {
19977
+ const before = rows[0]?.before_sha;
19978
+ const end = rows.findIndex((r) => r.status !== "completed" || r.result?.marker_kept !== true || r.before_sha !== before);
19979
+ return end === -1 ? rows.length : end;
19980
+ }
19967
19981
  function jobRepoOf(entry, row) {
19968
19982
  return row.repoOwner && row.repoName ? `${row.repoOwner}/${row.repoName}` : `${entry.repoOwner}/${entry.repoName}`;
19969
19983
  }
@@ -20003,6 +20017,7 @@ async function pollRepoOnce(entry, deps) {
20003
20017
  const read = await deps.readMarker(row.projectId, row.archmeBranch, jobRepo);
20004
20018
  const marker = { ...read, sha: read.rolledUpThrough ?? read.sha };
20005
20019
  const upstreamTip = await deps.git.revParse(entry.mirrorPath, `origin/${row.repoBranch}`);
20020
+ if (read.sha && read.sha === upstreamTip) return { kind: "idle", reason: "up to date" };
20006
20021
  const base = {
20007
20022
  marker,
20008
20023
  upstreamTip,
@@ -20039,7 +20054,7 @@ async function pollRepoOnce(entry, deps) {
20039
20054
  jobForTarget: jobForTarget ? { ...jobForTarget, createdAtMs: observedAtMs } : null
20040
20055
  });
20041
20056
  if (decision.kind !== "enqueue") return decision;
20042
- const result = await deps.enqueue(entry, row, decision.beforeSha, decision.afterSha);
20057
+ const result = await deps.enqueue(entry, row, decision.beforeSha, decision.afterSha, decision.afterJobId);
20043
20058
  if (result.dedup) {
20044
20059
  deps.log(` ${repo}: ${short4(decision.afterSha)} already enqueued elsewhere`);
20045
20060
  } else {
@@ -20120,8 +20135,11 @@ async function pollAllRepos(repos, deps) {
20120
20135
  }
20121
20136
  return outcomes;
20122
20137
  }
20123
- function enqueueArgs(entry, row, beforeSha, afterSha, commit) {
20138
+ function enqueueArgs(entry, row, beforeSha, afterSha, commit, afterJobId) {
20124
20139
  return {
20140
+ // Migration 172. Sent only for a re-run, so every other enqueue still
20141
+ // works against a server without it.
20142
+ ...afterJobId ? { p_after_job: afterJobId } : {},
20125
20143
  p_watched_repo_id: entry.watchedRepoId,
20126
20144
  // From the ROW, not the registry: these decide which lane the job lands
20127
20145
  // in, and a stale copy would enqueue against the wrong branch.
@@ -20186,16 +20204,20 @@ function makePollerDeps(client, log, gateTimeoutMs) {
20186
20204
  readMarker: (projectId, archmeBranch, repo) => readBranchMarker(client, projectId, archmeBranch, repo),
20187
20205
  async readJobForSha(projectId, archmeBranch, repo, sha2) {
20188
20206
  const [owner, name] = repo.split("/");
20189
- const { data, error } = await client.from("archme_jobs").select("status, attempt_count, created_at").eq("project_id", projectId).eq("archme_branch", archmeBranch).eq("repo_owner", owner ?? "").eq("repo_name", name ?? "").eq("after_sha", sha2).order("created_at", { ascending: false }).limit(1);
20207
+ const { data, error } = await client.from("archme_jobs").select("id, status, attempt_count, created_at, before_sha, result").eq("project_id", projectId).eq("archme_branch", archmeBranch).eq("repo_owner", owner ?? "").eq("repo_name", name ?? "").eq("after_sha", sha2).order("created_at", { ascending: false }).limit(MAX_UNLANDED_RUNS);
20190
20208
  if (error || !data || data.length === 0) return null;
20191
- const row = data[0];
20209
+ const rows = data;
20210
+ const row = rows[0];
20192
20211
  return {
20212
+ id: row.id,
20193
20213
  status: row.status,
20194
20214
  attemptCount: row.attempt_count ?? 0,
20195
- createdAtMs: new Date(row.created_at).getTime()
20215
+ createdAtMs: new Date(row.created_at).getTime(),
20216
+ beforeSha: row.before_sha,
20217
+ unlandedRuns: countUnlandedRuns(rows)
20196
20218
  };
20197
20219
  },
20198
- async enqueue(entry, row, beforeSha, afterSha) {
20220
+ async enqueue(entry, row, beforeSha, afterSha, afterJobId) {
20199
20221
  const meta = await readCommitMeta(entry.mirrorPath, afterSha);
20200
20222
  const subject = await resolvePushSubject(
20201
20223
  meta.message || null,
@@ -20207,7 +20229,7 @@ function makePollerDeps(client, log, gateTimeoutMs) {
20207
20229
  );
20208
20230
  const { data, error } = await client.rpc(
20209
20231
  "enqueue_local_archme_job",
20210
- enqueueArgs(entry, row, beforeSha, afterSha, { subject, meta })
20232
+ enqueueArgs(entry, row, beforeSha, afterSha, { subject, meta }, afterJobId)
20211
20233
  );
20212
20234
  if (error) throw new Error(`enqueue_local_archme_job: ${error.message}`);
20213
20235
  return data ?? {};
@@ -20774,7 +20796,7 @@ function shapeError(o2) {
20774
20796
  if (!isObj(o2.durations_ms) || !Object.values(o2.durations_ms).every((v) => typeof v === "number")) return "durations_ms";
20775
20797
  if (o2.error !== void 0 && typeof o2.error !== "string") return "error";
20776
20798
  if (o2.kind === "clone") {
20777
- if (o2.outcome !== "diff" && o2.outcome !== "skip" && o2.outcome !== "rejected" && o2.outcome !== "scan") return "outcome";
20799
+ if (!["diff", "skip", "off_branch", "rejected", "scan"].includes(o2.outcome)) return "outcome";
20778
20800
  if (o2.diff !== void 0 && !isObj(o2.diff)) return "diff";
20779
20801
  return null;
20780
20802
  }
@@ -23274,6 +23296,7 @@ async function runCloneStep(input, deps = {}) {
23274
23296
  const fetch2 = async (refspecs2) => {
23275
23297
  const r = await tryGit(["fetch", "--filter=blob:none", "--no-tags", "origin", ...refspecs2]);
23276
23298
  if (r.exitCode !== 0) log(`fetch ${refspecs2.join(" ")} failed: ${r.stderr.trim()}`);
23299
+ return r;
23277
23300
  };
23278
23301
  await must(["init", "-q", repoDir]);
23279
23302
  if ((await tryGit(["remote", "add", "origin", input.credentials.https_url])).exitCode !== 0) {
@@ -23281,12 +23304,19 @@ async function runCloneStep(input, deps = {}) {
23281
23304
  }
23282
23305
  await must(["config", "remote.origin.promisor", "true"], repoDir);
23283
23306
  await must(["config", "remote.origin.partialclonefilter", "blob:none"], repoDir);
23284
- const refspecs = [`+refs/heads/${job.repo_branch}:refs/remotes/origin/${job.repo_branch}`];
23307
+ const tracking = `refs/remotes/origin/${job.repo_branch}`;
23308
+ const refspecs = [`+refs/heads/${job.repo_branch}:${tracking}`];
23285
23309
  if (job.source_mode === "pr_update" && job.pr_number) {
23286
23310
  refspecs.push(`+refs/pull/${job.pr_number}/head:refs/remotes/origin/pr/${job.pr_number}`);
23287
23311
  }
23288
- await fetch2(refspecs);
23289
- const wanted = [target];
23312
+ const fetched = await fetch2(refspecs);
23313
+ const push = !scanRef && job.source_mode !== "pr_update";
23314
+ let branchTip = null;
23315
+ if (push) {
23316
+ if (fetched.exitCode !== 0) throw new Error(`could not fetch ${job.repo_branch} from origin: ${fetched.stderr.trim()}`);
23317
+ branchTip = (await must(["rev-parse", "--verify", `${tracking}^{commit}`], repoDir)).stdout.trim();
23318
+ }
23319
+ const wanted = push ? [] : [target];
23290
23320
  if (scanRef) {
23291
23321
  } else if (job.source_mode === "pr_update") {
23292
23322
  if (job.before_sha) wanted.push(job.before_sha);
@@ -23306,11 +23336,11 @@ async function runCloneStep(input, deps = {}) {
23306
23336
  log(`checked out ${scanRef.slice(0, 8)} for a first scan`);
23307
23337
  return { result: { kind: "clone", outcome: "scan" }, exitCode: 0 };
23308
23338
  }
23309
- const diff = await computeDiff(asArchmeJob(job), repoDir, marker, gitEnv);
23339
+ const diff = await computeDiff(asArchmeJob(job), repoDir, marker, branchTip, gitEnv);
23310
23340
  mark("diff");
23311
- if (diff === "skip") {
23312
- log("after_sha is already at or behind the clean marker \u2014 skip");
23313
- return { result: { kind: "clone", outcome: "skip" }, exitCode: EXIT_SKIP };
23341
+ if (isDiffSkip(diff)) {
23342
+ log(diffSkipSummary(diff, job.repo_branch));
23343
+ return { result: { kind: "clone", outcome: diff }, exitCode: EXIT_SKIP };
23314
23344
  }
23315
23345
  const persisted = {
23316
23346
  patch: diff.patch,
@@ -23662,8 +23692,10 @@ __export(run_exports, {
23662
23692
  claudeFailureDetail: () => claudeFailureDetail,
23663
23693
  computeDiff: () => computeDiff,
23664
23694
  createJobWorktree: () => createJobWorktree,
23695
+ diffSkipSummary: () => diffSkipSummary,
23665
23696
  forkRepoScope: () => forkRepoScope,
23666
23697
  isClaudeAuthFailure: () => isClaudeAuthFailure,
23698
+ isDiffSkip: () => isDiffSkip,
23667
23699
  parseClaudeResult: () => parseClaudeResult,
23668
23700
  parseJobTokenResponse: () => parseJobTokenResponse,
23669
23701
  probeMcpAuth: () => probeMcpAuth,
@@ -23841,34 +23873,44 @@ async function buildGitEnv(credentials) {
23841
23873
  return { env, cleanup: () => rm7(dir, { recursive: true, force: true }).catch(() => {
23842
23874
  }) };
23843
23875
  }
23876
+ async function fetchBranchTip(dir, branch, env) {
23877
+ const tracking = `refs/remotes/origin/${branch}`;
23878
+ const fetched = await execa("git", ["fetch", "--no-tags", "origin", `+refs/heads/${branch}:${tracking}`], { cwd: dir, env, reject: false });
23879
+ if (fetched.exitCode !== 0) throw new Error(`could not fetch ${branch} from origin: ${String(fetched.stderr).trim()}`);
23880
+ const { stdout } = await execa("git", ["rev-parse", "--verify", `${tracking}^{commit}`], { cwd: dir, env });
23881
+ return stdout.trim();
23882
+ }
23844
23883
  async function ensureLocalCloneAndFetch(job, entry) {
23845
23884
  const dir = entry.mirrorPath;
23846
23885
  assertLocalJobShape(job);
23886
+ let branchTip = null;
23847
23887
  await cloneMutex.runExclusive(dir, async () => {
23848
23888
  if (!await exists(join24(dir, ".git"))) {
23849
23889
  throw new Error(
23850
23890
  `local mirror ${dir} is missing or not a git repo \u2014 re-run \`archme init ${entry.sourcePath}\``
23851
23891
  );
23852
23892
  }
23853
- await execa("git", ["fetch", "--no-tags", "origin", job.repo_branch], { cwd: dir, env: localGitEnv(), reject: false });
23854
- if (job.source_mode === "pr_update") {
23855
- await verifyLocalPrJob(job, async (args) => {
23856
- const r = await execa("git", args, { cwd: dir, env: localGitEnv(), reject: false });
23857
- return { exitCode: r.exitCode ?? 1, stdout: String(r.stdout ?? ""), stderr: String(r.stderr ?? "") };
23893
+ if (job.source_mode !== "pr_update") {
23894
+ branchTip = await fetchBranchTip(dir, job.repo_branch, localGitEnv()).catch(async (err4) => {
23895
+ const tracked = await execa("git", ["rev-parse", "--verify", `refs/remotes/origin/${job.repo_branch}^{commit}`], { cwd: dir, env: localGitEnv(), reject: false });
23896
+ if (tracked.exitCode !== 0) throw err4;
23897
+ console.warn(`[${job.id}] ${err4.message}; using ${job.repo_branch} as last fetched`);
23898
+ return String(tracked.stdout).trim();
23858
23899
  });
23859
23900
  return;
23860
23901
  }
23861
- const afterCheck = await execa("git", ["cat-file", "-e", job.after_sha], { cwd: dir, env: localGitEnv(), reject: false });
23862
- if (afterCheck.exitCode !== 0) {
23863
- await execa("git", ["fetch", "origin"], { cwd: dir, env: localGitEnv(), reject: false });
23864
- }
23902
+ await execa("git", ["fetch", "--no-tags", "origin", job.repo_branch], { cwd: dir, env: localGitEnv(), reject: false });
23903
+ await verifyLocalPrJob(job, async (args) => {
23904
+ const r = await execa("git", args, { cwd: dir, env: localGitEnv(), reject: false });
23905
+ return { exitCode: r.exitCode ?? 1, stdout: String(r.stdout ?? ""), stderr: String(r.stderr ?? "") };
23906
+ });
23865
23907
  }).catch((err4) => {
23866
23908
  if (err4 instanceof LocalPrJobRejectedError) throw err4;
23867
23909
  const msg = err4 instanceof Error ? err4.message : String(err4);
23868
23910
  throw new Error(`local repo ${job.repo_owner}/${job.repo_name} is not usable: ${msg}`);
23869
23911
  });
23870
23912
  return { dir, gitEnv: localGitEnv(), cleanupGitEnv: async () => {
23871
- } };
23913
+ }, branchTip };
23872
23914
  }
23873
23915
  async function ensureCloneAndFetch(ctx, job, claimDeviceId) {
23874
23916
  const localEntry = findLocalRepoForJob(await loadLocalRepos(), job);
@@ -23880,6 +23922,7 @@ async function ensureCloneAndFetch(ctx, job, claimDeviceId) {
23880
23922
  await mkdir17(ctx.cloneBaseDir, { recursive: true });
23881
23923
  const dir = cloneDirFor(ctx.cloneBaseDir, job.repo_owner, job.repo_name);
23882
23924
  const { env, cleanup: cleanupGitEnv } = await buildGitEnv(credentials);
23925
+ let branchTip = null;
23883
23926
  await cloneMutex.runExclusive(dir, async () => {
23884
23927
  if (!await exists(join24(dir, ".git"))) {
23885
23928
  await mkdir17(join24(ctx.cloneBaseDir, job.repo_owner), { recursive: true });
@@ -23888,16 +23931,20 @@ async function ensureCloneAndFetch(ctx, job, claimDeviceId) {
23888
23931
  } else {
23889
23932
  await execa("git", ["remote", "set-url", "origin", credentials.https_url], { cwd: dir, env, reject: false });
23890
23933
  }
23934
+ if (job.source_mode !== "pr_update") {
23935
+ branchTip = await fetchBranchTip(dir, job.repo_branch, env);
23936
+ return;
23937
+ }
23891
23938
  await execa("git", ["fetch", "origin", job.repo_branch], { cwd: dir, env, reject: false });
23892
23939
  let afterCheck = await execa("git", ["cat-file", "-e", job.after_sha], { cwd: dir, reject: false });
23893
- if (afterCheck.exitCode !== 0 && job.source_mode === "pr_update" && job.pr_number) {
23940
+ if (afterCheck.exitCode !== 0 && job.pr_number) {
23894
23941
  await execa("git", ["fetch", "origin", `pull/${job.pr_number}/head`], { cwd: dir, env, reject: false });
23895
23942
  afterCheck = await execa("git", ["cat-file", "-e", job.after_sha], { cwd: dir, reject: false });
23896
23943
  }
23897
23944
  if (afterCheck.exitCode !== 0) {
23898
23945
  await execa("git", ["fetch", "origin"], { cwd: dir, env, reject: false });
23899
23946
  }
23900
- if (job.source_mode === "pr_update" && job.before_sha) {
23947
+ if (job.before_sha) {
23901
23948
  const baseCheck = await execa("git", ["cat-file", "-e", job.before_sha], { cwd: dir, reject: false });
23902
23949
  if (baseCheck.exitCode !== 0) {
23903
23950
  await execa("git", ["fetch", "origin", job.before_sha], { cwd: dir, env, reject: false });
@@ -23908,7 +23955,7 @@ async function ensureCloneAndFetch(ctx, job, claimDeviceId) {
23908
23955
  const msg = err4 instanceof Error ? err4.message : String(err4);
23909
23956
  throw new Error(`GitHub App cannot access ${job.repo_owner}/${job.repo_name}: ${msg}`);
23910
23957
  });
23911
- return { dir, gitEnv: env, cleanupGitEnv };
23958
+ return { dir, gitEnv: env, cleanupGitEnv, branchTip };
23912
23959
  }
23913
23960
  function checkoutGitEnv(jobDir) {
23914
23961
  const env = {
@@ -23950,6 +23997,12 @@ async function createJobWorktree(repoDir, job) {
23950
23997
  }
23951
23998
  };
23952
23999
  }
24000
+ function isDiffSkip(r) {
24001
+ return r === "skip" || r === "off_branch";
24002
+ }
24003
+ function diffSkipSummary(skip, branch) {
24004
+ return skip === "off_branch" ? `Commit is no longer on ${branch} (a force push removed it); skipped.` : "Push is behind the last reflected commit; skipped.";
24005
+ }
23953
24006
  function noUsableBaseError(branch, markerSha, detail) {
23954
24007
  return new Error(
23955
24008
  `no usable diff base for ${branch} (marker ${markerSha ?? "none"}): run a manual scan or admin replay \u2014 ${detail}`
@@ -23979,6 +24032,9 @@ async function forcePushProvenance(repoDir, base, after) {
23979
24032
  const forkNote = fork.trim() ? ` (history diverged at \`${fork.trim().slice(0, 8)}\`)` : "";
23980
24033
  return `Force push: the branch tip was rewritten${forkNote}. The diff below is the exact net delta from the last reflected commit \`${base.slice(0, 8)}\` to the new tip \`${after.slice(0, 8)}\`, computed tree-to-tree \u2014 the rewrite does not affect it.`;
23981
24034
  }
24035
+ function resetProvenance(base, after) {
24036
+ return `Branch reset: the branch was moved back to \`${after.slice(0, 8)}\`, dropping the commits after it up to \`${base.slice(0, 8)}\`, the last commit this board reflects. The diff below is the exact net removal of those commits, computed tree-to-tree.`;
24037
+ }
23982
24038
  function isGitSha(v) {
23983
24039
  return typeof v === "string" && GIT_SHA_RE.test(v);
23984
24040
  }
@@ -23987,23 +24043,28 @@ function assertGitSha(v, field) {
23987
24043
  throw new Error(`${field} ${v ?? "(null)"} is not a 40-character git SHA`);
23988
24044
  }
23989
24045
  }
23990
- async function computeDiff(job, repoDir, marker, gitEnv) {
24046
+ async function computeDiff(job, repoDir, marker, branchTip, gitEnv) {
23991
24047
  assertGitSha(job.after_sha, "after_sha");
23992
- if (!await isShaReachable(repoDir, job.after_sha)) {
23993
- throw new Error(`after_sha ${job.after_sha} is not reachable after fetch`);
23994
- }
23995
24048
  const after = job.after_sha;
23996
24049
  if (job.source_mode === "pr_update") {
24050
+ if (!await isShaReachable(repoDir, after)) {
24051
+ throw new Error(`after_sha ${after} is not reachable after fetch`);
24052
+ }
23997
24053
  if (!job.before_sha) throw noUsableBaseError(job.archme_branch, marker.sha, "PR job has no before_sha");
23998
24054
  if (!await isShaReachable(repoDir, job.before_sha)) {
23999
24055
  throw noUsableBaseError(job.archme_branch, marker.sha, `PR base ${job.before_sha.slice(0, 8)} is unreachable after fetch`);
24000
24056
  }
24001
- const { stdout, exitCode: exitCode2 } = await execa("git", ["merge-base", job.before_sha, after], { cwd: repoDir, reject: false });
24002
- if (exitCode2 !== 0 || !stdout.trim()) {
24057
+ const { stdout, exitCode } = await execa("git", ["merge-base", job.before_sha, after], { cwd: repoDir, reject: false });
24058
+ if (exitCode !== 0 || !stdout.trim()) {
24003
24059
  throw noUsableBaseError(job.archme_branch, marker.sha, `no merge-base between ${job.before_sha.slice(0, 8)} and ${after.slice(0, 8)}`);
24004
24060
  }
24005
24061
  return buildDiffPayload(repoDir, stdout.trim(), after);
24006
24062
  }
24063
+ if (!isGitSha(branchTip)) {
24064
+ throw new Error(`no fetched tip of ${job.repo_branch} to check ${after.slice(0, 8)} against`);
24065
+ }
24066
+ const onBranch = await isShaReachable(repoDir, after) && (await execa("git", ["merge-base", "--is-ancestor", after, branchTip], { cwd: repoDir, reject: false })).exitCode === 0;
24067
+ if (!onBranch) return "off_branch";
24007
24068
  if (!marker.sha) {
24008
24069
  throw noUsableBaseError(job.archme_branch, null, "no architecture marker for this branch (first scan hasn't established one)");
24009
24070
  }
@@ -24018,9 +24079,16 @@ async function computeDiff(job, repoDir, marker, gitEnv) {
24018
24079
  throw noUsableBaseError(job.archme_branch, base, "marker commit is unreachable after fetch-by-SHA (GC'd or a different clone)");
24019
24080
  }
24020
24081
  }
24021
- const { exitCode } = await execa("git", ["merge-base", "--is-ancestor", after, base], { cwd: repoDir, reject: false });
24022
- if (exitCode === 0) return "skip";
24023
24082
  const before = job.before_sha?.toLowerCase();
24083
+ const isAncestor2 = async (a2, b) => (await execa("git", ["merge-base", "--is-ancestor", a2, b], { cwd: repoDir, reject: false })).exitCode === 0;
24084
+ if (await isAncestor2(after, base)) {
24085
+ const fromMarker = !!before && (before === base.toLowerCase() || before === marker.rolledUpThrough?.toLowerCase());
24086
+ const resetsBoard = (job.forced || fromMarker) && !await isAncestor2(base, branchTip);
24087
+ if (!resetsBoard) return "skip";
24088
+ const payload2 = await buildDiffPayload(repoDir, base, after);
24089
+ payload2.provenance = resetProvenance(base, after);
24090
+ return payload2;
24091
+ }
24024
24092
  if (!job.forced && before && before !== base.toLowerCase() && before !== marker.rolledUpThrough?.toLowerCase()) {
24025
24093
  throw new Error(
24026
24094
  `commit ${after.slice(0, 8)} does not follow ${base.slice(0, 8)}, the last commit this board reflects for ${job.repo_owner}/${job.repo_name}: a commit between them has no architecture update. Requeue it, or roll it up into the next one.`
@@ -24195,7 +24263,9 @@ async function rpcComplete(ctx, jobId, deviceId, summary2, kind, changed, metric
24195
24263
  // `kind` drives lifecycle (squash, marker, retry). `changed` is the
24196
24264
  // decoupled what-changed verdict the Check Run / sticky comment render
24197
24265
  // (migration 083): a structural-only job is kind=applied but changed=false.
24198
- result: { summary: summary2, kind, changed },
24266
+ // `marker_kept`: this job landed nothing, so local watch may run its
24267
+ // commit again (`countUnlandedRuns`).
24268
+ result: { summary: summary2, kind, changed, ...advanceMarker ? {} : { marker_kept: true } },
24199
24269
  metrics,
24200
24270
  logs,
24201
24271
  advance_marker: advanceMarker
@@ -24901,12 +24971,13 @@ async function runJob(ctx, job, claimDeviceId) {
24901
24971
  const sandboxMetrics = outcome.metrics.sandbox;
24902
24972
  try {
24903
24973
  if (outcome.kind === "skip") {
24904
- log(`after_sha is already at or behind the clean marker \u2014 completing no_op without advancing the marker`);
24974
+ const summary2 = diffSkipSummary(outcome.skip, job.repo_branch);
24975
+ log(`${summary2} Completing no_op without advancing the marker.`);
24905
24976
  await rpcComplete(
24906
24977
  ctx,
24907
24978
  job.id,
24908
24979
  deviceId,
24909
- "Push is behind the last reflected commit; skipped.",
24980
+ summary2,
24910
24981
  "no_op",
24911
24982
  false,
24912
24983
  { mode: "skip", sandbox: sandboxMetrics, durations_ms: timings },
@@ -25110,20 +25181,21 @@ async function runJob(ctx, job, claimDeviceId) {
25110
25181
  );
25111
25182
  return;
25112
25183
  }
25113
- const { dir: repoDir, gitEnv, cleanupGitEnv } = clone;
25184
+ const { dir: repoDir, gitEnv, cleanupGitEnv, branchTip } = clone;
25114
25185
  cleanupFns.push(cleanupGitEnv);
25115
25186
  activeCleanups.add(cleanupGitEnv);
25116
25187
  markPhase("clone_fetch");
25117
25188
  const marker = job.source_mode === "pr_update" ? { sha: null, repo: null } : await readBranchMarker(ctx.supabase, job.project_id, job.archme_branch, `${job.repo_owner}/${job.repo_name}`);
25118
- const diffResult = await computeDiff(job, repoDir, marker, gitEnv);
25119
- if (diffResult === "skip") {
25120
- log(`after_sha is already at or behind the clean marker \u2014 completing no_op without advancing the marker`);
25189
+ const diffResult = await computeDiff(job, repoDir, marker, branchTip, gitEnv);
25190
+ if (isDiffSkip(diffResult)) {
25191
+ const summary2 = diffSkipSummary(diffResult, job.repo_branch);
25192
+ log(`${summary2} Completing no_op without advancing the marker.`);
25121
25193
  markPhase("diff", { mode: "skip" });
25122
25194
  await rpcComplete(
25123
25195
  ctx,
25124
25196
  job.id,
25125
25197
  deviceId,
25126
- "Push is behind the last reflected commit; skipped.",
25198
+ summary2,
25127
25199
  "no_op",
25128
25200
  false,
25129
25201
  { mode: "skip", durations_ms: timings },
@@ -27083,7 +27155,11 @@ var init_scanBranch = __esm({
27083
27155
  // ../shared/githubInstallations.ts
27084
27156
  function installationForOwner(installs, owner) {
27085
27157
  const key = owner.toLowerCase();
27086
- return installs.find((i2) => i2.account_login.toLowerCase() === key) ?? null;
27158
+ let newest = null;
27159
+ for (const i2 of installs) {
27160
+ if (i2.account_login.toLowerCase() === key && (!newest || i2.installation_id > newest.installation_id)) newest = i2;
27161
+ }
27162
+ return newest;
27087
27163
  }
27088
27164
  var init_githubInstallations = __esm({
27089
27165
  "../shared/githubInstallations.ts"() {
@@ -29364,6 +29440,71 @@ var init_plan = __esm({
29364
29440
  }
29365
29441
  });
29366
29442
 
29443
+ // src/init/selfScanGate.ts
29444
+ function decideSelfScan(state) {
29445
+ return state === "requested" || state === "queued" || state === "scanning" ? "takeover" : "carry-on";
29446
+ }
29447
+ function takeoverLine(repo) {
29448
+ return `You'd asked ArchMe to scan ${repo}; you're scanning it yourself now, so that request is closed.`;
29449
+ }
29450
+ async function selfScanPreflight(deps, ctx) {
29451
+ return postTakeover(deps, ctx, (await checkSelfScan(deps, ctx)).takeover);
29452
+ }
29453
+ async function checkSelfScan(deps, ctx) {
29454
+ if (ctx.keyed || !ctx.orgId || !ctx.repoSlug) return { takeover: false };
29455
+ try {
29456
+ return { takeover: decideSelfScan((await deps.fetchState(ctx.orgId, ctx.repoSlug)).state) === "takeover" };
29457
+ } catch (err4) {
29458
+ deps.log(` ! couldn't check whether ArchMe was asked to scan ${ctx.repoSlug} (${err4 instanceof Error ? err4.message : String(err4)}) \u2014 going ahead`);
29459
+ return { takeover: false };
29460
+ }
29461
+ }
29462
+ async function postTakeover(deps, ctx, takeover) {
29463
+ if (!takeover || !ctx.orgId || !ctx.repoSlug) return { go: true, tookOver: false };
29464
+ try {
29465
+ await deps.postSelfScan(ctx.orgId, ctx.repoSlug);
29466
+ } catch (err4) {
29467
+ deps.log(`
29468
+ archme init: couldn't close your request to ArchMe for ${ctx.repoSlug} (${err4 instanceof Error ? err4.message : String(err4)}). Nothing was scanned; try again.`);
29469
+ return { go: false, exitCode: 1 };
29470
+ }
29471
+ deps.log(takeoverLine(ctx.repoSlug));
29472
+ return { go: true, tookOver: true };
29473
+ }
29474
+ async function invoke(client, path7, body) {
29475
+ const { data, error } = await client.functions.invoke(path7, { body });
29476
+ if (error) {
29477
+ let detail = error.message;
29478
+ const ctx = error.context;
29479
+ if (ctx instanceof Response) {
29480
+ const b = await ctx.json().catch(() => null);
29481
+ detail = `${ctx.status} ${typeof b?.error === "string" ? b.error : typeof b?.status === "string" ? b.status : ""}`.trim();
29482
+ }
29483
+ throw new Error(detail);
29484
+ }
29485
+ return data;
29486
+ }
29487
+ function selfScanDeps(client, log) {
29488
+ return {
29489
+ fetchState: async (orgId, repo) => {
29490
+ const data = await invoke(client, "notifications/scan-state", { org_id: orgId, repo });
29491
+ if (!data || typeof data.state !== "string") throw new Error("malformed scan-state response");
29492
+ return data;
29493
+ },
29494
+ postSelfScan: async (orgId, repo) => {
29495
+ await invoke(client, "notifications/self-scan", { org_id: orgId, repo });
29496
+ },
29497
+ log
29498
+ };
29499
+ }
29500
+ var TAKEOVER_FAILED_NOTE;
29501
+ var init_selfScanGate = __esm({
29502
+ "src/init/selfScanGate.ts"() {
29503
+ "use strict";
29504
+ TAKEOVER_FAILED_NOTE = "Your request to ArchMe was closed when this scan started \u2014 re-run `archme init` here, or request a scan again from your board.";
29505
+ }
29506
+ });
29507
+
29367
29508
  // src/uninstall/edits.ts
29368
29509
  function stripArchmeClaudeBlock(content) {
29369
29510
  const start = content.indexOf(START_MARKER);
@@ -31260,6 +31401,27 @@ async function runSetup(opts, deps, { workspace, cloneDir }, handoff) {
31260
31401
  return { ok: false, reason: e instanceof Error ? e.message : String(e) };
31261
31402
  }
31262
31403
  }
31404
+ function guidedSelfScanDeps(opts, deps) {
31405
+ return deps.selfScan ?? selfScanDeps(opts.authed.supabase, opts.log);
31406
+ }
31407
+ async function guidedSelfScan(opts, deps, orgId, repos) {
31408
+ const ssDeps = guidedSelfScanDeps(opts, deps);
31409
+ const checked = [];
31410
+ for (const repo of repos) {
31411
+ const ctx = { keyed: opts.keyed, orgId, repoSlug: repo };
31412
+ checked.push({ ctx, takeover: (await checkSelfScan(ssDeps, ctx)).takeover });
31413
+ }
31414
+ let tookOver = false;
31415
+ for (const { ctx, takeover } of checked) {
31416
+ const posted = await postTakeover(ssDeps, ctx, takeover);
31417
+ if (!posted.go) {
31418
+ if (tookOver) opts.log(TAKEOVER_FAILED_NOTE);
31419
+ return posted;
31420
+ }
31421
+ tookOver ||= posted.tookOver;
31422
+ }
31423
+ return { go: true, tookOver };
31424
+ }
31263
31425
  async function offerDaemon(deps, interactive, log) {
31264
31426
  if (!interactive) return false;
31265
31427
  if (!await (deps.confirm ?? ((q) => promptYesNo(q)))(DAEMON_QUESTION)) return false;
@@ -31294,6 +31456,8 @@ async function buildSingle(opts, deps, setup, handoff, conversation, interactive
31294
31456
  if (!opts.force && (setup.scanned || setup.architectureExists && !resumedBuild)) {
31295
31457
  log(`\u2713 ${fullSlug} already has an architecture for ${repo.repo} \u2014 not rescanned (archme init --force rescans it)`);
31296
31458
  } else {
31459
+ const pre = await guidedSelfScan(opts, deps, project.orgId, [repo.repo]);
31460
+ if (!pre.go) return { exitCode: pre.exitCode, project: fullSlug, branch: scanBranch, webUrl };
31297
31461
  const measurement = await (deps.measure ?? measureRepo)(repo.root);
31298
31462
  const briefing = formatRepoBriefing(measurement, repo.root, { project: fullSlug, branch: scanBranch });
31299
31463
  log("\u2192 back to Claude Code for the scan \u2014 it will confirm before scanning");
@@ -31311,6 +31475,7 @@ async function buildSingle(opts, deps, setup, handoff, conversation, interactive
31311
31475
  if (exitCode !== 0) {
31312
31476
  log(`
31313
31477
  The scan did not finish (exit ${exitCode}). Run \`archme init\` here again to continue it.`);
31478
+ if (pre.tookOver) log(TAKEOVER_FAILED_NOTE);
31314
31479
  return { exitCode, project: fullSlug, branch: scanBranch, webUrl };
31315
31480
  }
31316
31481
  log(`
@@ -31374,6 +31539,9 @@ async function buildMulti(opts, deps, setup, handoff, conversation, interactive,
31374
31539
  if (setup.prepared.kind === "ready") {
31375
31540
  const { prepared } = setup.prepared;
31376
31541
  projectId = prepared.project.projectId;
31542
+ const pre = await guidedSelfScan(opts, deps, prepared.project.orgId, prepared.todo.map((c3) => c3.target.repo));
31543
+ if (!pre.go) return { exitCode: pre.exitCode, project: setup.project, branch: setup.scanBranch, webUrl: "" };
31544
+ const { tookOver } = pre;
31377
31545
  const out = await (deps.runPreparedAddRepos ?? runPreparedAddRepos)(
31378
31546
  prepared,
31379
31547
  { interactive, conversation, rerun: "archme init", daemonNote: false },
@@ -31381,6 +31549,7 @@ async function buildMulti(opts, deps, setup, handoff, conversation, interactive,
31381
31549
  );
31382
31550
  exitCode = out.exitCode;
31383
31551
  webUrl = out.webUrl;
31552
+ if (exitCode !== 0 && tookOver) log(TAKEOVER_FAILED_NOTE);
31384
31553
  reviewed = [...out.added, ...prepared.done.map((c3) => c3.target.repo)];
31385
31554
  } else if (setup.prepared.kind === "done") {
31386
31555
  const found = await (deps.findProject ?? findProject)(opts.authed.supabase, setup.project);
@@ -31422,6 +31591,7 @@ var init_guided = __esm({
31422
31591
  init_localGit();
31423
31592
  init_prompt();
31424
31593
  init_run3();
31594
+ init_selfScanGate();
31425
31595
  init_run2();
31426
31596
  init_repoContainer();
31427
31597
  init_agentConfig();
@@ -31628,14 +31798,24 @@ async function runInit(opts, deps = {}) {
31628
31798
  const architectureExists = detail.components.length > 0;
31629
31799
  const ran = signedIn ? [] : ["login"];
31630
31800
  ran.push("project");
31801
+ const onBoard = await (deps.boardRepos ?? readBoardRepos2)(authed2.supabase, project.projectId, scanBranch);
31802
+ const joint = !!git4.repoSlug && setupShape({ repos: 1, repo: git4.repoSlug, hasContainers: onBoard.hasContainers, boardRepos: onBoard.repos }) === "multi";
31803
+ let tookOver = false;
31804
+ const jointSkip = joint && opts.skipScan;
31805
+ if (!opts.skipScan && (joint || shouldRunScan({ architectureExists, force: opts.force }))) {
31806
+ const pre = await selfScanPreflight(
31807
+ deps.selfScan ?? selfScanDeps(authed2.supabase, log),
31808
+ { keyed, orgId: project.orgId, repoSlug: git4.repoSlug ?? null }
31809
+ );
31810
+ if (!pre.go) return { exitCode: pre.exitCode, project: fullSlug, branch: scanBranch, webUrl: "", ran };
31811
+ tookOver = pre.tookOver;
31812
+ }
31631
31813
  log("\u2192 installing agent config (.mcp.json, CLAUDE.md, architecture skill)\u2026");
31632
31814
  await (deps.installAgentConfig ?? installAgentConfig)(
31633
31815
  { repoRoot: repoPath, mcpBaseUrl: cfg.archmeMcpBaseUrl, project: fullSlug, branch: scanBranch, log }
31634
31816
  );
31635
31817
  ran.push("agent-config");
31636
- const onBoard = await (deps.boardRepos ?? readBoardRepos2)(authed2.supabase, project.projectId, scanBranch);
31637
- const joint = !!git4.repoSlug && setupShape({ repos: 1, repo: git4.repoSlug, hasContainers: onBoard.hasContainers, boardRepos: onBoard.repos }) === "multi";
31638
- if (joint && opts.skipScan) {
31818
+ if (jointSkip) {
31639
31819
  log(`
31640
31820
  ${fullSlug} already holds other repos, so ${git4.repoSlug} needs its own container and scan before it is watched.`);
31641
31821
  log(` Run \`archme add-repo --project ${fullSlug}\` here when you want it added.`);
@@ -31654,6 +31834,7 @@ ${fullSlug} already holds other repos, so ${git4.repoSlug} needs its own contain
31654
31834
  );
31655
31835
  if (!added.ok) {
31656
31836
  if (added.reason) log(`archme init: ${added.reason}`);
31837
+ if (tookOver) log(TAKEOVER_FAILED_NOTE);
31657
31838
  return { exitCode: added.exitCode, project: fullSlug, branch: scanBranch, webUrl: "", ran };
31658
31839
  }
31659
31840
  ran.push("scan");
@@ -31721,6 +31902,7 @@ Your board: ${webUrl}`);
31721
31902
  });
31722
31903
  ran.push("scan");
31723
31904
  const finalUrl = result.webUrl || webUrl;
31905
+ if (result.exitCode !== 0 && tookOver) log(TAKEOVER_FAILED_NOTE);
31724
31906
  if (result.exitCode === 0) {
31725
31907
  log(`
31726
31908
  \u2713 Done. Your architecture: ${finalUrl}`);
@@ -31858,6 +32040,7 @@ var init_run_init = __esm({
31858
32040
  init_prompt();
31859
32041
  init_localWatch();
31860
32042
  init_plan();
32043
+ init_selfScanGate();
31861
32044
  init_guided();
31862
32045
  init_run2();
31863
32046
  init_watchRepo();
@@ -32029,6 +32212,9 @@ for them). Then it sets everything up \u2014 clones,
32029
32212
  project, watching, agent config \u2014 and continues the same conversation to scan:
32030
32213
  one repo the usual way, several with one planned multi-repo bootstrap.
32031
32214
 
32215
+ If you asked ArchMe to scan a repo, running archme init there scans it yourself instead:
32216
+ your request is closed and ArchMe's queued or running scan is stopped first.
32217
+
32032
32218
  Usage:
32033
32219
  archme init [path] [options]
32034
32220
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@archme/cli",
3
- "version": "0.27.0",
3
+ "version": "0.29.0",
4
4
  "description": "Map your codebase into a living architecture diagram: run `archme init` in a repo to scan it, `archme daemon start` to keep it current on every commit.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "image": "ghcr.io/architectme/archme-job",
3
- "digest": "sha256:14179bd79f7e85721722c00d950b0337a509ea47cb563e8e0d80256dbc4fd9aa"
3
+ "digest": "sha256:9d4194104621126c8fd540b33c396ea22bb8e9794e3fd2dd80879e5837baa476"
4
4
  }