@xingular/harness 0.0.0-stage → 0.1.1

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 (135) hide show
  1. package/README.md +269 -2
  2. package/dist/cli.js +11510 -0
  3. package/dist/terminal-pi.js +326 -0
  4. package/package.json +41 -4
  5. package/src/accounts/accounts.test.ts +223 -0
  6. package/src/accounts/accounts.ts +522 -0
  7. package/src/accounts/env.test.ts +95 -0
  8. package/src/accounts/env.ts +338 -0
  9. package/src/accounts/secrets.ts +50 -0
  10. package/src/accounts/store.ts +338 -0
  11. package/src/capabilities/api.ts +75 -0
  12. package/src/capabilities/runSnapshot.ts +59 -0
  13. package/src/capabilities/types.ts +34 -0
  14. package/src/cli.ts +110 -0
  15. package/src/core/bus.ts +34 -0
  16. package/src/core/changes.ts +33 -0
  17. package/src/core/env.ts +27 -0
  18. package/src/core/errors.ts +32 -0
  19. package/src/core/frontmatter.ts +47 -0
  20. package/src/core/fs.test.ts +38 -0
  21. package/src/core/fs.ts +92 -0
  22. package/src/core/index.ts +193 -0
  23. package/src/core/path.ts +45 -0
  24. package/src/core/projects.ts +90 -0
  25. package/src/core/text.ts +39 -0
  26. package/src/harness.ts +299 -0
  27. package/src/index.ts +70 -0
  28. package/src/mcp/connections.ts +614 -0
  29. package/src/mcp/manager.ts +130 -0
  30. package/src/mcp/oauth.ts +195 -0
  31. package/src/mcp/scopeMigration.ts +204 -0
  32. package/src/mcp/service.test.ts +376 -0
  33. package/src/mcp/service.ts +549 -0
  34. package/src/mcp/types.ts +108 -0
  35. package/src/memory/api.test.ts +82 -0
  36. package/src/memory/api.ts +289 -0
  37. package/src/memory/blocks.test.ts +78 -0
  38. package/src/memory/blocks.ts +406 -0
  39. package/src/memory/caller.ts +57 -0
  40. package/src/memory/dispatch.ts +59 -0
  41. package/src/memory/facts.test.ts +41 -0
  42. package/src/memory/facts.ts +248 -0
  43. package/src/memory/graph.ts +103 -0
  44. package/src/memory/health.test.ts +130 -0
  45. package/src/memory/health.ts +74 -0
  46. package/src/memory/maintainer.ts +272 -0
  47. package/src/memory/maintenance.test.ts +176 -0
  48. package/src/memory/maintenance.ts +330 -0
  49. package/src/memory/migrate.ts +79 -0
  50. package/src/memory/operations.ts +138 -0
  51. package/src/memory/proposals.test.ts +168 -0
  52. package/src/memory/proposals.ts +576 -0
  53. package/src/memory/recall.test.ts +104 -0
  54. package/src/memory/recall.ts +271 -0
  55. package/src/memory/references.ts +77 -0
  56. package/src/memory/runContext.ts +93 -0
  57. package/src/memory/secrets.ts +6 -0
  58. package/src/memory/store.test.ts +66 -0
  59. package/src/memory/store.ts +385 -0
  60. package/src/memory/wiki.test.ts +47 -0
  61. package/src/memory/wiki.ts +422 -0
  62. package/src/memory/wikiIndex.test.ts +88 -0
  63. package/src/memory/wikiIndex.ts +116 -0
  64. package/src/plugins/api.ts +181 -0
  65. package/src/plugins/attachments.test.ts +84 -0
  66. package/src/plugins/attachments.ts +141 -0
  67. package/src/plugins/builtin.ts +82 -0
  68. package/src/plugins/catalogue.test.ts +254 -0
  69. package/src/plugins/catalogue.ts +251 -0
  70. package/src/plugins/cli.ts +184 -0
  71. package/src/plugins/discover.ts +151 -0
  72. package/src/plugins/firstParty.test.ts +143 -0
  73. package/src/plugins/firstParty.ts +129 -0
  74. package/src/plugins/hooks.test.ts +250 -0
  75. package/src/plugins/hooks.ts +239 -0
  76. package/src/plugins/identity.ts +37 -0
  77. package/src/plugins/install.test.ts +107 -0
  78. package/src/plugins/install.ts +106 -0
  79. package/src/plugins/inventory.ts +123 -0
  80. package/src/plugins/manifest.ts +76 -0
  81. package/src/plugins/plugins.test.ts +205 -0
  82. package/src/plugins/plugins.ts +189 -0
  83. package/src/plugins/proposal.ts +121 -0
  84. package/src/plugins/runtime.test.ts +40 -0
  85. package/src/plugins/runtime.ts +82 -0
  86. package/src/plugins/trust.ts +142 -0
  87. package/src/plugins/types.ts +149 -0
  88. package/src/prompt/compile.test.ts +261 -0
  89. package/src/prompt/compile.ts +732 -0
  90. package/src/server/methods.ts +314 -0
  91. package/src/server/remote.ts +77 -0
  92. package/src/server/rpc.ts +116 -0
  93. package/src/server/serve.ts +28 -0
  94. package/src/server/server.test.ts +174 -0
  95. package/src/sessions/approvals.ts +118 -0
  96. package/src/sessions/contracts.ts +299 -0
  97. package/src/sessions/conversation.test.ts +150 -0
  98. package/src/sessions/extensionSession.test.ts +74 -0
  99. package/src/sessions/extensionUi.test.ts +65 -0
  100. package/src/sessions/extensionUi.ts +102 -0
  101. package/src/sessions/history.ts +51 -0
  102. package/src/sessions/lineageJoin.ts +75 -0
  103. package/src/sessions/policy.ts +32 -0
  104. package/src/sessions/pricing.ts +60 -0
  105. package/src/sessions/reasoningSummaries.ts +59 -0
  106. package/src/sessions/registry.ts +294 -0
  107. package/src/sessions/runIndex.ts +99 -0
  108. package/src/sessions/runStore.test.ts +152 -0
  109. package/src/sessions/runStore.ts +332 -0
  110. package/src/sessions/runner.ts +556 -0
  111. package/src/sessions/runtimeResources.test.ts +61 -0
  112. package/src/sessions/sessions.test.ts +434 -0
  113. package/src/sessions/sessions.ts +295 -0
  114. package/src/skills/registry.test.ts +104 -0
  115. package/src/skills/registry.ts +407 -0
  116. package/src/terminal/cli.ts +149 -0
  117. package/src/terminal/client.ts +74 -0
  118. package/src/terminal/controller.ts +227 -0
  119. package/src/terminal/piExtension.ts +208 -0
  120. package/src/terminal/pluginControl.test.ts +146 -0
  121. package/src/terminal/pluginMenu.ts +112 -0
  122. package/src/terminal/socket.ts +182 -0
  123. package/src/terminal/standalone.test.ts +115 -0
  124. package/src/terminal/standalone.ts +126 -0
  125. package/src/terminal/terminal.test.ts +302 -0
  126. package/src/terminal/terminals.ts +429 -0
  127. package/src/tools/askUser.ts +45 -0
  128. package/src/tools/definitions.ts +187 -0
  129. package/src/tools/memoryTools.ts +22 -0
  130. package/src/tools/pluginPropose.ts +41 -0
  131. package/src/tools/types.ts +36 -0
  132. package/src/web/safeRequest.ts +171 -0
  133. package/src/web/text.ts +53 -0
  134. package/src/web/tools.ts +134 -0
  135. package/src/web/web.test.ts +141 -0
@@ -0,0 +1,27 @@
1
+ // What every harness module is given: where the data lives, and what the embedding application
2
+ // knows that the harness does not.
3
+
4
+ /** Names the harness shows but does not own. Every lookup may answer `null`. */
5
+ export interface Directory {
6
+ /** An agent's display name. */
7
+ agentName(agentId: string): string | null
8
+ /** The agent a conversation belongs to, when the session id is not the agent's own id. */
9
+ sessionAgent(sessionId: string): string | null
10
+ }
11
+
12
+ /** The name used when an application gives none. */
13
+ export const DEFAULT_PRODUCT_NAME = 'Xingular Harness'
14
+
15
+ export const EMPTY_DIRECTORY: Directory = { agentName: () => null, sessionAgent: () => null }
16
+
17
+ export interface HarnessEnv {
18
+ /** The data root: `wiki/`, `registry/`, `runs/`, `config/`, `index.sqlite`. */
19
+ root: string
20
+ directory: Directory
21
+ /** How the harness names itself to a model and in the Wiki it creates. */
22
+ productName: string
23
+ }
24
+
25
+ export function createEnv(root: string, options: Partial<Omit<HarnessEnv, 'root'>> = {}): HarnessEnv {
26
+ return { root, directory: options.directory ?? EMPTY_DIRECTORY, productName: options.productName ?? DEFAULT_PRODUCT_NAME }
27
+ }
@@ -0,0 +1,32 @@
1
+ /** A typed failure: a stable code, a message a person can read, and an optional hint on what to do next. */
2
+ export class HarnessError extends Error {
3
+ readonly code: string
4
+ readonly retryHint: string | null
5
+
6
+ constructor(code: string, message: string, retryHint: string | null = null) {
7
+ super(message)
8
+ this.name = 'HarnessError'
9
+ this.code = code
10
+ this.retryHint = retryHint
11
+ }
12
+
13
+ withHint(hint: string): HarnessError {
14
+ return new HarnessError(this.code, this.message, hint)
15
+ }
16
+ }
17
+
18
+ export const invalid = (message: string): HarnessError => new HarnessError('invalid_request', message)
19
+ export const notFound = (what: string): HarnessError => new HarnessError('not_found', `${what} was not found.`)
20
+
21
+ export interface ErrorShape {
22
+ code: string
23
+ message: string
24
+ retryHint?: string | null
25
+ }
26
+
27
+ export function toErrorShape(error: unknown, fallbackCode = 'harness_error'): ErrorShape {
28
+ if (error instanceof HarnessError) return { code: error.code, message: error.message, retryHint: error.retryHint }
29
+ const code = (error as { code?: unknown } | null)?.code
30
+ if (error instanceof Error && typeof code === 'string' && code.startsWith('E')) return { code: 'io_error', message: error.message }
31
+ return { code: fallbackCode, message: error instanceof Error ? error.message : String(error) }
32
+ }
@@ -0,0 +1,47 @@
1
+ // Markdown files with a YAML frontmatter block (`---` … `---`), used by Wiki pages, facts, blocks and registry items.
2
+ import { parse as parseYaml, stringify } from 'yaml'
3
+
4
+ import { HarnessError } from './errors'
5
+
6
+ export function split(text: string): { yaml: string; body: string } | null {
7
+ const rest = text.startsWith('---\n') ? text.slice(4) : text.startsWith('---\r\n') ? text.slice(5) : null
8
+ if (rest === null) return null
9
+ const end = rest.indexOf('\n---')
10
+ if (end < 0) return null
11
+ return { yaml: rest.slice(0, end), body: rest.slice(end + 4).replace(/^[\r\n]+/, '') }
12
+ }
13
+
14
+ /** The frontmatter as a plain object and the body, or `null` when the block is missing or is not a mapping. */
15
+ export function parse(text: string): { front: Record<string, unknown>; body: string } | null {
16
+ const parts = split(text)
17
+ if (!parts) return null
18
+ try {
19
+ const front = parseYaml(parts.yaml)
20
+ if (!front || typeof front !== 'object' || Array.isArray(front)) return null
21
+ return { front: front as Record<string, unknown>, body: parts.body }
22
+ } catch {
23
+ return null
24
+ }
25
+ }
26
+
27
+ /** The text after a readable frontmatter block, or the whole text when there is none. */
28
+ export function bodyOf(text: string): string {
29
+ const parts = split(text)
30
+ if (!parts) return text
31
+ try {
32
+ parseYaml(parts.yaml)
33
+ return parts.body
34
+ } catch {
35
+ return text
36
+ }
37
+ }
38
+
39
+ export function serialize(front: Record<string, unknown>, body: string): string {
40
+ let yaml: string
41
+ try {
42
+ yaml = stringify(front, { lineWidth: 0 })
43
+ } catch (error) {
44
+ throw new HarnessError('invalid_data', error instanceof Error ? error.message : String(error))
45
+ }
46
+ return `---\n${yaml}---\n\n${body.trimEnd()}\n`
47
+ }
@@ -0,0 +1,38 @@
1
+ import { mkdtempSync, readdirSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+ import { expect, test } from 'vitest'
5
+
6
+ import { parse, serialize } from './frontmatter'
7
+ import { appendLine, readJson, readText, safeId, safeRelative, writeJson } from './fs'
8
+
9
+ test('atomic write replaces contents', () => {
10
+ const path = join(mkdtempSync(join(tmpdir(), 'harness-')), 'nested/value.json')
11
+ writeJson(path, { a: 1 })
12
+ writeJson(path, { a: 2 })
13
+ expect(readJson<{ a: number }>(path)?.a).toBe(2)
14
+ expect(readdirSync(dirname(path))).toHaveLength(1)
15
+ expect(readJson(join(dirname(path), 'missing.json'))).toBeNull()
16
+ })
17
+
18
+ test('rejects unsafe ids and paths', () => {
19
+ expect(safeId('abc-123')).toBe('abc-123')
20
+ expect(() => safeId('../x')).toThrow()
21
+ expect(safeRelative('src/main.rs')).toBe('src/main.rs')
22
+ expect(() => safeRelative('../secret')).toThrow()
23
+ expect(() => safeRelative('/etc/passwd')).toThrow()
24
+ })
25
+
26
+ test('appends whole lines', () => {
27
+ const path = join(mkdtempSync(join(tmpdir(), 'harness-')), 'log.md')
28
+ appendLine(path, 'one')
29
+ appendLine(path, 'two')
30
+ expect(readText(path)).toBe('one\ntwo\n')
31
+ })
32
+
33
+ test('frontmatter round-trips', () => {
34
+ const text = serialize({ id: 'a', title: 'Has: a colon', tags: ['x'] }, 'Body\n\n')
35
+ expect(text.startsWith('---\n')).toBe(true)
36
+ expect(parse(text)).toEqual({ front: { id: 'a', title: 'Has: a colon', tags: ['x'] }, body: 'Body\n' })
37
+ expect(parse('no frontmatter')).toBeNull()
38
+ })
package/src/core/fs.ts ADDED
@@ -0,0 +1,92 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from 'node:fs'
3
+ import { basename, dirname, isAbsolute, join, normalize, sep } from 'node:path'
4
+
5
+ import { HarnessError, invalid } from './errors'
6
+
7
+ /** Writes through a temporary sibling file and renames it into place so readers never see a partial file. */
8
+ export function atomicWrite(path: string, contents: string | Uint8Array): void {
9
+ const parent = dirname(path)
10
+ mkdirSync(parent, { recursive: true })
11
+ const temporary = join(parent, `.${basename(path)}.${randomUUID()}.tmp`)
12
+ const file = openSync(temporary, 'w')
13
+ try {
14
+ writeSync(file, contents as string)
15
+ fsyncSync(file)
16
+ } finally {
17
+ closeSync(file)
18
+ }
19
+ try {
20
+ renameSync(temporary, path)
21
+ } catch (error) {
22
+ rmSync(temporary, { force: true })
23
+ throw error
24
+ }
25
+ }
26
+
27
+ export function writeJson(path: string, value: unknown): void {
28
+ atomicWrite(path, `${JSON.stringify(value, null, 2)}\n`)
29
+ }
30
+
31
+ /** `null` when the file does not exist; a file that exists but does not parse is an error. */
32
+ export function readJson<T>(path: string): T | null {
33
+ let text: string
34
+ try {
35
+ text = readFileSync(path, 'utf8')
36
+ } catch (error) {
37
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
38
+ throw error
39
+ }
40
+ try {
41
+ return JSON.parse(text) as T
42
+ } catch (error) {
43
+ throw new HarnessError('invalid_data', `Stored data could not be read: ${error instanceof Error ? error.message : String(error)}`)
44
+ }
45
+ }
46
+
47
+ /** `readJson` for callers that treat an unreadable file like a missing one. */
48
+ export function readJsonOr<T>(path: string, fallback: T): T {
49
+ try {
50
+ return readJson<T>(path) ?? fallback
51
+ } catch {
52
+ return fallback
53
+ }
54
+ }
55
+
56
+ export function readText(path: string): string | null {
57
+ try {
58
+ return readFileSync(path, 'utf8')
59
+ } catch {
60
+ return null
61
+ }
62
+ }
63
+
64
+ export function appendLine(path: string, line: string): void {
65
+ let next = readText(path) ?? ''
66
+ if (next && !next.endsWith('\n')) next += '\n'
67
+ atomicWrite(path, `${next}${line}\n`)
68
+ }
69
+
70
+ /** Accepts only IDs that are safe as a single path segment. */
71
+ export function safeId(id: string): string {
72
+ if (id.length > 0 && id.length <= 128 && /^[A-Za-z0-9_-]+$/.test(id)) return id
73
+ throw invalid('Invalid identifier.')
74
+ }
75
+
76
+ /** Accepts a relative path that stays inside its base directory. */
77
+ export function safeRelative(path: string): string {
78
+ const parts = path.split(/[\\/]/)
79
+ if (!path || isAbsolute(path) || parts.some((part) => part === '' || part === '.' || part === '..')) {
80
+ throw invalid('Path must stay inside the working directory.')
81
+ }
82
+ return normalize(path).split(sep).join('/')
83
+ }
84
+
85
+ /** Millisecond UTC timestamp, the format every record uses. */
86
+ export function now(): string {
87
+ return new Date().toISOString()
88
+ }
89
+
90
+ export function newId(): string {
91
+ return randomUUID()
92
+ }
@@ -0,0 +1,193 @@
1
+ // Derived SQLite index at `<data root>/index.sqlite`: full-text search over every Wiki entry
2
+ // (pages, facts, blocks, registry skills/prompts/rules), links, sources, revisions, run
3
+ // metadata, and recall passages. Markdown, raw sources, revision manifests, registry files, and
4
+ // run files stay canonical; the index can always be deleted and rebuilt from them.
5
+ import { copyFileSync, existsSync, readdirSync, rmSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { DatabaseSync, type SQLInputValue } from 'node:sqlite'
8
+
9
+ import { HarnessError } from './errors'
10
+
11
+ /** Index migration 4: recall, the searchable record of conversations and runs. */
12
+ const RECALL_SCHEMA = `CREATE TABLE recall_runs (run_id TEXT PRIMARY KEY, passages INTEGER NOT NULL, status TEXT NOT NULL);
13
+ CREATE VIRTUAL TABLE recall_fts USING fts5(run_id UNINDEXED, seq UNINDEXED, role UNINDEXED, at UNINDEXED,
14
+ mode UNINDEXED, session_id UNINDEXED, project_id UNINDEXED, text, tokenize = 'unicode61 remove_diacritics 2');`
15
+
16
+ /** Ordered, append-only migrations. Each runs in one transaction; the file is backed up first. */
17
+ export const MIGRATIONS: readonly string[] = [
18
+ // 1: initial schema
19
+ `CREATE TABLE pages (scope TEXT NOT NULL, id TEXT NOT NULL, title TEXT NOT NULL, type TEXT NOT NULL,
20
+ updated_at TEXT, path TEXT NOT NULL, source_ids TEXT NOT NULL, PRIMARY KEY (scope, id));
21
+ CREATE VIRTUAL TABLE pages_fts USING fts5(scope UNINDEXED, id UNINDEXED, title, body, links, sources,
22
+ tokenize = 'unicode61 remove_diacritics 2');
23
+ CREATE TABLE links (scope TEXT NOT NULL, from_id TEXT NOT NULL, to_id TEXT NOT NULL, type TEXT NOT NULL);
24
+ CREATE INDEX links_to ON links (scope, to_id);
25
+ CREATE TABLE sources (scope TEXT NOT NULL, id TEXT NOT NULL, name TEXT NOT NULL, imported_at TEXT, version INTEGER,
26
+ PRIMARY KEY (scope, id));
27
+ CREATE TABLE revisions (scope TEXT NOT NULL, page_id TEXT NOT NULL, id TEXT NOT NULL, created_at TEXT, actor TEXT,
28
+ PRIMARY KEY (scope, id));
29
+ CREATE TABLE runs (id TEXT PRIMARY KEY, project_id TEXT, mode TEXT, harness TEXT, session_type TEXT,
30
+ session_id TEXT, status TEXT, started_at TEXT, ended_at TEXT);
31
+ CREATE INDEX runs_session ON runs (session_id, started_at);`,
32
+ // 2: accounts and token usage per run
33
+ `ALTER TABLE runs ADD COLUMN account_id TEXT;
34
+ CREATE INDEX runs_account ON runs (account_id, started_at);
35
+ CREATE TABLE usage (run_id TEXT PRIMARY KEY, account_id TEXT, harness TEXT, model TEXT, day TEXT NOT NULL,
36
+ input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0);
37
+ CREATE INDEX usage_account ON usage (account_id, day);`,
38
+ // 3: one global Wiki; entries replace per-scope pages and include facts and registry items
39
+ `DROP TABLE IF EXISTS pages_fts; DROP TABLE IF EXISTS pages; DROP TABLE IF EXISTS links;
40
+ DROP TABLE IF EXISTS sources; DROP TABLE IF EXISTS revisions;
41
+ CREATE TABLE entries (id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, type TEXT, path TEXT NOT NULL,
42
+ namespace TEXT NOT NULL, file TEXT NOT NULL, updated_at TEXT, source_ids TEXT NOT NULL);
43
+ CREATE VIRTUAL TABLE entries_fts USING fts5(id UNINDEXED, kind UNINDEXED, namespace UNINDEXED, title, body, links, sources,
44
+ tokenize = 'unicode61 remove_diacritics 2');
45
+ CREATE TABLE links (from_id TEXT NOT NULL, to_id TEXT NOT NULL, type TEXT NOT NULL);
46
+ CREATE INDEX links_to ON links (to_id);
47
+ CREATE TABLE sources (id TEXT PRIMARY KEY, name TEXT NOT NULL, imported_at TEXT, version INTEGER);
48
+ CREATE TABLE revisions (entry_id TEXT NOT NULL, id TEXT PRIMARY KEY, created_at TEXT, actor TEXT);
49
+ CREATE INDEX revisions_entry ON revisions (entry_id, created_at);`,
50
+ RECALL_SCHEMA,
51
+ // 5: a per-run summary cache for the embedding application's analytics
52
+ `CREATE TABLE run_stats (run_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, version INTEGER NOT NULL, stats TEXT NOT NULL);
53
+ CREATE INDEX run_stats_session ON run_stats (session_id, version);`,
54
+ // 6: the agent that replied, so one agent's runs can be read across its sessions
55
+ `ALTER TABLE runs ADD COLUMN agent_id TEXT;
56
+ CREATE INDEX runs_agent ON runs (agent_id, started_at);
57
+ CREATE INDEX runs_started ON runs (started_at);`,
58
+ // 7: the per-account usage table goes
59
+ 'DROP TABLE IF EXISTS usage;'
60
+ ]
61
+
62
+ const connections = new Map<string, DatabaseSync>()
63
+
64
+ export function dbPath(root: string): string {
65
+ return join(root, 'index.sqlite')
66
+ }
67
+
68
+ function sqlError(error: unknown): HarnessError {
69
+ return new HarnessError('index_error', error instanceof Error ? error.message : String(error), 'Settings → Projects and Storage → Repair index.')
70
+ }
71
+
72
+ function schemaVersion(database: DatabaseSync): number {
73
+ database.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);')
74
+ const row = database.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get() as { value?: string } | undefined
75
+ const version = Number.parseInt(row?.value ?? '', 10)
76
+ return Number.isInteger(version) && version >= 0 ? version : 0
77
+ }
78
+
79
+ /** Runs `work` inside one transaction, rolling back if it throws. */
80
+ export function transaction<T>(database: DatabaseSync, work: () => T): T {
81
+ database.exec('BEGIN')
82
+ try {
83
+ const result = work()
84
+ database.exec('COMMIT')
85
+ return result
86
+ } catch (error) {
87
+ try {
88
+ database.exec('ROLLBACK')
89
+ } catch {
90
+ // The transaction is already gone.
91
+ }
92
+ throw error
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Applies pending migrations. The database file is copied first; if any migration fails, the
98
+ * copy is restored and the error is reported.
99
+ */
100
+ export function migrate(path: string, migrations: readonly string[]): DatabaseSync {
101
+ let database: DatabaseSync
102
+ let current: number
103
+ try {
104
+ database = new DatabaseSync(path)
105
+ current = schemaVersion(database)
106
+ } catch (error) {
107
+ throw sqlError(error)
108
+ }
109
+ if (current >= migrations.length) return database
110
+ const backup = `${path.replace(/\.sqlite$/, '')}.sqlite.bak-v${current}`
111
+ const hadFile = existsSync(path) && current > 0
112
+ if (hadFile) {
113
+ try {
114
+ database.exec('PRAGMA wal_checkpoint(TRUNCATE);')
115
+ } catch {
116
+ // A checkpoint that cannot run leaves the copy slightly behind, which a rebuild repairs.
117
+ }
118
+ copyFileSync(path, backup)
119
+ }
120
+ for (let index = current; index < migrations.length; index += 1) {
121
+ try {
122
+ transaction(database, () => {
123
+ database.exec(migrations[index])
124
+ database.prepare("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(index + 1))
125
+ })
126
+ } catch (error) {
127
+ database.close()
128
+ if (hadFile) copyFileSync(backup, path)
129
+ else rmSync(path, { force: true })
130
+ throw new HarnessError('migration_failed', `Index migration ${index + 1} failed and the previous index was restored: ${error instanceof Error ? error.message : String(error)}`)
131
+ }
132
+ }
133
+ return database
134
+ }
135
+
136
+ /** Runs `work` with the shared connection for this data root, opening and migrating it on first use. */
137
+ export function withIndex<T>(root: string, work: (database: DatabaseSync) => T): T {
138
+ const path = dbPath(root)
139
+ let database = connections.get(path)
140
+ if (!database) {
141
+ database = migrate(path, MIGRATIONS)
142
+ try {
143
+ database.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;')
144
+ } catch (error) {
145
+ database.close()
146
+ throw sqlError(error)
147
+ }
148
+ connections.set(path, database)
149
+ }
150
+ try {
151
+ return work(database)
152
+ } catch (error) {
153
+ throw error instanceof HarnessError ? error : sqlError(error)
154
+ }
155
+ }
156
+
157
+ /** Closes this data root's connection, if one is open. */
158
+ export function closeIndex(root: string): void {
159
+ const path = dbPath(root)
160
+ connections.get(path)?.close()
161
+ connections.delete(path)
162
+ }
163
+
164
+ /** Closes the connection and removes the index files; the next use rebuilds the schema. */
165
+ export function deleteIndex(root: string): void {
166
+ closeIndex(root)
167
+ for (const suffix of ['', '-wal', '-shm']) rmSync(`${dbPath(root)}${suffix}`, { force: true })
168
+ }
169
+
170
+ export type Param = SQLInputValue
171
+
172
+ export function all<T>(database: DatabaseSync, sql: string, ...params: Param[]): T[] {
173
+ return database.prepare(sql).all(...params) as T[]
174
+ }
175
+
176
+ export function run(database: DatabaseSync, sql: string, ...params: Param[]): void {
177
+ database.prepare(sql).run(...params)
178
+ }
179
+
180
+ /** Folder names under `<data root>/runs`. */
181
+ export function runFolders(root: string): string[] {
182
+ try {
183
+ return readdirSync(join(root, 'runs'))
184
+ } catch {
185
+ return []
186
+ }
187
+ }
188
+
189
+ /** Turns free text into an FTS5 query: each word becomes a quoted prefix term. */
190
+ export function ftsQuery(query: string): string | null {
191
+ const terms = query.split(/[^\p{Alphabetic}\p{N}]+/u).filter(Boolean).map((term) => `"${term.replaceAll('"', '')}"*`)
192
+ return terms.length ? terms.join(' ') : null
193
+ }
@@ -0,0 +1,45 @@
1
+ // Where executables are found. A desktop application starts with a minimal PATH, so the login
2
+ // shell's PATH is resolved once and used for everything the harness launches.
3
+ import { execFileSync } from 'node:child_process'
4
+ import { accessSync, constants, statSync } from 'node:fs'
5
+ import { homedir } from 'node:os'
6
+ import { delimiter, isAbsolute, join } from 'node:path'
7
+
8
+ let resolved: string | null = null
9
+
10
+ export function searchPath(): string {
11
+ if (resolved !== null) return resolved
12
+ const entries: string[] = []
13
+ try {
14
+ const output = execFileSync(process.env.SHELL || '/bin/zsh', ['-ilc', 'printf %s "$PATH"'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })
15
+ // Interactive shells may print banners; the PATH is the last line.
16
+ entries.push(...(output.split('\n').filter(Boolean).at(-1) ?? '').split(delimiter))
17
+ } catch {
18
+ // The inherited PATH and the usual folders still apply.
19
+ }
20
+ entries.push(...(process.env.PATH ?? '').split(delimiter))
21
+ const home = homedir()
22
+ if (home) entries.push(...['.local/bin', '.bun/bin', '.npm-global/bin', '.cargo/bin'].map((folder) => join(home, folder)))
23
+ entries.push('/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin')
24
+ resolved = [...new Set(entries.filter(Boolean))].join(delimiter)
25
+ return resolved
26
+ }
27
+
28
+ function isExecutable(path: string): boolean {
29
+ try {
30
+ accessSync(path, constants.X_OK)
31
+ return statSync(path).isFile()
32
+ } catch {
33
+ return false
34
+ }
35
+ }
36
+
37
+ /** The executable `name` resolves to: itself when absolute, else the first match on the search path. */
38
+ export function findBinary(name: string): string | null {
39
+ if (isAbsolute(name)) return isExecutable(name) ? name : null
40
+ for (const directory of searchPath().split(delimiter)) {
41
+ const candidate = join(directory, name)
42
+ if (isExecutable(candidate)) return candidate
43
+ }
44
+ return null
45
+ }
@@ -0,0 +1,90 @@
1
+ // Projects: named working folders, each with a Wiki namespace (`/projects/<slug>`). The harness
2
+ // reads `<data root>/projects.json`; the embedding application adds, renames, and removes them.
3
+ import { existsSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+
6
+ import { notFound } from './errors'
7
+ import { readJson } from './fs'
8
+ import { newId } from './fs'
9
+
10
+ interface ProjectRecord {
11
+ id: string
12
+ name: string
13
+ rootPath: string
14
+ autoMaintenance: boolean
15
+ createdAt: string
16
+ /** Stable Wiki namespace segment; kept when the project is renamed. */
17
+ slug?: string
18
+ }
19
+
20
+ export interface Project {
21
+ id: string
22
+ name: string
23
+ rootPath: string
24
+ isGitRepository: boolean
25
+ autoMaintenance: boolean
26
+ createdAt: string
27
+ slug: string
28
+ /** `/projects/<slug>`: where this project's pages live in the Wiki. */
29
+ wikiNamespace: string
30
+ }
31
+
32
+ /** Same rule as the Wiki's page slugs, kept here so `core` does not depend on `memory`. */
33
+ export function slugify(text: string): string {
34
+ let value = ''
35
+ for (const character of text.toLowerCase()) {
36
+ if (/^[a-z0-9]$/.test(character)) value += character
37
+ else if (value && !value.endsWith('-')) value += '-'
38
+ }
39
+ value = value.replace(/^-+|-+$/g, '').slice(0, 60)
40
+ return value || `page-${newId().slice(0, 8)}`
41
+ }
42
+
43
+ export function uniqueSlug(name: string, taken: readonly string[]): string {
44
+ const slug = slugify(name)
45
+ const base = slug.startsWith('page-') ? 'project' : slug
46
+ let candidate = base
47
+ for (let counter = 2; taken.includes(candidate); counter += 1) candidate = `${base}-${counter}`
48
+ return candidate
49
+ }
50
+
51
+ function load(root: string): ProjectRecord[] {
52
+ const records = readJson<ProjectRecord[]>(join(root, 'projects.json')) ?? []
53
+ // Records without a slug get a unique one derived from the name, in list order, so the result
54
+ // is the same on every read until the application persists it.
55
+ const taken = records.map((record) => record.slug ?? '').filter(Boolean)
56
+ for (const record of records) {
57
+ if (record.slug) continue
58
+ record.slug = uniqueSlug(record.name, taken)
59
+ taken.push(record.slug)
60
+ }
61
+ return records
62
+ }
63
+
64
+ export function listProjects(root: string): Project[] {
65
+ return load(root).map((record) => ({
66
+ id: record.id,
67
+ name: record.name,
68
+ rootPath: record.rootPath,
69
+ isGitRepository: existsSync(join(record.rootPath, '.git')),
70
+ autoMaintenance: record.autoMaintenance,
71
+ createdAt: record.createdAt,
72
+ slug: record.slug!,
73
+ wikiNamespace: `/projects/${record.slug}`
74
+ }))
75
+ }
76
+
77
+ /** `listProjects` for callers that treat an unreadable registry like an empty one. */
78
+ export function projectsOrNone(root: string): Project[] {
79
+ try {
80
+ return listProjects(root)
81
+ } catch {
82
+ return []
83
+ }
84
+ }
85
+
86
+ export function findProject(root: string, projectId: string): Project {
87
+ const project = listProjects(root).find((entry) => entry.id === projectId)
88
+ if (!project) throw notFound('Project')
89
+ return project
90
+ }
@@ -0,0 +1,39 @@
1
+ // Text helpers that count Unicode characters, not UTF-16 units, so budgets and cuts agree across languages.
2
+
3
+ export function charCount(text: string): number {
4
+ let count = 0
5
+ for (const _ of text) count += 1
6
+ return count
7
+ }
8
+
9
+ export function takeChars(text: string, count: number): string {
10
+ if (text.length <= count) return text
11
+ let taken = 0
12
+ let end = 0
13
+ for (const character of text) {
14
+ if (taken >= count) break
15
+ taken += 1
16
+ end += character.length
17
+ }
18
+ return text.slice(0, end)
19
+ }
20
+
21
+ /** Lines without their terminators; a final newline does not add an empty last line. */
22
+ export function lines(text: string): string[] {
23
+ if (!text) return []
24
+ const parts = text.split('\n')
25
+ if (parts[parts.length - 1] === '') parts.pop()
26
+ return parts.map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line))
27
+ }
28
+
29
+ /** Orders file paths segment by segment, so a folder sorts before a sibling whose name extends it. */
30
+ export function comparePaths(left: string, right: string): number {
31
+ const a = left.split('/')
32
+ const b = right.split('/')
33
+ for (let index = 0; index < Math.min(a.length, b.length); index += 1) {
34
+ if (a[index] !== b[index]) return a[index] < b[index] ? -1 : 1
35
+ }
36
+ return a.length - b.length
37
+ }
38
+
39
+ export const compareText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0)