minicode-ai 0.27.0 → 0.30.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.
- package/README.md +1 -1
- package/cli/args.ts +184 -57
- package/cli/bootstrap/presentation-bridge.ts +383 -0
- package/cli/commands/acp.ts +45 -29
- package/cli/commands/auth.ts +17 -17
- package/cli/commands/config.ts +65 -66
- package/cli/commands/daemon.ts +44 -16
- package/cli/commands/doctor.ts +18 -15
- package/cli/commands/exec.ts +41 -89
- package/cli/commands/mcp.ts +25 -8
- package/cli/commands/memory.ts +16 -24
- package/cli/commands/openwork.ts +6 -2
- package/cli/commands/pricing.ts +14 -12
- package/cli/commands/providers.ts +36 -57
- package/cli/commands/sessions.ts +24 -18
- package/cli/commands/skills.ts +33 -18
- package/cli/commands/stats.ts +15 -30
- package/cli/commands.ts +73 -44
- package/cli/context-command-run.ts +30 -18
- package/cli/index.ts +51 -100
- package/cli/model-manager.ts +7 -2
- package/cli/provider-manager.ts +33 -18
- package/cli/router.ts +41 -12
- package/cli/setup.ts +241 -485
- package/cli/tui.ts +303 -100
- package/docs/TERMINAL_CONTRACT.md +258 -73
- package/docs/UI_RENDER_PIPELINE.md +9 -1
- package/docs/agents.md +2 -2
- package/docs/architecture.md +17 -32
- package/docs/choosing-mode.md +7 -9
- package/docs/cli.md +3 -5
- package/docs/environment.md +1 -2
- package/docs/policy-sandbox.md +3 -3
- package/docs/repl.md +2 -2
- package/docs/tools.md +1 -1
- package/package.json +1 -1
- package/src/app/mentions.ts +60 -13
- package/src/app/rag-layer.ts +17 -20
- package/src/app/session.ts +144 -68
- package/src/app/tool-layer.ts +38 -16
- package/src/config.ts +64 -104
- package/src/constants.ts +4 -6
- package/src/daemon/capability.ts +8 -1
- package/src/daemon/control.ts +3 -2
- package/src/daemon/server.ts +57 -0
- package/src/hooks/run.ts +73 -41
- package/src/lib/atomic-write.ts +31 -59
- package/src/lib/db-path.ts +47 -0
- package/src/lib/process-tree.ts +62 -0
- package/src/lib/public-http.ts +88 -23
- package/src/lib/trusted-exec.ts +48 -1
- package/src/lsp/client.ts +62 -17
- package/src/mcp/client.ts +85 -38
- package/src/mcp/http-transport.ts +28 -16
- package/src/mcp/transport.ts +42 -6
- package/src/memory/files.ts +164 -134
- package/src/memory/vector.ts +371 -420
- package/src/policy/approval-binding.ts +122 -45
- package/src/policy/bash-guard.ts +18 -7
- package/src/policy/compaction.ts +51 -18
- package/src/policy/context-window.ts +31 -8
- package/src/policy/context.ts +62 -36
- package/src/policy/executor.ts +17 -7
- package/src/policy/jail.ts +6 -8
- package/src/policy/microcompact.ts +4 -3
- package/src/policy/no-progress.ts +103 -22
- package/src/policy/permission.ts +36 -12
- package/src/policy/tool-contract.ts +74 -416
- package/src/policy/usage.ts +24 -2
- package/src/policy/verifier.ts +50 -2
- package/src/policy/work-mode.ts +28 -54
- package/src/presentation/adapter.ts +24 -16
- package/src/providers/anthropic.ts +16 -5
- package/src/providers/provision.ts +6 -56
- package/src/providers/responses.ts +38 -7
- package/src/providers/sse-bounds.ts +6 -4
- package/src/runtime/execution-journal.ts +4 -29
- package/src/sandbox/docker.ts +58 -34
- package/src/sandbox/mask.ts +157 -0
- package/src/sandbox/os.ts +107 -73
- package/src/session/authority.ts +29 -10
- package/src/session/context-projection.ts +6 -5
- package/src/session/db/runs.ts +397 -0
- package/src/session/db/schema.ts +358 -0
- package/src/session/open-work.ts +26 -3
- package/src/session/persistence.ts +74 -998
- package/src/session/verification.ts +170 -20
- package/src/skills/loader.ts +31 -16
- package/src/task/db/schema.ts +325 -0
- package/src/task/db/types.ts +269 -0
- package/src/task/production-scheduler.ts +13 -1
- package/src/task/store.ts +92 -1021
- package/src/telemetry/trace.ts +27 -0
- package/src/tools/ask_user.ts +1 -13
- package/src/tools/bash.ts +27 -92
- package/src/tools/code_run.ts +1 -1
- package/src/tools/context.ts +133 -0
- package/src/tools/delete_file.ts +3 -2
- package/src/tools/edit.ts +37 -72
- package/src/tools/git.ts +86 -9
- package/src/tools/glob.ts +26 -51
- package/src/tools/grep.ts +67 -57
- package/src/tools/hashline.ts +4 -0
- package/src/tools/lsp.ts +11 -8
- package/src/tools/mcp_call.ts +9 -6
- package/src/tools/memory.ts +56 -33
- package/src/tools/move_file.ts +36 -10
- package/src/tools/patch.ts +13 -21
- package/src/tools/read_file.ts +18 -25
- package/src/tools/read_image.ts +35 -33
- package/src/tools/submit_result.ts +29 -8
- package/src/tools/task.ts +74 -17
- package/src/tools/todo.ts +181 -74
- package/src/tools/web_fetch.ts +42 -2
- package/src/tools/web_search.ts +47 -8
- package/src/ui/approval/prompt.ts +206 -47
- package/src/ui/assistant/turn-status.ts +14 -5
- package/src/ui/footer.ts +4 -4
- package/src/ui/i18n/en.ts +47 -23
- package/src/ui/i18n/id.ts +76 -51
- package/src/ui/input/input.ts +4 -3
- package/src/ui/input/prompt-engine.ts +35 -5
- package/src/ui/render/activity-panel.ts +4 -2
- package/src/ui/render/hint.ts +7 -4
- package/src/ui/render/list.ts +32 -0
- package/src/ui/render/markdown.ts +6 -3
- package/src/ui/render/notice.ts +19 -0
- package/src/ui/render/table-grid.ts +7 -8
- package/src/ui/render/theme.ts +113 -39
- package/src/ui/runtime/screen.ts +74 -10
- package/src/ui/runtime/spinner.ts +19 -6
- package/src/ui/screens/dialog.ts +19 -1
- package/src/ui/screens/form.ts +80 -35
- package/src/ui/screens/model-manager.ts +82 -61
- package/src/ui/screens/output-window.ts +263 -0
- package/src/ui/screens/picker.ts +94 -81
- package/src/ui/screens/provider-manager.ts +100 -69
- package/src/ui/screens/wizard.ts +117 -28
- package/src/ui/tui/app.ts +196 -33
- package/src/ui/tui/transcript.ts +158 -25
- package/vendor/minicore/src/core/executor.ts +2 -0
- package/vendor/minicore/src/core/loop.ts +17 -6
- package/vendor/minicore/src/core/session.ts +3 -0
- package/vendor/minicore/src/core/tool.ts +1 -0
- package/vendor/minicore/src/providers/openai-compat.ts +35 -19
|
@@ -1487,18 +1487,8 @@ export async function checkWorkspaceIntegrity(
|
|
|
1487
1487
|
}
|
|
1488
1488
|
|
|
1489
1489
|
// ── [Fase 6A / ACE-02] Anti-Reward-Hacking Tamper Guard ──────────────────────
|
|
1490
|
-
//
|
|
1491
|
-
//
|
|
1492
|
-
// bekerja. Dua jalur curang yang paling murah:
|
|
1493
|
-
// 1. menyentuh skrip gate/evaluator (`bench/eval-gate.ts`,
|
|
1494
|
-
// `scripts/telemetry-gate.ts`) atau mengganti script test/verify di
|
|
1495
|
-
// `package.json`, dan
|
|
1496
|
-
// 2. menyuntik `.skip(` / `.todo(` baru ke file `test/**/*.test.ts` yang
|
|
1497
|
-
// sedang dimodifikasi agar test yang gagal berhenti dieksekusi.
|
|
1498
|
-
//
|
|
1499
|
-
// Deteksi ini SANGAT konservatif pada arah yang aman (fail-closed): tanpa
|
|
1500
|
-
// baseline yang bisa dibaca, file gate dianggap tersentuh. Baseline diambil
|
|
1501
|
-
// dari parameter eksplisit (test hermetik) atau `git show HEAD:<path>`.
|
|
1490
|
+
// Tolak klaim selesai bila permukaan evaluator/gate/test dimanipulasi selama sesi
|
|
1491
|
+
// (fail-closed terhadap `HEAD` / baseline pra-sesi).
|
|
1502
1492
|
|
|
1503
1493
|
export interface EvaluationTamperingReport {
|
|
1504
1494
|
readonly tampered: boolean
|
|
@@ -1513,13 +1503,168 @@ export interface EvaluationTamperingOptions {
|
|
|
1513
1503
|
readonly baselineContentByFile?: ReadonlyMap<string, string>
|
|
1514
1504
|
}
|
|
1515
1505
|
|
|
1516
|
-
const EVALUATOR_GATE_FILES = new Set([
|
|
1506
|
+
const EVALUATOR_GATE_FILES = new Set([
|
|
1507
|
+
"bench/eval-gate.ts",
|
|
1508
|
+
"bench/harness-audit.ts",
|
|
1509
|
+
"scripts/telemetry-gate.ts",
|
|
1510
|
+
"scripts/coverage-gate.ts",
|
|
1511
|
+
"scripts/pack-budget.ts",
|
|
1512
|
+
"tsconfig.json",
|
|
1513
|
+
"biome.json",
|
|
1514
|
+
])
|
|
1517
1515
|
const SKIP_TODO_RE = /\.(?:skip|skipIf|only|todo|fails)\s*\(/g
|
|
1516
|
+
const ASSERTION_CALL_RE = /\b(?:expect|assert(?:\.[A-Za-z_]+)?)\s*\(/g
|
|
1517
|
+
const TAUTOLOGY_RE =
|
|
1518
|
+
/\bexpect\s*\(\s*(?:true|false|1|0|"[^"]*"|'[^']*')\s*\)\s*\.(?:toBe|toEqual|toStrictEqual)\s*\(\s*(?:true|false|1|0|"[^"]*"|'[^']*')\s*\)/g
|
|
1519
|
+
const EVALUATION_SCAN_ROOTS = [
|
|
1520
|
+
"test",
|
|
1521
|
+
"bench",
|
|
1522
|
+
"scripts",
|
|
1523
|
+
"package.json",
|
|
1524
|
+
"tsconfig.json",
|
|
1525
|
+
"biome.json",
|
|
1526
|
+
".github",
|
|
1527
|
+
] as const
|
|
1528
|
+
|
|
1529
|
+
/** Baseline status git pra-sesi per (root::sessionId) agar edit user sebelum sesi tak jadi false-positive. */
|
|
1530
|
+
const sessionEvaluationBaselines = new Map<string, Map<string, string>>()
|
|
1531
|
+
|
|
1532
|
+
function sessionBaselineKey(sessionId: string, workspaceRoot: string): string {
|
|
1533
|
+
return `${resolve(workspaceRoot)}::${sessionId}`
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
function isProtectedEvaluatorSurface(rel: string): boolean {
|
|
1537
|
+
return EVALUATOR_GATE_FILES.has(rel) || rel.startsWith(".github/workflows/")
|
|
1538
|
+
}
|
|
1518
1539
|
|
|
1519
1540
|
function countSkipTodo(text: string): number {
|
|
1520
1541
|
return (text.match(SKIP_TODO_RE) ?? []).length
|
|
1521
1542
|
}
|
|
1522
1543
|
|
|
1544
|
+
function countAssertions(text: string): number {
|
|
1545
|
+
return (text.match(ASSERTION_CALL_RE) ?? []).length
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
function countTautologies(text: string): number {
|
|
1549
|
+
return (text.match(TAUTOLOGY_RE) ?? []).length
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
function listDirtyEvaluationPaths(root: string): string[] {
|
|
1553
|
+
if (!isGitRepo(root)) return []
|
|
1554
|
+
try {
|
|
1555
|
+
const r = spawnSync(
|
|
1556
|
+
resolveTrustedExecutable("git"),
|
|
1557
|
+
[
|
|
1558
|
+
...GIT_SAFE_BASE,
|
|
1559
|
+
"status",
|
|
1560
|
+
"--porcelain",
|
|
1561
|
+
"--untracked-files=all",
|
|
1562
|
+
"--",
|
|
1563
|
+
...EVALUATION_SCAN_ROOTS,
|
|
1564
|
+
],
|
|
1565
|
+
{
|
|
1566
|
+
cwd: root,
|
|
1567
|
+
encoding: "utf8",
|
|
1568
|
+
timeout: GIT_OBSERVE_TIMEOUT_MS,
|
|
1569
|
+
maxBuffer: INTEGRITY_MAX_BYTES,
|
|
1570
|
+
},
|
|
1571
|
+
)
|
|
1572
|
+
if (r.status !== 0 || typeof r.stdout !== "string") return []
|
|
1573
|
+
const out: string[] = []
|
|
1574
|
+
for (const rawLine of r.stdout.split(/\r?\n/)) {
|
|
1575
|
+
if (rawLine.length < 4) continue
|
|
1576
|
+
let p = rawLine.slice(3).trim()
|
|
1577
|
+
const arrow = p.indexOf(" -> ")
|
|
1578
|
+
if (arrow !== -1) p = p.slice(arrow + 4).trim()
|
|
1579
|
+
if ((p.startsWith('"') && p.endsWith('"')) || (p.startsWith("'") && p.endsWith("'"))) {
|
|
1580
|
+
p = p.slice(1, -1)
|
|
1581
|
+
}
|
|
1582
|
+
if (p) out.push(p.replace(/\\/g, "/"))
|
|
1583
|
+
}
|
|
1584
|
+
return out
|
|
1585
|
+
} catch {
|
|
1586
|
+
return []
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
async function hashWorkspaceRel(root: string, rel: string): Promise<string> {
|
|
1591
|
+
try {
|
|
1592
|
+
const raw = await safeReadFile(resolve(root, rel), root)
|
|
1593
|
+
return createHash("sha256").update(raw, "utf8").digest("hex")
|
|
1594
|
+
} catch {
|
|
1595
|
+
return "MISSING"
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/**
|
|
1600
|
+
* Rekam sidik jari permukaan evaluator/test yang sudah kotor SEBELUM sesi
|
|
1601
|
+
* dimulai, sehingga perubahan lokal sah milik developer tidak memicu false-positive
|
|
1602
|
+
* EVALUATOR_TAMPER_ATTEMPT saat `--verify` berjalan.
|
|
1603
|
+
*/
|
|
1604
|
+
export async function captureSessionEvaluationBaseline(
|
|
1605
|
+
sessionId: string,
|
|
1606
|
+
workspaceRoot: string,
|
|
1607
|
+
): Promise<void> {
|
|
1608
|
+
const root = resolve(workspaceRoot)
|
|
1609
|
+
const key = sessionBaselineKey(sessionId, root)
|
|
1610
|
+
const baseline = new Map<string, string>()
|
|
1611
|
+
for (const rel of listDirtyEvaluationPaths(root)) {
|
|
1612
|
+
baseline.set(rel, await hashWorkspaceRel(root, rel))
|
|
1613
|
+
}
|
|
1614
|
+
sessionEvaluationBaselines.set(key, baseline)
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* Kumpulkan SEMUA file dimutasi milik sesi ini — menggabungkan jurnal induk,
|
|
1619
|
+
* jurnal seluruh child sub-agent (`delegate_task`), dan perubahan in-session pada
|
|
1620
|
+
* permukaan evaluator/test melalui `bash`/`code_run` (terdeteksi lewat git status).
|
|
1621
|
+
*/
|
|
1622
|
+
export async function collectSessionModifiedFiles(
|
|
1623
|
+
sessionId: string,
|
|
1624
|
+
workspaceRoot: string,
|
|
1625
|
+
parentRecords?: readonly JournalRecord[],
|
|
1626
|
+
): Promise<string[]> {
|
|
1627
|
+
const root = resolve(workspaceRoot)
|
|
1628
|
+
let records = parentRecords
|
|
1629
|
+
if (!records) {
|
|
1630
|
+
const loaded = await loadJournal(sessionId, root).catch(() => null)
|
|
1631
|
+
if (loaded?.status === "valid") records = loaded.records
|
|
1632
|
+
}
|
|
1633
|
+
const combined = new Set<string>(records ? collectModifiedFilesFromJournal(records) : [])
|
|
1634
|
+
if (records) {
|
|
1635
|
+
const childIds = new Set<string>()
|
|
1636
|
+
for (const r of records) {
|
|
1637
|
+
if (r.tool === "delegate_task" && typeof r.childSessionId === "string" && r.childSessionId) {
|
|
1638
|
+
childIds.add(r.childSessionId)
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
for (const cid of [...childIds].slice(0, 20)) {
|
|
1642
|
+
const childLoaded = await loadJournal(cid, root).catch(() => null)
|
|
1643
|
+
if (childLoaded?.status === "valid") {
|
|
1644
|
+
for (const p of collectModifiedFilesFromJournal(childLoaded.records)) {
|
|
1645
|
+
combined.add(p)
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
const dirtyPaths = listDirtyEvaluationPaths(root)
|
|
1651
|
+
if (dirtyPaths.length > 0) {
|
|
1652
|
+
const baseline = sessionEvaluationBaselines.get(sessionBaselineKey(sessionId, root))
|
|
1653
|
+
for (const rel of dirtyPaths) {
|
|
1654
|
+
if (!baseline) {
|
|
1655
|
+
combined.add(rel)
|
|
1656
|
+
continue
|
|
1657
|
+
}
|
|
1658
|
+
const prevHash = baseline.get(rel)
|
|
1659
|
+
const nowHash = await hashWorkspaceRel(root, rel)
|
|
1660
|
+
if (prevHash === undefined || prevHash !== nowHash) {
|
|
1661
|
+
combined.add(rel)
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
return [...combined]
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1523
1668
|
function verificationScriptsFingerprint(text: string): string | null {
|
|
1524
1669
|
try {
|
|
1525
1670
|
const parsed = JSON.parse(text) as { scripts?: Record<string, unknown> }
|
|
@@ -1576,8 +1721,8 @@ export async function detectEvaluationTampering(
|
|
|
1576
1721
|
if (!rel || rel.startsWith("..") || isAbsolute(rel) || seen.has(rel)) continue
|
|
1577
1722
|
seen.add(rel)
|
|
1578
1723
|
|
|
1579
|
-
// 1. Skrip gate/evaluator kritis tidak boleh berubah sama sekali.
|
|
1580
|
-
if (
|
|
1724
|
+
// 1. Skrip gate/evaluator kritis & workflow CI tidak boleh berubah sama sekali.
|
|
1725
|
+
if (isProtectedEvaluatorSurface(rel)) {
|
|
1581
1726
|
offending.push(rel)
|
|
1582
1727
|
continue
|
|
1583
1728
|
}
|
|
@@ -1602,8 +1747,9 @@ export async function detectEvaluationTampering(
|
|
|
1602
1747
|
continue
|
|
1603
1748
|
}
|
|
1604
1749
|
|
|
1605
|
-
// 3.
|
|
1606
|
-
|
|
1750
|
+
// 3. Berkas test & helper (`test/**/*.ts`): deteksi .skip/.todo baru,
|
|
1751
|
+
// penghapusan assertion (`expect`/`assert`), atau assertion tautologi.
|
|
1752
|
+
if (rel.startsWith("test/") && rel.endsWith(".ts")) {
|
|
1607
1753
|
let current: string
|
|
1608
1754
|
try {
|
|
1609
1755
|
current = await safeReadFile(abs, root)
|
|
@@ -1611,9 +1757,13 @@ export async function detectEvaluationTampering(
|
|
|
1611
1757
|
continue
|
|
1612
1758
|
}
|
|
1613
1759
|
const baselineText = opts.baselineContentByFile?.get(rel) ?? gitBaselineContent(root, rel)
|
|
1614
|
-
|
|
1615
|
-
const
|
|
1616
|
-
|
|
1760
|
+
const beforeSkip = baselineText == null ? 0 : countSkipTodo(baselineText)
|
|
1761
|
+
const beforeAsserts = baselineText == null ? 0 : countAssertions(baselineText)
|
|
1762
|
+
const beforeTaut = baselineText == null ? 0 : countTautologies(baselineText)
|
|
1763
|
+
const skipAdded = countSkipTodo(current) > beforeSkip
|
|
1764
|
+
const assertsDropped = beforeAsserts > 0 && countAssertions(current) < beforeAsserts
|
|
1765
|
+
const tautologyAdded = countTautologies(current) > beforeTaut
|
|
1766
|
+
if (skipAdded || assertsDropped || tautologyAdded) offending.push(rel)
|
|
1617
1767
|
}
|
|
1618
1768
|
}
|
|
1619
1769
|
|
package/src/skills/loader.ts
CHANGED
|
@@ -154,32 +154,43 @@ async function loadSkillAssets(
|
|
|
154
154
|
return out
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
-
let skillsCache: {
|
|
157
|
+
let skillsCache: { key: string; at: number; skills: Skill[] } | undefined
|
|
158
158
|
const SKILLS_CACHE_TTL_MS = 5 * 60 * 1000
|
|
159
159
|
|
|
160
|
-
export
|
|
160
|
+
export interface LoadSkillsOptions {
|
|
161
|
+
/** Izinkan pemuatan skill lokal `<cwd>/.minicode/skills` (butuh `--allow-local-config`). */
|
|
162
|
+
allowLocal?: boolean
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function loadSkills(
|
|
166
|
+
cwd = process.cwd(),
|
|
167
|
+
opts: LoadSkillsOptions = {},
|
|
168
|
+
): Promise<Skill[]> {
|
|
161
169
|
// cache in-memory 5 menit — loadSkills dipanggil berulang (setup, REPL, one-shot)
|
|
162
170
|
const now = Date.now()
|
|
163
|
-
const
|
|
164
|
-
|
|
171
|
+
const allowLocal = opts.allowLocal === true
|
|
172
|
+
const cacheKey = `${resolve(cwd)}::local=${allowLocal ? 1 : 0}`
|
|
173
|
+
if (skillsCache && skillsCache.key === cacheKey && now - skillsCache.at < SKILLS_CACHE_TTL_MS) {
|
|
165
174
|
return skillsCache.skills
|
|
166
175
|
}
|
|
167
176
|
const skills: Skill[] = []
|
|
168
177
|
await loadDir(GLOBAL_SKILLS, skills)
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
+
if (allowLocal) {
|
|
179
|
+
const localSkills: Skill[] = []
|
|
180
|
+
await loadDir(resolve(cwd, LOCAL_SKILLS), localSkills, resolve(cwd, LOCAL_SKILLS))
|
|
181
|
+
if (localSkills.length > 0) {
|
|
182
|
+
try {
|
|
183
|
+
process.stderr.write(
|
|
184
|
+
`[warn] skills: loaded ${localSkills.length} project skill(s) from ${LOCAL_SKILLS} (untrusted repo instructions)\n`,
|
|
185
|
+
)
|
|
186
|
+
} catch {}
|
|
187
|
+
skills.push(...localSkills)
|
|
188
|
+
}
|
|
178
189
|
}
|
|
179
190
|
// local overrides global by name
|
|
180
191
|
const map = new Map<string, Skill>()
|
|
181
192
|
for (const s of skills) map.set(s.name, s)
|
|
182
|
-
skillsCache = {
|
|
193
|
+
skillsCache = { key: cacheKey, at: now, skills: [...map.values()] }
|
|
183
194
|
return skillsCache.skills
|
|
184
195
|
}
|
|
185
196
|
|
|
@@ -191,8 +202,12 @@ export async function renderSkill(skill: Skill, args: string): Promise<string> {
|
|
|
191
202
|
return skill.body.replace(/\{\{args\}\}/g, args).replace(/\$ARGUMENTS/g, args)
|
|
192
203
|
}
|
|
193
204
|
|
|
194
|
-
export async function findSkill(
|
|
195
|
-
|
|
205
|
+
export async function findSkill(
|
|
206
|
+
name: string,
|
|
207
|
+
cwd = process.cwd(),
|
|
208
|
+
opts: LoadSkillsOptions = {},
|
|
209
|
+
): Promise<Skill | undefined> {
|
|
210
|
+
const all = await loadSkills(cwd, opts)
|
|
196
211
|
return all.find((s) => s.name === name || s.name === name.replace(/^\//, ""))
|
|
197
212
|
}
|
|
198
213
|
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite"
|
|
2
|
+
import { createHash } from "node:crypto"
|
|
3
|
+
import { LIMITS } from "../../constants.ts"
|
|
4
|
+
import { resolveLocalDbPath, withSqliteBusyRetrySync } from "../../lib/db-path.ts"
|
|
5
|
+
import { scrubSecrets } from "../../policy/scrub.ts"
|
|
6
|
+
import {
|
|
7
|
+
isTaskStatus,
|
|
8
|
+
type Task,
|
|
9
|
+
type TaskAcceptance,
|
|
10
|
+
TaskError,
|
|
11
|
+
type TaskEvidence,
|
|
12
|
+
type TaskProvenance,
|
|
13
|
+
type TaskStatus,
|
|
14
|
+
type TaskVerification,
|
|
15
|
+
} from "../model.ts"
|
|
16
|
+
import { TASK_DATA_VERSION, TASK_DB_FILENAME, type TaskRow } from "./types.ts"
|
|
17
|
+
|
|
18
|
+
export const SCHEMA_ATTEMPTS = 8
|
|
19
|
+
export const SCHEMA_BACKOFF_MS = 25
|
|
20
|
+
|
|
21
|
+
export function withBusyRetrySync<T>(fn: () => T, attempts = SCHEMA_ATTEMPTS): T | null {
|
|
22
|
+
return withSqliteBusyRetrySync(fn, { attempts, backoffMs: SCHEMA_BACKOFF_MS })
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const DDL = `
|
|
26
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
27
|
+
session_id TEXT NOT NULL,
|
|
28
|
+
task_id TEXT NOT NULL,
|
|
29
|
+
title TEXT NOT NULL,
|
|
30
|
+
status TEXT NOT NULL,
|
|
31
|
+
task_order INTEGER NOT NULL,
|
|
32
|
+
parent_id TEXT,
|
|
33
|
+
depends_on_json TEXT,
|
|
34
|
+
blocked_reason TEXT,
|
|
35
|
+
verification_json TEXT,
|
|
36
|
+
evidence_json TEXT,
|
|
37
|
+
acceptance_json TEXT,
|
|
38
|
+
provenance_json TEXT,
|
|
39
|
+
created_at TEXT NOT NULL,
|
|
40
|
+
updated_at TEXT NOT NULL,
|
|
41
|
+
revision INTEGER NOT NULL,
|
|
42
|
+
exec_generation INTEGER NOT NULL DEFAULT 0,
|
|
43
|
+
attempt_generation INTEGER,
|
|
44
|
+
execution_owner TEXT,
|
|
45
|
+
PRIMARY KEY (session_id, task_id)
|
|
46
|
+
);
|
|
47
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_session_order ON tasks(session_id, task_order);
|
|
48
|
+
CREATE TABLE IF NOT EXISTS task_meta (
|
|
49
|
+
key TEXT PRIMARY KEY,
|
|
50
|
+
value TEXT NOT NULL
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
CREATE TABLE IF NOT EXISTS session_authority (
|
|
54
|
+
session_id TEXT NOT NULL,
|
|
55
|
+
incarnation INTEGER NOT NULL,
|
|
56
|
+
owner_token TEXT NOT NULL,
|
|
57
|
+
owner_pid INTEGER NOT NULL,
|
|
58
|
+
acquired_at INTEGER NOT NULL,
|
|
59
|
+
lease_expires_at INTEGER NOT NULL,
|
|
60
|
+
PRIMARY KEY (session_id, incarnation)
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
CREATE TABLE IF NOT EXISTS task_transfers (
|
|
64
|
+
transfer_id TEXT PRIMARY KEY,
|
|
65
|
+
task_id TEXT NOT NULL,
|
|
66
|
+
from_session_id TEXT NOT NULL,
|
|
67
|
+
from_incarnation INTEGER NOT NULL,
|
|
68
|
+
to_session_id TEXT NOT NULL,
|
|
69
|
+
to_incarnation INTEGER NOT NULL,
|
|
70
|
+
expected_revision INTEGER NOT NULL,
|
|
71
|
+
new_revision INTEGER NOT NULL,
|
|
72
|
+
status TEXT NOT NULL,
|
|
73
|
+
exec_generation INTEGER NOT NULL,
|
|
74
|
+
attempt_generation INTEGER,
|
|
75
|
+
execution_owner TEXT,
|
|
76
|
+
transferred_at TEXT NOT NULL
|
|
77
|
+
);
|
|
78
|
+
CREATE INDEX IF NOT EXISTS idx_task_transfers_from ON task_transfers(from_session_id, task_id);
|
|
79
|
+
CREATE INDEX IF NOT EXISTS idx_task_transfers_to ON task_transfers(to_session_id, task_id);
|
|
80
|
+
CREATE TABLE IF NOT EXISTS task_merges (
|
|
81
|
+
merge_id TEXT PRIMARY KEY,
|
|
82
|
+
session_id TEXT NOT NULL,
|
|
83
|
+
survivor_id TEXT NOT NULL,
|
|
84
|
+
duplicate_id TEXT NOT NULL,
|
|
85
|
+
evidence TEXT NOT NULL,
|
|
86
|
+
survivor_status TEXT NOT NULL,
|
|
87
|
+
duplicate_status TEXT NOT NULL,
|
|
88
|
+
duplicate_revision INTEGER NOT NULL,
|
|
89
|
+
merged_at TEXT NOT NULL
|
|
90
|
+
);
|
|
91
|
+
CREATE INDEX IF NOT EXISTS idx_task_merges_session ON task_merges(session_id, duplicate_id);
|
|
92
|
+
`
|
|
93
|
+
|
|
94
|
+
const DDL_STATEMENTS: readonly string[] = DDL.split(";")
|
|
95
|
+
.map((s) => s.trim())
|
|
96
|
+
.filter((s) => s.length > 0)
|
|
97
|
+
|
|
98
|
+
export const handles = new Map<string, Database>()
|
|
99
|
+
const initialized = new Set<string>()
|
|
100
|
+
export const txDepth = new Map<string, number>()
|
|
101
|
+
|
|
102
|
+
export function openTxPaths(): string[] {
|
|
103
|
+
return [...txDepth.entries()].filter(([, d]) => d > 0).map(([p]) => p)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function assertNoOpenTx(p: string, what: string): void {
|
|
107
|
+
if ((txDepth.get(p) ?? 0) > 0) {
|
|
108
|
+
throw new TaskError(
|
|
109
|
+
"TASK_TX_ACTIVE",
|
|
110
|
+
`cannot ${what} while a TaskStore transaction is open for this database`,
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function dbFile(cwd?: string): string {
|
|
116
|
+
return resolveLocalDbPath(TASK_DB_FILENAME, cwd)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* [PHASE 6K] Migrasi idempoten & non-destruktif kolom `exec_generation` dan `attempt_generation`
|
|
121
|
+
* memakai introspeksi `PRAGMA table_info(tasks)`.
|
|
122
|
+
*/
|
|
123
|
+
function migrateExecutionLineageSchema(db: Database): void {
|
|
124
|
+
const present = new Set(
|
|
125
|
+
(db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[]).map((r) => r.name),
|
|
126
|
+
)
|
|
127
|
+
if (present.size === 0) return
|
|
128
|
+
|
|
129
|
+
const needsExec = !present.has("exec_generation")
|
|
130
|
+
const needsAttempt = !present.has("attempt_generation")
|
|
131
|
+
if (!needsExec && !needsAttempt) return
|
|
132
|
+
|
|
133
|
+
const run = db.transaction(() => {
|
|
134
|
+
if (needsExec) {
|
|
135
|
+
db.exec("ALTER TABLE tasks ADD COLUMN exec_generation INTEGER NOT NULL DEFAULT 0")
|
|
136
|
+
}
|
|
137
|
+
if (needsAttempt) {
|
|
138
|
+
db.exec("ALTER TABLE tasks ADD COLUMN attempt_generation INTEGER")
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
try {
|
|
142
|
+
withBusyRetrySync(() => {
|
|
143
|
+
run()
|
|
144
|
+
return true
|
|
145
|
+
})
|
|
146
|
+
} catch (e) {
|
|
147
|
+
throw new TaskError(
|
|
148
|
+
"TASK_MIGRATION_FAILURE",
|
|
149
|
+
`lineage migration failed: ${(e as Error).message}`,
|
|
150
|
+
)
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
const cur = db.prepare("SELECT value FROM task_meta WHERE key = ?").get("data_version") as
|
|
154
|
+
| { value: string }
|
|
155
|
+
| null
|
|
156
|
+
| undefined
|
|
157
|
+
const n = cur ? Number(cur.value) : 0
|
|
158
|
+
if (!Number.isFinite(n) || n < TASK_DATA_VERSION) {
|
|
159
|
+
db.prepare(
|
|
160
|
+
"INSERT INTO task_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
161
|
+
).run("data_version", String(TASK_DATA_VERSION))
|
|
162
|
+
}
|
|
163
|
+
} catch {}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* [PHASE 6P] Tambahkan kolom `execution_owner` secara aditif tanpa backfill spekulatif.
|
|
168
|
+
*/
|
|
169
|
+
function migrateExecutionOwnershipSchema(db: Database): void {
|
|
170
|
+
const present = new Set(
|
|
171
|
+
(db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[]).map((r) => r.name),
|
|
172
|
+
)
|
|
173
|
+
if (present.size === 0 || present.has("execution_owner")) return
|
|
174
|
+
try {
|
|
175
|
+
withBusyRetrySync(() => {
|
|
176
|
+
db.exec("ALTER TABLE tasks ADD COLUMN execution_owner TEXT")
|
|
177
|
+
return true
|
|
178
|
+
})
|
|
179
|
+
} catch (e) {
|
|
180
|
+
throw new TaskError(
|
|
181
|
+
"TASK_MIGRATION_FAILURE",
|
|
182
|
+
`execution-ownership migration failed: ${(e as Error).message}`,
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function handle(cwd?: string): Database {
|
|
188
|
+
const p = dbFile(cwd)
|
|
189
|
+
const existing = handles.get(p)
|
|
190
|
+
if (existing) return existing
|
|
191
|
+
const opened = withBusyRetrySync(() => {
|
|
192
|
+
const d = new Database(p)
|
|
193
|
+
try {
|
|
194
|
+
d.exec(`PRAGMA busy_timeout=${LIMITS.SQLITE_BUSY_TIMEOUT_MS}`)
|
|
195
|
+
} catch {}
|
|
196
|
+
return d
|
|
197
|
+
})
|
|
198
|
+
if (!opened) {
|
|
199
|
+
throw new TaskError(
|
|
200
|
+
"TASK_DB_INIT_FAILURE",
|
|
201
|
+
`cannot open ${p} after ${SCHEMA_ATTEMPTS} busy-retry attempts`,
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
const db = opened
|
|
205
|
+
try {
|
|
206
|
+
if (!initialized.has(p)) {
|
|
207
|
+
const walOk = withBusyRetrySync(() => {
|
|
208
|
+
db.exec(
|
|
209
|
+
`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=${LIMITS.SQLITE_BUSY_TIMEOUT_MS}; PRAGMA synchronous=NORMAL; PRAGMA journal_size_limit=${LIMITS.SQLITE_WAL_SIZE_LIMIT_BYTES}; PRAGMA wal_autocheckpoint=${LIMITS.SQLITE_WAL_AUTOCHECKPOINT_PAGES};`,
|
|
210
|
+
)
|
|
211
|
+
return true
|
|
212
|
+
})
|
|
213
|
+
if (walOk === null) {
|
|
214
|
+
process.stderr.write(`[warn] taskstore: wal setup deferred, retry next open: ${p}\n`)
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
const { chmodSync } = require("node:fs") as typeof import("node:fs")
|
|
218
|
+
chmodSync(p, 0o600)
|
|
219
|
+
} catch {}
|
|
220
|
+
}
|
|
221
|
+
for (const stmt of DDL_STATEMENTS) {
|
|
222
|
+
const ok = withBusyRetrySync(() => {
|
|
223
|
+
db.exec(stmt)
|
|
224
|
+
return true
|
|
225
|
+
})
|
|
226
|
+
if (ok === null) throw new Error(`schema init did not complete: ${stmt.slice(0, 40)}`)
|
|
227
|
+
}
|
|
228
|
+
migrateExecutionLineageSchema(db)
|
|
229
|
+
migrateExecutionOwnershipSchema(db)
|
|
230
|
+
initialized.add(p)
|
|
231
|
+
} catch (e) {
|
|
232
|
+
try {
|
|
233
|
+
db.close()
|
|
234
|
+
} catch {}
|
|
235
|
+
handles.delete(p)
|
|
236
|
+
throw new TaskError("TASK_DB_INIT_FAILURE", `schema init failed: ${(e as Error).message}`)
|
|
237
|
+
}
|
|
238
|
+
handles.set(p, db)
|
|
239
|
+
return db
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function closeTaskStoreHandle(cwd?: string): void {
|
|
243
|
+
const p = dbFile(cwd)
|
|
244
|
+
assertNoOpenTx(p, "close the store")
|
|
245
|
+
const db = handles.get(p)
|
|
246
|
+
if (db) {
|
|
247
|
+
try {
|
|
248
|
+
db.close()
|
|
249
|
+
} catch {}
|
|
250
|
+
handles.delete(p)
|
|
251
|
+
initialized.delete(p)
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function parseJson<T>(raw: string | null, fallback: T): T {
|
|
256
|
+
if (!raw) return fallback
|
|
257
|
+
try {
|
|
258
|
+
const v = JSON.parse(raw) as T
|
|
259
|
+
return v ?? fallback
|
|
260
|
+
} catch {
|
|
261
|
+
return fallback
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function parseStringArrayStrict(raw: string | null): string[] | null {
|
|
266
|
+
if (raw === null || raw.trim() === "") return []
|
|
267
|
+
try {
|
|
268
|
+
const v: unknown = JSON.parse(raw)
|
|
269
|
+
if (!Array.isArray(v)) return null
|
|
270
|
+
if (v.some((x) => typeof x !== "string")) return null
|
|
271
|
+
return v as string[]
|
|
272
|
+
} catch {
|
|
273
|
+
return null
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function rowToTask(r: TaskRow): Task {
|
|
278
|
+
return {
|
|
279
|
+
id: r.task_id,
|
|
280
|
+
sessionId: r.session_id,
|
|
281
|
+
title: r.title,
|
|
282
|
+
status: (isTaskStatus(r.status) ? r.status : "PENDING") as TaskStatus,
|
|
283
|
+
order: r.task_order,
|
|
284
|
+
parentId: r.parent_id,
|
|
285
|
+
dependsOn: parseJson<string[]>(r.depends_on_json, []),
|
|
286
|
+
blockedReason: r.blocked_reason,
|
|
287
|
+
verification: parseJson<TaskVerification | null>(r.verification_json, null),
|
|
288
|
+
evidence: parseJson<TaskEvidence[]>(r.evidence_json, []),
|
|
289
|
+
acceptance: parseJson<TaskAcceptance | null>(r.acceptance_json, null),
|
|
290
|
+
provenance: parseJson<TaskProvenance>(r.provenance_json, {
|
|
291
|
+
origin: "runtime",
|
|
292
|
+
source: "unknown",
|
|
293
|
+
}),
|
|
294
|
+
createdAt: r.created_at,
|
|
295
|
+
updatedAt: r.updated_at,
|
|
296
|
+
revision: r.revision,
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function j(value: unknown): string | null {
|
|
301
|
+
return value === null || value === undefined ? null : JSON.stringify(value)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Discard the handle cache. For hermetic tests only. */
|
|
305
|
+
export function resetTaskStoreHandles(): void {
|
|
306
|
+
const open = openTxPaths()
|
|
307
|
+
if (open.length > 0) {
|
|
308
|
+
throw new TaskError(
|
|
309
|
+
"TASK_TX_ACTIVE",
|
|
310
|
+
`cannot reset task store handles while ${open.length} transaction(s) are open`,
|
|
311
|
+
)
|
|
312
|
+
}
|
|
313
|
+
for (const db of handles.values()) {
|
|
314
|
+
try {
|
|
315
|
+
db.close()
|
|
316
|
+
} catch {}
|
|
317
|
+
}
|
|
318
|
+
handles.clear()
|
|
319
|
+
initialized.clear()
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Legacy-source fingerprint, used by migration so a re-import of identical content changes nothing. */
|
|
323
|
+
export function legacyDigest(raw: string): string {
|
|
324
|
+
return createHash("sha256").update(scrubSecrets(raw)).digest("hex").slice(0, 32)
|
|
325
|
+
}
|