Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
Add bounded update reminders to diagram delivery receipts
tt-a1i56ef913296c9
diff --git a/archify.zip b/archify.zipindex 597e4ded..352bd0d1 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex c7ad3cf9..754e80d3 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -20,7 +20,7 @@ For a real codebase, read [Repository authoring](references/repository-authoringWhen the user supplies a frozen candidate, run `finalize` first as one CLI invocation. Its passing receipt completes the automated gates; follow any visual review recommendation under Delivery before claiming visual quality. For repair, follow step 5.-The optional update check never delays `finalize`; see Update awareness.+`finalize` includes a bounded update check in its delivery receipt; see Update awareness.## Fast authoring path@@ -43,10 +43,7 @@ Use this path for ordinary generation. Read branch references only when their st## Update awareness-After the first candidate exists, a harness with true parallel tool calls may run `scripts/check-update.mjs` once alongside `finalize`. Otherwise skip it without delaying delivery.--- For `silent`, continue without mentioning the update check.-- For `update_available`, read `references/update-awareness.md`, follow it, then continue the requested task.+`finalize` and standalone `deliver` include `update` in their receipts. Do not run a separate check for the same delivery. If `update.noticeRequired` is true, read `references/update-awareness.md` and keep one update line in your final response to the user, even after a quality gate fails. For a task with several diagrams, mention the update once in the final response. Never acknowledge, snooze, ignore, install, or update on the user's behalf.Before the first candidate, use the authoring references and relevant repository source, not Archify implementation or tests. Inspect Archify implementation if diagnostics remain unactionable after focused repairs.diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex e28ad318..fa2066d9 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -4163,7 +4163,7 @@ function commandRender(args) {if (result.status !== 0) exitFrom(result);}-function reportArtifactFailure({ command, json, stage, type, input, output, error, diagnostics = [], status = 1, checker, receiptId, provenance }) {+function reportArtifactFailure({ command, json, stage, type, input, output, error, diagnostics = [], status = 1, checker, receiptId, provenance, update }) {const receipt = {schemaVersion: 1,ok: false,@@ -4177,9 +4177,13 @@ function reportArtifactFailure({ command, json, stage, type, input, output, errodiagnostics,...(provenance ? { provenance } : {}),...(checker ? { checker } : {}),+ ...(update ? { update } : {}),};if (json) console.log(JSON.stringify(receipt, null, 2));- else console.error(formatDiagnostics(error, diagnostics));+ else {+ console.error(formatDiagnostics(error, diagnostics));+ if (update?.noticeRequired) console.log(update.noticeText);+ }process.exitCode = status;}@@ -4319,16 +4323,18 @@ async function commandDeliver(args) {releaseRegularFileBinding,};const receiptId = randomUUID();+ let updateCheck;let deliveryOwnership;let recoveryRequired = false;let stagingDirectory;let stagingIdentity;let deliveryAliasOutput;- const reportDeliveryFailure = (options) => {+ const reportDeliveryFailure = async (options) => {const ownership = deliveryOwnership;deliveryOwnership = undefined;const recorded = writeDeliveryFailureReceipt({...options,+ ...(updateCheck ? { update: await updateCheck } : {}),pathsAlias,receiptId,ownership,@@ -4343,6 +4349,10 @@ async function commandDeliver(args) {recoveryRequired = true;}};+ const reportPreparedArtifactFailure = async (options) => reportArtifactFailure({+ ...options,+ ...(updateCheck ? { update: await updateCheck } : {}),+ });const inputPath = path.resolve(input);let specification;let diagram;@@ -4351,7 +4361,7 @@ async function commandDeliver(args) {diagram = JSON.parse(specification.toString('utf8'));} catch (error) {const repair = inputDiagnostic(error, inputPath);- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'input',type,@@ -4402,9 +4412,9 @@ async function commandDeliver(args) {})],};if (outputPath) {- reportDeliveryFailure(failure);+ await reportDeliveryFailure(failure);} else {- reportArtifactFailure({ ...failure, command: 'deliver', receiptId });+ await reportPreparedArtifactFailure({ ...failure, command: 'deliver', receiptId });}return;}@@ -4413,7 +4423,7 @@ async function commandDeliver(args) {fs.mkdirSync(outputDirectory, { recursive: true });} catch (error) {const message = `Could not create delivery directory "${outputDirectory}": ${error.message}`;- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'prepare',type,@@ -4466,9 +4476,9 @@ async function commandDeliver(args) {})],};if (error?.code === 'ARCHIFY_SIDECAR_NAMESPACE_INDETERMINATE') {- reportArtifactFailure({ ...failure, command: 'deliver', receiptId });+ await reportPreparedArtifactFailure({ ...failure, command: 'deliver', receiptId });} else {- reportDeliveryFailure(failure);+ await reportDeliveryFailure(failure);}return;}@@ -4506,8 +4516,10 @@ async function commandDeliver(args) {outputPath = artifactCapture.commitPath;provenancePath = provenanceCapture.commitPath;outputDirectory = path.dirname(outputPath);+ const { startDeliveryUpdateCheck } = await import('./delivery-update.mjs');+ updateCheck = startDeliveryUpdateCheck();} catch (error) {- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'prepare', type, input: inputPath, output: outputPath, receiptId,error: error.message,diagnostics: error.archifyDiagnostics || [diagnostic({@@ -4532,7 +4544,7 @@ async function commandDeliver(args) {stagingIdentity = staging.identity;} catch (error) {const message = `Could not create a delivery candidate beside "${outputPath}": ${error.message}`;- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'prepare',type,@@ -4586,7 +4598,7 @@ async function commandDeliver(args) {} catch (error) {const message = `Could not start delivery for "${outputPath}": ${error.message}`;const recorded = error.deliveryFailureRecord;- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'prepare', type, input: inputPath, output: outputPath, receiptId,error: message,...(recorded ? { provenance: recorded.status } : {}),@@ -4625,7 +4637,7 @@ async function commandDeliver(args) {releaseError = cause;}deliveryOwnership = undefined;- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'prepare', type, input: inputPath, output: outputPath, receiptId,error: error.message,diagnostics: [@@ -4653,7 +4665,7 @@ async function commandDeliver(args) {// The lock is the remaining fail-closed barrier. Do not write failure// provenance or release it after journal rollback itself became unsafe.deliveryOwnership = undefined;- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'prepare', type, input: inputPath, output: outputPath, receiptId,error: `Could not persist the delivery attempt before rendering: ${error.message}`,diagnostics: [deliveryJournalRecoveryDiagnostic(outputPath, error)],@@ -4668,14 +4680,14 @@ async function commandDeliver(args) {recoveryDirectory: stagingDirectory,recoverableBackups: [],};- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'prepare', type, input: inputPath, output: outputPath, receiptId,error: `Could not persist the delivery attempt before rendering: ${error.message}`,diagnostics: [deliveryLockFailureDiagnostic(outputPath, error)],});return;}- reportDeliveryFailure({+ await reportDeliveryFailure({json, stage: 'prepare', type, input: inputPath, output: outputPath,error: 'Could not persist the delivery attempt before rendering.',diagnostics: [diagnostic({@@ -4700,7 +4712,7 @@ async function commandDeliver(args) {);} catch (error) {const message = `Could not freeze the delivery specification: ${error.message}`;- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'prepare',type,@@ -4724,7 +4736,7 @@ async function commandDeliver(args) {});if (render.status !== 0) {const failure = rendererFailure(render);- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'render',type,@@ -4760,7 +4772,7 @@ async function commandDeliver(args) {} catch {checker = { ok: false, file: outputPath, diagnostic: check.stdout.trim() };}- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'check',type,@@ -4779,7 +4791,7 @@ async function commandDeliver(args) {result = JSON.parse(check.stdout);} catch (error) {const message = `Could not parse the successful artifact-check receipt: ${error.message}`;- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'receipt',type,@@ -4800,7 +4812,7 @@ async function commandDeliver(args) {artifact = fs.readFileSync(candidatePath);} catch (error) {const message = `Could not read the verified delivery candidate: ${error.message}`;- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'receipt',type,@@ -4821,7 +4833,7 @@ async function commandDeliver(args) {sourceEvidence = sourceEvidenceFromArtifact(artifact);} catch (error) {const message = `Could not read the repository evidence receipt: ${error.message}`;- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'receipt',type,@@ -4893,7 +4905,7 @@ async function commandDeliver(args) {// cleanup must not claim a candidate that could not be bound here.}} catch (error) {- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'commit',type,@@ -4928,7 +4940,7 @@ async function commandDeliver(args) {otherOutputPaths: [currentOutputPath],});} catch (error) {- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'commit',type,@@ -4974,7 +4986,7 @@ async function commandDeliver(args) {// barrier around retained backups and any claimant we did not create.// Do not write failure provenance or release ownership here.deliveryOwnership = undefined;- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'commit', type, input: inputPath, output: outputPath, receiptId,error: message,diagnostics: [@@ -4995,7 +5007,7 @@ async function commandDeliver(args) {releaseError = cause;}deliveryOwnership = undefined;- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'commit', type, input: inputPath, output: outputPath, receiptId,error: message,diagnostics: [@@ -5007,14 +5019,14 @@ async function commandDeliver(args) {}if (error.deliveryOwnershipCode === 'delivery/ownership-lost') {deliveryOwnership = undefined;- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'commit', type, input: inputPath, output: outputPath, receiptId,error: message,diagnostics: [deliveryLockFailureDiagnostic(outputPath, error)],});return;}- reportDeliveryFailure({+ await reportDeliveryFailure({json,stage: 'commit',type,@@ -5050,7 +5062,7 @@ async function commandDeliver(args) {};}const message = `Delivery committed, but its lock could not be released for "${outputPath}": ${error.message}`;- reportArtifactFailure({+ await reportPreparedArtifactFailure({command: 'deliver', json, stage: 'release', type, input: inputPath, output: outputPath, receiptId,error: message,diagnostics: [deliveryLockFailureDiagnostic(outputPath, error)],@@ -5075,6 +5087,8 @@ async function commandDeliver(args) {}}+ receipt.update = await updateCheck;+if (json) {console.log(JSON.stringify(receipt, null, 2));} else {@@ -5084,6 +5098,7 @@ async function commandDeliver(args) {: '';console.log(`${receipt.validation.checksPassed}/${receipt.validation.checkCount} artifact checks; composition ${receipt.validation.compositionProfile}: ${receipt.validation.compositionStatus}${engineering}; sha256 ${receipt.artifact.sha256.slice(0, 12)}`);if (receipt.open?.status === 'opened') console.log(`opened ${outputPath}`);+ if (receipt.update.noticeRequired) console.log(receipt.update.noticeText);}} finally {if (deliveryOwnership) {@@ -5718,6 +5733,7 @@ async function commandFinalize(rawArgs) {console.log(`gates ${Object.entries(result.summary.gates).map(([stage, status]) => `${stage}:${status}`).join(' ')}`);console.log(`receipt ${result.summary.evidence.receipt}`);console.log(`perceptual visual review ${result.summary.visualReview}`);+ if (result.summary.update?.noticeRequired) console.log(result.summary.update.noticeText);}process.exitCode = result.exitCode;}diff --git a/archify/bin/delivery-update.mjs b/archify/bin/delivery-update.mjsnew file mode 100644index 00000000..36569e7f--- /dev/null+++ b/archify/bin/delivery-update.mjs@@ -0,0 +1,92 @@+import { spawn } from 'node:child_process';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const childPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'scripts', 'delivery-update-child.mjs');+const DEADLINE_MS = 1_000;+const MAX_OUTPUT_BYTES = 16 * 1_024;++function unavailable(reason) {+ return { status: 'unavailable', installedVersion: null, availableVersion: null,+ releaseNotes: null, checkedAt: null, source: null, noticeRequired: false,+ noticeText: null, reason };+}++function normalize(result) {+ if (result?.status === 'current') return {+ status: 'current', installedVersion: result.installedVersion,+ availableVersion: result.availableVersion, releaseNotes: null,+ checkedAt: result.checkedAt, source: result.source,+ noticeRequired: false, noticeText: null,+ };+ if (result?.status !== 'update_available') {+ return unavailable(result?.reason || (result?.status === 'silent' ? 'no-update' : 'invalid-result'));+ }+ const noticeRequired = result.noticeRequired !== false;+ const cached = result.source === 'cache';+ const noticeText = noticeRequired+ ? `Archify ${result.severity === 'security' ? 'security update' : 'update'}: ${result.installedVersion} → ${result.latestVersion}. ${cached+ ? result.checkedAt+ ? `A previous check at ${result.checkedAt} found a newer release.`+ : 'A previous check found a newer release; its check time is unknown.'+ : 'A newer release is available.'} Release notes: ${result.releaseNotes}. The installed Skill has not changed.`+ : null;+ return {+ status: 'update_available',+ installedVersion: result.installedVersion,+ availableVersion: result.latestVersion,+ releaseNotes: result.releaseNotes,+ severity: result.severity,+ checkedAt: result.checkedAt,+ source: result.source,+ noticeRequired,+ noticeText,+ ...(result.eventKey ? { eventKey: result.eventKey } : {}),+ ...(result.reason ? { reason: result.reason } : {}),+ ...(result.suppressedUntil ? { suppressedUntil: result.suppressedUntil } : {}),+ };+}++export function startDeliveryUpdateCheck({+ env = process.env, deadlineMs = DEADLINE_MS, checkerPath = childPath,+} = {}) {+ if (env.ARCHIFY_UPDATE_CHECK_DISABLED === '1') return Promise.resolve(unavailable('disabled'));+ return new Promise((resolve) => {+ let child;+ try {+ child = spawn(process.execPath, [checkerPath, String(Date.now() + deadlineMs)], {+ env,+ stdio: ['ignore', 'pipe', 'ignore'],+ windowsHide: true,+ });+ } catch {+ resolve(unavailable('runtime-unavailable'));+ return;+ }+ let output = '';+ let timedOut = false;+ let overflow = false;+ const timer = setTimeout(() => {+ timedOut = true;+ child.kill('SIGKILL');+ }, deadlineMs);+ child.stdout.on('data', (chunk) => {+ if (Buffer.byteLength(output) + chunk.length > MAX_OUTPUT_BYTES) {+ overflow = true;+ child.kill('SIGKILL');+ } else output += chunk.toString('utf8');+ });+ child.on('error', () => {});+ child.on('close', (code) => {+ clearTimeout(timer);+ if (overflow) return resolve(unavailable('invalid-result'));+ // A synchronous renderer can delay both this callback and the parent's+ // timer. A complete child result wins even if the timer fired meanwhile.+ if (code === 0 && output.endsWith('\n')) {+ try { return resolve(normalize(JSON.parse(output))); }+ catch { return resolve(unavailable('invalid-result')); }+ }+ resolve(unavailable(timedOut || child.signalCode === 'SIGKILL' ? 'timeout' : 'check-failed'));+ });+ });+}diff --git a/archify/bin/finalize.mjs b/archify/bin/finalize.mjsindex f96f727b..7854009e 100644--- a/archify/bin/finalize.mjs+++ b/archify/bin/finalize.mjs@@ -16,6 +16,7 @@ import {findChrome,VISUAL_CHECK_VIEWPORTS,} from './visual-check.mjs';+import { startDeliveryUpdateCheck } from './delivery-update.mjs';export const FINALIZE_STAGES = Object.freeze(['validate', 'deliver', 'check', 'browser-check']);@@ -550,6 +551,7 @@ export function compactFinalizeReceipt(receipt) {truncated: allDiagnostics.length > selectedDiagnostics.length,},evidence: receipt.evidence,+ ...(receipt.update ? { update: receipt.update } : {}),visualReview: receipt.visualReview || 'not-requested',durationMs: receipt.durationMs,};@@ -623,6 +625,7 @@ export async function runFinalize({env = process.env,runCommand = defaultRunner,runBrowserCheck,+ startUpdateCheck = startDeliveryUpdateCheck,resolveChrome = findChrome,createBrowser = (chromePath, options) => new ChromeVisualBrowser(chromePath, options),} = {}) {@@ -690,6 +693,7 @@ export async function runFinalize({summaryCapture = writeJsonAtomic(resolvedSummary, compactFinalizeReceipt(receipt), summaryCapture, assertReceiptPaths);};persistReceipts();+ const updateCheck = startUpdateCheck({ env });// Only launch/attach the blank browser here. The normal browser gate still// verifies current delivery provenance before it consumes this one-shot factory.@@ -739,7 +743,8 @@ export async function runFinalize({});result = { status: checked.exitCode, stdout: JSON.stringify(checked.receipt) };} else {- result = await runCommand({ stage, cliPath, args, cwd, env });+ result = await runCommand({ stage, cliPath, args, cwd,+ env: stage === 'deliver' ? { ...env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' } : env });}const stageReceipt = parsedReceipt(result.stdout);const code = result.status ?? 1;@@ -877,9 +882,11 @@ export async function runFinalize({: identity(resolvedOutput);receipt.finishedAt = new Date().toISOString();receipt.durationMs = durationMs(started);+ receipt.update = await updateCheck;persistReceipts();return { exitCode, receipt, summary: compactFinalizeReceipt(receipt) };} finally {if (browser && !browserTransferred) await browser.close();+ await updateCheck;}}diff --git a/archify/references/update-awareness.md b/archify/references/update-awareness.mdindex 45d84587..5ab52704 100644--- a/archify/references/update-awareness.md+++ b/archify/references/update-awareness.md@@ -1,9 +1,10 @@# Update awareness-Read this file only when `scripts/check-update.mjs` returns `update_available`.+Read this file when a `finalize` or standalone `deliver` receipt has `update.noticeRequired: true`.-Show one compact notice in the user's conversation language with the installed version, latest version, the checker's fixed local summary, and official release-notes link. When `severity` is `security`, label it as a security update with restrained emphasis; this changes emphasis only, never user autonomy. Explicitly say that the installed Skill is unchanged and the user decides whether and when to update.+Keep one compact line in the final response, in the user's language, with `installedVersion`, `availableVersion`, and the official `releaseNotes` link. Say that the installed Skill has not changed. If `source` is `cache`, say that a previous check found the update; use `checkedAt` only when present, and otherwise say the check time is unknown. A process message or tool output does not replace this final line.+For `severity: "security"`, label it as a security update without making installation automatic or urgent by default.-You may translate the fixed local sentence. Never quote, summarize, or translate the remote manifest's summary. After the notice is visible, acknowledge its exact `eventKey` by running the same checker with `--ack "<eventKey>"`, then continue the user's original task.+You may translate the fixed local `noticeText`. Never quote, summarize, or translate the remote manifest's summary. Do not run `--ack`, `--snooze`, or `--ignore` yourself. A user may explicitly choose `--snooze <eventKey>` (seven days by default) or `--ignore <eventKey>` (this exact release only); those commands do not install an update.The notice is information, not permission. Keep the installed version unchanged. This workflow never downloads, installs, or executes an update, and silence is never consent.diff --git a/archify/scripts/check-update.mjs b/archify/scripts/check-update.mjsindex 30d529aa..adb984e0 100644--- a/archify/scripts/check-update.mjs+++ b/archify/scripts/check-update.mjs@@ -27,6 +27,7 @@ const ACTIVE_CLAIM_DIRECTORY = 'active-claim';const OPERATION_NAME = /^(reserved|pending|committed|fenced|cancelled)-(\d{1,20})$/;const MAX_OPERATION_GENERATION = (10n ** 20n) - 1n;const CHECK_TTL_MS = 72 * 60 * 60 * 1_000;+const DELIVERY_CHECK_TTL_MS = 24 * 60 * 60 * 1_000;const MAX_CACHE_HORIZON_MS = Math.ceil(CHECK_TTL_MS * 1.2);const FIRST_FAILURE_DELAY_MS = 6 * 60 * 60 * 1_000;const LATER_FAILURE_DELAY_MS = 24 * 60 * 60 * 1_000;@@ -44,11 +45,16 @@ const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));const defaultReleasePath = path.resolve(scriptDirectory, '..', 'skill-release.json');class FileIdentityChangedError extends Error {}+class ManifestWithdrawnError extends Error {}function silent(reason) {return { status: 'silent', reason };}+function updatesDisabled() {+ return process.env.ARCHIFY_UPDATE_CHECK_DISABLED === '1';+}+function isPlainObject(value) {return Boolean(value) && typeof value === 'object' && !Array.isArray(value);}@@ -70,13 +76,15 @@ function validateManifest(value) {function validateCachedCandidate(value) {if (!isPlainObject(value)|| !hasOnlyKeys(value, new Set([- 'version', 'targetDigest', 'severity', 'releaseNotes',+ 'version', 'targetDigest', 'severity', 'releaseNotes', 'checkedAt',]))) return null;try {if (!isStableCoreVersion(value.version)) return null;if (!DIGEST_PATTERN.test(value.targetDigest)|| !['normal', 'security'].includes(value.severity)) return null;validateReleaseNotesUrl(value.releaseNotes, value.version);+ if (value.checkedAt !== undefined && (typeof value.checkedAt !== 'string'+ || !Number.isFinite(Date.parse(value.checkedAt)))) return null;return { ...value };} catch {return null;@@ -99,6 +107,37 @@ function emptyState(installedVersion = null) {};}+function validPreference(value) {+ return isPlainObject(value)+ && hasOnlyKeys(value, new Set(['targetDigest', 'version', 'mode', 'until']))+ && DIGEST_PATTERN.test(value.targetDigest)+ && isStableCoreVersion(value.version)+ && ['ignore', 'snooze'].includes(value.mode)+ && (value.mode === 'ignore' ? value.until === null+ : typeof value.until === 'string' && Number.isFinite(Date.parse(value.until)));+}++function deliveryState(state) {+ return {+ ...state,+ schemaVersion: 2,+ legacyMigrated: true,+ preferences: state.preferences || [],+ };+}++function withMigratedCandidate(state, candidate) {+ if (state.candidate || !candidate) return state;+ return {+ ...state,+ candidate,+ notification: {+ ...state.notification,+ offeredDigests: [...new Set([...state.notification.offeredDigests, candidate.targetDigest])],+ },+ };+}+function encodeBoundedState(state) {const encoded = Buffer.from(`${JSON.stringify(state)}\n`, 'utf8');return encoded.length <= MAX_CACHE_STATE_BYTES ? encoded : null;@@ -151,7 +190,7 @@ function versionCacheDirectory(cacheDirectory, installedVersion) {function normalizeState(value, installedVersion) {const effectiveInstalledVersion = installedVersion ?? value?.installedVersion ?? null;- if (!isPlainObject(value) || value.schemaVersion !== 1 || value.skillId !== SKILL_ID+ if (!isPlainObject(value) || ![1, 2].includes(value.schemaVersion) || value.skillId !== SKILL_ID|| (installedVersion !== null && value.installedVersion !== installedVersion)|| (value.installedVersion !== null && typeof value.installedVersion !== 'string')|| !isPlainObject(value.check)@@ -182,6 +221,14 @@ function normalizeState(value, installedVersion) {return null;}state.notification.acknowledgedDigests = [...new Set(acknowledgedDigests)];+ if (value.schemaVersion === 2) {+ if (!Array.isArray(value.preferences) || value.preferences.length > 32+ || value.preferences.some((preference) => !validPreference(preference))+ || value.legacyMigrated !== true) return null;+ state.schemaVersion = 2;+ state.legacyMigrated = true;+ state.preferences = value.preferences.map((preference) => ({ ...preference }));+ }const hasCandidate = Object.hasOwn(value, 'candidate');const candidate = validateCachedCandidate(value.candidate);if (hasCandidate && !candidate) return null;@@ -792,6 +839,19 @@ async function operationIsActive({ bigint: true },);if (!ownerMetadata.isFile() || ownerMetadata.isSymbolicLink()) return false;+ try {+ const owner = await readJsonFile(+ path.join(operation.directory, OPERATION_OWNER_FILE),+ MAX_CLAIM_OWNER_BYTES,+ ownerMetadata,+ );+ if (Number.isSafeInteger(owner?.pid) && owner.pid > 0 && processIsGone(owner.pid)) {+ return false;+ }+ } catch (error) {+ if (error instanceof FileIdentityChangedError) throw error;+ // A malformed owner still gets the hard lease before recovery.+ }return metadataIsWithinLease(ownerMetadata);} catch (error) {if (error?.code !== 'ENOENT') throw error;@@ -805,6 +865,15 @@ async function operationIsActive(}}+function processIsGone(pid) {+ try {+ process.kill(pid, 0);+ return false;+ } catch (error) {+ return error?.code === 'ESRCH';+ }+}+function validateClaimOwner(value) {if (!isPlainObject(value)|| !hasOnlyKeys(value, new Set(['pid', 'token', 'generation']))@@ -1267,10 +1336,10 @@ async function commitOperation(cacheDirectory, operation, installedVersion, muta}}-function nextSuccessfulCheck(nowMs, random) {+function nextSuccessfulCheck(nowMs, random, ttlMs = CHECK_TTL_MS) {const boundedRandom = Math.min(1, Math.max(0, Number(random()) || 0));const multiplier = 0.8 + (boundedRandom * 0.4);- return new Date(nowMs + Math.round(CHECK_TTL_MS * multiplier)).toISOString();+ return new Date(nowMs + Math.round(ttlMs * multiplier)).toISOString();}function nextFailedCheck(nowMs, failures) {@@ -1299,7 +1368,7 @@ function digestForEventKey(eventKey) {return DIGEST_PATTERN.test(digest) ? digest : null;}-function notification(localRelease, candidate) {+function notification(localRelease, candidate, source = 'cache', repeatNotice = false) {return {status: 'update_available',eventKey: eventKeyForDigest(candidate.targetDigest),@@ -1309,17 +1378,40 @@ function notification(localRelease, candidate) {severity: candidate.severity,summary: `Archify ${candidate.version} is available; see the official release notes for details.`,releaseNotes: candidate.releaseNotes,+ ...(repeatNotice ? { source, checkedAt: candidate.checkedAt ?? null, noticeRequired: true } : {}),};}-function resultForCandidate(localRelease, state) {+function resultForCandidate(localRelease, state, {+ repeatNotice = false, source = 'cache', nowMs = Date.now(),+} = {}) {if (!state.candidate) return silent('cache-valid');const comparison = compareSemver(state.candidate.version, localRelease.version);- if (comparison <= 0) return silent('current');- if (state.notification.acknowledgedDigests.includes(state.candidate.targetDigest)) {+ if (comparison <= 0) return repeatNotice ? {+ status: 'current', installedVersion: localRelease.version,+ availableVersion: state.candidate.version,+ checkedAt: state.candidate.checkedAt ?? null,+ source, noticeRequired: false,+ } : silent('current');+ if (!repeatNotice && state.notification.acknowledgedDigests.includes(state.candidate.targetDigest)) {return silent('already-notified');}- return notification(localRelease, state.candidate);+ if (repeatNotice) {+ const preference = state.preferences?.find((entry) => entry.targetDigest === state.candidate.targetDigest+ && entry.version === state.candidate.version);+ if (preference?.mode === 'ignore') return {+ ...notification(localRelease, state.candidate, source, true),+ noticeRequired: false,+ reason: 'ignored',+ };+ if (preference?.mode === 'snooze' && Date.parse(preference.until) > nowMs) return {+ ...notification(localRelease, state.candidate, source, true),+ noticeRequired: false,+ reason: 'snoozed',+ suppressedUntil: preference.until,+ };+ }+ return notification(localRelease, state.candidate, source, repeatNotice);}async function readBoundedBody(response) {@@ -1391,6 +1483,9 @@ async function fetchCandidate({ fetchImpl, manifestUrl, timeoutMs }) {});if (response.status !== 200) {await cancelResponseBody(response);+ if (response.status === 404 || response.status === 410) {+ throw new ManifestWithdrawnError('manifest was withdrawn');+ }throw new Error(`manifest returned HTTP ${response.status}`);}const mediaType = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase();@@ -1425,21 +1520,22 @@ function defaultCacheDirectory() {return path.join(xdgCache && path.isAbsolute(xdgCache) ? xdgCache : path.join(homeDirectory, '.cache'), 'archify-skill');}-function freshStateResult(localRelease, state, nowMs) {+function freshStateResult(localRelease, state, nowMs, repeatNotice = false) {const nextCheckAt = Date.parse(state.check.nextCheckAt || '');if (Number.isFinite(nextCheckAt) && nextCheckAt > nowMs- && nextCheckAt <= nowMs + MAX_CACHE_HORIZON_MS) {- return resultForCandidate(localRelease, state);+ && nextCheckAt <= nowMs + (repeatNotice+ ? Math.ceil(DELIVERY_CHECK_TTL_MS * 1.2) : MAX_CACHE_HORIZON_MS)) {+ return resultForCandidate(localRelease, state, { repeatNotice, nowMs });}return null;}-async function resultAfterLosingOperation(cacheDirectory, operation, localRelease) {+async function resultAfterLosingOperation(cacheDirectory, operation, localRelease, repeatNotice = false, nowMs = Date.now()) {await cancelOperation(cacheDirectory, operation);const cached = await readState(cacheDirectory, localRelease.version);if (cached.candidate&& cached.notification.offeredDigests.includes(cached.candidate.targetDigest)) {- return resultForCandidate(localRelease, cached);+ return resultForCandidate(localRelease, cached, { repeatNotice, nowMs });}return silent('check-in-progress');}@@ -1466,7 +1562,9 @@ export async function checkForUpdate({now = Date.now,random = Math.random,timeoutMs = DEFAULT_TIMEOUT_MS,+ repeatNotice = false,} = {}) {+ if (updatesDisabled()) return silent('disabled');if (typeof fetchImpl !== 'function') return silent('runtime-unavailable');let localRelease;try {@@ -1477,7 +1575,10 @@ export async function checkForUpdate({const nowMs = Number(now());if (!Number.isFinite(nowMs)) return silent('invalid-clock');- let stateDirectory = versionCacheDirectory(cacheDirectory, localRelease.version);+ let stateDirectory = versionCacheDirectory(+ repeatNotice ? path.join(cacheDirectory, 'reminders-v2') : cacheDirectory,+ localRelease.version,+ );let state;try {stateDirectory = await prepareCacheDirectory(stateDirectory);@@ -1485,7 +1586,19 @@ export async function checkForUpdate({} catch {return silent('cache-unavailable');}- const cachedResult = freshStateResult(localRelease, state, nowMs);+ let legacyCandidate;+ if (repeatNotice && !state.candidate && !state.legacyMigrated) {+ try {+ const legacyDirectory = versionCacheDirectory(cacheDirectory, localRelease.version);+ const legacy = await readState(legacyDirectory, localRelease.version);+ if (legacy.candidate && compareSemver(legacy.candidate.version, localRelease.version) > 0) {+ legacyCandidate = legacy.candidate;+ }+ } catch {+ // Existing state is optional; a failed migration cannot block delivery.+ }+ }+ const cachedResult = freshStateResult(localRelease, state, nowMs, repeatNotice);if (cachedResult) return cachedResult;let operation;@@ -1499,29 +1612,31 @@ export async function checkForUpdate({const cached = await readState(stateDirectory, localRelease.version);if (cached.candidate&& cached.notification.offeredDigests.includes(cached.candidate.targetDigest)) {- return resultForCandidate(localRelease, cached);+ return resultForCandidate(localRelease, cached, { repeatNotice, nowMs });}} catch {return silent('cache-unavailable');}- return silent('check-in-progress');+ return legacyCandidate+ ? resultForCandidate(localRelease, { candidate: legacyCandidate }, { repeatNotice, nowMs })+ : silent('check-in-progress');}try {state = await readState(stateDirectory, localRelease.version);- const racedResult = freshStateResult(localRelease, state, nowMs);+ const racedResult = freshStateResult(localRelease, state, nowMs, repeatNotice);if (racedResult) {await cancelOperation(stateDirectory, operation);return racedResult;}if (!await operationOwnsActiveClaim(stateDirectory, operation)) {- return await resultAfterLosingOperation(stateDirectory, operation, localRelease);+ return await resultAfterLosingOperation(stateDirectory, operation, localRelease, repeatNotice, nowMs);}await verifyCacheToken(cacheTokenFor(stateDirectory));if (!await operationOwnsActiveClaim(stateDirectory, operation)) {- return await resultAfterLosingOperation(stateDirectory, operation, localRelease);+ return await resultAfterLosingOperation(stateDirectory, operation, localRelease, repeatNotice, nowMs);}let fetched;try {@@ -1531,21 +1646,39 @@ export async function checkForUpdate({timeoutMs,});} catch (error) {- const reason = error instanceof UpdateContractError ? 'invalid-manifest' : 'check-failed';+ const reason = error instanceof ManifestWithdrawnError ? 'withdrawn'+ : error instanceof UpdateContractError ? 'invalid-manifest' : 'check-failed';try {const committed = await commitOperation(stateDirectory,operation,localRelease.version,(current) => ({- state: stateAfterFailedCheck(current, nowMs),- result: silent(reason),+ state: stateAfterFailedCheck(repeatNotice+ ? withMigratedCandidate(deliveryState(current), legacyCandidate)+ : current, nowMs, error instanceof ManifestWithdrawnError),+ result: error instanceof ManifestWithdrawnError ? silent('withdrawn')+ : repeatNotice && (current.candidate || legacyCandidate)+ ? resultForCandidate(localRelease,+ { ...current, candidate: current.candidate || legacyCandidate },+ { repeatNotice, nowMs })+ : silent(reason),}),);+ if (committed.fenced && repeatNotice) {+ return await resultAfterLosingOperation(+ stateDirectory, operation, localRelease, repeatNotice, nowMs,+ );+ }return committed.result;} catch {await cancelOperation(stateDirectory, operation).catch(() => {});- return silent('cache-unavailable');+ if (error instanceof ManifestWithdrawnError) return silent('withdrawn');+ return repeatNotice && (state.candidate || legacyCandidate)+ ? resultForCandidate(localRelease,+ { ...state, candidate: state.candidate || legacyCandidate },+ { repeatNotice, nowMs })+ : silent('cache-unavailable');}}@@ -1556,10 +1689,13 @@ export async function checkForUpdate({localRelease.version,(current) => {const next = {- ...current,- candidate: fetched.candidate,+ ...(repeatNotice ? deliveryState(current) : current),+ candidate: repeatNotice+ ? { ...fetched.candidate, checkedAt: new Date(nowMs).toISOString() }+ : fetched.candidate,check: {- nextCheckAt: nextSuccessfulCheck(nowMs, random),+ nextCheckAt: nextSuccessfulCheck(nowMs, random,+ repeatNotice ? DELIVERY_CHECK_TTL_MS : CHECK_TTL_MS),consecutiveFailures: 0,},notification: {@@ -1567,7 +1703,7 @@ export async function checkForUpdate({acknowledgedDigests: [...current.notification.acknowledgedDigests],},};- const result = resultForCandidate(localRelease, next);+ const result = resultForCandidate(localRelease, next, { repeatNotice, source: 'network', nowMs });if (result.status === 'update_available') {if (!next.notification.offeredDigests.includes(next.candidate.targetDigest)) {next.notification.offeredDigests.push(next.candidate.targetDigest);@@ -1578,15 +1714,25 @@ export async function checkForUpdate({result,capacityFallback: {state: stateAfterFailedCheck(current, nowMs, true),- result: silent('cache-unavailable'),+ result: repeatNotice ? result : silent('cache-unavailable'),},};},);+ if (committed.fenced && repeatNotice) {+ return await resultAfterLosingOperation(+ stateDirectory, operation, localRelease, repeatNotice, nowMs,+ );+ }return committed.result;} catch {await cancelOperation(stateDirectory, operation).catch(() => {});- return silent('cache-unavailable');+ return repeatNotice+ ? resultForCandidate(localRelease, {+ ...state,+ candidate: { ...fetched.candidate, checkedAt: new Date(nowMs).toISOString() },+ }, { repeatNotice, source: 'network', nowMs })+ : silent('cache-unavailable');}} catch {await cancelOperation(stateDirectory, operation).catch(() => {});@@ -1660,12 +1806,93 @@ export async function acknowledgeUpdate({}}+export async function setUpdatePreference({+ releasePath = defaultReleasePath,+ cacheDirectory = defaultCacheDirectory(),+ eventKey,+ mode,+ days = 7,+ now = Date.now,+ monotonicNow = () => performance.now(),+} = {}) {+ const targetDigest = digestForEventKey(eventKey);+ if (!targetDigest || !['snooze', 'ignore'].includes(mode)+ || (mode === 'snooze' && (!Number.isInteger(days) || days < 1 || days > 365))) {+ return silent('invalid-preference');+ }+ let localRelease;+ try {+ localRelease = validateLocalRelease(await readJsonFile(releasePath, MAX_LOCAL_RELEASE_BYTES));+ } catch {+ return silent('invalid-local-release');+ }+ let stateDirectory = versionCacheDirectory(+ path.join(cacheDirectory, 'reminders-v2'), localRelease.version,+ );+ try {+ stateDirectory = await prepareCacheDirectory(stateDirectory);+ } catch {+ return silent('cache-unavailable');+ }+ const nowMs = Number(now());+ if (!Number.isFinite(nowMs)) return silent('invalid-clock');+ const deadline = Number(monotonicNow()) + ACK_LOCK_WAIT_MS;+ while (Number(monotonicNow()) < deadline) {+ let operation;+ try {+ operation = await acquireOperation(stateDirectory);+ } catch {+ return silent('cache-unavailable');+ }+ if (!operation) {+ if (!await waitUntilRetry(deadline, monotonicNow)) break;+ continue;+ }+ try {+ const committed = await commitOperation(+ stateDirectory, operation, localRelease.version, (state) => {+ if (!state.candidate || state.candidate.targetDigest !== targetDigest+ || compareSemver(state.candidate.version, localRelease.version) <= 0) {+ return { state: null, result: silent('invalid-preference') };+ }+ const preference = {+ targetDigest,+ version: state.candidate.version,+ mode,+ until: mode === 'snooze' ? new Date(nowMs + days * 24 * 60 * 60 * 1_000).toISOString() : null,+ };+ const preferences = (state.preferences || [])+ .filter((entry) => entry.targetDigest !== targetDigest)+ .slice(-30);+ preferences.push(preference);+ return {+ state: { ...deliveryState(state), preferences },+ result: { status: mode === 'snooze' ? 'snoozed' : 'ignored', eventKey,+ ...(preference.until ? { suppressedUntil: preference.until } : {}) },+ };+ },+ );+ if (!committed.fenced) return committed.result;+ } catch {+ await cancelOperation(stateDirectory, operation).catch(() => {});+ return silent('cache-unavailable');+ }+ }+ return silent('check-in-progress');+}+async function runCli() {- if (process.env.ARCHIFY_UPDATE_CHECK_DISABLED === '1') return silent('disabled');+ if (updatesDisabled()) return silent('disabled');const argumentsList = process.argv.slice(2);if (argumentsList.length === 0) return checkForUpdate();if (argumentsList.length === 2 && argumentsList[0] === '--ack') {- return acknowledgeUpdate({ eventKey: argumentsList[1] });+ return silent('legacy-ack-no-op');+ }+ if (argumentsList.length === 2 && argumentsList[0] === '--snooze') {+ return setUpdatePreference({ eventKey: argumentsList[1], mode: 'snooze' });+ }+ if (argumentsList.length === 2 && argumentsList[0] === '--ignore') {+ return setUpdatePreference({ eventKey: argumentsList[1], mode: 'ignore' });}return silent('invalid-arguments');}diff --git a/archify/scripts/delivery-update-child.mjs b/archify/scripts/delivery-update-child.mjsnew file mode 100644index 00000000..399f321b--- /dev/null+++ b/archify/scripts/delivery-update-child.mjs@@ -0,0 +1,22 @@+#!/usr/bin/env node++import { checkForUpdate } from './check-update.mjs';++// The parent can be busy in synchronous renderer work. Enforce its original+// deadline here, in a separate event loop, so cache work cannot continue late.+const deadlineAt = Number(process.argv[2]);+if (!Number.isSafeInteger(deadlineAt)) process.exit(1);+const remainingMs = deadlineAt - Date.now();+if (remainingMs <= 0) process.exit(1);+const deadlineTimer = setTimeout(() => process.kill(process.pid, 'SIGKILL'), remainingMs);+deadlineTimer.unref();++const result = await checkForUpdate({+ repeatNotice: true,+ ...(process.env.ARCHIFY_UPDATE_RELEASE_PATH+ ? { releasePath: process.env.ARCHIFY_UPDATE_RELEASE_PATH } : {}),+ ...(process.env.ARCHIFY_UPDATE_CACHE_DIRECTORY+ ? { cacheDirectory: process.env.ARCHIFY_UPDATE_CACHE_DIRECTORY } : {}),+ timeoutMs: 850,+});+process.stdout.write(`${JSON.stringify(result)}\n`);diff --git a/archify/test/delivery-update.test.mjs b/archify/test/delivery-update.test.mjsnew file mode 100644index 00000000..252cfed5--- /dev/null+++ b/archify/test/delivery-update.test.mjs@@ -0,0 +1,198 @@+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawnSync } from 'node:child_process';+import test from 'node:test';+import { fileURLToPath } from 'node:url';++import { checkForUpdate } from '../scripts/check-update.mjs';+import { startDeliveryUpdateCheck } from '../bin/delivery-update.mjs';+import { runFinalize } from '../bin/finalize.mjs';++const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const cli = path.join(skillRoot, 'bin', 'archify.mjs');+const installed = '2.15.0';+const available = '2.16.0';++function fixture(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-delivery-update-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const releasePath = path.join(root, 'skill-release.json');+ const cacheDirectory = path.join(root, 'cache');+ fs.writeFileSync(releasePath, `${JSON.stringify({+ schemaVersion: 1, skillId: 'archify', channel: 'stable', version: installed,+ source: { repository: 'https://github.com/tt-a1i/archify' },+ updateManifestUrl: 'https://tt-a1i.github.io/archify/skill-updates/archify/stable.json',+ })}\n`);+ return { root, releasePath, cacheDirectory };+}++function manifest() {+ return {+ schemaVersion: 1, skillId: 'archify', channel: 'stable', version: available,+ publishedAt: '2026-08-28T07:00:00Z',+ source: { repository: 'https://github.com/tt-a1i/archify', ref: 'v2.16.0', treeSha: 'a'.repeat(40) },+ artifact: { sha256: 'b'.repeat(64) },+ summary: 'A release is available.',+ releaseNotes: 'https://github.com/tt-a1i/archify/releases/tag/v2.16.0',+ severity: 'normal',+ };+}++async function seed(testFixture) {+ return checkForUpdate({ ...testFixture, repeatNotice: true,+ fetchImpl: async () => new Response(JSON.stringify(manifest()), {+ status: 200, headers: { 'content-type': 'application/json' },+ }),+ });+}++function env(testFixture) {+ return { ...process.env,+ ARCHIFY_UPDATE_RELEASE_PATH: testFixture.releasePath,+ ARCHIFY_UPDATE_CACHE_DIRECTORY: testFixture.cacheDirectory,+ };+}++test('bounded service returns the same cached notice on repeated deliveries', async (t) => {+ const testFixture = fixture(t);+ assert.equal((await seed(testFixture)).status, 'update_available');+ for (let index = 0; index < 2; index += 1) {+ const started = performance.now();+ const result = await startDeliveryUpdateCheck({ env: env(testFixture) });+ assert.equal(result.status, 'update_available');+ assert.equal(result.source, 'cache');+ assert.equal(result.noticeRequired, true);+ assert.match(result.noticeText, /previous check/);+ assert.ok(performance.now() - started < 1_200);+ }+});++test('service deadline kills a blocked child and leaves no later result', async (t) => {+ const testFixture = fixture(t);+ const root = testFixture.root;+ const blocker = path.join(root, 'blocker.mjs');+ fs.writeFileSync(blocker, 'setInterval(() => {}, 1000);\n');+ const result = await startDeliveryUpdateCheck({+ env: env(testFixture), checkerPath: blocker,+ deadlineMs: 80,+ });+ assert.equal(result.status, 'unavailable');+ assert.equal(result.reason, 'timeout');+ assert.deepEqual(fs.readdirSync(root).sort(), ['blocker.mjs', 'skill-release.json']);+});++test('a synchronous renderer delay does not turn a completed check into a timeout', async (t) => {+ const testFixture = fixture(t);+ await seed(testFixture);+ const pending = startDeliveryUpdateCheck({ env: env(testFixture), deadlineMs: 500 });+ spawnSync(process.execPath, ['-e', 'setTimeout(() => {}, 800)'], { timeout: 2_000 });+ const result = await pending;+ assert.equal(result.status, 'update_available');+ assert.equal(result.noticeRequired, true);+});++test('a killed checker holding the cache claim can be followed by a new check', async (t) => {+ const testFixture = fixture(t);+ const blockedChecker = path.join(testFixture.root, 'blocked-checker.mjs');+ fs.writeFileSync(blockedChecker, `+ import { checkForUpdate } from ${JSON.stringify(new URL('../scripts/check-update.mjs', import.meta.url).href)};+ await checkForUpdate({+ releasePath: ${JSON.stringify(testFixture.releasePath)},+ cacheDirectory: ${JSON.stringify(testFixture.cacheDirectory)},+ repeatNotice: true,+ fetchImpl: async () => {+ process.stdout.write('entered fetch\\n');+ return new Promise(() => {});+ },+ });+ `);+ const killed = await startDeliveryUpdateCheck({+ env: env(testFixture), checkerPath: blockedChecker, deadlineMs: 250,+ });+ assert.equal(killed.reason, 'timeout');+ const fresh = await seed(testFixture);+ assert.equal(fresh.status, 'update_available');+ assert.equal(fresh.source, 'network');+});++test('standalone deliver and finalize receipts include one update without changing diagram identity', async (t) => {+ const testFixture = fixture(t);+ assert.equal((await seed(testFixture)).status, 'update_available');+ const input = path.join(skillRoot, 'examples', 'web-app.architecture.json');+ const output = path.join(testFixture.root, 'diagram.html');+ const environment = { ...env(testFixture), ARCHIFY_CHROME: path.join(testFixture.root, 'missing-chrome') };+ const deliver = spawnSync(process.execPath,+ [cli, 'deliver', 'architecture', input, output, '--quality', 'showcase', '--json'],+ { cwd: skillRoot, encoding: 'utf8', env: environment, timeout: 15_000 });+ assert.equal(deliver.status, 0, deliver.stdout || deliver.stderr);+ const deliveryReceipt = JSON.parse(deliver.stdout);+ assert.equal(deliveryReceipt.update.noticeRequired, true);+ const artifactHash = deliveryReceipt.artifact.sha256;+ const disabled = spawnSync(process.execPath,+ [cli, 'deliver', 'architecture', input, output, '--quality', 'showcase', '--json'],+ { cwd: skillRoot, encoding: 'utf8', env: { ...environment, ARCHIFY_UPDATE_CHECK_DISABLED: '1' }, timeout: 15_000 });+ assert.equal(disabled.status, 0, disabled.stdout || disabled.stderr);+ const disabledReceipt = JSON.parse(disabled.stdout);+ assert.equal(disabledReceipt.update.reason, 'disabled');+ assert.equal(disabledReceipt.artifact.sha256, artifactHash);+ const finalize = spawnSync(process.execPath,+ [cli, 'finalize', 'architecture', input, output, '--quality', 'showcase', '--json'],+ { cwd: skillRoot, encoding: 'utf8', env: environment, timeout: 30_000 });+ assert.equal(finalize.status, 2, finalize.stdout || finalize.stderr);+ const compact = JSON.parse(finalize.stdout);+ const full = JSON.parse(fs.readFileSync(compact.evidence.receipt, 'utf8'));+ assert.equal(compact.update.noticeRequired, true);+ assert.deepEqual(compact.update, full.update);+ assert.equal(full.artifact.sha256, artifactHash);+ assert.equal(full.stages.deliver.receipt.update.reason, 'disabled');+ const readableDeliver = spawnSync(process.execPath,+ [cli, 'deliver', 'architecture', input, output, '--quality', 'showcase'],+ { cwd: skillRoot, encoding: 'utf8', env: environment, timeout: 15_000 });+ assert.equal(readableDeliver.status, 0, readableDeliver.stdout || readableDeliver.stderr);+ assert.match(readableDeliver.stdout, /Archify update:.*2\.15\.0.*2\.16\.0/);+ const readableFinalize = spawnSync(process.execPath,+ [cli, 'finalize', 'architecture', input, output, '--quality', 'showcase'],+ { cwd: skillRoot, encoding: 'utf8', env: environment, timeout: 30_000 });+ assert.equal(readableFinalize.status, 2, readableFinalize.stdout || readableFinalize.stderr);+ assert.match(readableFinalize.stdout, /Archify update:.*2\.15\.0.*2\.16\.0/);+});++test('a failed finalize gate preserves update in full and compact receipts', async (t) => {+ const testFixture = fixture(t);+ const input = path.join(skillRoot, 'examples', 'web-app.architecture.json');+ const output = path.join(testFixture.root, 'failed.html');+ const update = { status: 'update_available', installedVersion: installed,+ availableVersion: available, releaseNotes: manifest().releaseNotes,+ checkedAt: null, source: 'cache', noticeRequired: true,+ noticeText: 'A cached update is available.' };+ const result = await runFinalize({ cliPath: cli, type: 'architecture', input, output,+ startUpdateCheck: async () => update,+ runCommand: async () => ({ status: 1, stdout: JSON.stringify({+ ok: false, command: 'deliver', stage: 'render', diagnostics: [],+ }) }),+ });+ assert.equal(result.exitCode, 1);+ assert.deepEqual(result.receipt.update, update);+ assert.deepEqual(result.summary.update, update);+ assert.deepEqual(JSON.parse(fs.readFileSync(result.summary.evidence.receipt)).update, update);+});++test('a standalone delivery quality failure retains a known update', async (t) => {+ const testFixture = fixture(t);+ await seed(testFixture);+ const input = path.join(testFixture.root, 'invalid.json');+ const document = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'web-app.architecture.json')));+ document.components[0].type = 'unknown-component-type';+ fs.writeFileSync(input, `${JSON.stringify(document)}\n`);+ const output = path.join(testFixture.root, 'invalid.html');+ const delivery = spawnSync(process.execPath,+ [cli, 'deliver', 'architecture', input, output, '--quality', 'showcase', '--json'],+ { cwd: skillRoot, encoding: 'utf8', env: env(testFixture), timeout: 15_000 });+ assert.equal(delivery.status, 1, delivery.stdout || delivery.stderr);+ const receipt = JSON.parse(delivery.stdout);+ assert.equal(receipt.ok, false);+ assert.equal(receipt.update.noticeRequired, true);+ assert.ok(receipt.diagnostics.length > 0);+});diff --git a/archify/test/release-package-gates.test.mjs b/archify/test/release-package-gates.test.mjsindex 323e6ea6..2916a310 100644--- a/archify/test/release-package-gates.test.mjs+++ b/archify/test/release-package-gates.test.mjs@@ -684,6 +684,8 @@ canonicalZipTest('built archives contain the embedded notifier runtime', () => {const entries = new Set(listing.stdout.trim().split('\n'));assert.ok(entries.has('archify/skill-release.json'));assert.ok(entries.has('archify/scripts/check-update.mjs'));+ assert.ok(entries.has('archify/scripts/delivery-update-child.mjs'));+ assert.ok(entries.has('archify/bin/delivery-update.mjs'));assert.ok(entries.has('archify/scripts/update-contract.mjs'));assert.ok(entries.has('archify/renderers/shared/atomic-output.mjs'));assert.ok(entries.has('archify/renderers/shared/sidecar-path.mjs'));diff --git a/archify/test/skill-metadata.test.mjs b/archify/test/skill-metadata.test.mjsindex e1ed442f..aa4ebe3a 100644--- a/archify/test/skill-metadata.test.mjs+++ b/archify/test/skill-metadata.test.mjs@@ -51,13 +51,12 @@ test('main skill stays a bounded authoring router with progressive references',});test('update awareness is notification-only and never replaces the requested workflow', () => {- assert.match(skill + updateAwareness, /`scripts\/check-update\.mjs`/);- assert.match(skill + updateAwareness, /`silent`[\s\S]*without mentioning/i);- assert.match(skill + updateAwareness, /`update_available`[\s\S]*compact notice/i);+ assert.match(skill + updateAwareness, /`finalize` and standalone `deliver` include `update`/);+ assert.match(skill + updateAwareness, /`update\.noticeRequired`[\s\S]*final response/i);+ assert.match(skill + updateAwareness, /several diagrams[\s\S]*once in the final response/i);assert.match(skill + updateAwareness, /information, not permission/i);- assert.match(skill + updateAwareness, /`severity` is `security`[\s\S]*security update[\s\S]*emphasis only, never user autonomy/i);- assert.match(skill + updateAwareness, /continue the user's original task/i);- assert.match(skill + updateAwareness, /installed version unchanged/i);+ assert.match(skill + updateAwareness, /Do not run `--ack`, `--snooze`, or `--ignore` yourself/);+ assert.match(skill + updateAwareness, /installed Skill has not changed/i);assert.doesNotMatch(skill, /npx skills update|gh skill update/i);});diff --git a/archify/test/update-notifier.test.mjs b/archify/test/update-notifier.test.mjsindex eb950041..15ded13c 100644--- a/archify/test/update-notifier.test.mjs+++ b/archify/test/update-notifier.test.mjs@@ -12,6 +12,7 @@ import {acknowledgeUpdate,checkForUpdate,isMainModule,+ setUpdatePreference,} from '../scripts/check-update.mjs';import { DEFAULT_MANIFEST_URL, compareSemver, parseSemver } from '../scripts/update-contract.mjs';@@ -2416,7 +2417,7 @@ test('a fenced owner rechecks its active claim immediately before network accessreturn new Promise((resolve) => { releaseFetch = resolve; });};- const delayedOwner = checkForUpdate(options(testFixture, fetchImpl));+ const delayedOwner = checkForUpdate(options(testFixture, fetchImpl, { timeoutMs: 2_000 }));await pause.reached;const staleTime = new Date(Date.now() - 60_000);fs.utimesSync(@@ -2424,7 +2425,7 @@ test('a fenced owner rechecks its active claim immediately before network accessstaleTime,staleTime,);- const successor = checkForUpdate(options(testFixture, fetchImpl));+ const successor = checkForUpdate(options(testFixture, fetchImpl, { timeoutMs: 2_000 }));await fetchStarted;assert.equal(requests, 1);@@ -3400,7 +3401,7 @@ test('disabled CLI returns one silent JSON line and never needs the network', ()assert.equal(result.stdout.trim().split('\n').length, 1);});-test('CLI acknowledgement emits the documented one-line success schema', async (t) => {+test('legacy CLI acknowledgement is a harmless one-line no-op', async (t) => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-update-cli-ack-'));t.after(() => fs.rmSync(root, { recursive: true, force: true }));const home = path.join(root, 'home');@@ -3439,8 +3440,7 @@ test('CLI acknowledgement emits the documented one-line success schema', async (});assert.equal(acknowledgement.status, 0, acknowledgement.stderr);assert.deepEqual(JSON.parse(acknowledgement.stdout), {- status: 'acknowledged',- eventKey: offered.eventKey,+ status: 'silent', reason: 'legacy-ack-no-op',});assert.equal(acknowledgement.stdout.trim().split('\n').length, 1);});@@ -3490,3 +3490,132 @@ test('notifier source has no process execution or remote-origin override surface]);assert.doesNotMatch(combinedSource, /updateCommand/);});++test('delivery checks repeat a cached update despite legacy acknowledgement', async (t) => {+ const testFixture = fixture();+ t.after(() => fs.rmSync(testFixture.root, { recursive: true, force: true }));+ const first = await checkForUpdate(options(testFixture,+ async () => response(remoteRelease()), { repeatNotice: true }));+ assert.equal(first.status, 'update_available');+ assert.equal(first.source, 'network');+ assert.equal(first.noticeRequired, true);+ assert.equal(first.checkedAt, new Date(baseTime).toISOString());+ const ack = await acknowledgeUpdate({ ...testFixture, eventKey: first.eventKey });+ assert.equal(ack.status, 'silent');+ const second = await checkForUpdate(options(testFixture,+ async () => { throw new Error('should use cache'); }, { repeatNotice: true }));+ assert.equal(second.status, 'update_available');+ assert.equal(second.source, 'cache');+ assert.equal(second.noticeRequired, true);+});++test('delivery preferences are explicit and scoped to the exact release digest', async (t) => {+ const testFixture = fixture();+ t.after(() => fs.rmSync(testFixture.root, { recursive: true, force: true }));+ const first = await checkForUpdate(options(testFixture,+ async () => response(remoteRelease()), { repeatNotice: true }));+ const ignored = await setUpdatePreference({ ...testFixture,+ eventKey: first.eventKey, mode: 'ignore', now: () => baseTime });+ assert.equal(ignored.status, 'ignored');+ const suppressed = await checkForUpdate(options(testFixture,+ async () => { throw new Error('should use cache'); }, { repeatNotice: true }));+ assert.equal(suppressed.noticeRequired, false);+ assert.equal(suppressed.reason, 'ignored');+ const newer = await checkForUpdate(options(testFixture,+ async () => response(remoteReleaseForVersion('2.17.0', 'c'.repeat(64))),+ { repeatNotice: true, now: () => baseTime + 2 * 24 * 60 * 60 * 1_000 }));+ assert.equal(newer.status, 'update_available');+ assert.equal(newer.noticeRequired, true);+ const snoozed = await setUpdatePreference({ ...testFixture,+ eventKey: newer.eventKey, mode: 'snooze', now: () => baseTime + 2 * 24 * 60 * 60 * 1_000 });+ assert.equal(snoozed.status, 'snoozed');+ const during = await checkForUpdate(options(testFixture,+ async () => { throw new Error('should use cache'); }, { repeatNotice: true,+ now: () => baseTime + 3 * 24 * 60 * 60 * 1_000 }));+ assert.equal(during.noticeRequired, false);+ assert.equal(during.reason, 'snoozed');+ const after = await checkForUpdate(options(testFixture,+ async () => { throw new Error('offline'); }, { repeatNotice: true,+ now: () => baseTime + 10 * 24 * 60 * 60 * 1_000 }));+ assert.equal(after.noticeRequired, true);+ assert.equal(after.source, 'cache');+});++test('delivery fallback does not invent a check time for a legacy cache', async (t) => {+ const testFixture = fixture();+ t.after(() => fs.rmSync(testFixture.root, { recursive: true, force: true }));+ const legacy = await checkForUpdate(options(testFixture,+ async () => response(remoteRelease())));+ assert.equal(legacy.status, 'update_available');+ const next = await checkForUpdate(options(testFixture,+ async () => { throw new Error('offline'); }, { repeatNotice: true }));+ assert.equal(next.status, 'update_available');+ assert.equal(next.source, 'cache');+ assert.equal(next.checkedAt, null);+});++test('delivery check treats a withdrawn manifest differently from an invalid response', async (t) => {+ const testFixture = fixture();+ t.after(() => fs.rmSync(testFixture.root, { recursive: true, force: true }));+ await checkForUpdate(options(testFixture,+ async () => response(remoteRelease()), { repeatNotice: true }));+ const invalid = await checkForUpdate(options(testFixture,+ async () => response('invalid JSON'), { repeatNotice: true,+ now: () => baseTime + 2 * 24 * 60 * 60 * 1_000 }));+ assert.equal(invalid.status, 'update_available');+ assert.equal(invalid.source, 'cache');+ const withdrawn = await checkForUpdate(options(testFixture,+ async () => response('{}', { status: 404 }), { repeatNotice: true,+ now: () => baseTime + 3 * 24 * 60 * 60 * 1_000 }));+ assert.deepEqual(withdrawn, { status: 'silent', reason: 'withdrawn' });+ const cached = await checkForUpdate(options(testFixture,+ async () => { throw new Error('backoff'); }, { repeatNotice: true,+ now: () => baseTime + 3 * 24 * 60 * 60 * 1_000 + 1_000 }));+ assert.notEqual(cached.status, 'update_available');+});++test('a validated network result survives a cache publication failure without inventing an upgrade', async (t) => {+ const testFixture = fixture();+ t.after(() => fs.rmSync(testFixture.root, { recursive: true, force: true }));+ const originalRename = fsPromises.rename;+ fsPromises.rename = async (source, destination, ...args) => {+ if (destination.endsWith('state.json')) throw Object.assign(new Error('read-only state'), { code: 'EACCES' });+ return originalRename(source, destination, ...args);+ };+ try {+ const offered = await checkForUpdate(options(testFixture,+ async () => response(remoteRelease()), { repeatNotice: true }));+ assert.equal(offered.status, 'update_available');+ assert.equal(offered.source, 'network');+ const currentFixture = fixture('2.16.0');+ t.after(() => fs.rmSync(currentFixture.root, { recursive: true, force: true }));+ const current = await checkForUpdate(options(currentFixture,+ async () => response(remoteRelease()), { repeatNotice: true }));+ assert.equal(current.status, 'current');+ assert.equal(current.noticeRequired, false);+ } finally {+ fsPromises.rename = originalRename;+ }+});++test('an offline delivery still offers the last validated candidate when backoff cannot be written', async (t) => {+ const testFixture = fixture();+ t.after(() => fs.rmSync(testFixture.root, { recursive: true, force: true }));+ await checkForUpdate(options(testFixture,+ async () => response(remoteRelease()), { repeatNotice: true }));+ const originalRename = fsPromises.rename;+ fsPromises.rename = async (source, destination, ...args) => {+ if (destination.endsWith('state.json')) throw Object.assign(new Error('read-only state'), { code: 'EACCES' });+ return originalRename(source, destination, ...args);+ };+ try {+ const result = await checkForUpdate(options(testFixture,+ async () => { throw new Error('offline'); }, { repeatNotice: true,+ now: () => baseTime + 2 * 24 * 60 * 60 * 1_000 }));+ assert.equal(result.status, 'update_available');+ assert.equal(result.source, 'cache');+ assert.equal(result.noticeRequired, true);+ } finally {+ fsPromises.rename = originalRename;+ }+});diff --git a/scripts/stage-clean-skill.mjs b/scripts/stage-clean-skill.mjsindex 78cd1abb..bf6b6a59 100644--- a/scripts/stage-clean-skill.mjs+++ b/scripts/stage-clean-skill.mjs@@ -21,7 +21,9 @@ const REQUIRED_INPUTS = new Set(['archify/THIRD_PARTY_NOTICES.md','archify/renderers/shared/generated-validators.mjs','archify/scripts/check-update.mjs',+ 'archify/scripts/delivery-update-child.mjs','archify/scripts/update-contract.mjs',+ 'archify/bin/delivery-update.mjs','archify/skill-release.json',]);const RUNTIME_DEPENDENCIES = Object.freeze([