akm-cli 0.10.261130-beta.2 → 0.10.261130-beta.4

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/CHANGELOG.md CHANGED
@@ -24,6 +24,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
24
24
  - `akm-cli/workspace`: `assets.bundleFiles` `newFile` names an environment file or a secret (`through: "protected-editor"`) in the top-level `env/` and `secrets/`; `documents.check` names a file by its bundle path, not its scratch folder; `documents.frontmatter` returns `markdown` and `bodyStart` (in a bundle of any adapter) and `applyFrontmatter` the new `bodyStart`; `sensitive.describe` returns `actions: {edit, delete}` with akm's sentence in place of `writable`; `documents.createFile` takes a `type` in place of a folder; `assets.copyEntry` copies a file or folder to a chosen folder; `bundles.list`'s `git.dirtyPaths` is removed (`uncommitted` is the count).
25
25
  - AKM Desktop shows a file's frontmatter as Properties under the title for every kind and edits it as fields (akm applies each change; unknown keys and the body stay as written, with a Text switch for the whole file). A script reads as code, a task as YAML, Source is the whole file. Save checks the text with akm first: findings are listed beside the editor with their lines, a text akm could not read as the asset stops the save with Save anyway, and the file is then shown as not indexed with akm's reason.
26
26
  - `akm-cli/workspace`: `activity.taskHistory` runs carry `targetKind`, `targetRef` and `engine`, and `activity.taskRunLog` returns a task run's recorded output from `logs.db` (read-only; `available: false` when there is none). `setup.detect`'s harnesses carry `modelWorkReadOnly`, whether akm's model calls on that program can be limited to reading and searching. AKM Desktop's task run view shows what the run executed and a Log output section; Setup's "Choose it only if you accept that" follows `modelWorkReadOnly`, not the wording of the note.
27
+ - AKM Desktop's 3D library map is easier to choose from: a point is chosen from anywhere over its drawn disc, whatever the zoom (before, only within a fixed 14 pixels of its middle, which missed a point drawn larger than that), the point under the pointer is ringed, the chosen one is haloed and named by a label that stays over every other mark, and the left and right arrow keys step to the previous or next asset of its group and announce it.
28
+ - AKM Desktop's 3D library map draws three levels of joins from a chosen asset: its joins, theirs and theirs again, each level thinner and more muted than the last (the third dashed) with its assets ringed to match, and a key naming each level with the assets at it. A join is drawn once, at its nearest level; a level shows its 300 most joined assets and the key says how many it left out or could not place on the map. They are the links and near-duplicates `assets.graph` reports; nothing is inferred.
29
+ - AKM Desktop's Activity replay has a 2D / 3D switch (2D by default, the choice kept until the app closes). 3D plays the same events, with the same controls and figures, on the 3D map the Library uses: an asset used so far is in its type's colour, the rest are faint, and the asset an event reads, a search returns or feedback touches is ringed in a colour per kind as it plays. Events on assets with no place on the 3D map, or that the index no longer lists, are counted and said.
27
30
 
28
31
  ### Changed
29
32
 
@@ -49,6 +52,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
49
52
 
50
53
  ### Fixed
51
54
 
55
+ - Package-local plugin CLIs invoked directly with Bun no longer default to an npm-global upgrade when npm ownership is unproven; the `npm` on PATH proves a global install when no launching Node does (#1708).
56
+ - Accepting an enabled task's retirement reconciles its host-local activation before archiving. A refused retirement leaves the task enabled as it was, another task's sync failure or an unreadable native scheduler is a warning, and reverting does not reactivate it (#1705).
57
+ - Failed scheduled source resolution or preparation records a typed failure with an unknown target in task history, without dispatching the task body. Interactive preflight remains non-mutating (#1711).
58
+ - Consolidation reports same-run retirement conflicts as deferrals, counts parsed verdicts accurately, and keeps deferred pairs eligible for later runs. Health separates deferrals from failures and reports unknown deferral totals for older records (#1706).
59
+ - Stale-path lint treats fenced code as documentation examples. Current paths in prose and frontmatter remain checked, with bundle-level `lint.skip` suppression (#1707).
60
+ - Writable Git bundle updates publish the fetched upstream tracking revision alongside the verified checkout update, preserving local work and concurrent tracking changes; a refused fast-forward restores the tracking revision (#1709).
61
+ - Scheduler version advice recommends rebinding only when the scheduled CLI is older; a newer scheduled CLI directs the caller to update instead (#1710).
62
+
63
+ - `akm upgrade --channel <channel>` no longer exits 1 when every installed plugin already follows that channel and one update is `deferred` (OpenCode is running) or `skipped`: the entry reports it, as in an upgrade with no `--channel`. It exited 1 on every such run, so AKM Desktop's Update, which always names the channel, failed whenever OpenCode was open. A plugin left on the other channel still makes the switch exit 1. When akm exits 1 without a failed step, AKM Desktop now shows what akm reported as not done (akm's message and each deferred or skipped plugin with its reason) instead of "AKM's upgrade exited with an error."
52
64
  - AKM Desktop's asset page says why its usage and proposal read failed instead of only that it is unavailable. The Software page's hold on Update no longer guesses from the shape of a version whether Desktop's channel will offer that release.
53
65
  - AKM Desktop's Activity views show what akm reports and say when akm reported nothing. `assets.searchMisses` and `activity.retrievalTrend` return `available: false` with the reason when `state.db` is absent or needs a migration, and the Runs, Usage and search-gap views and the Library map's searches that found nothing say so instead of "No runs recorded" or "No searches"; `activity.overview` names it in `errors.state`. `activity.pulse`, `assets.improvement` and `activity.improveImpact` report an unresolvable bundle directory instead of reading it as no proposals. Needs attention counts every failed task run from akm's full count, not the pulse's three-row preview; the Usage summary calls the proposals counted in its window "updated in this window" instead of "pending"; Repeated search gaps lists the queries akm marks `repeated`.
54
66
  - `activity.improveImpact` returns `usageSince`, `usageComplete` and, per changed asset, `beforeComplete`, so a change whose 28 days before are older than the usage akm keeps shows "Not recorded", not 0. `activity.retrievalTrend` marks `partial` weeks and returns `enoughHistory`: no centre or usual range is drawn from fewer than four whole weeks. `activity.events` rows carry `byPerson`; Replay plays the person's events by default so its figures match the Usage tab, offers everyone's, and shows curates apart from searches. The workflow trace header sums tokens from the attempts akm reported and says "tokens not reported" when none did, and units that name no step get no invented status.
@@ -108,6 +108,7 @@ export function emptyImproveMetrics() {
108
108
  totalChunks: 0,
109
109
  pairsJudged: 0,
110
110
  failedPairs: 0,
111
+ deferredPairs: 0,
111
112
  durationMs: 0,
112
113
  },
113
114
  memoryInference: {
@@ -233,6 +234,9 @@ function projectRunMetrics(result) {
233
234
  if (pairPass) {
234
235
  cons.pairsJudged += toFiniteNumber(pairPass.pairsJudged);
235
236
  cons.failedPairs += toFiniteNumber(pairPass.failedJudgments);
237
+ const deferred = pairPass.deferredJudgments;
238
+ cons.deferredPairs =
239
+ typeof deferred === "number" && Number.isSafeInteger(deferred) && deferred >= 0 ? deferred : null;
236
240
  }
237
241
  }
238
242
  const memoryInference = result.memoryInference;
@@ -291,6 +295,10 @@ function mergeImproveMetrics(dst, src) {
291
295
  dst.consolidation.totalChunks += src.consolidation.totalChunks;
292
296
  dst.consolidation.pairsJudged += src.consolidation.pairsJudged;
293
297
  dst.consolidation.failedPairs += src.consolidation.failedPairs;
298
+ dst.consolidation.deferredPairs =
299
+ dst.consolidation.deferredPairs === null || src.consolidation.deferredPairs === null
300
+ ? null
301
+ : dst.consolidation.deferredPairs + src.consolidation.deferredPairs;
294
302
  dst.consolidation.durationMs += src.consolidation.durationMs;
295
303
  dst.memoryInference.considered += src.memoryInference.considered;
296
304
  dst.memoryInference.freshAttempts += src.memoryInference.freshAttempts;
@@ -21,6 +21,8 @@
21
21
  * a second crontab/launchd/schtasks text parser.
22
22
  */
23
23
  import { spawnSync } from "node:child_process";
24
+ import { isExactSemver } from "../../registry/semver.js";
25
+ import { semverOrder } from "../../runtime.js";
24
26
  import { selectBackend } from "../../tasks/backends/index.js";
25
27
  import { pkgVersion } from "../../version.js";
26
28
  /**
@@ -118,12 +120,22 @@ export async function collectSchedulerBinaryAdvisory(probe, deps = {}) {
118
120
  evidence: { binding, scheduledVersion, cliVersion },
119
121
  };
120
122
  }
123
+ const order = isExactSemver(scheduledVersion) && isExactSemver(cliVersion)
124
+ ? semverOrder(scheduledVersion, cliVersion)
125
+ : undefined;
126
+ const advice = order === -1
127
+ ? " — run `akm doctor scheduler sync --rebind` to rebind the schedule."
128
+ : order === 1
129
+ ? "; the scheduled CLI is newer. Update the calling CLI or plugin, then run health again."
130
+ : order === 0
131
+ ? "; the versions have equal semantic precedence. Inspect both installations before deciding whether to rebind."
132
+ : "; version ordering is unknown. Inspect both installations before deciding whether to rebind.";
121
133
  return {
122
134
  name: "scheduler-binary",
123
135
  kind: "deterministic",
124
136
  status: "warn",
125
137
  confidence: "high",
126
- message: `Scheduled tasks are bound to akm v${scheduledVersion}, but the running CLI is v${cliVersion} — run \`akm doctor scheduler sync --rebind\` to rebind the schedule.`,
138
+ message: `Scheduled tasks are bound to akm v${scheduledVersion}, but the running CLI is v${cliVersion}${advice}`,
127
139
  evidence: { binding, scheduledVersion, cliVersion },
128
140
  };
129
141
  }
@@ -735,13 +735,10 @@ async function judgeOne(ctx, candidate) {
735
735
  // durable half).
736
736
  const retiredKey = stripBundle(retired.asset.ref);
737
737
  const successorKey = stripBundle(successor.asset.ref);
738
- // A retire-worthy verdict the same-run
739
- // chain guard drops is not a settled "no action" — a LATER run, once the
740
- // conflicting retirement has been reviewed, may well mint it. Counted as
741
- // failed so its initiator gets no row (real data: night 1 alone judged 177
742
- // duplicate verdicts into only 59 proposals — 118 silently abandoned).
738
+ // The verdict is valid, but the conflicting proposal must resolve before
739
+ // this retirement can proceed. Leave its initiator eligible for a later run.
743
740
  if (ctx.retiredThisRun.has(retiredKey) || ctx.retiredThisRun.has(successorKey)) {
744
- return failedPair("other", "a note in this pair was already retired earlier in this run");
741
+ return { deferred: "same_run_retirement" };
745
742
  }
746
743
  ctx.retiredThisRun.add(retiredKey);
747
744
  ctx.retiredThisRun.add(successorKey);
@@ -821,7 +818,7 @@ async function judgeOne(ctx, candidate) {
821
818
  catch (error) {
822
819
  ctx.warnings.push(`Pair pass: could not mint a retire proposal for ${retired.asset.ref}: ${error instanceof Error ? error.message : String(error)}`);
823
820
  // A mint failure is transient (a lock, a disk error, a
824
- // validation hiccup) — treated the same as a same-run drop, so no row is
821
+ // validation hiccup) — no row is
825
822
  // written and the pair is retried next run instead of abandoned.
826
823
  return failedPair("other", error instanceof Error ? error.message : String(error));
827
824
  }
@@ -851,6 +848,7 @@ seams = {}) {
851
848
  labelCounts: emptyLabelCounts(),
852
849
  retired: [],
853
850
  failedJudgments: 0,
851
+ deferredJudgments: 0,
854
852
  };
855
853
  const llmRunner = opts.llmRunner ?? undefined;
856
854
  if (!bundleId || !llmRunner)
@@ -958,27 +956,31 @@ seams = {}) {
958
956
  continuitySearch: seams.continuitySearch ?? createContinuitySearch(stashDir, config),
959
957
  };
960
958
  const failures = [];
961
- // An initiator with any failed (or never-sent) judge call
962
- // gets no ledger row — a failure attempted nothing conclusive, so writing
963
- // one would mean the pair is never retried.
964
- const failedInitiators = new Set();
959
+ const deferrals = [];
960
+ // Failed or deferred pairs get no ledger row: their work is still unsettled.
961
+ const unsettledInitiators = new Set();
965
962
  if (judgeable.length > 0) {
966
963
  const results = await concurrentMap(judgeable, (candidate) => judgeOne(ctx, candidate), (llmRunner.kind === "connection" ? llmRunner.concurrency : undefined) ?? 1, { signal: opts.signal });
967
964
  results.forEach((r, idx) => {
968
965
  // `concurrentMap` leaves an entry `undefined` for a call an aborted run never sent at all: that pair did not
969
966
  // settle either, so it is counted as cancelled rather than as a clean "no action" verdict.
970
967
  const failure = r === undefined ? { kind: "cancelled", reason: "not sent: the run was cancelled" } : r.failure;
971
- if (!failure)
968
+ const deferred = r?.deferred;
969
+ if (!failure && !deferred)
972
970
  return;
973
971
  const candidate = judgeable[idx];
974
- failedInitiators.add(candidate.initiator.ref);
975
- failures.push({ initiator: candidate.initiator.ref, other: candidate.other.ref, ...failure });
972
+ unsettledInitiators.add(candidate.initiator.ref);
973
+ const pair = { initiator: candidate.initiator.ref, other: candidate.other.ref };
974
+ if (failure)
975
+ failures.push({ ...pair, ...failure });
976
+ if (deferred)
977
+ deferrals.push({ ...pair, reason: deferred });
976
978
  });
977
979
  }
978
980
  // S1: a ledger row is written for an initiator only once ALL of its OWN
979
981
  // candidates were admitted (whole-initiator admission above makes this a
980
982
  // simple membership check: judgeable either has every one of an
981
- // initiator's candidates, or none of them) and none of them failed
983
+ // initiator's candidates, or none of them) and none failed or were deferred
982
984
  // — including an initiator with zero candidates, which
983
985
  // trivially satisfies both. One left out by the cap or a pending-proposal
984
986
  // collision gets no row at all, so the next run reconsiders it rather
@@ -995,7 +997,7 @@ seams = {}) {
995
997
  return true;
996
998
  if (!admittedRefs.has(i.ref))
997
999
  return false;
998
- return !failedInitiators.has(i.ref);
1000
+ return !unsettledInitiators.has(i.ref);
999
1001
  })
1000
1002
  .map((i) => ({
1001
1003
  stashDir,
@@ -1006,6 +1008,10 @@ seams = {}) {
1006
1008
  }));
1007
1009
  recordLedgerAttempt({ proposalsCtx: opts.proposalsCtx }, ledgerInputs);
1008
1010
  }
1011
+ const deferredJudgments = deferrals.length;
1012
+ if (deferredJudgments > 0) {
1013
+ warnings.push(`Pair pass: ${deferredJudgments} retire decisions deferred because a note is already reserved for retirement in this run; these pairs remain eligible for later runs.`);
1014
+ }
1009
1015
  const failedJudgments = failures.length;
1010
1016
  const failureKinds = {};
1011
1017
  for (const { kind } of failures)
@@ -1020,12 +1026,13 @@ seams = {}) {
1020
1026
  initiators: initiators.length,
1021
1027
  initiatorsBacklog,
1022
1028
  pairsConsidered: candidates.length,
1023
- // Parsed verdicts only — judgeable.length counted pairs that
1024
- // were admitted, not pairs a verdict actually came back for.
1025
- pairsJudged: judgeable.length - failedJudgments,
1029
+ // Count the judge's parsed verdicts, including decisions deferred or failing after the verdict.
1030
+ pairsJudged: Object.values(ctx.labelCounts).reduce((sum, count) => sum + count, 0),
1026
1031
  labelCounts: ctx.labelCounts,
1027
1032
  retired: ctx.retired,
1028
1033
  failedJudgments,
1034
+ deferredJudgments,
1035
+ ...(deferredJudgments > 0 ? { deferrals: deferrals.slice(0, PAIR_FAILURES_REPORTED_MAX) } : {}),
1029
1036
  ...(failedJudgments > 0 ? { failureKinds, failures: failures.slice(0, PAIR_FAILURES_REPORTED_MAX) } : {}),
1030
1037
  };
1031
1038
  }
@@ -99,6 +99,7 @@ export async function akmProposalAccept(options) {
99
99
  assetPath: result.assetPath,
100
100
  proposal: result.proposal,
101
101
  ...(result.commit ? { commit: result.commit } : {}),
102
+ ...(result.warnings ? { warnings: result.warnings } : {}),
102
103
  };
103
104
  }
104
105
  /**
@@ -17,7 +17,7 @@ import { isDeepStrictEqual } from "node:util";
17
17
  import { parse as parseYaml } from "yaml";
18
18
  import { ensureAkmMarkdownType } from "../../core/asset/akm-markdown.js";
19
19
  import { filesForRef, placementTypes, stashDirFor } from "../../core/asset/asset-placement.js";
20
- import { isBundleSlug, parseBundleRef } from "../../core/asset/asset-ref.js";
20
+ import { isBundleSlug, makeBundleRef, parseBundleRef } from "../../core/asset/asset-ref.js";
21
21
  import { assembleAsset, serializeFrontmatter } from "../../core/asset/asset-serialize.js";
22
22
  import { carryForwardBookkeepingFrontmatter, parseFrontmatter, replaceFrontmatterBlocks, } from "../../core/asset/frontmatter.js";
23
23
  import { MEMORY_ARCHIVE_REL } from "../../core/asset/memory-archive.js";
@@ -43,11 +43,14 @@ import { insertEventOnce } from "../../storage/repositories/events-repository.js
43
43
  import { CONSOLIDATE_LEDGER_SOURCE, forgetImproveLedgerDecision, PAIR_PASS_LEDGER_SOURCE, recordImproveLedger, recordImproveLedgerDecision, reopenImproveLedgerDecision, } from "../../storage/repositories/improve-ledger-repository.js";
44
44
  import { getStateProposal, isLegacyProposalRef, listStateProposalIdsByPrefix, listStateProposals, upsertProposal, } from "../../storage/repositories/proposals-repository.js";
45
45
  import { openSqliteReadSnapshot } from "../../storage/sqlite-read-snapshot.js";
46
+ import { schedulerEnabledRefs, setSchedulerRefEnabled } from "../../tasks/activation-config.js";
47
+ import { withSchedulerLock } from "../../tasks/scheduler-lock.js";
46
48
  import { pkgVersion } from "../../version.js";
47
49
  import { contentHash } from "../improve/content-hash.js";
48
50
  import { writeSupersededEdge } from "../improve/memory/memory-belief.js";
49
51
  import { archiveCleanupCandidate, derivedTwinPath } from "../improve/memory/memory-improve.js";
50
52
  import { runBaseChecks } from "../lint/base-linter.js";
53
+ import { akmTasksDisable, akmTasksEnable, inspectTaskSchedulerBindings } from "../tasks/tasks.js";
51
54
  import { formatNewAssetDiff, formatRetireDiff, formatUnifiedDiff } from "./diff-format.js";
52
55
  import { ASSET_MISSING_GATE_REASON, EXPIRED_GATE_REASON, isAutomatedProposalSource, isRetireProposal, isValidProposalSource, PROPOSAL_SOURCES, proposalWaitingSince, STALE_TARGET_GATE_REASON, } from "./proposal-types.js";
53
56
  import { canonicalOnlyProposalValidators, hasCanonicalProposalValidator, runProposalValidators, } from "./validators/proposal-validators.js";
@@ -1456,6 +1459,7 @@ async function retireProposalWithLease(stashDir, config, proposal, options, ctx)
1456
1459
  throw new UsageError(`Cannot resolve proposal target ${proposal.ref}.`, "INVALID_PROPOSAL");
1457
1460
  let working = proposal;
1458
1461
  let intent = proposal.retireAcceptIntent;
1462
+ let scheduler;
1459
1463
  if (!intent) {
1460
1464
  // Fresh accept — no recorded intent yet, so the target must still be there.
1461
1465
  if (!fs.existsSync(assetPath)) {
@@ -1481,6 +1485,7 @@ async function retireProposalWithLease(stashDir, config, proposal, options, ctx)
1481
1485
  // the original.
1482
1486
  intent = { assetPath, backupContent: currentBytes.toString("utf8") };
1483
1487
  working = recordRetireAcceptIntent(stashDir, proposal.id, intent, ctx);
1488
+ scheduler = await disableRetiredTask(ref, target.source.name);
1484
1489
  if (retirement?.judgeLabel === "supersedes") {
1485
1490
  try {
1486
1491
  writeSupersededEdge(assetPath, retirement.successorRef);
@@ -1492,91 +1497,181 @@ async function retireProposalWithLease(stashDir, config, proposal, options, ctx)
1492
1497
  }
1493
1498
  else {
1494
1499
  assertAkmAssetWrite(target.source);
1500
+ assertRetiringTaskUnchanged(ref, intent, proposal);
1495
1501
  // Revalidate the survivor even after a partial archive. The recorded original
1496
1502
  // is the judged retired side when its file has already moved.
1497
1503
  if (working.retirement) {
1498
1504
  assertRetirementStillFresh(proposal.id, proposal.ref, working.retirement, target.source, fs.existsSync(intent.assetPath) ? fs.readFileSync(intent.assetPath) : Buffer.from(intent.backupContent));
1499
1505
  }
1506
+ scheduler = await disableRetiredTask(ref, target.source.name);
1500
1507
  }
1501
- // Phase 2: move, idempotently — a resumed call skips whichever file a
1502
- // tombstone under this proposal's own id already claims. A failure undoes this
1503
- // call's own moves, so a refused accept leaves no asset half-retired.
1504
- const mutationTarget = prepareWriteTargetForMutation(target);
1505
- assertWritePathsInsideSource(mutationTarget.source, [
1506
- intent.assetPath,
1507
- path.join(mutationTarget.source.path, MEMORY_ARCHIVE_REL, "archive-check"),
1508
- ]);
1509
- const already = findRetireArchiveDirsByProposalId(mutationTarget.source.path, proposal.id) ?? [];
1510
- const alreadyDone = alreadyArchivedOriginalPaths(mutationTarget.source.path, already);
1511
- const archiveDirs = [...already];
1512
- const paths = [];
1513
- const moved = [];
1514
- const candidate = {
1515
- ref: proposal.ref,
1516
- reason: working.retirement?.reason ?? "manual",
1517
- proposalId: proposal.id,
1518
- ...(working.retirement?.successorRef ? { successorRefs: [working.retirement.successorRef] } : {}),
1519
- };
1520
- const moveToArchive = (original) => {
1521
- const record = archiveCleanupCandidate(mutationTarget.source.path, candidate, original);
1522
- moved.push({ original, record });
1523
- archiveDirs.push(path.dirname(record.auditPath));
1524
- paths.push(original, path.join(mutationTarget.source.path, record.archivedPath), path.join(mutationTarget.source.path, record.auditPath));
1525
- };
1526
1508
  // The twin path is re-derived, not carried on the
1527
1509
  // intent — it is a pure function of assetPath and the ref's type, and the
1528
- // tombstone scan above (`alreadyDone`) already finds one archived earlier,
1510
+ // tombstone scan below (`alreadyDone`) already finds one archived earlier,
1529
1511
  // so storing it was redundant persisted state.
1530
1512
  const twinPath = derivedTwinPath(intent.assetPath, ref.type);
1513
+ let mutationTarget;
1514
+ let commit;
1515
+ let accepted;
1531
1516
  try {
1532
- if (!alreadyDone.has(path.resolve(intent.assetPath)) && fs.existsSync(intent.assetPath))
1533
- moveToArchive(intent.assetPath);
1534
- if (twinPath &&
1535
- !alreadyDone.has(path.resolve(twinPath)) &&
1536
- fs.existsSync(twinPath) &&
1537
- sameScope(scopeFromFrontmatter(parseFrontmatter(fs.readFileSync(twinPath, "utf8")).data), scopeFromFrontmatter(parseFrontmatter(intent.backupContent).data)))
1538
- moveToArchive(twinPath);
1539
- }
1540
- catch (error) {
1541
- for (const { original, record } of moved.reverse()) {
1542
- // A failed undo must not hide the failure that caused it; the tombstone stays to explain the file.
1543
- try {
1544
- fs.renameSync(path.join(mutationTarget.source.path, record.archivedPath), original);
1545
- fs.rmSync(path.dirname(path.join(mutationTarget.source.path, record.auditPath)), {
1546
- recursive: true,
1547
- force: true,
1548
- });
1549
- }
1550
- catch (undoError) {
1551
- warn(`[retire] could not put ${original} back from ${record.archivedPath}: ${undoError instanceof Error ? undoError.message : String(undoError)}`);
1517
+ // Native reconciliation awaits external work; a direct file edit can happen outside AKM's mutation lease.
1518
+ assertRetiringTaskUnchanged(ref, intent, proposal);
1519
+ // Phase 2: move, idempotently — a resumed call skips whichever file a
1520
+ // tombstone under this proposal's own id already claims. A failure undoes this
1521
+ // call's own moves, so a refused accept leaves no asset half-retired.
1522
+ mutationTarget = prepareWriteTargetForMutation(target);
1523
+ assertWritePathsInsideSource(mutationTarget.source, [
1524
+ intent.assetPath,
1525
+ path.join(mutationTarget.source.path, MEMORY_ARCHIVE_REL, "archive-check"),
1526
+ ]);
1527
+ const already = findRetireArchiveDirsByProposalId(mutationTarget.source.path, proposal.id) ?? [];
1528
+ const alreadyDone = alreadyArchivedOriginalPaths(mutationTarget.source.path, already);
1529
+ const archiveDirs = [...already];
1530
+ const paths = [];
1531
+ const moved = [];
1532
+ const candidate = {
1533
+ ref: proposal.ref,
1534
+ reason: working.retirement?.reason ?? "manual",
1535
+ proposalId: proposal.id,
1536
+ ...(working.retirement?.successorRef ? { successorRefs: [working.retirement.successorRef] } : {}),
1537
+ };
1538
+ const moveToArchive = (original) => {
1539
+ const record = archiveCleanupCandidate(mutationTarget.source.path, candidate, original);
1540
+ moved.push({ original, record });
1541
+ archiveDirs.push(path.dirname(record.auditPath));
1542
+ paths.push(original, path.join(mutationTarget.source.path, record.archivedPath), path.join(mutationTarget.source.path, record.auditPath));
1543
+ };
1544
+ try {
1545
+ if (!alreadyDone.has(path.resolve(intent.assetPath)) && fs.existsSync(intent.assetPath))
1546
+ moveToArchive(intent.assetPath);
1547
+ if (twinPath &&
1548
+ !alreadyDone.has(path.resolve(twinPath)) &&
1549
+ fs.existsSync(twinPath) &&
1550
+ sameScope(scopeFromFrontmatter(parseFrontmatter(fs.readFileSync(twinPath, "utf8")).data), scopeFromFrontmatter(parseFrontmatter(intent.backupContent).data)))
1551
+ moveToArchive(twinPath);
1552
+ }
1553
+ catch (error) {
1554
+ for (const { original, record } of moved.reverse()) {
1555
+ // A failed undo must not hide the failure that caused it; the tombstone stays to explain the file.
1556
+ try {
1557
+ fs.renameSync(path.join(mutationTarget.source.path, record.archivedPath), original);
1558
+ fs.rmSync(path.dirname(path.join(mutationTarget.source.path, record.auditPath)), {
1559
+ recursive: true,
1560
+ force: true,
1561
+ });
1562
+ }
1563
+ catch (undoError) {
1564
+ warn(`[retire] could not put ${original} back from ${record.archivedPath}: ${undoError instanceof Error ? undoError.message : String(undoError)}`);
1565
+ }
1552
1566
  }
1567
+ throw error;
1568
+ }
1569
+ commit = paths.length > 0 ? commitAccept(options.commitCollector, mutationTarget, proposal, paths) : undefined;
1570
+ if (archiveDirs.length === 0) {
1571
+ // Recorded intent, but neither file is at its original location NOR
1572
+ // archived under this proposal's id: something else removed the target
1573
+ // between intent and move. Refuse cleanly rather than finalize on
1574
+ // nothing.
1575
+ throw new UsageError(`Retire proposal ${proposal.id} target (${proposal.ref}) no longer exists and was not archived by this proposal — refusing to accept.`, "PROPOSAL_STALE");
1553
1576
  }
1577
+ // Phase 3: finalize — always from the recorded intent's own backupContent,
1578
+ // never a hash guessed from the archived copy.
1579
+ accepted = persistRetireAcceptance(stashDir, working, {
1580
+ targetName: mutationTarget.source.name,
1581
+ targetRoot: mutationTarget.source.path,
1582
+ assetPath: intent.assetPath,
1583
+ contentHash: contentHash(intent.backupContent),
1584
+ archiveDirs,
1585
+ backupContent: intent.backupContent,
1586
+ ...(options.gateDecision ? { gateDecision: options.gateDecision } : {}),
1587
+ ...(options.decidedBy ? { decidedBy: options.decidedBy } : {}),
1588
+ ...(options.eventMetadata ? { eventMetadata: options.eventMetadata } : {}),
1589
+ }, ctx);
1590
+ }
1591
+ catch (error) {
1592
+ // A retirement that does not go through leaves the task scheduled as it was.
1593
+ await scheduler.restore();
1554
1594
  throw error;
1555
1595
  }
1556
- const commit = paths.length > 0 ? commitAccept(options.commitCollector, mutationTarget, proposal, paths) : undefined;
1557
- if (archiveDirs.length === 0) {
1558
- // Recorded intent, but neither file is at its original location NOR
1559
- // archived under this proposal's id: something else removed the target
1560
- // between intent and move. Refuse cleanly rather than finalize on
1561
- // nothing.
1562
- throw new UsageError(`Retire proposal ${proposal.id} target (${proposal.ref}) no longer exists and was not archived by this proposal — refusing to accept.`, "PROPOSAL_STALE");
1563
- }
1564
- // Phase 3: finalize — always from the recorded intent's own backupContent,
1565
- // never a hash guessed from the archived copy.
1566
- const accepted = persistRetireAcceptance(stashDir, working, {
1567
- targetName: mutationTarget.source.name,
1568
- targetRoot: mutationTarget.source.path,
1569
- assetPath: intent.assetPath,
1570
- contentHash: contentHash(intent.backupContent),
1571
- archiveDirs,
1572
- backupContent: intent.backupContent,
1573
- ...(options.gateDecision ? { gateDecision: options.gateDecision } : {}),
1574
- ...(options.decidedBy ? { decidedBy: options.decidedBy } : {}),
1575
- ...(options.eventMetadata ? { eventMetadata: options.eventMetadata } : {}),
1576
- }, ctx);
1577
1596
  // The moved files left the index's view; drop their rows now, not at the next `akm index`.
1578
1597
  await indexWrittenProposalAssets(mutationTarget, twinPath ? [intent.assetPath, twinPath] : [intent.assetPath]);
1579
- return { proposal: accepted, assetPath: intent.assetPath, ref: accepted.ref, ...(commit ? { commit } : {}) };
1598
+ return {
1599
+ proposal: accepted,
1600
+ assetPath: intent.assetPath,
1601
+ ref: accepted.ref,
1602
+ ...(commit ? { commit } : {}),
1603
+ ...(scheduler.warnings.length ? { warnings: scheduler.warnings } : {}),
1604
+ };
1605
+ }
1606
+ function assertRetiringTaskUnchanged(ref, intent, proposal) {
1607
+ // The intent holds the bytes this retirement was validated against; `beforeHash` is absent on some proposals.
1608
+ if (ref.type === "task" &&
1609
+ fs.existsSync(intent.assetPath) &&
1610
+ fs.readFileSync(intent.assetPath, "utf8") !== intent.backupContent) {
1611
+ throw new UsageError(`Retire proposal ${proposal.id} target (${proposal.ref}) changed since retirement started.`, "PROPOSAL_STALE");
1612
+ }
1613
+ }
1614
+ /**
1615
+ * Stop scheduling a task that is being retired. Activation and reconciliation
1616
+ * stay with the operation `task disable` uses. `restore` puts back the
1617
+ * activation this call removed, for a retirement that does not go through.
1618
+ */
1619
+ async function disableRetiredTask(ref, bundle) {
1620
+ if (ref.type !== "task")
1621
+ return { warnings: [], restore: async () => { } };
1622
+ const qualifiedRef = makeBundleRef(bundle, ref.conceptId);
1623
+ let disabled = false;
1624
+ const restore = async () => {
1625
+ if (!disabled)
1626
+ return;
1627
+ disabled = false;
1628
+ try {
1629
+ await akmTasksEnable(qualifiedRef);
1630
+ }
1631
+ catch (error) {
1632
+ warn(`[retire] could not re-enable ${qualifiedRef} after its retirement was refused: ${error instanceof Error ? error.message : String(error)}. Run akm task enable ${qualifiedRef}.`);
1633
+ }
1634
+ };
1635
+ const unverified = (reason) => [
1636
+ `Task ${qualifiedRef} is disabled in local config, but native scheduler cleanup is unverified: ${reason}. ` +
1637
+ "Installed bindings may remain; repair the scheduler and run akm doctor scheduler sync.",
1638
+ ];
1639
+ try {
1640
+ const warnings = await withSchedulerLock(async () => {
1641
+ const before = await inspectTaskSchedulerBindings(qualifiedRef);
1642
+ const enabledRefs = schedulerEnabledRefs(loadConfig());
1643
+ const enabled = enabledRefs?.includes(qualifiedRef) === true;
1644
+ if (before.state === "unavailable") {
1645
+ // No native state can be read, so none can be reconciled: only this host's own list changes.
1646
+ if (enabled)
1647
+ disabled = setSchedulerRefEnabled(qualifiedRef, false).changed;
1648
+ return unverified(before.reason);
1649
+ }
1650
+ // Not on the host's list and not installed (a host with no list schedules exactly what is installed).
1651
+ if (!enabled && before.state === "not-installed")
1652
+ return [];
1653
+ if (!enabled && before.state === "unknown")
1654
+ return unverified(before.reason);
1655
+ disabled = enabled || enabledRefs === undefined;
1656
+ const { sync } = await akmTasksDisable(qualifiedRef);
1657
+ const failures = sync.failures.map((failure) => `${failure.path}: ${failure.reason}`).join("; ");
1658
+ const after = await inspectTaskSchedulerBindings(qualifiedRef);
1659
+ if (after.state === "installed") {
1660
+ throw new Error(`Task ${qualifiedRef} remains installed in the native scheduler after cleanup${failures ? `: ${failures}` : ""}. ` +
1661
+ "Retry retirement or run akm doctor scheduler sync.");
1662
+ }
1663
+ // The sync covers the whole bundle; only this task's own bindings decide its retirement.
1664
+ return [
1665
+ ...("reason" in after ? unverified(after.reason) : []),
1666
+ ...(failures ? [`Scheduler sync of bundle ${bundle} also reported: ${failures}.`] : []),
1667
+ ];
1668
+ });
1669
+ return { warnings, restore };
1670
+ }
1671
+ catch (error) {
1672
+ await restore();
1673
+ throw error;
1674
+ }
1580
1675
  }
1581
1676
  /**
1582
1677
  * Restore an accepted proposal's target from the backup taken at promotion.
@@ -386,21 +386,47 @@ function gitOrThrow(repoDir, args) {
386
386
  }
387
387
  return result.stdout.trim();
388
388
  }
389
+ /** The current branch's upstream in the origin that the provider verified, when configured. */
390
+ function originUpstream(repo) {
391
+ // A detached HEAD names no branch, and an unborn one has no ref yet: neither has an upstream.
392
+ const branch = runGit(["-C", repo, "symbolic-ref", "-q", "HEAD"]);
393
+ if (branch.status !== 0)
394
+ return undefined;
395
+ const [ref, remote] = gitOrThrow(repo, [
396
+ "for-each-ref",
397
+ "--format=%(upstream) %(upstream:remotename)",
398
+ branch.stdout.trim(),
399
+ ]).split(" ");
400
+ return ref && remote === "origin" ? { ref, revision: gitOrThrow(repo, ["rev-parse", "--verify", ref]) } : undefined;
401
+ }
389
402
  /**
390
403
  * Publish a staged writable checkout: fast-forward the live checkout to
391
404
  * exactly the staged commit. Git refuses a non-fast-forward or a merge that
392
- * would overwrite local work, and changes nothing in that case.
405
+ * would overwrite local work, preserving those files in that case.
393
406
  */
394
- function fastForwardCheckout(liveRepo, stagedRepo) {
407
+ function fastForwardCheckout(liveRepo, stagedRepo, expectedUpstream) {
395
408
  const head = gitOrThrow(stagedRepo, ["rev-parse", "HEAD"]);
396
- gitOrThrow(liveRepo, ["fetch", "--no-tags", stagedRepo, head]);
409
+ const upstream = originUpstream(stagedRepo);
410
+ if (upstream?.ref !== expectedUpstream?.ref || originUpstream(liveRepo)?.ref !== expectedUpstream?.ref) {
411
+ throw new UsageError(`Writable Git install at ${liveRepo} changed its upstream while the update was prepared.`);
412
+ }
413
+ gitOrThrow(liveRepo, ["fetch", "--no-tags", stagedRepo, head, ...(upstream ? [upstream.ref] : [])]);
414
+ if (upstream && expectedUpstream) {
415
+ // Use the tip Git fetched, not HEAD: local commits or a moving remote can
416
+ // make them differ. The pre-staging value preserves a concurrent live fetch.
417
+ gitOrThrow(liveRepo, ["update-ref", upstream.ref, upstream.revision, expectedUpstream.revision]);
418
+ }
397
419
  const merge = runGit(["-C", liveRepo, "merge", "--ff-only", "--no-overwrite-ignore", head], { timeout: 120_000 });
420
+ if (merge.status !== 0 && upstream && expectedUpstream) {
421
+ // A refused publish publishes nothing: put the tracking ref back, unless another writer has moved it since.
422
+ runGit(["-C", liveRepo, "update-ref", upstream.ref, expectedUpstream.revision, upstream.revision]);
423
+ }
398
424
  if (merge.status === null) {
399
425
  // Spawn failure, timeout or signal: git may have been interrupted mid-checkout.
400
426
  throw new UsageError(`git merge did not finish in ${liveRepo} (${merge.error?.message ?? `killed by ${merge.signal}`}); the checkout may be partly updated. Check \`git status\` there.`);
401
427
  }
402
428
  if (merge.status !== 0) {
403
- throw new UsageError(`Writable Git install at ${liveRepo} cannot fast-forward without overwriting local work; nothing was changed. ${merge.stderr.trim()}`, "INVALID_FLAG_VALUE", UPDATE_REFUSAL_HINT);
429
+ throw new UsageError(`Writable Git install at ${liveRepo} cannot fast-forward without overwriting local work; local work was preserved. ${merge.stderr.trim()}`, "INVALID_FLAG_VALUE", UPDATE_REFUSAL_HINT);
404
430
  }
405
431
  }
406
432
  /**
@@ -492,6 +518,7 @@ async function stageManagedUpdate(managed, force) {
492
518
  throw new UsageError(`Writable Git install at ${managed.localRoot} is not a checkout; refusing to update it.`);
493
519
  }
494
520
  const liveRepo = topLevel.stdout.trim();
521
+ const expectedUpstream = originUpstream(liveRepo);
495
522
  const stagingParent = createStagingParent(path.dirname(liveRepo));
496
523
  const stagedRepo = path.join(stagingParent, path.basename(liveRepo));
497
524
  try {
@@ -508,8 +535,10 @@ async function stageManagedUpdate(managed, force) {
508
535
  return {
509
536
  synced: { ...fetched, contentDir: managed.localRoot, cacheDir: liveRepo, extractedDir: liveRepo },
510
537
  staged: {
511
- unchanged: gitOrThrow(liveRepo, ["rev-parse", "HEAD"]) === gitOrThrow(stagedRepo, ["rev-parse", "HEAD"]),
512
- publish: () => fastForwardCheckout(liveRepo, stagedRepo),
538
+ unchanged: gitOrThrow(liveRepo, ["rev-parse", "HEAD"]) === gitOrThrow(stagedRepo, ["rev-parse", "HEAD"]) &&
539
+ expectedUpstream?.revision === originUpstream(stagedRepo)?.revision &&
540
+ originUpstream(liveRepo)?.revision === expectedUpstream?.revision,
541
+ publish: () => fastForwardCheckout(liveRepo, stagedRepo, expectedUpstream),
513
542
  cleanup: () => cleanupDirectoryBestEffort(stagingParent, "bundle update"),
514
543
  },
515
544
  };
@@ -575,6 +604,7 @@ async function syncGitPlainSource(config, gitSource, stashDir, lockMode) {
575
604
  // A writable mirror may carry local commits: pull into a copy, then
576
605
  // fast-forward the live checkout to it.
577
606
  const liveCheckout = component.writable && fs.existsSync(livePaths.repoDir);
607
+ const expectedUpstream = liveCheckout ? originUpstream(livePaths.repoDir) : undefined;
578
608
  if (liveCheckout)
579
609
  fs.cpSync(livePaths.rootDir, stagedPaths.rootDir, { recursive: true, preserveTimestamps: true });
580
610
  await syncMirroredRepo(gitSource, {
@@ -587,7 +617,7 @@ async function syncGitPlainSource(config, gitSource, stashDir, lockMode) {
587
617
  });
588
618
  const index = await publishAndIndex(stashDir, lockMode, () => {
589
619
  if (liveCheckout)
590
- fastForwardCheckout(livePaths.repoDir, stagedPaths.repoDir);
620
+ fastForwardCheckout(livePaths.repoDir, stagedPaths.repoDir, expectedUpstream);
591
621
  else
592
622
  replaceDirectory(stagedPaths.rootDir, livePaths.rootDir);
593
623
  });
@@ -891,12 +891,11 @@ export async function runUpgrade(args, currentVersion, deps) {
891
891
  // blocked or could not run is not done, and neither is one whose plugin
892
892
  // step failed.
893
893
  const migrationFailed = upgraded.migration?.status === "blocked" || upgraded.migration?.status === "failed";
894
+ // A plugin left on the other channel is a switch that did not happen. A "current" entry there is one the switch
895
+ // left alone on purpose, and a deferred or skipped plugin already follows the channel asked for: its update waits
896
+ // for the harness to exit, as in an upgrade with no --channel, and is reported in its entry.
894
897
  const switchIncomplete = switchChannel !== undefined &&
895
- plugins.some((p) => p.channel !== undefined &&
896
- // A "current" entry still on the other channel is one the switch left alone on purpose.
897
- ((p.channel !== switchChannel && p.outcome !== "current") ||
898
- p.outcome === "deferred" ||
899
- p.outcome === "skipped"));
898
+ plugins.some((p) => p.channel !== undefined && p.channel !== switchChannel && p.outcome !== "current");
900
899
  return {
901
900
  mode: "upgrade",
902
901
  result,