opencode-growth 0.1.0

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.
@@ -0,0 +1,96 @@
1
+ // Candidate state machine (R1 §1.4): proposed -> validated | rejected.
2
+ //
3
+ // A candidate is never knowledge. Only the writer turns a validated candidate into a
4
+ // published record. Candidates carry their evidence reference so provenance survives.
5
+ import fs from "node:fs"
6
+ import path from "node:path"
7
+ import { candidateId, nowIso } from "./ids.mjs"
8
+
9
+ const TERMINAL = new Set(["published", "rejected"])
10
+
11
+ function fileFor(L, id) {
12
+ return path.join(L.candidates, `${id}.json`)
13
+ }
14
+
15
+ export function createCandidate(L, input) {
16
+ const id = candidateId()
17
+ const cand = {
18
+ id,
19
+ status: "proposed",
20
+ createdAt: nowIso(),
21
+ updatedAt: nowIso(),
22
+ kind: input.kind,
23
+ semanticKey: input.semanticKey,
24
+ title: input.title ?? null,
25
+ body: input.body,
26
+ scope: input.scope,
27
+ evidenceIds: input.evidenceIds ?? [],
28
+ source: input.source ?? null,
29
+ origin: input.origin ?? "unknown", // "user-correction" | "review-session" | "import"
30
+ supersedes: input.supersedes ?? [],
31
+ review: { state: "unreviewed", reviewedAt: null, reviewedBy: null },
32
+ }
33
+ fs.mkdirSync(L.candidates, { recursive: true })
34
+ fs.writeFileSync(fileFor(L, id), JSON.stringify(cand, null, 2) + "\n")
35
+ return cand
36
+ }
37
+
38
+ export function readCandidate(L, id) {
39
+ try {
40
+ return JSON.parse(fs.readFileSync(fileFor(L, id), "utf8"))
41
+ } catch {
42
+ return null
43
+ }
44
+ }
45
+
46
+ export function writeCandidate(L, cand) {
47
+ cand.updatedAt = nowIso()
48
+ const tmp = `${fileFor(L, cand.id)}.tmp`
49
+ fs.writeFileSync(tmp, JSON.stringify(cand, null, 2) + "\n")
50
+ fs.renameSync(tmp, fileFor(L, cand.id))
51
+ return cand
52
+ }
53
+
54
+ export function listCandidates(L, { status } = {}) {
55
+ let names = []
56
+ try {
57
+ names = fs.readdirSync(L.candidates).filter((n) => n.endsWith(".json"))
58
+ } catch {
59
+ return []
60
+ }
61
+ const out = []
62
+ for (const n of names) {
63
+ try {
64
+ const c = JSON.parse(fs.readFileSync(path.join(L.candidates, n), "utf8"))
65
+ if (!status || c.status === status) out.push(c)
66
+ } catch {}
67
+ }
68
+ return out.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
69
+ }
70
+
71
+ export function validateCandidate(L, id) {
72
+ const c = readCandidate(L, id)
73
+ if (!c) return { ok: false, reason: "not-found" }
74
+ if (TERMINAL.has(c.status)) return { ok: false, reason: `terminal:${c.status}` }
75
+ c.status = "validated"
76
+ c.review = { state: "schema-validated", reviewedAt: nowIso(), reviewedBy: null }
77
+ return { ok: true, candidate: writeCandidate(L, c) }
78
+ }
79
+
80
+ export function rejectCandidate(L, id, reason) {
81
+ const c = readCandidate(L, id)
82
+ if (!c) return { ok: false, reason: "not-found" }
83
+ if (TERMINAL.has(c.status)) return { ok: false, reason: `terminal:${c.status}` }
84
+ c.status = "rejected"
85
+ c.review = { state: "rejected", reviewedAt: nowIso(), reviewedBy: null, note: reason ?? null }
86
+ return { ok: true, candidate: writeCandidate(L, c) }
87
+ }
88
+
89
+ export function markPublished(L, id, recordId) {
90
+ const c = readCandidate(L, id)
91
+ if (!c) return { ok: false, reason: "not-found" }
92
+ c.status = "published"
93
+ c.publishedRecordId = recordId
94
+ c.review = { ...c.review, state: "published", reviewedAt: nowIso() }
95
+ return { ok: true, candidate: writeCandidate(L, c) }
96
+ }
@@ -0,0 +1,61 @@
1
+ // 数据 home 的解析(对齐 Hermes `hermes_constants.py::_get_platform_default_hermes_home`)。
2
+ //
3
+ // 规则(逐条照 Hermes):
4
+ // · Windows(win32)→ `%LOCALAPPDATA%\opencode-growth`;LOCALAPPDATA 缺失则 `~/AppData/Local/opencode-growth`
5
+ // · 其他一切平台(linux/darwin/…)→ `~/.opencode-growth`(**macOS 不特殊处理**)
6
+ // · 解析顺序 = **显式 override → 环境变量 → 平台默认**
7
+ // · WSL 只在**行为/提示**上分支(`isWsl`),不改路径规则
8
+ //
9
+ // 与 Hermes 的差别只在目录名(hermes → opencode-growth),机制一致。
10
+ //
11
+ // **fail closed**:拿不到唯一根(家目录未知、值全是空白)⇒ 返回 `null`,
12
+ // 由调用方停下来要信息——**不许猜一个目录写进去**(多配置根串用是数据正确性级问题)。
13
+
14
+ const DIR_NAME = "opencode-growth"
15
+ const ENV_VAR = "OCG_HOME"
16
+
17
+ const clean = (v) => (typeof v === "string" && v.trim() ? v.trim() : null)
18
+
19
+ /** WSL 判定(`/proc/version` 含 microsoft)。只影响行为/提示,不影响路径。 */
20
+ export function isWsl({ procVersion = "" } = {}) {
21
+ return /microsoft/i.test(String(procVersion))
22
+ }
23
+
24
+ /** 平台默认 home(不读环境变量、不看 override)。 */
25
+ export function platformDefaultHome({ platform = process.platform, env = {}, homeDir = null } = {}) {
26
+ if (platform === "win32") {
27
+ const base = clean(env.LOCALAPPDATA) ?? (clean(homeDir) ? `${clean(homeDir)}\\AppData\\Local` : null)
28
+ return base ? `${base}\\${DIR_NAME}` : null
29
+ }
30
+ // 照 Hermes:POSIX 用点目录(~/.hermes ↔ ~/.opencode-growth),Windows 不用点(%LOCALAPPDATA%\hermes)
31
+ const home = clean(homeDir)
32
+ return home ? `${home}/.${DIR_NAME}` : null
33
+ }
34
+
35
+ /** 完整解析顺序:override → 环境变量 → 平台默认;拿不到 ⇒ null(不猜)。 */
36
+ export function resolveStoreHome({ platform = process.platform, env = {}, homeDir = null, override = null } = {}) {
37
+ const hi = clean(override)
38
+ if (hi) return hi
39
+ const fromEnv = clean(env?.[ENV_VAR])
40
+ if (fromEnv) return fromEnv
41
+ return platformDefaultHome({ platform, env, homeDir })
42
+ }
43
+
44
+
45
+ /**
46
+ * **安装器**用的解析(照 `docs/PENDING-STAGE4.md` §1:安装器与运行时同一规则;CLI 仍无默认)。
47
+ * · 调用方给了 store ⇒ `source: "explicit"`
48
+ * · 否则 `$OCG_HOME` ⇒ `source: "env"`
49
+ * · 否则平台默认 ⇒ `source: "default"`
50
+ * · 都拿不到 ⇒ `store: null`(调用方必须报错,不许猜)
51
+ * 注意:**CLI 不调用本函数**——`oc-grow` 始终要求 `--store`/`$OCG_STORE`;
52
+ * 运行时(插件)也不自己挑目录,它用安装器写进 shim 的那一个。
53
+ */
54
+ export function resolveInstallStore({ override = null, platform = process.platform, env = {}, homeDir = null } = {}) {
55
+ const hi = clean(override)
56
+ if (hi) return { store: hi, source: "explicit" }
57
+ const fromEnv = clean(env?.[ENV_VAR])
58
+ if (fromEnv) return { store: fromEnv, source: "env" }
59
+ const dflt = platformDefaultHome({ platform, env, homeDir })
60
+ return { store: dflt, source: dflt ? "default" : null }
61
+ }
@@ -0,0 +1,100 @@
1
+ // Project identity + the three orthogonal record dimensions (R1 §1.1–§1.2).
2
+ //
3
+ // The review's hardest finding: a single `scope` field cannot express "which project does
4
+ // this apply to". Governance / visibility / applicability are separate axes.
5
+ import fs from "node:fs"
6
+ import path from "node:path"
7
+ import { shortHash } from "./ids.mjs"
8
+ import { GOVERNANCE, KINDS, VISIBILITY } from "./paths.mjs"
9
+
10
+ /** Walk up to the repo root. A `.git` *file* means a worktree (see below). */
11
+ export function findRepoRoot(startDir) {
12
+ let dir = path.resolve(startDir)
13
+ for (;;) {
14
+ const gitDir = path.join(dir, ".git")
15
+ if (fs.existsSync(gitDir)) {
16
+ const isFile = fs.statSync(gitDir).isFile()
17
+ return { root: dir, worktree: isFile }
18
+ }
19
+ const parent = path.dirname(dir)
20
+ if (parent === dir) return { root: path.resolve(startDir), worktree: false }
21
+ dir = parent
22
+ }
23
+ }
24
+
25
+ function loadRegistry(projectsPath) {
26
+ try {
27
+ return JSON.parse(fs.readFileSync(projectsPath, "utf8"))
28
+ } catch {
29
+ return { projects: {} }
30
+ }
31
+ }
32
+
33
+ function saveRegistry(projectsPath, reg) {
34
+ fs.mkdirSync(path.dirname(projectsPath), { recursive: true })
35
+ const tmp = `${projectsPath}.${process.pid}.tmp`
36
+ fs.writeFileSync(tmp, JSON.stringify(reg, null, 2) + "\n")
37
+ fs.renameSync(tmp, projectsPath)
38
+ }
39
+
40
+ /**
41
+ * Map a working directory to a stable project id.
42
+ * - never derived from the提炼 model, never from a mutable cwd string alone
43
+ * - realpath'd, so symlinks and `..` do not mint duplicate ids
44
+ * - worktrees are ISOLATED by default (R1: rather under-recall than cross projects)
45
+ */
46
+ export function resolveProject(cwd, projectsPath, opts = {}) {
47
+ const { root, worktree } = findRepoRoot(cwd)
48
+ let canonical
49
+ try {
50
+ canonical = fs.realpathSync(root)
51
+ } catch {
52
+ canonical = path.resolve(root)
53
+ }
54
+ const key = worktree ? `${canonical}#worktree` : canonical
55
+
56
+ const reg = loadRegistry(projectsPath)
57
+ if (!reg.projects[key]) {
58
+ reg.projects[key] = {
59
+ id: `proj_${shortHash(key)}`,
60
+ path: canonical,
61
+ worktree: Boolean(worktree),
62
+ linkedTo: null,
63
+ createdAt: new Date().toISOString(),
64
+ }
65
+ saveRegistry(projectsPath, reg)
66
+ }
67
+ const entry = reg.projects[key]
68
+
69
+ // Explicit link: the user decided this worktree belongs to a known project, so it shares
70
+ // that project's memory. Without an explicit link a worktree stays isolated (R1 §1.2).
71
+ if (worktree && opts.linkWorktree && entry.linkedTo !== opts.linkWorktree) {
72
+ entry.linkedTo = opts.linkWorktree
73
+ saveRegistry(projectsPath, reg)
74
+ }
75
+ if (worktree && entry.linkedTo) {
76
+ return { projectId: entry.linkedTo, canonicalPath: canonical, worktree: true, key, linked: true }
77
+ }
78
+ return { projectId: entry.id, canonicalPath: canonical, worktree, key, linked: false }
79
+ }
80
+
81
+ /** Validate + normalise the three axes. Throws on anything ambiguous rather than guessing. */
82
+ export function makeScope(input) {
83
+ const problems = []
84
+ if (!GOVERNANCE.includes(input.governance)) problems.push(`governance must be one of ${GOVERNANCE}`)
85
+ if (!KINDS.includes(input.kind)) problems.push(`kind must be one of ${KINDS}`)
86
+
87
+ if (problems.length) throw new Error(`invalid scope: ${problems.join("; ")}`)
88
+
89
+ const appliesWhen = input.appliesWhen ?? {}
90
+ return {
91
+ governance: input.governance,
92
+ kind: input.kind,
93
+ ownerId: input.visibility === "personal" ? input.ownerId : null,
94
+ appliesWhen: {
95
+ environmentId: appliesWhen.environmentId ?? null,
96
+ platform: appliesWhen.platform ?? null,
97
+ expiresAt: appliesWhen.expiresAt ?? null,
98
+ },
99
+ }
100
+ }
@@ -0,0 +1,22 @@
1
+ // Identity, hashing and time helpers. Pure functions only.
2
+ import { createHash, randomUUID } from "node:crypto"
3
+
4
+ export const sha256 = (buf) => createHash("sha256").update(buf).digest("hex")
5
+
6
+ export const shortHash = (buf) => sha256(buf).slice(0, 12)
7
+
8
+ /** Stable id for a record. Deterministic on (kind, semantic key) so re-learning the same
9
+ * fact converges on the same id instead of creating a twin (see R1 §1.5: duplicates must
10
+ * surface as conflicts, never as silent duplicates). */
11
+ export function recordId(kind, semanticKey) {
12
+ const key = String(semanticKey).trim().toLowerCase()
13
+ return `${kind}_${shortHash(`${kind}\u0000${key}`)}`
14
+ }
15
+
16
+ export const candidateId = () => `cand_${randomUUID().replace(/-/g, "").slice(0, 20)}`
17
+ export const evidenceId = () => `ev_${randomUUID().replace(/-/g, "").slice(0, 20)}`
18
+ export const txId = () => `tx_${Date.now().toString(36)}_${randomUUID().replace(/-/g, "").slice(0, 8)}`
19
+ export const jobId = () => `job_${Date.now().toString(36)}_${randomUUID().replace(/-/g, "").slice(0, 8)}`
20
+
21
+ export const nowIso = () => new Date().toISOString()
22
+ export const nowMs = () => Date.now()
@@ -0,0 +1,107 @@
1
+ // Cross-process commit lock (R4 §3.2).
2
+ //
3
+ // Design constraints from the review:
4
+ // - never release a lock by "it looks expired" alone -> lease + fencing token
5
+ // - a stale owner must not be able to write after being fenced out
6
+ // - bounded wait, explicit busy status instead of blocking forever
7
+ import fs from "node:fs"
8
+ import path from "node:path"
9
+ import { randomUUID } from "node:crypto"
10
+
11
+ const DEFAULT_LEASE_MS = 15_000
12
+ const DEFAULT_WAIT_MS = 5_000
13
+ const POLL_MS = 40
14
+
15
+ function readOwner(lockPath) {
16
+ try {
17
+ return JSON.parse(fs.readFileSync(path.join(lockPath, "owner.json"), "utf8"))
18
+ } catch {
19
+ return null
20
+ }
21
+ }
22
+
23
+ function tryAcquire(lockPath, meta) {
24
+ try {
25
+ fs.mkdirSync(lockPath)
26
+ } catch (e) {
27
+ if (e.code === "EEXIST") return false
28
+ throw e
29
+ }
30
+ fs.writeFileSync(path.join(lockPath, "owner.json"), JSON.stringify(meta))
31
+ return true
32
+ }
33
+
34
+ /** Take over a lock whose lease has expired. Returns the new owner meta, or null if the
35
+ * holder looks alive or someone else won the race. */
36
+ function stealIfExpired(lockPath, base) {
37
+ const owner = readOwner(lockPath)
38
+ const now = Date.now()
39
+ if (owner && typeof owner.expiresAt === "number" && owner.expiresAt > now) return null
40
+ // Fencing: every takeover gets a strictly larger token than anything we can observe.
41
+ const fencing = Math.max(base.fencing, (owner?.fencing ?? 0) + 1)
42
+ const meta = { ...base, fencing, stolenFrom: owner?.token ?? null, acquiredAt: now, expiresAt: now + base.leaseMs }
43
+ try {
44
+ fs.rmSync(lockPath, { recursive: true, force: true })
45
+ } catch {}
46
+ if (!tryAcquire(lockPath, meta)) return null
47
+ return meta
48
+ }
49
+
50
+ /**
51
+ * Run `fn` while holding the store commit lock.
52
+ * `fn` receives { fencing, assertStillOwner } and must finish fast (no LLM calls inside).
53
+ * Returns { ok: true, value } or { ok: false, reason: "busy" | "lost" }.
54
+ */
55
+ export function withCommitLock(lockPath, fn, opts = {}) {
56
+ const leaseMs = opts.leaseMs ?? DEFAULT_LEASE_MS
57
+ const waitMs = opts.waitMs ?? DEFAULT_WAIT_MS
58
+ const base = {
59
+ pid: process.pid,
60
+ token: randomUUID(),
61
+ leaseMs,
62
+ fencing: (opts.baseFencing ?? 0) + 1,
63
+ }
64
+
65
+ const deadline = Date.now() + waitMs
66
+ let meta = null
67
+ while (Date.now() <= deadline) {
68
+ const candidate = { ...base, acquiredAt: Date.now(), expiresAt: Date.now() + leaseMs }
69
+ if (tryAcquire(lockPath, candidate)) { meta = candidate; break }
70
+ const stolen = stealIfExpired(lockPath, base)
71
+ if (stolen) { meta = stolen; break }
72
+ // Bounded synchronous wait. Callers are short-lived CLI/plugin operations.
73
+ const until = Math.min(Date.now() + POLL_MS, deadline)
74
+ while (Date.now() < until) { /* spin */ }
75
+ }
76
+ if (!meta) return { ok: false, reason: "busy" }
77
+
78
+ // 回调**必须是同步的**(A6 实测):锁在 `fn` 返回时就释放,而 async 回调在第一个 `await`
79
+ // 处就返回了 ⇒ 锁在 await 之后不再保护任何东西,调用方却以为自己持锁。fail-closed。
80
+ if (fn.constructor && fn.constructor.name === "AsyncFunction") {
81
+ throw new TypeError("withCommitLock 的回调必须是同步函数:锁在回调返回时释放,async 回调会在第一个 await 后失去保护(见 A6/C28)")
82
+ }
83
+
84
+ const assertStillOwner = () => {
85
+ const owner = readOwner(lockPath)
86
+ return !!owner && owner.token === meta.token
87
+ }
88
+
89
+ try {
90
+ const value = fn({ fencing: meta.fencing, assertStillOwner })
91
+ if (!assertStillOwner()) return { ok: false, reason: "lost" }
92
+ return { ok: true, value, fencing: meta.fencing }
93
+ } finally {
94
+ if (assertStillOwner()) {
95
+ try { fs.rmSync(lockPath, { recursive: true, force: true }) } catch {}
96
+ }
97
+ }
98
+ }
99
+
100
+ /** Release without running anything (used by crash-recovery tooling). */
101
+ export function forceRelease(lockPath) {
102
+ fs.rmSync(lockPath, { recursive: true, force: true })
103
+ }
104
+
105
+ export function lockInfo(lockPath) {
106
+ return readOwner(lockPath)
107
+ }