@acryldev/harness-runtime 0.0.0-stage → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +49 -0
  2. package/lib/index.mjs +5693 -0
  3. package/lib/index.mjs.map +1 -0
  4. package/lib/types/acryl-home.d.ts +81 -0
  5. package/lib/types/app/new-app.d.ts +65 -0
  6. package/lib/types/app/start-source.d.ts +47 -0
  7. package/lib/types/blueprint/blueprint.d.ts +74 -0
  8. package/lib/types/blueprint/brand-identity.d.ts +26 -0
  9. package/lib/types/blueprint/compose.d.ts +53 -0
  10. package/lib/types/blueprint/definition.d.ts +22 -0
  11. package/lib/types/blueprint/index.d.ts +7 -0
  12. package/lib/types/blueprint/manifest.d.ts +35 -0
  13. package/lib/types/blueprint/selection.d.ts +19 -0
  14. package/lib/types/cli-market-install.d.ts +97 -0
  15. package/lib/types/cli-market-plugins.d.ts +81 -0
  16. package/lib/types/coding-capabilities.d.ts +29 -0
  17. package/lib/types/durable-message.d.ts +18 -0
  18. package/lib/types/engine-dsh.d.ts +181 -0
  19. package/lib/types/engine-files.d.ts +8 -0
  20. package/lib/types/engine-host.d.ts +32 -0
  21. package/lib/types/engine-tools.d.ts +11 -0
  22. package/lib/types/index.d.ts +67 -0
  23. package/lib/types/instance/announce-self.d.ts +38 -0
  24. package/lib/types/instance/app-instance.d.ts +125 -0
  25. package/lib/types/instance/index.d.ts +6 -0
  26. package/lib/types/instance/offline-lock.d.ts +29 -0
  27. package/lib/types/instance/online-secret.d.ts +29 -0
  28. package/lib/types/instance/registry.d.ts +26 -0
  29. package/lib/types/instance/select.d.ts +43 -0
  30. package/lib/types/module-hooks.d.ts +19 -0
  31. package/lib/types/module-resolution.d.ts +31 -0
  32. package/lib/types/package-overlay.d.ts +41 -0
  33. package/lib/types/pinned-pnpm.d.ts +15 -0
  34. package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
  35. package/lib/types/plugin-doctor.d.ts +49 -0
  36. package/lib/types/plugin-lifecycle-state.d.ts +92 -0
  37. package/lib/types/plugin-lifecycle.d.ts +87 -0
  38. package/lib/types/profile-layout.d.ts +17 -0
  39. package/lib/types/profile-owner.d.ts +25 -0
  40. package/lib/types/profile-repair/backup.d.ts +37 -0
  41. package/lib/types/profile-repair/findings.d.ts +29 -0
  42. package/lib/types/profile-repair/index.d.ts +9 -0
  43. package/lib/types/profile-repair/inspector.d.ts +11 -0
  44. package/lib/types/profile-repair/repair.d.ts +38 -0
  45. package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
  46. package/lib/types/profile-resolution/resolver.d.ts +41 -0
  47. package/lib/types/profile-resolution/service.d.ts +22 -0
  48. package/lib/types/prompt-budget.d.ts +44 -0
  49. package/lib/types/session-bridge.d.ts +57 -0
  50. package/lib/types/session-log-exporter.d.ts +31 -0
  51. package/lib/types/system-prompt-capture.d.ts +29 -0
  52. package/lib/types/web-favicon-data.d.ts +5 -0
  53. package/lib/types/web-favicon.d.ts +23 -0
  54. package/lib/types/web-market-install.d.ts +114 -0
  55. package/lib/types/web-market-plugins.d.ts +106 -0
  56. package/lib/types/web-port.d.ts +15 -0
  57. package/package.json +211 -3
  58. package/src/acryl-home.ts +103 -0
  59. package/src/app/new-app.ts +239 -0
  60. package/src/app/start-source.ts +110 -0
  61. package/src/blueprint/blueprint.ts +141 -0
  62. package/src/blueprint/brand-identity.ts +75 -0
  63. package/src/blueprint/compose.ts +222 -0
  64. package/src/blueprint/definition.ts +92 -0
  65. package/src/blueprint/index.ts +20 -0
  66. package/src/blueprint/manifest.ts +145 -0
  67. package/src/blueprint/selection.ts +74 -0
  68. package/src/cli-market-install.ts +181 -0
  69. package/src/cli-market-plugins.ts +176 -0
  70. package/src/coding-capabilities.ts +61 -0
  71. package/src/durable-message.ts +23 -0
  72. package/src/engine-dsh.ts +856 -0
  73. package/src/engine-files.ts +9 -0
  74. package/src/engine-host.ts +128 -0
  75. package/src/engine-tools.ts +26 -0
  76. package/src/index.ts +436 -0
  77. package/src/instance/announce-self.ts +88 -0
  78. package/src/instance/app-instance.ts +240 -0
  79. package/src/instance/index.ts +45 -0
  80. package/src/instance/offline-lock.ts +71 -0
  81. package/src/instance/online-secret.ts +55 -0
  82. package/src/instance/registry.ts +53 -0
  83. package/src/instance/select.ts +134 -0
  84. package/src/module-hooks.ts +41 -0
  85. package/src/module-resolution.ts +187 -0
  86. package/src/package-overlay.ts +160 -0
  87. package/src/pinned-pnpm.ts +67 -0
  88. package/src/plugin-acryl-workspace-status.ts +99 -0
  89. package/src/plugin-doctor.ts +141 -0
  90. package/src/plugin-lifecycle-state.ts +347 -0
  91. package/src/plugin-lifecycle.ts +223 -0
  92. package/src/profile-layout.ts +97 -0
  93. package/src/profile-owner.ts +52 -0
  94. package/src/profile-repair/backup.ts +119 -0
  95. package/src/profile-repair/findings.ts +43 -0
  96. package/src/profile-repair/index.ts +10 -0
  97. package/src/profile-repair/inspector.ts +156 -0
  98. package/src/profile-repair/repair.ts +137 -0
  99. package/src/profile-resolution/moved-framework.ts +64 -0
  100. package/src/profile-resolution/resolver.ts +876 -0
  101. package/src/profile-resolution/service.ts +99 -0
  102. package/src/prompt-budget.ts +118 -0
  103. package/src/session-bridge.ts +350 -0
  104. package/src/session-log-exporter.ts +68 -0
  105. package/src/system-prompt-capture.ts +99 -0
  106. package/src/web-favicon-data.ts +6 -0
  107. package/src/web-favicon.ts +43 -0
  108. package/src/web-market-install.ts +206 -0
  109. package/src/web-market-plugins.ts +215 -0
  110. package/src/web-port.ts +39 -0
  111. package/tests/account-callback.spec.ts +173 -0
  112. package/tests/acryl-home.spec.ts +39 -0
  113. package/tests/agent-self-hosting.spec.ts +101 -0
  114. package/tests/announce-self.spec.ts +84 -0
  115. package/tests/app-lifecycle.spec.ts +99 -0
  116. package/tests/blank-blueprint.spec.ts +110 -0
  117. package/tests/blueprint-definition.spec.ts +128 -0
  118. package/tests/blueprint.spec.ts +138 -0
  119. package/tests/bulkhead.spec.ts +187 -0
  120. package/tests/coding-vocabulary.spec.ts +15 -0
  121. package/tests/dump-system-prompt.spec.ts +65 -0
  122. package/tests/e2e-real-model.spec.ts +71 -0
  123. package/tests/e2e-restart-real-model.spec.ts +77 -0
  124. package/tests/engine-dsh.spec.ts +340 -0
  125. package/tests/engine-host-mount-root-include.spec.ts +118 -0
  126. package/tests/engine-host.spec.ts +176 -0
  127. package/tests/engine-optional.spec.ts +81 -0
  128. package/tests/extension-examples.spec.ts +261 -0
  129. package/tests/hooks-thread-stack.ts +27 -0
  130. package/tests/instance-patches.spec.ts +25 -0
  131. package/tests/instance.spec.ts +235 -0
  132. package/tests/live/community-plugins.spec.ts +83 -0
  133. package/tests/module-hooks.spec.ts +35 -0
  134. package/tests/module-resolution.spec.ts +265 -0
  135. package/tests/moved-framework.spec.ts +61 -0
  136. package/tests/new-app.spec.ts +132 -0
  137. package/tests/organizer-growth.spec.ts +117 -0
  138. package/tests/pinned-pnpm.spec.ts +34 -0
  139. package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
  140. package/tests/plugin-context.spec.ts +640 -0
  141. package/tests/plugin-doctor.spec.ts +183 -0
  142. package/tests/plugin-enablement-one-store.spec.ts +130 -0
  143. package/tests/plugin-lifecycle-state.spec.ts +169 -0
  144. package/tests/profile-layout.spec.ts +58 -0
  145. package/tests/profile-owner.spec.ts +38 -0
  146. package/tests/profile-repair/profile-repair.spec.ts +231 -0
  147. package/tests/profile-resolution-port.spec.ts +30 -0
  148. package/tests/profile-resolution-service.spec.ts +273 -0
  149. package/tests/profile-resolution-swap.spec.ts +69 -0
  150. package/tests/profile-resolution.spec.ts +2535 -0
  151. package/tests/profile.spec.ts +70 -0
  152. package/tests/project-registry.spec.ts +81 -0
  153. package/tests/prompt-budget.spec.ts +58 -0
  154. package/tests/real-home-guard.spec.ts +178 -0
  155. package/tests/session-bridge.spec.ts +316 -0
  156. package/tests/start-source.spec.ts +65 -0
  157. package/tests/system-prompt-shape.spec.ts +95 -0
  158. package/tests/three-levels.spec.ts +84 -0
  159. package/tests/tool-gateway.spec.ts +116 -0
  160. package/tests/tool-schemas.spec.ts +41 -0
  161. package/tests/web-favicon.spec.ts +42 -0
  162. package/tests/web-port.spec.ts +38 -0
  163. package/tests/web-startup-hold.spec.ts +79 -0
  164. package/tsconfig.json +24 -0
  165. package/tsdown.config.ts +2 -0
  166. package/vitest.config.ts +18 -0
  167. package/README.md +0 -3
@@ -0,0 +1,52 @@
1
+ /**
2
+ * One profile, one live installation (spec 036, "Self-containment"): a Protection Proxy in front of the one resource two installations can still point at.
3
+ *
4
+ * A Web or CLI profile links ACRYL's own packages into its `node_modules` from the installation that boots it. Two installations (a main checkout and a
5
+ * worktree, a dev build and an installed app) booting the SAME profile silently re-point each other's links, and the one still running then serves the
6
+ * other's code: that is how a worktree run blanked a running main-branch app. So every write to a profile goes through this guard, which holds the profile
7
+ * with a Pessimistic Offline Lock (`instance/offline-lock.ts`): the same installation is always admitted, another is refused while the holder is alive,
8
+ * and a stopped holder is taken over.
9
+ *
10
+ * @module @acryldev/harness-runtime/profile-owner
11
+ */
12
+
13
+ import { realpathSync } from 'node:fs'
14
+ import { join } from 'node:path'
15
+ import { LockHeldError, acquireLock } from './instance/index.ts'
16
+
17
+ export const PROFILE_OWNER_FILE = '.acryl-owner.json'
18
+
19
+ export interface ProfileOwner {
20
+ readonly installRoot: string
21
+ readonly pid: number
22
+ readonly since: string
23
+ }
24
+
25
+ export class ProfileInUseError extends Error {
26
+ constructor(profileDir: string, owner: { installRoot: unknown, pid: number }, installRoot: string) {
27
+ super(
28
+ `ACRYL profile ${profileDir} is in use by another ACRYL installation (${String(owner.installRoot)}, pid ${String(owner.pid)}). `
29
+ + `This one (${installRoot}) would re-link its packages under the running app. Stop that app, or run this one in its own home `
30
+ + '(set ACRYL_HOME, or start an app created with `acryl new` through its bin/acryl).',
31
+ )
32
+ this.name = 'ProfileInUseError'
33
+ }
34
+ }
35
+
36
+ function canonical(path: string): string {
37
+ try { return realpathSync(path) } catch { return path }
38
+ }
39
+
40
+ /** Take the profile for this installation, or throw naming the live installation that holds it. */
41
+ export function claimProfile(profileDir: string, installRoot: string, pid: number = process.pid, alive?: (pid: number) => boolean): void {
42
+ const root = canonical(installRoot)
43
+ try {
44
+ acquireLock(join(profileDir, PROFILE_OWNER_FILE), { pid, installRoot: root }, {
45
+ ...(alive === undefined ? {} : { alive }),
46
+ compatible: holder => typeof holder.installRoot === 'string' && canonical(holder.installRoot) === root,
47
+ })
48
+ } catch (error) {
49
+ if (error instanceof LockHeldError) throw new ProfileInUseError(profileDir, { installRoot: error.holder.installRoot, pid: error.holder.pid }, root)
50
+ throw error
51
+ }
52
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Pre-image backups for repairs: every file a repair may change is copied first, so a repair can be undone
3
+ * and an interrupted one can be rolled back.
4
+ *
5
+ * A backup is complete only when its manifest exists, and the manifest is written last and atomically, so a
6
+ * repair killed halfway through making the backup leaves nothing that looks valid.
7
+ */
8
+
9
+ import { createHash, randomBytes } from 'node:crypto'
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
11
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
12
+ import { writeFileAtomic } from '../engine-files.ts'
13
+
14
+ const BACKUPS_DIR = 'repair-backups'
15
+ const MANIFEST = 'manifest.json'
16
+
17
+ export interface BackupEntry {
18
+ readonly path: string
19
+ /** False when the file did not exist, so undoing the repair removes it. */
20
+ readonly existed: boolean
21
+ /** The pre-image's name inside the backup directory. */
22
+ readonly stored?: string
23
+ readonly sha256?: string
24
+ }
25
+
26
+ export interface BackupManifest {
27
+ readonly id: string
28
+ readonly createdAt: string
29
+ readonly profileName: string
30
+ readonly recipes: readonly string[]
31
+ readonly entries: readonly BackupEntry[]
32
+ }
33
+
34
+ const sha = (data: Buffer): string => createHash('sha256').update(data).digest('hex')
35
+
36
+ /** A file a backup may touch must lie inside the engine home. */
37
+ function assertInside(dshHome: string, path: string): void {
38
+ const rel = relative(resolve(dshHome), resolve(path))
39
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) throw new Error(`refusing to back up or restore a file outside the ACRYL home: ${path}`)
40
+ }
41
+
42
+ export const backupsDir = (dshHome: string): string => join(dshHome, BACKUPS_DIR)
43
+
44
+ /** Copy each file's current content aside. @returns the manifest of the new backup. */
45
+ export async function createBackup(input: {
46
+ readonly dshHome: string
47
+ readonly profileName: string
48
+ readonly recipes: readonly string[]
49
+ readonly files: readonly string[]
50
+ readonly now?: () => Date
51
+ }): Promise<BackupManifest> {
52
+ const now = (input.now ?? (() => new Date()))()
53
+ const id = `${now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')}-${randomBytes(3).toString('hex')}`
54
+ const dir = join(backupsDir(input.dshHome), id)
55
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
56
+ const entries: BackupEntry[] = []
57
+ let index = 0
58
+ for (const file of input.files) {
59
+ assertInside(input.dshHome, file)
60
+ if (!existsSync(file)) { entries.push({ path: file, existed: false }); continue }
61
+ const data = readFileSync(file)
62
+ const stored = `${String(index)}-${basename(file)}`
63
+ index += 1
64
+ await writeFileAtomic(join(dir, stored), data.toString('utf8'), { mode: 0o600, dirMode: 0o700 })
65
+ entries.push({ path: file, existed: true, stored, sha256: sha(data) })
66
+ }
67
+ const manifest: BackupManifest = { id, createdAt: now.toISOString(), profileName: input.profileName, recipes: [...input.recipes], entries }
68
+ // Last, so a backup that was interrupted before this point is not mistaken for a complete one.
69
+ await writeFileAtomic(join(dir, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 })
70
+ return manifest
71
+ }
72
+
73
+ /** Complete backups, newest first; incomplete or damaged ones are skipped. */
74
+ export function listBackups(dshHome: string): BackupManifest[] {
75
+ let ids: string[]
76
+ try {
77
+ ids = readdirSync(backupsDir(dshHome))
78
+ } catch {
79
+ return []
80
+ }
81
+ const found: BackupManifest[] = []
82
+ for (const id of ids) {
83
+ try {
84
+ const manifest = JSON.parse(readFileSync(join(backupsDir(dshHome), id, MANIFEST), 'utf8')) as BackupManifest
85
+ if (manifest.id === id && Array.isArray(manifest.entries)) found.push(manifest)
86
+ } catch {
87
+ // No manifest, or an unreadable one: not a usable backup.
88
+ }
89
+ }
90
+ return found.sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : b.id.localeCompare(a.id)))
91
+ }
92
+
93
+ /** The pre-image bytes of one stored file, verified against its recorded hash. */
94
+ export function readPreImage(dshHome: string, manifest: BackupManifest, entry: BackupEntry): Buffer {
95
+ if (entry.stored === undefined) throw new Error('that backup entry has no stored content')
96
+ const data = readFileSync(join(backupsDir(dshHome), manifest.id, entry.stored))
97
+ if (entry.sha256 !== undefined && sha(data) !== entry.sha256) throw new Error(`the backup of ${entry.path} is damaged (checksum mismatch)`)
98
+ return data
99
+ }
100
+
101
+ /** Put every file back as it was: restore what existed, remove what the repair created. */
102
+ export async function restoreBackup(dshHome: string, id: string): Promise<BackupManifest> {
103
+ const manifest = listBackups(dshHome).find(candidate => candidate.id === id)
104
+ if (manifest === undefined) throw new Error(`no complete backup named ${id}`)
105
+ // Verify everything first, so a damaged backup changes nothing.
106
+ const restores = manifest.entries.map((entry) => {
107
+ assertInside(dshHome, entry.path)
108
+ return { entry, data: entry.existed ? readPreImage(dshHome, manifest, entry) : undefined }
109
+ })
110
+ for (const { entry, data } of restores) {
111
+ if (data !== undefined) {
112
+ mkdirSync(dirname(entry.path), { recursive: true })
113
+ await writeFileAtomic(entry.path, data.toString('utf8'), { mode: 0o600, dirMode: 0o700 })
114
+ } else if (existsSync(entry.path)) {
115
+ rmSync(entry.path, { force: true })
116
+ }
117
+ }
118
+ return manifest
119
+ }
@@ -0,0 +1,43 @@
1
+ /** What a static diagnosis of a profile can say, and what repairs exist for it. */
2
+
3
+ export type ProfileFindingCode =
4
+ | 'profile-missing'
5
+ | 'state-unreadable'
6
+ | 'profile-manifest-unreadable'
7
+ | 'bundle-missing'
8
+ | 'pnpm-layout-mismatch'
9
+ | 'plugin-activation-failed'
10
+ | 'pnpm-store-mismatch'
11
+
12
+ /**
13
+ * The repairs that may ever run without a person choosing each step. The list is short on purpose: it grows
14
+ * only by a reviewed change (spec 041, question 6).
15
+ */
16
+ export const SAFE_RECIPES = ['restore-override-file', 'disable-failing-row'] as const
17
+ export type RecipeId = (typeof SAFE_RECIPES)[number]
18
+
19
+ export interface ProfileFinding {
20
+ /** `error` means the profile is broken; `warning` means it is surprising or degraded. */
21
+ readonly severity: 'error' | 'warning'
22
+ readonly code: ProfileFindingCode
23
+ readonly message: string
24
+ /** The file the finding is about. */
25
+ readonly file?: string
26
+ /** The Loader row or package it is about. */
27
+ readonly entryId?: string
28
+ /** The safe recipe that addresses it, when there is one. */
29
+ readonly recipe?: RecipeId
30
+ /** What a person should do when no safe recipe applies. */
31
+ readonly guidance?: string
32
+ }
33
+
34
+ export interface ProfileDiagnosis {
35
+ readonly profileName: string
36
+ readonly profileDir: string
37
+ readonly dshHome: string
38
+ readonly findings: readonly ProfileFinding[]
39
+ }
40
+
41
+ export function isSafeRecipe(value: string): value is RecipeId {
42
+ return (SAFE_RECIPES as readonly string[]).includes(value)
43
+ }
@@ -0,0 +1,10 @@
1
+ /** Offline diagnosis and repair of a profile (spec 041, Scope B): static, reversible, and safe to run when the app cannot start. */
2
+
3
+ export { createBackup, listBackups, restoreBackup, backupsDir } from './backup.ts'
4
+ export type { BackupEntry, BackupManifest } from './backup.ts'
5
+ export { SAFE_RECIPES, isSafeRecipe } from './findings.ts'
6
+ export type { ProfileDiagnosis, ProfileFinding, ProfileFindingCode, RecipeId } from './findings.ts'
7
+ export { inspectProfile } from './inspector.ts'
8
+ export type { InspectOptions } from './inspector.ts'
9
+ export { applyRepairPlan, describePlan, planRepairs, undoRepair } from './repair.ts'
10
+ export type { RepairPlan, RepairResult, RepairStep } from './repair.ts'
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Static diagnosis of a profile: files, manifests and logs only. It never starts the app, never imports a
3
+ * plugin, and never writes anything, so it works when the app is too broken to launch (spec 041, Scope B).
4
+ */
5
+
6
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { resolveProfileDir } from '@deepseek-ai/dsh-app-boot'
9
+ import { parse } from 'yaml'
10
+ import {
11
+ readDisabledPluginLifecycleEntries,
12
+ readUserMutableBundleNames,
13
+ resolvePluginLifecycleStatePath,
14
+ } from '../plugin-lifecycle-state.ts'
15
+ import type { ProfileDiagnosis, ProfileFinding } from './findings.ts'
16
+
17
+ /** Loader rows that are infrastructure, not plugins: a failure inside one is not fixed by disabling it. */
18
+ const INFRASTRUCTURE_ROWS: ReadonlySet<string> = new Set(['acryl-engine', 'include', 'webserver'])
19
+ /** How much of each recent log to read, and how many logs. */
20
+ const LOG_TAIL_BYTES = 256 * 1024
21
+ const RECENT_LOGS = 3
22
+
23
+ export interface InspectOptions {
24
+ readonly dshHome: string
25
+ readonly profileName: string
26
+ }
27
+
28
+ const describe = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause))
29
+
30
+ function recentLogFiles(dshHome: string): string[] {
31
+ const dir = join(dshHome, 'logs')
32
+ let names: string[]
33
+ try {
34
+ names = readdirSync(dir)
35
+ } catch {
36
+ return []
37
+ }
38
+ return names
39
+ .filter(name => /\.(?:log|jsonl)$/.test(name))
40
+ .flatMap((name) => {
41
+ try {
42
+ const path = join(dir, name)
43
+ const stats = statSync(path)
44
+ return stats.isFile() ? [{ path, modifiedAt: stats.mtimeMs }] : []
45
+ } catch {
46
+ return []
47
+ }
48
+ })
49
+ .sort((a, b) => b.modifiedAt - a.modifiedAt)
50
+ .slice(0, RECENT_LOGS)
51
+ .map(file => file.path)
52
+ }
53
+
54
+ function tailOf(path: string): string {
55
+ try {
56
+ const text = readFileSync(path, 'utf8')
57
+ return text.length > LOG_TAIL_BYTES ? text.slice(text.length - LOG_TAIL_BYTES) : text
58
+ } catch {
59
+ return ''
60
+ }
61
+ }
62
+
63
+ const ACTIVATION_FAILURE = /failed to apply loader entry ([A-Za-z0-9@/._:-]+)/g
64
+
65
+ /** The innermost failing Loader row of each log line: the outer rows only say "my child failed". */
66
+ function activationFailures(text: string): Array<{ entryId: string; cause: string }> {
67
+ const found = new Map<string, string>()
68
+ for (const line of text.split('\n')) {
69
+ let last: RegExpExecArray | undefined
70
+ ACTIVATION_FAILURE.lastIndex = 0
71
+ for (let match = ACTIVATION_FAILURE.exec(line); match !== null; match = ACTIVATION_FAILURE.exec(line)) last = match
72
+ if (last === undefined) continue
73
+ const entryId = last[1] ?? ''
74
+ const rest = line.slice(last.index + last[0].length).replace(/^[^:]*\):\s*/, '').trim()
75
+ if (!found.has(entryId)) found.set(entryId, rest.slice(0, 200))
76
+ }
77
+ return [...found].map(([entryId, cause]) => ({ entryId, cause }))
78
+ }
79
+
80
+ function layoutFinding(profileDir: string): ProfileFinding | undefined {
81
+ const modules = join(profileDir, 'node_modules', '.modules.yaml')
82
+ const workspace = join(profileDir, 'pnpm-workspace.yaml')
83
+ if (!existsSync(modules) || !existsSync(workspace)) return undefined
84
+ try {
85
+ const recorded = (parse(readFileSync(modules, 'utf8')) as { nodeLinker?: unknown } | null)?.nodeLinker
86
+ const declared = (parse(readFileSync(workspace, 'utf8')) as { nodeLinker?: unknown } | null)?.nodeLinker ?? 'isolated'
87
+ if (typeof recorded === 'string' && recorded !== declared) {
88
+ return {
89
+ severity: 'warning', code: 'pnpm-layout-mismatch', file: workspace,
90
+ message: `the profile's dependencies were installed with nodeLinker "${recorded}" but pnpm-workspace.yaml says "${String(declared)}"; a reinstall would relink the whole tree`,
91
+ guidance: 'Do not reinstall by hand. Run the profile through ACRYL, which pins the recorded layout before any package operation.',
92
+ }
93
+ }
94
+ } catch {
95
+ // An unreadable YAML file is reported by the boot itself; it is not a layout finding.
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ /** Diagnose a profile from its files and recent logs. Never throws for a broken profile: that is the finding. */
101
+ export function inspectProfile(options: InspectOptions): ProfileDiagnosis {
102
+ const profileDir = resolveProfileDir(options.profileName, options.dshHome)
103
+ const findings: ProfileFinding[] = []
104
+ if (!existsSync(profileDir)) {
105
+ findings.push({ severity: 'error', code: 'profile-missing', file: profileDir, message: `profile ${JSON.stringify(options.profileName)} has no directory at ${profileDir}`, guidance: 'Check the profile name with `acryl plugin list --profile <name>`; ACRYL creates a profile on first use.' })
106
+ return { profileName: options.profileName, profileDir, dshHome: options.dshHome, findings }
107
+ }
108
+
109
+ const statePath = resolvePluginLifecycleStatePath(options.dshHome)
110
+ if (existsSync(statePath)) {
111
+ try {
112
+ readDisabledPluginLifecycleEntries({ profileName: options.profileName, statePath })
113
+ } catch (cause) {
114
+ findings.push({ severity: 'error', code: 'state-unreadable', file: statePath, recipe: 'restore-override-file', message: `the plugin override file ${statePath} cannot be read: ${describe(cause)}` })
115
+ }
116
+ }
117
+
118
+ const manifest = join(profileDir, 'package.json')
119
+ if (existsSync(manifest)) {
120
+ try {
121
+ JSON.parse(readFileSync(manifest, 'utf8'))
122
+ } catch (cause) {
123
+ findings.push({ severity: 'error', code: 'profile-manifest-unreadable', file: manifest, message: `the profile manifest ${manifest} is not valid JSON: ${describe(cause)}`, guidance: 'Restore it from a backup or from another profile\'s copy; it lists the profile\'s bundles.' })
124
+ }
125
+ for (const bundle of [...readUserMutableBundleNames(profileDir)].sort()) {
126
+ if (!existsSync(join(profileDir, 'node_modules', ...bundle.split('/'), 'package.json'))) {
127
+ findings.push({ severity: 'error', code: 'bundle-missing', entryId: bundle, file: manifest, message: `the profile lists ${bundle} but it is not installed in ${join(profileDir, 'node_modules')}`, guidance: `Reinstall it with \`acryl plugin add ${bundle}\`, or remove it from dsh.profile.bundles.` })
128
+ }
129
+ }
130
+ }
131
+
132
+ const layout = layoutFinding(profileDir)
133
+ if (layout !== undefined) findings.push(layout)
134
+
135
+ const seen = new Set<string>()
136
+ let storeMismatch = false
137
+ for (const log of recentLogFiles(options.dshHome)) {
138
+ const text = tailOf(log)
139
+ for (const failure of activationFailures(text)) {
140
+ if (seen.has(failure.entryId)) continue
141
+ seen.add(failure.entryId)
142
+ const infrastructure = INFRASTRUCTURE_ROWS.has(failure.entryId)
143
+ findings.push({
144
+ severity: 'error', code: 'plugin-activation-failed', entryId: failure.entryId, file: log,
145
+ message: `${failure.entryId} failed to activate${failure.cause === '' ? '' : `: ${failure.cause}`}`,
146
+ ...(infrastructure ? { guidance: `${failure.entryId} is part of the engine, not a plugin; disabling it would not fix this. Fix the cause named above.` } : { recipe: 'disable-failing-row' as const }),
147
+ })
148
+ }
149
+ if (/package manager did not complete successfully/i.test(text)) storeMismatch = true
150
+ }
151
+ if (storeMismatch) {
152
+ findings.push({ severity: 'warning', code: 'pnpm-store-mismatch', message: 'the package manager did not complete a recent install; this is the known symptom of a pnpm store made by a different pnpm version', guidance: 'Use the pnpm ACRYL pins (through the Lifecycle tab or `acryl plugin`), not the one on PATH, and do not delete the profile to fix it.' })
153
+ }
154
+
155
+ return { profileName: options.profileName, profileDir, dshHome: options.dshHome, findings }
156
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Repair recipes and the plan that runs them.
3
+ *
4
+ * A recipe is a named step with a precondition, a dry-run description that names the exact files it will
5
+ * change, and an undo through the pre-image backup. Nothing is guessed: with no matching finding a recipe does
6
+ * not exist in the plan. There are only two recipes and they can only grow by a reviewed change.
7
+ */
8
+
9
+ import { rmSync, writeFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import { writeFileAtomic } from '../engine-files.ts'
12
+ import {
13
+ entryPatchId,
14
+ readDisabledPluginLifecycleEntries,
15
+ resolvePluginLifecycleStatePath,
16
+ setPluginLifecycleEntryEnabled,
17
+ } from '../plugin-lifecycle-state.ts'
18
+ import { createBackup, listBackups, readPreImage, restoreBackup, type BackupManifest } from './backup.ts'
19
+ import { SAFE_RECIPES, type ProfileDiagnosis, type ProfileFinding, type RecipeId } from './findings.ts'
20
+
21
+ export interface RepairStep {
22
+ readonly recipe: RecipeId
23
+ /** What will change, in words, naming the file or row. */
24
+ readonly description: string
25
+ /** Every file the step may write; each is backed up first. */
26
+ readonly files: readonly string[]
27
+ /** The finding that made this step applicable. */
28
+ readonly because: ProfileFinding
29
+ }
30
+
31
+ export interface RepairPlan {
32
+ readonly profileName: string
33
+ readonly dshHome: string
34
+ readonly steps: readonly RepairStep[]
35
+ }
36
+
37
+ export interface RepairResult {
38
+ readonly backupId: string
39
+ readonly applied: readonly RecipeId[]
40
+ }
41
+
42
+ const EMPTY_STATE = `${JSON.stringify({ version: 1, profiles: [] }, null, 2)}\n`
43
+
44
+ /** Whether a stored override file still parses under the current rules. */
45
+ function isValidState(dshHome: string, profileName: string, text: string): boolean {
46
+ const probe = join(dshHome, '.repair-probe-state.json')
47
+ try {
48
+ // The reader takes a path, so a parseable copy is judged through the same function the app uses.
49
+ writeFileSync(probe, text)
50
+ readDisabledPluginLifecycleEntries({ profileName, statePath: probe })
51
+ return true
52
+ } catch {
53
+ return false
54
+ } finally {
55
+ rmSync(probe, { force: true })
56
+ }
57
+ }
58
+
59
+
60
+ /** The newest backed-up copy of the override file that is valid, if any. */
61
+ function lastValidOverride(dshHome: string, profileName: string, statePath: string): string | undefined {
62
+ for (const manifest of listBackups(dshHome)) {
63
+ for (const entry of manifest.entries) {
64
+ if (entry.path !== statePath || !entry.existed) continue
65
+ try {
66
+ const text = readPreImage(dshHome, manifest, entry).toString('utf8')
67
+ if (isValidState(dshHome, profileName, text)) return text
68
+ } catch {
69
+ // A damaged backup is skipped; an older one may be fine.
70
+ }
71
+ }
72
+ }
73
+ return undefined
74
+ }
75
+
76
+ /**
77
+ * Build the plan for the chosen recipes.
78
+ * @param recipes - the recipes to include; only ones with a matching finding are planned.
79
+ */
80
+ export function planRepairs(diagnosis: ProfileDiagnosis, recipes: readonly RecipeId[] = SAFE_RECIPES): RepairPlan {
81
+ const statePath = resolvePluginLifecycleStatePath(diagnosis.dshHome)
82
+ const steps: RepairStep[] = []
83
+ for (const finding of diagnosis.findings) {
84
+ if (finding.recipe === undefined || !recipes.includes(finding.recipe)) continue
85
+ if (finding.recipe === 'restore-override-file') {
86
+ const previous = lastValidOverride(diagnosis.dshHome, diagnosis.profileName, statePath)
87
+ steps.push({
88
+ recipe: 'restore-override-file', because: finding, files: [statePath],
89
+ description: previous === undefined
90
+ ? `Replace the unreadable ${statePath} with an empty override file (no plugin is recorded as disabled). The damaged file is kept in the backup.`
91
+ : `Replace the unreadable ${statePath} with the last valid copy from a backup. The damaged file is kept in the new backup.`,
92
+ })
93
+ } else if (finding.entryId !== undefined) {
94
+ steps.push({
95
+ recipe: 'disable-failing-row', because: finding, files: [statePath],
96
+ description: `Record ${finding.entryId} as disabled for profile ${JSON.stringify(diagnosis.profileName)} in ${statePath}, so the app starts without it. Nothing is uninstalled.`,
97
+ })
98
+ }
99
+ }
100
+ // The override file must be readable before a row can be recorded in it.
101
+ steps.sort((a, b) => Number(b.recipe === 'restore-override-file') - Number(a.recipe === 'restore-override-file'))
102
+ return { profileName: diagnosis.profileName, dshHome: diagnosis.dshHome, steps }
103
+ }
104
+
105
+ /** Back up, then apply every step; on any failure the backup is put back and the error is thrown. */
106
+ export async function applyRepairPlan(plan: RepairPlan): Promise<RepairResult> {
107
+ if (plan.steps.length === 0) throw new Error('there is nothing to repair')
108
+ const statePath = resolvePluginLifecycleStatePath(plan.dshHome)
109
+ const files = [...new Set(plan.steps.flatMap(step => step.files))]
110
+ const backup: BackupManifest = await createBackup({ dshHome: plan.dshHome, profileName: plan.profileName, recipes: plan.steps.map(step => step.recipe), files })
111
+ try {
112
+ for (const step of plan.steps) {
113
+ if (step.recipe === 'restore-override-file') {
114
+ const previous = lastValidOverride(plan.dshHome, plan.profileName, statePath)
115
+ await writeFileAtomic(statePath, previous ?? EMPTY_STATE, { mode: 0o600, dirMode: 0o700 })
116
+ } else if (step.because.entryId !== undefined) {
117
+ await setPluginLifecycleEntryEnabled({ profileName: plan.profileName, statePath }, entryPatchId(step.because.entryId), false)
118
+ }
119
+ }
120
+ } catch (cause) {
121
+ await restoreBackup(plan.dshHome, backup.id)
122
+ throw new Error(`the repair failed and was rolled back: ${cause instanceof Error ? cause.message : String(cause)}`)
123
+ }
124
+ return { backupId: backup.id, applied: plan.steps.map(step => step.recipe) }
125
+ }
126
+
127
+ /** Undo a repair by putting its pre-images back. */
128
+ export async function undoRepair(dshHome: string, backupId: string): Promise<BackupManifest> {
129
+ return restoreBackup(dshHome, backupId)
130
+ }
131
+
132
+ /** The plan as readable text, for a dry run or a confirmation. */
133
+ export function describePlan(plan: RepairPlan): string {
134
+ if (plan.steps.length === 0) return 'Nothing to repair.'
135
+ return plan.steps.map((step, index) => `${String(index + 1)}. [${step.recipe}] ${step.description}`).join('\n')
136
+ }
137
+
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The framework packages that moved into `acrylblends` (spec 049 slice 17). An app plugin written before the move imports them by
3
+ * their old names, which no longer resolve; there is no alias, because `@acryldev/router/middleware` maps to one subpath per middleware
4
+ * and an alias would hide that. This module names what to import instead, and `movedFrameworkImports` registers a resolve hook
5
+ * that adds it to the "cannot find package" error a boot would otherwise end on.
6
+ *
7
+ * @module @acryldev/harness-runtime/profile-resolution/moved-framework
8
+ */
9
+
10
+ import type { ModuleHooks } from 'node:module'
11
+ import { registerModuleHooks } from '../module-hooks.ts'
12
+
13
+ /** Each old specifier and what replaces it. */
14
+ export const MOVED_FRAMEWORK_IMPORTS: Readonly<Record<string, string>> = Object.freeze({
15
+ '@acryldev/router': "'acrylblends' (Acryl, Context and the types), '@acryldev/blends/http-exception' (HTTPException) and '@acryldev/blends/cordis/router' (the Cordis plugin, connectionOf, and the ctx.router type)",
16
+ '@acryldev/router/middleware': "one subpath per middleware: '@acryldev/blends/body-limit', '@acryldev/blends/loopback-only', '@acryldev/blends/method-not-allowed', '@acryldev/blends/trailing-slash', '@acryldev/blends/bearer-auth' and the others under their names",
17
+ '@acryldev/router/helpers': "'@acryldev/blends/streaming' (streamSSE) and '@acryldev/blends/schema-validator' (schemaValidator)",
18
+ '@acryldev/router-http': "'@acryldev/blends/cordis/router-http'",
19
+ '@acryldev/state': "'@acryldev/blends/cordis/state'",
20
+ '@acryldev/inspect': "'@acryldev/blends/cordis/inspect'",
21
+ '@acryldev/node-server': "'@acryldev/blends/node-server' (serve) or '@acryldev/blends/cordis/node-server' (the Cordis plugin)",
22
+ '@acryldev/door': "'@acryldev/blends/cordis/door'",
23
+ '@acryldev/door/protocol': "'@acryldev/blends/door/protocol'",
24
+ '@acryldev/door/host': "'@acryldev/blends/door/host'",
25
+ '@acryldev/door/page': "'@acryldev/blends/door/page'",
26
+ '@acryldev/db': "'@acryldev/blends/db'",
27
+ '@acryldev/db/cordis': "'@acryldev/blends/cordis/db'",
28
+ '@acryldev/db/conformance': "'@acryldev/blends/db/conformance'",
29
+ '@acryldev/db-sqlite': "'@acryldev/blends/db/sqlite' or '@acryldev/blends/cordis/db-sqlite' (the Cordis plugin)",
30
+ '@acryldev/kv': "'@acryldev/blends/kv'",
31
+ '@acryldev/kv-json': "'@acryldev/blends/kv/json' or '@acryldev/blends/cordis/kv-json' (the Cordis plugin)",
32
+ '@acryldev/kv-db': "'@acryldev/blends/kv/db' or '@acryldev/blends/cordis/kv-db' (the Cordis plugin)",
33
+ })
34
+
35
+ /** What replaces an old framework import, or undefined for any other specifier. */
36
+ export function movedFrameworkImport(specifier: string): string | undefined {
37
+ return MOVED_FRAMEWORK_IMPORTS[specifier]
38
+ }
39
+
40
+ /** The message for an old framework import that did not resolve. */
41
+ export function movedFrameworkMessage(specifier: string, original: string): string {
42
+ return `${original}\n'${specifier}' is part of acrylblends since the framework moved to its own repository: import ${MOVED_FRAMEWORK_IMPORTS[specifier] ?? "from '@acryldev/blends'"} instead.`
43
+ }
44
+
45
+ /**
46
+ * A resolve hook that names the replacement when an old framework import does not resolve. Registered after the profile's own
47
+ * resolution, so it sees that resolution's failure; anything that resolves, and every other error, passes through unchanged.
48
+ * @returns the hooks, for the caller to deregister with the resolution it wraps.
49
+ */
50
+ export function registerMovedFrameworkImports(): ModuleHooks {
51
+ return registerModuleHooks({
52
+ resolve(specifier, context, nextResolve) {
53
+ try {
54
+ return nextResolve(specifier, context)
55
+ } catch (error) {
56
+ const code = (error as NodeJS.ErrnoException).code
57
+ if (error instanceof Error && movedFrameworkImport(specifier) !== undefined && (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND')) {
58
+ error.message = movedFrameworkMessage(specifier, error.message)
59
+ }
60
+ throw error
61
+ }
62
+ },
63
+ })
64
+ }