@acryldev/harness-runtime 0.0.0-stage → 0.2.12

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/README.md +14 -2
  3. package/lib/index.mjs +5693 -0
  4. package/lib/index.mjs.map +1 -0
  5. package/lib/types/acryl-home.d.ts +81 -0
  6. package/lib/types/app/new-app.d.ts +65 -0
  7. package/lib/types/app/start-source.d.ts +47 -0
  8. package/lib/types/blueprint/blueprint.d.ts +74 -0
  9. package/lib/types/blueprint/brand-identity.d.ts +26 -0
  10. package/lib/types/blueprint/compose.d.ts +53 -0
  11. package/lib/types/blueprint/definition.d.ts +22 -0
  12. package/lib/types/blueprint/index.d.ts +7 -0
  13. package/lib/types/blueprint/manifest.d.ts +35 -0
  14. package/lib/types/blueprint/selection.d.ts +19 -0
  15. package/lib/types/cli-market-install.d.ts +97 -0
  16. package/lib/types/cli-market-plugins.d.ts +81 -0
  17. package/lib/types/coding-capabilities.d.ts +29 -0
  18. package/lib/types/durable-message.d.ts +18 -0
  19. package/lib/types/engine-dsh.d.ts +181 -0
  20. package/lib/types/engine-files.d.ts +8 -0
  21. package/lib/types/engine-host.d.ts +32 -0
  22. package/lib/types/engine-tools.d.ts +11 -0
  23. package/lib/types/index.d.ts +67 -0
  24. package/lib/types/instance/announce-self.d.ts +38 -0
  25. package/lib/types/instance/app-instance.d.ts +125 -0
  26. package/lib/types/instance/index.d.ts +6 -0
  27. package/lib/types/instance/offline-lock.d.ts +29 -0
  28. package/lib/types/instance/online-secret.d.ts +29 -0
  29. package/lib/types/instance/registry.d.ts +26 -0
  30. package/lib/types/instance/select.d.ts +43 -0
  31. package/lib/types/module-hooks.d.ts +19 -0
  32. package/lib/types/module-resolution.d.ts +31 -0
  33. package/lib/types/package-overlay.d.ts +41 -0
  34. package/lib/types/pinned-pnpm.d.ts +15 -0
  35. package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
  36. package/lib/types/plugin-doctor.d.ts +49 -0
  37. package/lib/types/plugin-lifecycle-state.d.ts +92 -0
  38. package/lib/types/plugin-lifecycle.d.ts +87 -0
  39. package/lib/types/profile-layout.d.ts +17 -0
  40. package/lib/types/profile-owner.d.ts +25 -0
  41. package/lib/types/profile-repair/backup.d.ts +37 -0
  42. package/lib/types/profile-repair/findings.d.ts +29 -0
  43. package/lib/types/profile-repair/index.d.ts +9 -0
  44. package/lib/types/profile-repair/inspector.d.ts +11 -0
  45. package/lib/types/profile-repair/repair.d.ts +38 -0
  46. package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
  47. package/lib/types/profile-resolution/resolver.d.ts +41 -0
  48. package/lib/types/profile-resolution/service.d.ts +22 -0
  49. package/lib/types/prompt-budget.d.ts +44 -0
  50. package/lib/types/session-bridge.d.ts +57 -0
  51. package/lib/types/session-log-exporter.d.ts +31 -0
  52. package/lib/types/system-prompt-capture.d.ts +29 -0
  53. package/lib/types/web-favicon-data.d.ts +5 -0
  54. package/lib/types/web-favicon.d.ts +23 -0
  55. package/lib/types/web-market-install.d.ts +114 -0
  56. package/lib/types/web-market-plugins.d.ts +106 -0
  57. package/lib/types/web-port.d.ts +15 -0
  58. package/package.json +211 -3
  59. package/src/acryl-home.ts +103 -0
  60. package/src/app/new-app.ts +239 -0
  61. package/src/app/start-source.ts +110 -0
  62. package/src/blueprint/blueprint.ts +141 -0
  63. package/src/blueprint/brand-identity.ts +75 -0
  64. package/src/blueprint/compose.ts +222 -0
  65. package/src/blueprint/definition.ts +92 -0
  66. package/src/blueprint/index.ts +20 -0
  67. package/src/blueprint/manifest.ts +145 -0
  68. package/src/blueprint/selection.ts +74 -0
  69. package/src/cli-market-install.ts +181 -0
  70. package/src/cli-market-plugins.ts +176 -0
  71. package/src/coding-capabilities.ts +61 -0
  72. package/src/durable-message.ts +23 -0
  73. package/src/engine-dsh.ts +856 -0
  74. package/src/engine-files.ts +9 -0
  75. package/src/engine-host.ts +128 -0
  76. package/src/engine-tools.ts +26 -0
  77. package/src/index.ts +436 -0
  78. package/src/instance/announce-self.ts +88 -0
  79. package/src/instance/app-instance.ts +240 -0
  80. package/src/instance/index.ts +45 -0
  81. package/src/instance/offline-lock.ts +71 -0
  82. package/src/instance/online-secret.ts +55 -0
  83. package/src/instance/registry.ts +53 -0
  84. package/src/instance/select.ts +134 -0
  85. package/src/module-hooks.ts +41 -0
  86. package/src/module-resolution.ts +187 -0
  87. package/src/package-overlay.ts +160 -0
  88. package/src/pinned-pnpm.ts +67 -0
  89. package/src/plugin-acryl-workspace-status.ts +99 -0
  90. package/src/plugin-doctor.ts +141 -0
  91. package/src/plugin-lifecycle-state.ts +347 -0
  92. package/src/plugin-lifecycle.ts +223 -0
  93. package/src/profile-layout.ts +97 -0
  94. package/src/profile-owner.ts +52 -0
  95. package/src/profile-repair/backup.ts +119 -0
  96. package/src/profile-repair/findings.ts +43 -0
  97. package/src/profile-repair/index.ts +10 -0
  98. package/src/profile-repair/inspector.ts +156 -0
  99. package/src/profile-repair/repair.ts +137 -0
  100. package/src/profile-resolution/moved-framework.ts +64 -0
  101. package/src/profile-resolution/resolver.ts +876 -0
  102. package/src/profile-resolution/service.ts +99 -0
  103. package/src/prompt-budget.ts +118 -0
  104. package/src/session-bridge.ts +350 -0
  105. package/src/session-log-exporter.ts +68 -0
  106. package/src/system-prompt-capture.ts +99 -0
  107. package/src/web-favicon-data.ts +6 -0
  108. package/src/web-favicon.ts +43 -0
  109. package/src/web-market-install.ts +206 -0
  110. package/src/web-market-plugins.ts +215 -0
  111. package/src/web-port.ts +39 -0
  112. package/tests/account-callback.spec.ts +173 -0
  113. package/tests/acryl-home.spec.ts +39 -0
  114. package/tests/agent-self-hosting.spec.ts +101 -0
  115. package/tests/announce-self.spec.ts +84 -0
  116. package/tests/app-lifecycle.spec.ts +99 -0
  117. package/tests/blank-blueprint.spec.ts +110 -0
  118. package/tests/blueprint-definition.spec.ts +128 -0
  119. package/tests/blueprint.spec.ts +138 -0
  120. package/tests/bulkhead.spec.ts +187 -0
  121. package/tests/coding-vocabulary.spec.ts +15 -0
  122. package/tests/dump-system-prompt.spec.ts +65 -0
  123. package/tests/e2e-real-model.spec.ts +71 -0
  124. package/tests/e2e-restart-real-model.spec.ts +77 -0
  125. package/tests/engine-dsh.spec.ts +340 -0
  126. package/tests/engine-host-mount-root-include.spec.ts +118 -0
  127. package/tests/engine-host.spec.ts +176 -0
  128. package/tests/engine-optional.spec.ts +81 -0
  129. package/tests/extension-examples.spec.ts +261 -0
  130. package/tests/hooks-thread-stack.ts +27 -0
  131. package/tests/instance-patches.spec.ts +25 -0
  132. package/tests/instance.spec.ts +235 -0
  133. package/tests/live/community-plugins.spec.ts +83 -0
  134. package/tests/module-hooks.spec.ts +35 -0
  135. package/tests/module-resolution.spec.ts +265 -0
  136. package/tests/moved-framework.spec.ts +61 -0
  137. package/tests/new-app.spec.ts +132 -0
  138. package/tests/organizer-growth.spec.ts +117 -0
  139. package/tests/pinned-pnpm.spec.ts +34 -0
  140. package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
  141. package/tests/plugin-context.spec.ts +640 -0
  142. package/tests/plugin-doctor.spec.ts +183 -0
  143. package/tests/plugin-enablement-one-store.spec.ts +130 -0
  144. package/tests/plugin-lifecycle-state.spec.ts +169 -0
  145. package/tests/profile-layout.spec.ts +58 -0
  146. package/tests/profile-owner.spec.ts +38 -0
  147. package/tests/profile-repair/profile-repair.spec.ts +231 -0
  148. package/tests/profile-resolution-port.spec.ts +30 -0
  149. package/tests/profile-resolution-service.spec.ts +273 -0
  150. package/tests/profile-resolution-swap.spec.ts +69 -0
  151. package/tests/profile-resolution.spec.ts +2535 -0
  152. package/tests/profile.spec.ts +70 -0
  153. package/tests/project-registry.spec.ts +81 -0
  154. package/tests/prompt-budget.spec.ts +58 -0
  155. package/tests/real-home-guard.spec.ts +178 -0
  156. package/tests/session-bridge.spec.ts +316 -0
  157. package/tests/start-source.spec.ts +65 -0
  158. package/tests/system-prompt-shape.spec.ts +95 -0
  159. package/tests/three-levels.spec.ts +84 -0
  160. package/tests/tool-gateway.spec.ts +116 -0
  161. package/tests/tool-schemas.spec.ts +41 -0
  162. package/tests/web-favicon.spec.ts +42 -0
  163. package/tests/web-port.spec.ts +38 -0
  164. package/tests/web-startup-hold.spec.ts +79 -0
  165. package/tsconfig.json +24 -0
  166. package/tsdown.config.ts +2 -0
  167. package/vitest.config.ts +18 -0
@@ -0,0 +1,70 @@
1
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { afterEach, describe, expect, it } from 'vitest'
5
+ import { DEFAULT_PROFILE_BUNDLES, initProfile, resolveProfileDir } from '@deepseek-ai/dsh-app-boot'
6
+ import { bootAcrylHarnessProfile, bootAcrylWebProfile } from '../src/index.ts'
7
+
8
+ const temporaryHomes: string[] = []
9
+ const initialDshHome = process.env.DSH_HOME
10
+
11
+ afterEach(async () => {
12
+ // Assigning undefined would store the string "undefined" and the next boot would create a ./undefined profile directory.
13
+ if (initialDshHome === undefined) delete process.env.DSH_HOME
14
+ else process.env.DSH_HOME = initialDshHome
15
+ await Promise.all(temporaryHomes.splice(0).map(home => rm(home, { force: true, recursive: true, maxRetries: 10, retryDelay: 200 })))
16
+ })
17
+
18
+ describe('bootAcrylHarnessProfile', () => {
19
+ it('rejects an HMR-enabled profile outside an exposed-internals Node process', async () => {
20
+ const home = await mkdtemp(join(tmpdir(), 'acryl-harness-home-'))
21
+ temporaryHomes.push(home)
22
+ process.env.DSH_HOME = home
23
+ // The pinned profile now ships HMR disabled, so this rejection only applies when a profile
24
+ // explicitly enables it.
25
+ const profileDirectory = resolveProfileDir('acryl-test')
26
+ initProfile(profileDirectory, DEFAULT_PROFILE_BUNDLES)
27
+ await writeFile(join(profileDirectory, 'cordis.patch.yml'), '- id: hmr\n disabled: false\n')
28
+
29
+ await bootAcrylHarnessProfile({ profile: 'acryl-test' }).then(
30
+ () => { throw new Error('expected HMR-enabled profile boot to reject') },
31
+ error => expect(error).toHaveProperty('message', expect.stringContaining(
32
+ 'must be launched with Node --expose-internals',
33
+ )),
34
+ )
35
+ })
36
+
37
+ it('boots the pinned profile in one root with durable session and agent services', async () => {
38
+ const home = await mkdtemp(join(tmpdir(), 'acryl-harness-home-'))
39
+ temporaryHomes.push(home)
40
+ process.env.DSH_HOME = home
41
+ const profileDirectory = resolveProfileDir('acryl-test')
42
+ initProfile(profileDirectory, DEFAULT_PROFILE_BUNDLES)
43
+ await writeFile(join(profileDirectory, 'cordis.patch.yml'), '- id: hmr\n disabled: true\n')
44
+
45
+ const runtime = await bootAcrylHarnessProfile({ profile: 'acryl-test' })
46
+
47
+ expect(runtime.ctx.get('sessions')).toBeDefined()
48
+ expect(runtime.ctx.get('agents')).toBeDefined()
49
+ expect(runtime.ctx.get('authorization')).toBeDefined()
50
+ // The runtime composes the shared coding-capability rows on a base profile.
51
+ // `agentPresets` is a Typert remote service that stays PENDING until the
52
+ // typert registries are mounted (the web/base composition does), so it is
53
+ // asserted via the session bridge behaviour rather than `ctx.get`.
54
+ expect(runtime.ctx.get('sessionProjections')).toBeDefined()
55
+ await runtime.dispose()
56
+ })
57
+ })
58
+
59
+ describe('bootAcrylWebProfile', () => {
60
+ it('boots the pinned web profile with shared authorization available', async () => {
61
+ const home = await mkdtemp(join(tmpdir(), 'acryl-web-home-'))
62
+ temporaryHomes.push(home)
63
+ process.env.DSH_HOME = home
64
+
65
+ const runtime = await bootAcrylWebProfile({ cmdlineArgs: ['--no-open', '--port', '0'] })
66
+
67
+ expect(runtime.ctx.get('authorization')).toBeDefined()
68
+ await runtime.dispose()
69
+ }, 60_000)
70
+ })
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The project registry (T046 S2) on the real web engine: ACRYL's own list of project folders, kept in the ACRYL home through `@acryldev/settings`,
3
+ * served by the workspace Host plugin, and still there after the engine is torn down and booted again on the same home. The chat's workspaces are not
4
+ * involved: nothing here needs the DSH chat.
5
+ */
6
+ import { existsSync, mkdtempSync, readFileSync } from 'node:fs'
7
+ import { mkdtemp, rm } from 'node:fs/promises'
8
+ import { tmpdir } from 'node:os'
9
+ import { join } from 'node:path'
10
+ import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
11
+ import { afterEach, describe, expect, it } from 'vitest'
12
+ import { createWebEngineDefinition } from '../src/engine-dsh.ts'
13
+ import { createAcrylEngineHost } from '../src/engine-host.ts'
14
+ import { codingCapabilities } from '@acryldev/coding-capabilities'
15
+
16
+ const initialDshHome = process.env.DSH_HOME
17
+ const initialBlueprint = process.env.ACRYL_BLUEPRINT
18
+ const folders: string[] = []
19
+ afterEach(async () => {
20
+ for (const [key, value] of [['DSH_HOME', initialDshHome], ['ACRYL_BLUEPRINT', initialBlueprint]] as const) {
21
+ if (value === undefined) delete process.env[key]
22
+ else process.env[key] = value
23
+ }
24
+ await Promise.all(folders.splice(0).map(folder => rm(folder, { force: true, recursive: true })))
25
+ })
26
+
27
+ type Host = Awaited<ReturnType<typeof createAcrylEngineHost>>
28
+
29
+ async function boot(home: string, blueprint: string): Promise<{ host: Host, origin: string, acrylHome: string }> {
30
+ process.env.DSH_HOME = home
31
+ process.env.ACRYL_BLUEPRINT = blueprint
32
+ const host = await createAcrylEngineHost({
33
+ engines: [createWebEngineDefinition(new URL('../package.json', import.meta.url).href, codingCapabilities)],
34
+ initialEngine: 'dsh',
35
+ prepare: ctx => { provideCmdline(ctx, { args: ['--no-open', '--port', '0'], exit: () => {} }) },
36
+ })
37
+ await host.ctx.loader.await()
38
+ await new Promise(resolve => setTimeout(resolve, 300))
39
+ const web = host.ctx.get('webServer' as never) as { port: number }
40
+ const instance = host.ctx.get('appInstance' as never) as { home: string }
41
+ return { host, origin: `http://127.0.0.1:${String(web.port)}`, acrylHome: instance.home }
42
+ }
43
+
44
+ async function projects(origin: string, body?: unknown): Promise<{ status: number, json: any }> {
45
+ const headers: Record<string, string> = { origin, 'sec-fetch-site': 'same-origin' }
46
+ if (body !== undefined) headers['content-type'] = 'application/json'
47
+ const response = await fetch(`${origin}/api/acryl-workspace/projects`, { method: body === undefined ? 'GET' : 'POST', headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) })
48
+ return { status: response.status, json: await response.json() }
49
+ }
50
+
51
+ describe('the project registry on the real engine', () => {
52
+ it('keeps the list in the ACRYL home across a restart, with the DSH chat on or off', async () => {
53
+ const home = await mkdtemp(join(tmpdir(), 'acryl-projects-'))
54
+ folders.push(home)
55
+ const projectA = mkdtempSync(join(tmpdir(), 'acryl-project-a-'))
56
+ const projectB = mkdtempSync(join(tmpdir(), 'acryl-project-b-'))
57
+ folders.push(projectA, projectB)
58
+
59
+ const first = await boot(home, 'acryl.agents') // the chat is off: the list never needed it
60
+ try {
61
+ expect((await projects(first.origin)).json).toEqual({
62
+ ok: true,
63
+ view: { paths: [], adopted: false, workspaces: [{ id: 'default', name: 'Default', kind: 'individual', projects: [] }], current: 'default' },
64
+ })
65
+ expect((await projects(first.origin, { op: 'add', path: projectA })).json.view.paths).toEqual([projectA])
66
+ expect((await projects(first.origin, { op: 'add', path: projectB })).json.view.paths).toEqual([projectA, projectB])
67
+ expect((await projects(first.origin, { op: 'add', path: '/definitely/not/here' })).json).toMatchObject({ ok: false, code: 'not-a-folder' })
68
+ const file = join(first.acrylHome, 'acryl-settings.yaml')
69
+ expect(existsSync(file)).toBe(true)
70
+ expect(readFileSync(file, 'utf8')).toContain(projectA)
71
+ } finally { await first.host.dispose() }
72
+
73
+ const second = await boot(home, 'acryl.ide') // a different composition, the same home
74
+ try {
75
+ expect((await projects(second.origin)).json.view.paths).toEqual([projectA, projectB])
76
+ expect((await projects(second.origin, { op: 'remove', path: projectA })).json.view.paths).toEqual([projectB])
77
+ expect((await projects(second.origin, { op: 'adopt', paths: [projectA] })).json.view).toMatchObject({ paths: [projectB, projectA], adopted: true, current: 'default' })
78
+ expect((await projects(second.origin, { op: 'adopt', paths: [] })).json.view.adopted).toBe(true)
79
+ } finally { await second.host.dispose() }
80
+ }, 180_000)
81
+ })
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { ceilingsFor, estimateTokens, measurePromptBudget, overBudget, splitSections } from '../src/prompt-budget.ts'
3
+ import type { CapturedSystemPrompt } from '../src/system-prompt-capture.ts'
4
+
5
+ const captured = (system: string, tools: Array<[string, object]>): CapturedSystemPrompt => ({
6
+ system,
7
+ model: 'p/m',
8
+ tools: tools.map(([name, definition]) => ({ name, description: '', definition: { name, ...definition } })),
9
+ })
10
+
11
+ describe('splitSections', () => {
12
+ it('names the identity paragraph and each tagged section, with exact sizes', () => {
13
+ const system = 'You are X.\n\n<persona>\nBe kind.\n</persona>\n\n<cwd>\nHere.\n</cwd>'
14
+ const sections = splitSections(system)
15
+ expect(sections.map(s => s.name)).toEqual(['identity', 'persona', 'cwd'])
16
+ expect(sections[0]?.chars).toBe('You are X.'.length)
17
+ expect(sections[1]?.chars).toBe('<persona>\nBe kind.\n</persona>'.length)
18
+ })
19
+ it('has no sections for an empty prompt', () => {
20
+ expect(splitSections('')).toEqual([])
21
+ })
22
+ })
23
+
24
+ describe('the budget guard', () => {
25
+ const base = captured('You are X.\n\n<a>\n12345\n</a>\n\n<cwd>\n/some/path/on/this/machine\n</cwd>', [['t1', { d: 'x'.repeat(50) }], ['t2', { d: 'y'.repeat(10) }]])
26
+ const budget = measurePromptBudget(base)
27
+
28
+ it('sorts tools largest first and totals them', () => {
29
+ expect(budget.tools.map(t => t.name)).toEqual(['t1', 't2'])
30
+ expect(budget.toolsChars).toBe(budget.tools.reduce((sum, t) => sum + t.chars, 0))
31
+ })
32
+
33
+ it('records a ceiling rounded up to 100 and passes at it', () => {
34
+ const ceilings = ceilingsFor(budget)
35
+ expect(ceilings.systemChars % 100).toBe(0)
36
+ expect(ceilings.toolsChars % 100).toBe(0)
37
+ expect(overBudget(budget, ceilings)).toEqual([])
38
+ })
39
+
40
+ it('fails, naming what grew, when the prompt or the tools pass their ceiling', () => {
41
+ const ceilings = ceilingsFor(budget)
42
+ const grownSystem = measurePromptBudget(captured(`${base.system}\n\n<extra>\n${'z'.repeat(200)}\n</extra>`, [['t1', { d: 'x'.repeat(50) }], ['t2', { d: 'y'.repeat(10) }]]))
43
+ expect(overBudget(grownSystem, ceilings)).toEqual([expect.stringContaining('system prompt')])
44
+ const grownTools = measurePromptBudget(captured(base.system, [['t1', { d: 'x'.repeat(500) }], ['t2', { d: 'y'.repeat(10) }]]))
45
+ expect(overBudget(grownTools, ceilings)).toEqual([expect.stringContaining('tool definitions')])
46
+ })
47
+
48
+ it('does not count sections that name this machine, so the ceiling is the same on every checkout', () => {
49
+ const elsewhere = measurePromptBudget(captured(base.system.replace('/some/path/on/this/machine', '/a/much/longer/path/on/another/machine/entirely'), [['t1', { d: 'x'.repeat(50) }], ['t2', { d: 'y'.repeat(10) }]]))
50
+ expect(ceilingsFor(elsewhere)).toEqual(ceilingsFor(budget))
51
+ })
52
+ })
53
+
54
+ describe('estimateTokens', () => {
55
+ it('uses the documented ratio', () => {
56
+ expect(estimateTokens(3400)).toBe(1000)
57
+ })
58
+ })
@@ -0,0 +1,178 @@
1
+ /**
2
+ * The gate's real-home guard (`scripts/real-home-guard.mjs`) excuses exactly the apps that are running: their homes are left out because a live app
3
+ * writes its own home all the time (the development app's logs, the installed app's settings), and the guard must not fail the gate for that. A home
4
+ * with no live entry is still watched, and so is a Registry entry whose process is gone. Each case runs the real script against a throwaway OS home,
5
+ * with a command that writes into it, and checks the exit code and the report.
6
+ */
7
+ import { spawn, spawnSync } from 'node:child_process'
8
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { tmpdir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import { afterEach, describe, expect, it } from 'vitest'
13
+
14
+ const guard = fileURLToPath(new URL('../../../scripts/real-home-guard.mjs', import.meta.url))
15
+ const cleanups: Array<() => void> = []
16
+ afterEach(() => {
17
+ for (const step of cleanups.splice(0).reverse()) step()
18
+ })
19
+
20
+ /** A throwaway OS home, with the folder a test would write. */
21
+ function home(): string {
22
+ const dir = mkdtempSync(join(tmpdir(), 'real-home-guard-'))
23
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }))
24
+ return dir
25
+ }
26
+
27
+ /** A Registry entry as `announce` writes it: `~/.acryl-instances/.running/<id>.json`. */
28
+ function announce(osHome: string, entry: { id: string, name: string, home: string, pid: number }): void {
29
+ const dir = join(osHome, '.acryl-instances', '.running')
30
+ mkdirSync(dir, { recursive: true })
31
+ writeFileSync(join(dir, `${entry.id}.json`), JSON.stringify({ ...entry, surface: 'web', since: new Date().toISOString() }))
32
+ }
33
+
34
+ /** A process that stays alive while the guard runs, so its Registry entry reads as live; killed afterwards. */
35
+ function liveProcess(): number {
36
+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
37
+ cleanups.push(() => child.kill('SIGKILL'))
38
+ return child.pid!
39
+ }
40
+
41
+ /** Writes a file under an app home inside the throwaway OS home, as a running app would. */
42
+ function write(file: string): string[] {
43
+ return ['-e', `require('node:fs').mkdirSync(require('node:path').dirname(${JSON.stringify(file)}), { recursive: true }); require('node:fs').writeFileSync(${JSON.stringify(file)}, 'x')`]
44
+ }
45
+
46
+ function run(osHome: string, command: string[]): { status: number | null, output: string } {
47
+ const result = spawnSync(process.execPath, [guard, '--', process.execPath, ...command], {
48
+ env: { ...process.env, HOME: osHome, USERPROFILE: osHome },
49
+ encoding: 'utf8',
50
+ })
51
+ return { status: result.status, output: `${result.stdout}${result.stderr}` }
52
+ }
53
+
54
+ describe('the real-home guard and live apps', () => {
55
+ it('leaves out the home of a live app, says so, and passes when that app writes its own home', () => {
56
+ const osHome = home()
57
+ const appHome = join(osHome, '.acryl-dev')
58
+ const pid = liveProcess()
59
+ announce(osHome, { id: 'acryl-dev', name: 'ACRYL Development', home: appHome, pid })
60
+ const { status, output } = run(osHome, write(join(appHome, 'logs', 'session.log')))
61
+ expect(output).toContain('skipped ~/.acryl-dev: app ACRYL Development pid')
62
+ expect(status).toBe(0)
63
+ })
64
+
65
+ it('fails a write into a home with no live entry, and names the file', () => {
66
+ const osHome = home()
67
+ const appHome = join(osHome, '.acryl-worktrees', 'someone-else')
68
+ const { status, output } = run(osHome, write(join(appHome, 'not-a-live-app.log')))
69
+ expect(output).toContain('not-a-live-app.log')
70
+ // Trays the old apps do not write: the pre-T011 hint belongs to ~/.acryl, ~/.acryl-dev and ~/.dsh only.
71
+ expect(output).not.toContain('built before 905a801c')
72
+ expect(status).toBe(1)
73
+ })
74
+
75
+ it('reports a write that only happens when the file is missing, as CI found for credentials and workspace storage', () => {
76
+ const osHome = home()
77
+ const file = join(osHome, '.acryl', '.dsh', '.credentials.yaml')
78
+ // The writer that failed CI on 3e373538 created its file only when absent, which a developer machine that already has the file cannot show; an
79
+ // empty home can. The guard reports the creation like any other addition.
80
+ const onlyIfMissing = [
81
+ '-e',
82
+ `const fs = require('node:fs'); if (!fs.existsSync(${JSON.stringify(file)})) { fs.mkdirSync(require('node:path').dirname(${JSON.stringify(file)}), { recursive: true }); fs.writeFileSync(${JSON.stringify(file)}, 'x') }`,
83
+ ]
84
+ const { status, output } = run(osHome, onlyIfMissing)
85
+ expect(output).toContain('.credentials.yaml')
86
+ expect(status).toBe(1)
87
+ })
88
+
89
+ it('does not excuse a Registry entry whose process is gone', () => {
90
+ const osHome = home()
91
+ const appHome = join(osHome, '.acryl-dev')
92
+ announce(osHome, { id: 'stale', name: 'Stale App', home: appHome, pid: 2_147_483_600 })
93
+ const { status, output } = run(osHome, write(join(appHome, 'stale-write.log')))
94
+ expect(output).not.toContain('skipped ~/.acryl-dev')
95
+ expect(output).toContain('stale-write.log')
96
+ // An app built before 905a801c (T011) announces nothing, so a change here may be that app, and the failure says what to do about it.
97
+ expect(output).toContain('An ACRYL app built before 905a801c (T011) does not announce itself; if one is running against this home, quit it or run with ACRYL_REAL_HOME_GUARD=off.')
98
+ expect(status).toBe(1)
99
+ })
100
+
101
+ it('always checks ~/.acryl-instances, but lets a live app change its own Registry entry', () => {
102
+ const osHome = home()
103
+ const pid = liveProcess()
104
+ announce(osHome, { id: 'mine', name: 'My App', home: join(osHome, '.acryl-dev'), pid })
105
+ const ownEntry = join(osHome, '.acryl-instances', '.running', 'mine.json')
106
+ const rewriteOwn = ['-e', `require('node:fs').writeFileSync(${JSON.stringify(ownEntry)}, '{"pid":${String(pid)},"home":"x"}')`]
107
+ expect(run(osHome, rewriteOwn).status).toBe(0)
108
+
109
+ const foreignEntry = join(osHome, '.acryl-instances', '.running', 'other.json')
110
+ const addForeign = write(foreignEntry)
111
+ const foreign = run(osHome, addForeign)
112
+ expect(foreign.status).toBe(1)
113
+ expect(foreign.output).toContain('other.json')
114
+ })
115
+ })
116
+
117
+ /** Keeps `file` open and appends to it, as a long-running database does. */
118
+ const holderSource = (file: string): string =>
119
+ `const fs = require('node:fs'); fs.mkdirSync(require('node:path').dirname(${JSON.stringify(file)}), { recursive: true }); const fd = fs.openSync(${JSON.stringify(file)}, 'a'); setInterval(() => fs.writeSync(fd, 'x'), 100)`
120
+
121
+ /** A process older than the gate that keeps writing `file`. The ages are compared in whole seconds, so it is given more than one. */
122
+ async function olderHolder(file: string): Promise<void> {
123
+ const child = spawn(process.execPath, ['-e', holderSource(file)], { stdio: 'ignore' })
124
+ cleanups.push(() => child.kill('SIGKILL'))
125
+ await new Promise(done => setTimeout(done, 2_200))
126
+ }
127
+
128
+ const pause = ['-e', 'setTimeout(() => {}, 1200)']
129
+
130
+ // lsof and ps -o lstart do not exist on Windows; there the guard excuses nothing, which fails safe.
131
+ describe.skipIf(process.platform === 'win32')('the real-home guard and processes older than the gate', () => {
132
+ it('excuses a file only a process older than the gate holds open, and names both', async () => {
133
+ const osHome = home()
134
+ const wal = join(osHome, '.dsh', 'state', 'superagent', 'orchestrator.sqlite-wal')
135
+ await olderHolder(wal)
136
+ const { status, output } = run(osHome, pause)
137
+ expect(output).toMatch(/real-home-guard: excused ~\/\.dsh\/state\/superagent\/orchestrator\.sqlite-wal: held open by pid \d+, older than this gate/)
138
+ expect(status).toBe(0)
139
+ }, 20_000)
140
+
141
+ it('still fails what the gate itself wrote while an older process writes beside it', async () => {
142
+ const osHome = home()
143
+ await olderHolder(join(osHome, '.dsh', 'state', 'superagent', 'orchestrator.sqlite-wal'))
144
+ const { status, output } = run(osHome, write(join(osHome, '.dsh', 'state', 'a-test-wrote-this.log')))
145
+ expect(output).toContain('a-test-wrote-this.log')
146
+ expect(status).toBe(1)
147
+ }, 20_000)
148
+
149
+ it('does not excuse a writer the gate started and left running', () => {
150
+ const osHome = home()
151
+ const file = join(osHome, '.dsh', 'state', 'leaked.log')
152
+ const leak = ['-e', `const { spawn } = require('node:child_process'); const c = spawn(process.execPath, ['-e', ${JSON.stringify(holderSource(file))}], { stdio: 'ignore', detached: true }); c.unref(); console.log('leaked-pid=' + c.pid); setTimeout(() => {}, 1200)`]
153
+ const { status, output } = run(osHome, leak)
154
+ const pid = Number(/leaked-pid=(\d+)/u.exec(output)?.[1])
155
+ if (pid > 0) cleanups.push(() => process.kill(pid, 'SIGKILL'))
156
+ expect(output).toContain('leaked.log')
157
+ expect(status).toBe(1)
158
+ }, 20_000)
159
+
160
+ it('excuses only a database file under ~/.dsh/state, so an older holder cannot excuse an arbitrary path', async () => {
161
+ for (const path of [join('.dsh', 'state', 'superagent', 'notes.log'), join('.dsh', 'orchestrator.sqlite-wal'), join('.acryl', 'state', 'orchestrator.sqlite-wal')]) {
162
+ const osHome = home()
163
+ await olderHolder(join(osHome, path))
164
+ const { status, output } = run(osHome, pause)
165
+ expect(output, path).not.toContain('excused')
166
+ expect(status, path).toBe(1)
167
+ }
168
+ }, 30_000)
169
+
170
+ it('never excuses a change in the Registry, whoever holds it', async () => {
171
+ const osHome = home()
172
+ const entry = join(osHome, '.acryl-instances', '.running', 'held.json')
173
+ await olderHolder(entry)
174
+ const { status, output } = run(osHome, pause)
175
+ expect(output).toContain('held.json')
176
+ expect(status).toBe(1)
177
+ }, 20_000)
178
+ })