connore 0.1.0 → 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 (128) hide show
  1. package/README.md +53 -46
  2. package/package.json +35 -33
  3. package/packs/CONTRIBUTING.md +32 -0
  4. package/packs/base/catalog/README.md +24 -0
  5. package/packs/base/catalog/api.md +46 -0
  6. package/packs/base/catalog/auth.md +46 -0
  7. package/packs/base/catalog/backend.md +46 -0
  8. package/packs/base/catalog/blueprints.md +46 -0
  9. package/packs/base/catalog/components.md +46 -0
  10. package/packs/base/catalog/database.md +46 -0
  11. package/packs/base/catalog/docs.md +46 -0
  12. package/packs/base/catalog/github.md +46 -0
  13. package/packs/base/catalog/golden.md +46 -0
  14. package/packs/base/catalog/motion.md +46 -0
  15. package/packs/base/catalog/plan.md +46 -0
  16. package/packs/base/catalog/screenshots.md +46 -0
  17. package/packs/base/catalog/skills.md +46 -0
  18. package/packs/base/catalog/tokens.md +47 -0
  19. package/packs/base/planning/START.md +28 -0
  20. package/packs/base/planning/blueprint-template.md +46 -0
  21. package/packs/base/planning/plan-template.md +45 -0
  22. package/packs/base/rules/anti-patterns.md +43 -0
  23. package/packs/base/rules/code-style.md +43 -0
  24. package/packs/base/rules/definition-of-done.md +47 -0
  25. package/packs/base/rules/dependency-policy.md +43 -0
  26. package/packs/base/rules/error-handling.md +43 -0
  27. package/packs/base/rules/security-baseline.md +43 -0
  28. package/packs/base/templates/bug-report.md +43 -0
  29. package/packs/base/templates/feature-spec.md +43 -0
  30. package/packs/base/templates/handoff.md +43 -0
  31. package/packs/base/templates/project-brief.md +43 -0
  32. package/packs/base/workflow/build-loop.md +48 -0
  33. package/packs/base/workflow/code-review.md +43 -0
  34. package/packs/base/workflow/debugging.md +43 -0
  35. package/packs/base/workflow/git-and-commits.md +43 -0
  36. package/packs/base/workflow/idea-to-spec.md +43 -0
  37. package/packs/base/workflow/session-handoff.md +43 -0
  38. package/packs/base/workflow/spec-to-plan.md +43 -0
  39. package/packs/nextjs-fullstack/backend/api-conventions.md +48 -0
  40. package/packs/nextjs-fullstack/backend/auth-and-roles.md +43 -0
  41. package/packs/nextjs-fullstack/backend/background-jobs.md +43 -0
  42. package/packs/nextjs-fullstack/backend/caching.md +43 -0
  43. package/packs/nextjs-fullstack/backend/database.md +43 -0
  44. package/packs/nextjs-fullstack/backend/file-uploads.md +43 -0
  45. package/packs/nextjs-fullstack/backend/logging.md +43 -0
  46. package/packs/nextjs-fullstack/backend/migrations.md +43 -0
  47. package/packs/nextjs-fullstack/backend/rate-limiting.md +43 -0
  48. package/packs/nextjs-fullstack/backend/secrets-and-env.md +43 -0
  49. package/packs/nextjs-fullstack/backend/validation.md +43 -0
  50. package/packs/nextjs-fullstack/blueprints/ai-app.md +84 -0
  51. package/packs/nextjs-fullstack/blueprints/internal-tool.md +83 -0
  52. package/packs/nextjs-fullstack/blueprints/saas-app.md +83 -0
  53. package/packs/nextjs-fullstack/build-deploy/ci.md +43 -0
  54. package/packs/nextjs-fullstack/build-deploy/deploy.md +43 -0
  55. package/packs/nextjs-fullstack/build-deploy/monitoring.md +43 -0
  56. package/packs/nextjs-fullstack/build-deploy/performance.md +43 -0
  57. package/packs/nextjs-fullstack/build-deploy/project-structure.md +43 -0
  58. package/packs/nextjs-fullstack/build-deploy/release-checklist.md +43 -0
  59. package/packs/nextjs-fullstack/build-deploy/testing.md +43 -0
  60. package/packs/nextjs-fullstack/evals/README.md +43 -0
  61. package/packs/nextjs-fullstack/examples/golden-app/README.md +43 -0
  62. package/packs/nextjs-fullstack/frontend/accessibility.md +43 -0
  63. package/packs/nextjs-fullstack/frontend/components.md +43 -0
  64. package/packs/nextjs-fullstack/frontend/forms.md +43 -0
  65. package/packs/nextjs-fullstack/frontend/layout.md +43 -0
  66. package/packs/nextjs-fullstack/frontend/loading-empty-error.md +43 -0
  67. package/packs/nextjs-fullstack/frontend/motion.md +43 -0
  68. package/packs/nextjs-fullstack/frontend/responsive.md +43 -0
  69. package/packs/nextjs-fullstack/frontend/seo.md +43 -0
  70. package/packs/nextjs-fullstack/frontend/tables.md +43 -0
  71. package/packs/nextjs-fullstack/frontend/tokens.md +43 -0
  72. package/packs/nextjs-fullstack/integrations/analytics.md +43 -0
  73. package/packs/nextjs-fullstack/integrations/email.md +43 -0
  74. package/packs/nextjs-fullstack/integrations/llm-apis.md +43 -0
  75. package/packs/nextjs-fullstack/integrations/oauth.md +43 -0
  76. package/packs/nextjs-fullstack/integrations/object-storage.md +43 -0
  77. package/packs/nextjs-fullstack/integrations/payments.md +43 -0
  78. package/packs/nextjs-fullstack/integrations/queues.md +43 -0
  79. package/packs/nextjs-fullstack/integrations/search.md +43 -0
  80. package/packs/nextjs-fullstack/integrations/webhooks.md +43 -0
  81. package/packs/nextjs-fullstack/playbooks/add-ai-feature.md +43 -0
  82. package/packs/nextjs-fullstack/playbooks/add-auth.md +43 -0
  83. package/packs/nextjs-fullstack/playbooks/add-billing.md +50 -0
  84. package/packs/nextjs-fullstack/playbooks/add-crud.md +43 -0
  85. package/packs/nextjs-fullstack/playbooks/add-email.md +43 -0
  86. package/packs/nextjs-fullstack/playbooks/add-file-upload.md +43 -0
  87. package/packs/nextjs-fullstack/playbooks/add-webhook.md +43 -0
  88. package/packs/nextjs-fullstack/playbooks/ship-to-prod.md +43 -0
  89. package/src/cli.js +288 -90
  90. package/src/commands/add.js +61 -57
  91. package/src/commands/catalog.js +21 -0
  92. package/src/commands/doctor.js +42 -0
  93. package/src/commands/hook.js +67 -50
  94. package/src/commands/init.js +69 -55
  95. package/src/commands/learn.js +39 -0
  96. package/src/commands/lint.js +5 -0
  97. package/src/commands/list.js +10 -10
  98. package/src/commands/log.js +25 -0
  99. package/src/commands/memory.js +14 -0
  100. package/src/commands/plan.js +41 -0
  101. package/src/commands/reindex.js +8 -8
  102. package/src/commands/review.js +31 -0
  103. package/src/commands/search.js +21 -0
  104. package/src/commands/stats.js +35 -0
  105. package/src/commands/undo.js +7 -0
  106. package/src/commands/update.js +16 -14
  107. package/src/lib/catalog.js +32 -0
  108. package/src/lib/config.js +64 -0
  109. package/src/lib/fs-safe.js +36 -11
  110. package/src/lib/gitlog.js +75 -0
  111. package/src/lib/ignore.js +47 -0
  112. package/src/lib/index.js +27 -12
  113. package/src/lib/lessons.js +173 -0
  114. package/src/lib/lint.js +67 -0
  115. package/src/lib/lock.js +47 -0
  116. package/src/lib/memory.js +49 -0
  117. package/src/lib/mutate.js +24 -0
  118. package/src/lib/packs.js +10 -0
  119. package/src/lib/paths.js +6 -2
  120. package/src/lib/plan.js +156 -0
  121. package/src/lib/pointers.js +3 -3
  122. package/src/lib/provider.js +27 -0
  123. package/src/lib/report.js +20 -4
  124. package/src/lib/run.js +73 -0
  125. package/src/lib/search.js +40 -0
  126. package/src/lib/secrets.js +25 -0
  127. package/src/lib/signals.js +55 -0
  128. package/src/lib/sync.js +20 -12
@@ -0,0 +1,64 @@
1
+ import { join } from "node:path"
2
+ import { readOptional } from "./fs-safe.js"
3
+ import { commitWrite } from "./mutate.js"
4
+
5
+ export const SCHEMA_VERSION = 1
6
+
7
+ export const DEFAULT_IGNORE = ["node_modules", ".git", "dist", "build", ".next", "out", "coverage", ".turbo", "vault"]
8
+
9
+ export function defaultConfig(tools = []) {
10
+ return {
11
+ schemaVersion: SCHEMA_VERSION,
12
+ tools: [...tools],
13
+ ignore: [...DEFAULT_IGNORE],
14
+ provider: "local",
15
+ lessonBudget: 400,
16
+ lessonLimit: 5,
17
+ }
18
+ }
19
+
20
+ export function configText(config) {
21
+ return `${JSON.stringify(config, null, 2)}\n`
22
+ }
23
+
24
+ export function migrateConfig(input) {
25
+ const source = input && typeof input === "object" && !Array.isArray(input) ? input : {}
26
+ const version = Number.isInteger(source.schemaVersion) ? source.schemaVersion : 0
27
+ if (version > SCHEMA_VERSION) {
28
+ throw new Error(`This folder uses schemaVersion ${version}. Upgrade connore before writing to it.`)
29
+ }
30
+ const next = defaultConfig(Array.isArray(source.tools) ? source.tools.filter((tool) => typeof tool === "string") : [])
31
+ if (Array.isArray(source.ignore) && source.ignore.length) next.ignore = source.ignore.map(String)
32
+ if (typeof source.provider === "string" && source.provider) next.provider = source.provider
33
+ if (Number.isInteger(source.lessonBudget) && source.lessonBudget > 0) next.lessonBudget = source.lessonBudget
34
+ if (Number.isInteger(source.lessonLimit) && source.lessonLimit > 0) next.lessonLimit = source.lessonLimit
35
+ next.schemaVersion = SCHEMA_VERSION
36
+ return next
37
+ }
38
+
39
+ export function configPath(root) {
40
+ return join(root, ".ctx", "config.json")
41
+ }
42
+
43
+ export async function readConfig(root) {
44
+ const file = configPath(root)
45
+ const raw = await readOptional(file)
46
+ if (!raw) return { file, raw: null, parsed: null, config: null }
47
+ let parsed
48
+ try {
49
+ parsed = JSON.parse(raw.toString("utf8"))
50
+ } catch {
51
+ throw new Error(".ctx/config.json is not valid JSON.")
52
+ }
53
+ return { file, raw, parsed, config: migrateConfig(parsed) }
54
+ }
55
+
56
+ export async function ensureConfig(root, report, tools, options = {}) {
57
+ const current = await readConfig(root)
58
+ const config = current.config || defaultConfig(tools || [])
59
+ if (!current.raw || options.replaceTools) config.tools = [...(tools || [])]
60
+ const next = configText(config)
61
+ if (!current.raw || current.raw.toString("utf8") !== next) await commitWrite(current.file, next, report, ".ctx/config.json")
62
+ else report.add("skipped", ".ctx/config.json")
63
+ return config
64
+ }
@@ -2,6 +2,8 @@ import { randomBytes } from "node:crypto"
2
2
  import { mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises"
3
3
  import { basename, dirname, join } from "node:path"
4
4
 
5
+ const RETRYABLE = new Set(["EPERM", "EBUSY", "EACCES"])
6
+
5
7
  export async function exists(filePath) {
6
8
  try {
7
9
  await stat(filePath)
@@ -21,41 +23,64 @@ export async function readOptional(filePath) {
21
23
  }
22
24
  }
23
25
 
24
- export async function writeAtomic(filePath, data) {
25
- await mkdir(dirname(filePath), { recursive: true })
26
+ async function writeOnce(filePath, data, io) {
27
+ await io.mkdir(dirname(filePath), { recursive: true })
26
28
  const tmp = join(dirname(filePath), `.${basename(filePath)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`)
27
- await writeFile(tmp, data)
29
+ await io.writeFile(tmp, data)
28
30
  try {
29
- await rename(tmp, filePath)
31
+ await io.rename(tmp, filePath)
30
32
  } catch (error) {
31
33
  if (error.code !== "EEXIST" && error.code !== "EPERM") {
32
- await unlink(tmp).catch(() => {})
34
+ await io.unlink(tmp).catch(() => {})
33
35
  throw error
34
36
  }
35
37
  const backup = `${filePath}.${process.pid}.bak`
36
- await rename(filePath, backup)
38
+ await io.rename(filePath, backup)
37
39
  try {
38
- await rename(tmp, filePath)
40
+ await io.rename(tmp, filePath)
39
41
  } catch (renameError) {
40
- await rename(backup, filePath).catch(() => {})
42
+ await io.rename(backup, filePath).catch(() => {})
41
43
  throw renameError
42
44
  }
43
- await unlink(backup).catch(() => {})
45
+ await io.unlink(backup).catch(() => {})
46
+ }
47
+ }
48
+
49
+ export async function writeAtomic(filePath, data, io = {}) {
50
+ const fsio = {
51
+ mkdir: io.mkdir || mkdir,
52
+ writeFile: io.writeFile || writeFile,
53
+ rename: io.rename || rename,
54
+ unlink: io.unlink || unlink,
55
+ }
56
+ const sleep = io.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
57
+ let last
58
+ for (let attempt = 0; attempt < 5; attempt += 1) {
59
+ try {
60
+ await writeOnce(filePath, data, fsio)
61
+ return
62
+ } catch (error) {
63
+ last = error
64
+ if (!RETRYABLE.has(error.code) || attempt === 4) throw error
65
+ await sleep(20 * (attempt + 1))
66
+ }
44
67
  }
68
+ throw last
45
69
  }
46
70
 
47
71
  export async function removeFile(filePath) {
48
72
  await rm(filePath, { force: true })
49
73
  }
50
74
 
51
- export async function walkFiles(dir) {
75
+ export async function walkFiles(dir, ignore = new Set()) {
52
76
  if (!(await exists(dir))) return []
53
77
  const entries = await readdir(dir, { withFileTypes: true })
54
78
  entries.sort((a, b) => a.name.localeCompare(b.name))
55
79
  const files = []
56
80
  for (const entry of entries) {
81
+ if (ignore.has(entry.name)) continue
57
82
  const filePath = join(dir, entry.name)
58
- if (entry.isDirectory()) files.push(...(await walkFiles(filePath)))
83
+ if (entry.isDirectory()) files.push(...(await walkFiles(filePath, ignore)))
59
84
  else if (entry.isFile()) files.push(filePath)
60
85
  }
61
86
  return files
@@ -0,0 +1,75 @@
1
+ import { execFile } from "node:child_process"
2
+ import { promisify } from "node:util"
3
+
4
+ const exec = promisify(execFile)
5
+
6
+ export function signalsFromGitLog(text) {
7
+ const commits = []
8
+ let current = null
9
+ for (const line of String(text || "").split(/\r?\n/)) {
10
+ if (!line.trim()) {
11
+ if (current) commits.push(current)
12
+ current = null
13
+ continue
14
+ }
15
+ if (!current) {
16
+ const [hash, date, ...rest] = line.split("\t")
17
+ current = { hash, date, subject: rest.join("\t"), files: [] }
18
+ } else current.files.push(line.trim())
19
+ }
20
+ if (current) commits.push(current)
21
+
22
+ const signals = []
23
+ const seen = new Map()
24
+ for (const commit of commits.reverse()) {
25
+ const when = Date.parse(commit.date)
26
+ if (/^revert\b/i.test(commit.subject)) {
27
+ signals.push({
28
+ at: commit.date,
29
+ kind: "failure",
30
+ text: commit.subject,
31
+ files: commit.files,
32
+ source: "git",
33
+ })
34
+ }
35
+ if (!/^fix\b/i.test(commit.subject)) {
36
+ for (const file of commit.files) seen.set(file, when)
37
+ continue
38
+ }
39
+ for (const file of commit.files) {
40
+ const earlier = seen.get(file)
41
+ if (Number.isFinite(earlier) && Number.isFinite(when) && Math.abs(when - earlier) <= 24 * 60 * 60 * 1000) {
42
+ signals.push({
43
+ at: commit.date,
44
+ kind: "fix",
45
+ text: `fix after a recent change in ${file}`,
46
+ files: [file],
47
+ source: "git",
48
+ })
49
+ }
50
+ }
51
+ }
52
+ return signals
53
+ }
54
+
55
+ export async function readGitSignals(root) {
56
+ try {
57
+ const { stdout } = await exec("git", ["-C", root, "log", "-n", "80", "--pretty=format:%H%x09%cI%x09%s", "--name-only"], {
58
+ timeout: 5000,
59
+ windowsHide: true,
60
+ })
61
+ return signalsFromGitLog(stdout)
62
+ } catch {
63
+ return []
64
+ }
65
+ }
66
+
67
+ export async function changedFiles(root) {
68
+ try {
69
+ const unstaged = await exec("git", ["-C", root, "diff", "--name-only", "HEAD"], { timeout: 5000, windowsHide: true })
70
+ const staged = await exec("git", ["-C", root, "diff", "--name-only", "--cached"], { timeout: 5000, windowsHide: true })
71
+ return [...new Set(`${unstaged.stdout}\n${staged.stdout}`.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))]
72
+ } catch {
73
+ return []
74
+ }
75
+ }
@@ -0,0 +1,47 @@
1
+ import { join } from "node:path"
2
+ import { readOptional } from "./fs-safe.js"
3
+ import { commitWrite } from "./mutate.js"
4
+
5
+ export const CTXIGNORE = `# Folders connore skips while scanning
6
+ node_modules
7
+ .git
8
+ dist
9
+ build
10
+ .next
11
+ out
12
+ coverage
13
+ .turbo
14
+ vault
15
+ `
16
+
17
+ export const GITIGNORE_BLOCK = `# connore local state
18
+ .ctx/.signals/
19
+ .ctx/.runs/
20
+ .ctx/.lock
21
+ .ctx/vault/
22
+ `
23
+
24
+ export async function ignoreNames(root, config) {
25
+ const names = new Set(config?.ignore || [])
26
+ const file = await readOptional(join(root, ".ctxignore"))
27
+ if (!file) return names
28
+ for (const line of file.toString("utf8").split(/\r?\n/)) {
29
+ const trimmed = line.trim()
30
+ if (!trimmed || trimmed.startsWith("#")) continue
31
+ names.add(trimmed.replace(/^\//, "").replace(/\/$/, ""))
32
+ }
33
+ return names
34
+ }
35
+
36
+ export async function ensureLocalIgnores(root, report) {
37
+ await commitWrite(join(root, ".ctxignore"), CTXIGNORE, report, ".ctxignore")
38
+ const gitignore = join(root, ".gitignore")
39
+ const current = await readOptional(gitignore)
40
+ const text = current ? current.toString("utf8") : ""
41
+ if (text.includes(".ctx/.signals/")) {
42
+ report.add("skipped", ".gitignore")
43
+ return
44
+ }
45
+ const next = text ? `${text.replace(/\s*$/, "\n\n")}${GITIGNORE_BLOCK}` : GITIGNORE_BLOCK
46
+ await commitWrite(gitignore, next, report, ".gitignore")
47
+ }
package/src/lib/index.js CHANGED
@@ -1,20 +1,35 @@
1
1
  import { readFile } from "node:fs/promises"
2
2
  import { join } from "node:path"
3
- import { exists, readOptional, walkFiles, writeAtomic } from "./fs-safe.js"
3
+ import { exists, readOptional, walkFiles } from "./fs-safe.js"
4
+ import { commitWrite } from "./mutate.js"
4
5
  import { parseFrontmatter } from "./frontmatter.js"
5
6
  import { ctxPath, fromRoot } from "./paths.js"
6
7
 
7
- export async function collectEntries(root) {
8
+ export function entryVisible(data, file, { includeDrafts = false } = {}) {
9
+ if (!data) return false
10
+ const path = file.replace(/\\/g, "/")
11
+ if (path.includes("/_proposed/") || path.includes("/_rejected/") || path.includes("/vault/")) return false
12
+ if (path.includes("/library/catalog/")) return false
13
+ if (data.status === "proposed" || data.status === "rejected") return false
14
+ if (data.status === "draft" && !includeDrafts) return false
15
+ return true
16
+ }
17
+
18
+ export async function collectEntries(root, options = {}) {
8
19
  const files = []
9
- for (const dir of [ctxPath(root, "library"), ctxPath(root, "mine")]) files.push(...(await walkFiles(dir)))
20
+ for (const dir of [ctxPath(root, "library"), ctxPath(root, "mine"), ctxPath(root, "memory")]) files.push(...(await walkFiles(dir)))
10
21
  const processFile = ctxPath(root, "PROCESS.md")
11
22
  if (await exists(processFile)) files.push(processFile)
23
+ const startFile = ctxPath(root, "START.md")
24
+ if (await exists(startFile)) files.push(startFile)
12
25
 
13
26
  const entries = []
14
27
  for (const file of files) {
15
28
  if (!file.endsWith(".md")) continue
16
- const data = parseFrontmatter(await readFile(file, "utf8"))
17
- if (!data) continue
29
+ const text = await readFile(file, "utf8")
30
+ const data = parseFrontmatter(text)
31
+ if (!entryVisible(data, file, options)) continue
32
+ if (file.replace(/\\/g, "/").includes("/memory/") && !/^## \d{4}-\d{2}-\d{2}\s*$/m.test(text)) continue
18
33
  entries.push({
19
34
  path: fromRoot(root, file),
20
35
  type: data.type || "",
@@ -23,14 +38,16 @@ export async function collectEntries(root) {
23
38
  })
24
39
  }
25
40
  entries.sort((a, b) => a.path.localeCompare(b.path))
26
- return entries
41
+ const start = entries.filter((entry) => entry.path === ".ctx/START.md")
42
+ const rest = entries.filter((entry) => entry.path !== ".ctx/START.md")
43
+ return [...start, ...rest]
27
44
  }
28
45
 
29
46
  export function renderIndex(entries) {
30
47
  const lines = [
31
48
  "# Index",
32
49
  "",
33
- "Load only the entries relevant to the task. Prefer text specs over opening images.",
50
+ "Read .ctx/START.md before new work. Load only the entries relevant to the task. Prefer text specs over opening images.",
34
51
  "",
35
52
  "| Path | Type | Tags | Description |",
36
53
  "| --- | --- | --- | --- |",
@@ -42,16 +59,14 @@ export function renderIndex(entries) {
42
59
  return lines.join("\n")
43
60
  }
44
61
 
45
- export async function rebuildIndex(root, report) {
62
+ export async function rebuildIndex(root, report, options = {}) {
46
63
  const file = join(root, ".ctx", "INDEX.md")
47
- const next = renderIndex(await collectEntries(root))
64
+ const next = renderIndex(await collectEntries(root, options))
48
65
  const current = await readOptional(file)
49
66
  const currentText = current ? current.toString("utf8") : null
50
67
  if (currentText === next) {
51
68
  report.add("skipped", ".ctx/INDEX.md")
52
69
  return
53
70
  }
54
- const kind = currentText === null ? "created" : "changed"
55
- if (!report.dryRun) await writeAtomic(file, next)
56
- report.add(kind, ".ctx/INDEX.md")
71
+ await commitWrite(file, next, report, ".ctx/INDEX.md")
57
72
  }
@@ -0,0 +1,173 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { exists, readOptional, removeFile, walkFiles } from "./fs-safe.js"
4
+ import { parseFrontmatter } from "./frontmatter.js"
5
+ import { commitWrite } from "./mutate.js"
6
+ import { fromRoot } from "./paths.js"
7
+
8
+ export function lessonFile(lesson) {
9
+ const files = lesson.files ? `\nfiles: ${lesson.files}` : ""
10
+ const flagged = lesson.flagged ? `\nflagged: ${lesson.flagged}` : ""
11
+ const stale = lesson.stale ? `\nstale: true` : ""
12
+ return `---
13
+ title: ${one(lesson.title)}
14
+ type: lesson
15
+ tags: [lesson]
16
+ stack: project
17
+ status: ${lesson.status || "proposed"}
18
+ scope: ${lesson.scope || "project"}
19
+ trigger: ${one(lesson.trigger)}
20
+ mistake: ${one(lesson.mistake)}
21
+ fix: ${one(lesson.fix)}
22
+ evidence: ${one(lesson.evidence)}
23
+ confidence: ${lesson.confidence || "medium"}
24
+ source: ${lesson.source || "agent-inferred"}
25
+ last_seen: ${lesson.lastSeen || ""}${files}${flagged}${stale}
26
+ description: ${one(lesson.mistake)}
27
+ ---
28
+
29
+ # ${one(lesson.title)}
30
+
31
+ Watch-out: ${one(lesson.mistake)}
32
+ Fix: ${one(lesson.fix)}
33
+ `
34
+ }
35
+
36
+ function one(value) {
37
+ return String(value || "").replace(/\s+/g, " ").trim()
38
+ }
39
+
40
+ export function proposedDir(root) {
41
+ return join(root, ".ctx", "mine", "lessons", "_proposed")
42
+ }
43
+
44
+ export function acceptedDir(root) {
45
+ return join(root, ".ctx", "mine", "lessons")
46
+ }
47
+
48
+ export async function writeProposal(root, id, lesson, report) {
49
+ const file = join(proposedDir(root), `${id}.md`)
50
+ await commitWrite(file, lessonFile({ ...lesson, status: "proposed" }), report, fromRoot(root, file))
51
+ return file
52
+ }
53
+
54
+ async function readLessonFile(file) {
55
+ const text = await readFile(file, "utf8")
56
+ const data = parseFrontmatter(text)
57
+ if (!data || data.type !== "lesson") return null
58
+ return {
59
+ file,
60
+ id: file.split(/[/\\]/).pop().replace(/\.md$/, ""),
61
+ title: data.title || "",
62
+ status: data.status || "",
63
+ scope: data.scope || "project",
64
+ trigger: data.trigger || "",
65
+ mistake: data.mistake || "",
66
+ fix: data.fix || "",
67
+ evidence: data.evidence || "",
68
+ confidence: data.confidence || "medium",
69
+ source: data.source || "agent-inferred",
70
+ files: data.files || "",
71
+ lastSeen: data.last_seen || "",
72
+ flagged: data.flagged || "",
73
+ stale: data.stale === "true",
74
+ }
75
+ }
76
+
77
+ export async function listProposals(root) {
78
+ const lessons = []
79
+ for (const file of await walkFiles(proposedDir(root))) {
80
+ if (!file.endsWith(".md")) continue
81
+ const lesson = await readLessonFile(file)
82
+ if (lesson?.status === "proposed") lessons.push(lesson)
83
+ }
84
+ return lessons
85
+ }
86
+
87
+ export async function listAccepted(root) {
88
+ const dir = acceptedDir(root)
89
+ const lessons = []
90
+ for (const file of await walkFiles(dir)) {
91
+ if (!file.endsWith(".md")) continue
92
+ if (file.includes(`${join("lessons", "_proposed")}`) || file.includes(`${join("lessons", "_rejected")}`)) continue
93
+ const lesson = await readLessonFile(file)
94
+ if (lesson?.status === "accepted") lessons.push(lesson)
95
+ }
96
+ return lessons
97
+ }
98
+
99
+ export async function moveProposal(root, id, status, report, edits = {}) {
100
+ const source = join(proposedDir(root), `${id}.md`)
101
+ if (!(await exists(source))) throw new Error(`No proposal "${id}".`)
102
+ const current = await readLessonFile(source)
103
+ const lesson = {
104
+ ...current,
105
+ ...edits,
106
+ status,
107
+ lastSeen: status === "accepted" ? new Date().toISOString().slice(0, 10) : current.lastSeen,
108
+ }
109
+ const destDir = status === "accepted" ? acceptedDir(root) : join(acceptedDir(root), "_rejected")
110
+ const dest = join(destDir, `${id}.md`)
111
+ await commitWrite(dest, lessonFile(lesson), report, fromRoot(root, dest))
112
+ const previous = await readOptional(source)
113
+ if (previous) {
114
+ if (!report.dryRun) await removeFile(source)
115
+ report.add("removed", fromRoot(root, source), { previous })
116
+ }
117
+ return lesson
118
+ }
119
+
120
+ export function watchLine(lesson) {
121
+ return `- ${lesson.trigger}: ${lesson.mistake} Fix: ${lesson.fix}`
122
+ }
123
+
124
+ export function selectLessons(lessons, changed, { limit = 5, budget = 400 } = {}) {
125
+ const paths = changed.map((file) => file.replace(/\\/g, "/"))
126
+ const ranked = []
127
+ for (const lesson of lessons) {
128
+ if (lesson.status !== "accepted" || lesson.stale) continue
129
+ const files = String(lesson.files || "").split(",").map((file) => file.trim()).filter(Boolean)
130
+ const trigger = String(lesson.trigger || "").toLowerCase()
131
+ let score = 0
132
+ for (const path of paths) {
133
+ if (files.some((file) => path === file || path.endsWith(file))) score += 3
134
+ else if (trigger && path.toLowerCase().includes(trigger.replace(/^when editing /, ""))) score += 1
135
+ }
136
+ if (score > 0) ranked.push({ lesson, score })
137
+ }
138
+ ranked.sort((a, b) => b.score - a.score || a.lesson.id.localeCompare(b.lesson.id))
139
+ const chosen = []
140
+ let used = 0
141
+ for (const item of ranked) {
142
+ if (chosen.length >= limit) break
143
+ const cost = Math.max(1, Math.ceil(watchLine(item.lesson).length / 4))
144
+ if (used + cost > budget) continue
145
+ used += cost
146
+ chosen.push(item.lesson)
147
+ }
148
+ return chosen
149
+ }
150
+
151
+ export function lessonBlock(lessons) {
152
+ if (!lessons.length) return ""
153
+ return `\nWatch-outs\n${lessons.map(watchLine).join("\n")}\n`
154
+ }
155
+
156
+ const DAY = 24 * 60 * 60 * 1000
157
+
158
+ export async function markLessonHealth(root, signals, report, now = new Date()) {
159
+ for (const lesson of await listAccepted(root)) {
160
+ const seen = Date.parse(lesson.lastSeen)
161
+ const stale = Number.isFinite(seen) && now.getTime() - seen > 90 * DAY
162
+ const recurring = signals.some((signal) => {
163
+ if (signal.kind !== "failure" || !lesson.mistake) return false
164
+ const at = Date.parse(signal.at)
165
+ if (Number.isFinite(seen) && Number.isFinite(at) && at < seen) return false
166
+ return String(signal.text || "").toLowerCase().includes(lesson.mistake.toLowerCase())
167
+ })
168
+ if (!stale && !recurring) continue
169
+ if (Boolean(lesson.stale) === stale && (lesson.flagged === "recurring") === recurring) continue
170
+ const next = { ...lesson, stale, flagged: recurring ? "recurring" : lesson.flagged }
171
+ await commitWrite(lesson.file, lessonFile(next), report, fromRoot(root, lesson.file))
172
+ }
173
+ }
@@ -0,0 +1,67 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { walkFiles } from "./fs-safe.js"
4
+ import { parseFrontmatter } from "./frontmatter.js"
5
+ import { packRoot, toPosix, fromRoot } from "./paths.js"
6
+
7
+ const REQUIRED = ["title", "type", "tags", "stack", "status", "verified", "description"]
8
+ const HEADINGS = [
9
+ "Use when",
10
+ "Default",
11
+ "Use instead when",
12
+ "Never",
13
+ "Why",
14
+ "Steps",
15
+ "Done when",
16
+ "Example",
17
+ "Common mistakes",
18
+ "Sources",
19
+ ]
20
+
21
+ function section(text, heading) {
22
+ const normalized = text.replace(/\r\n/g, "\n")
23
+ const match = new RegExp(`^## ${heading}\\n([\\s\\S]*?)(?=\\n## |$)`, "m").exec(normalized)
24
+ return match ? match[1].trim() : ""
25
+ }
26
+
27
+ export function lintText(file, text) {
28
+ const problems = []
29
+ const data = parseFrontmatter(text)
30
+ if (!data) {
31
+ problems.push(`${file}: missing frontmatter`)
32
+ return problems
33
+ }
34
+ if (!data.status) return problems
35
+ for (const key of REQUIRED) {
36
+ if (data[key] === undefined || data[key] === "" && key !== "verified") problems.push(`${file}: frontmatter ${key} is empty`)
37
+ }
38
+ if (data.status !== "draft" && data.status !== "reviewed") problems.push(`${file}: status must be draft or reviewed`)
39
+ if (data.status !== "reviewed") return problems
40
+ if (data.type === "blueprint") {
41
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(data.verified || "")) problems.push(`${file}: verified must be YYYY-MM-DD`)
42
+ for (const heading of ["Summary", "Capabilities", "Reference architecture", "Data model starter", "Integrations", "Phases", "Gate", "Pitfalls", "Confirm with user", "Entries to load"]) {
43
+ if (!section(text, heading)) problems.push(`${file}: empty or missing ${heading}`)
44
+ }
45
+ return problems
46
+ }
47
+ const lines = text.split(/\r?\n/).length
48
+ if (lines > 60) problems.push(`${file}: ${lines} lines, reviewed entries stay under 60`)
49
+ if (text.includes("TODO")) problems.push(`${file}: reviewed entries cannot contain TODO`)
50
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(data.verified || "")) problems.push(`${file}: verified must be YYYY-MM-DD`)
51
+ if (!/^license:/im.test(text)) problems.push(`${file}: missing a license line`)
52
+ for (const heading of HEADINGS) {
53
+ if (!section(text, heading)) problems.push(`${file}: empty or missing ${heading}`)
54
+ }
55
+ return problems
56
+ }
57
+
58
+ export async function lintPacks() {
59
+ const root = join(packRoot, "packs")
60
+ const files = (await walkFiles(root)).filter((file) => file.endsWith(".md") && !file.endsWith("CONTRIBUTING.md"))
61
+ const problems = []
62
+ for (const file of files) {
63
+ const text = await readFile(file, "utf8")
64
+ problems.push(...lintText(toPosix(fromRoot(packRoot, file)), text))
65
+ }
66
+ return problems
67
+ }
@@ -0,0 +1,47 @@
1
+ import { mkdir, unlink, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { readOptional } from "./fs-safe.js"
4
+
5
+ const STALE_MS = 10 * 60 * 1000
6
+
7
+ function pidAlive(pid) {
8
+ if (!Number.isInteger(pid) || pid <= 0) return false
9
+ try {
10
+ process.kill(pid, 0)
11
+ return true
12
+ } catch (error) {
13
+ return error.code === "EPERM"
14
+ }
15
+ }
16
+
17
+ export function lockIsStale(lock, now = Date.now()) {
18
+ const time = Date.parse(lock?.time)
19
+ if (!Number.isFinite(time)) return true
20
+ if (now - time > STALE_MS) return true
21
+ return !pidAlive(lock.pid)
22
+ }
23
+
24
+ export async function withLock(root, fn) {
25
+ const dir = join(root, ".ctx")
26
+ const file = join(dir, ".lock")
27
+ await mkdir(dir, { recursive: true })
28
+ const existing = await readOptional(file)
29
+ if (existing) {
30
+ let lock
31
+ try {
32
+ lock = JSON.parse(existing.toString("utf8"))
33
+ } catch {
34
+ lock = null
35
+ }
36
+ if (lock && !lockIsStale(lock)) {
37
+ throw new Error(`Another connore run holds .ctx/.lock (pid ${lock.pid}).`)
38
+ }
39
+ await unlink(file).catch(() => {})
40
+ }
41
+ await writeFile(file, JSON.stringify({ pid: process.pid, time: new Date().toISOString() }))
42
+ try {
43
+ return await fn()
44
+ } finally {
45
+ await unlink(file).catch(() => {})
46
+ }
47
+ }