feat: init mlkem project with Verilator test framework

- sync_rtl/common/: skid_buffer, pipeline_reg, defines (valid/ready)
- sync_rtl/mod_add/: modular adder example with Verilator C++ TB
- test_framework/: Python-driven Verilator compile/sim/compare pipeline
- test_framework/modules/mod_add/: 50-vector test plan, full鏈路 PASS
- .trellis/spec/: RTL and test_framework conventions documented
This commit is contained in:
2026-06-24 19:43:29 +08:00
commit 8fdf944555
216 changed files with 24140 additions and 0 deletions

View File

@@ -0,0 +1,432 @@
/* global process */
import { existsSync, readFileSync, readdirSync, statSync } from "fs"
import { basename, join } from "path"
import { execFileSync } from "child_process"
import { platform } from "os"
import { debugLog } from "./trellis-context.js"
const PYTHON_CMD = platform() === "win32" ? "python" : "python3"
const FIRST_REPLY_NOTICE = `<first-reply-notice>
On the first visible assistant reply in this session, begin with exactly one short Chinese sentence:
Trellis SessionStart 已注入workflow、当前任务状态、开发者身份、git 状态、active tasks、spec 索引已加载。
Then continue directly with the user's request. This notice is one-shot: do not repeat it after the first assistant reply in the same session.
</first-reply-notice>`
function hasCuratedJsonlEntry(jsonlPath) {
try {
const content = readFileSync(jsonlPath, "utf-8")
for (const rawLine of content.split(/\r?\n/)) {
const line = rawLine.trim()
if (!line) continue
try {
const row = JSON.parse(line)
if (row && typeof row === "object" && typeof row.file === "string" && row.file) {
return true
}
} catch {
// Ignore malformed line
}
}
} catch {
return false
}
return false
}
function getTaskStatus(ctx, platformInput = null) {
const active = ctx.getActiveTask(platformInput)
const taskRef = active.taskPath
if (!taskRef) {
return `Status: NO ACTIVE TASK\nSource: ${active.source}\nNext: Describe what you want to work on`
}
const taskDir = ctx.resolveTaskDir(taskRef)
if (active.stale || !taskDir || !existsSync(taskDir)) {
return `Status: STALE POINTER\nTask: ${taskRef}\nSource: ${active.source}\nNext: Task directory not found. Run: python3 ./.trellis/scripts/task.py finish`
}
let taskData = {}
const taskJsonPath = join(taskDir, "task.json")
if (existsSync(taskJsonPath)) {
try {
taskData = JSON.parse(readFileSync(taskJsonPath, "utf-8"))
} catch {
// Ignore parse errors
}
}
const taskTitle = taskData.title || taskRef
const taskStatus = taskData.status || "unknown"
if (taskStatus === "completed") {
const dirName = basename(taskDir)
return `Status: COMPLETED\nTask: ${taskTitle}\nSource: ${active.source}\nNext: Archive with \`python3 ./.trellis/scripts/task.py archive ${dirName}\` or start a new task`
}
let hasContext = false
for (const jsonlName of ["implement.jsonl", "check.jsonl"]) {
const jsonlPath = join(taskDir, jsonlName)
if (existsSync(jsonlPath) && hasCuratedJsonlEntry(jsonlPath)) {
hasContext = true
break
}
}
const hasPrd = existsSync(join(taskDir, "prd.md"))
if (!hasPrd) {
return `Status: NOT READY\nTask: ${taskTitle}\nSource: ${active.source}\nMissing: prd.md not created\nNext: Write PRD (see workflow.md Phase 1.1) then curate implement.jsonl per Phase 1.3`
}
if (!hasContext) {
return `Status: NOT READY\nTask: ${taskTitle}\nSource: ${active.source}\nMissing: implement.jsonl / check.jsonl missing or empty\nNext: Curate entries per workflow.md Phase 1.3 (spec + research files only), then \`task.py start\``
}
return (
`Status: READY\nTask: ${taskTitle}\n` +
`Source: ${active.source}\n` +
"Next required action: dispatch `trellis-implement` per Phase 2.1. " +
"For agent-capable platforms, the default is to NOT edit code in the main session. " +
"After implementation, dispatch `trellis-check` per Phase 2.2 before reporting completion.\n" +
"User override (per-turn escape hatch): if the user's CURRENT message explicitly tells the " +
"main session to handle it directly (\"你直接改\" / \"别派 sub-agent\" / \"main session 写就行\" / " +
"\"do it inline\" / \"不用 sub-agent\"), honor it for this turn and edit code directly. " +
"Per-turn only; do NOT invent an override the user did not say."
)
}
function loadTrellisConfig(directory, contextKey = null) {
const scriptPath = join(directory, ".trellis", "scripts", "get_context.py")
if (!existsSync(scriptPath)) {
return { isMonorepo: false, packages: {}, specScope: null, activeTaskPackage: null, defaultPackage: null }
}
try {
const output = execFileSync(PYTHON_CMD, [scriptPath, "--mode", "packages", "--json"], {
cwd: directory,
timeout: 5000,
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
...(contextKey ? { TRELLIS_CONTEXT_ID: contextKey } : {}),
},
})
const data = JSON.parse(output)
if (data.mode !== "monorepo") {
return { isMonorepo: false, packages: {}, specScope: null, activeTaskPackage: null, defaultPackage: null }
}
const pkgDict = {}
for (const pkg of (data.packages || [])) {
pkgDict[pkg.name] = pkg
}
return {
isMonorepo: true,
packages: pkgDict,
specScope: data.specScope || null,
activeTaskPackage: data.activeTaskPackage || null,
defaultPackage: data.defaultPackage || null,
}
} catch (e) {
debugLog("session", "loadTrellisConfig error:", e.message)
return { isMonorepo: false, packages: {}, specScope: null, activeTaskPackage: null, defaultPackage: null }
}
}
function checkLegacySpec(directory, config) {
if (!config.isMonorepo || Object.keys(config.packages).length === 0) {
return null
}
const specDir = join(directory, ".trellis", "spec")
if (!existsSync(specDir)) return null
let hasLegacy = false
for (const name of ["backend", "frontend"]) {
if (existsSync(join(specDir, name, "index.md"))) {
hasLegacy = true
break
}
}
if (!hasLegacy) return null
const pkgNames = Object.keys(config.packages).sort()
const missing = pkgNames.filter(name => !existsSync(join(specDir, name)))
if (missing.length === 0) return null
if (missing.length === pkgNames.length) {
return (
`[!] Legacy spec structure detected: found \`spec/backend/\` or \`spec/frontend/\` ` +
`but no package-scoped \`spec/<package>/\` directories.\n` +
`Monorepo packages: ${pkgNames.join(", ")}\n` +
`Please reorganize: \`spec/backend/\` -> \`spec/<package>/backend/\``
)
}
return (
`[!] Partial spec migration detected: packages ${missing.join(", ")} ` +
`still missing \`spec/<pkg>/\` directory.\n` +
`Please complete migration for all packages.`
)
}
function resolveSpecScope(config) {
if (!config.isMonorepo || Object.keys(config.packages).length === 0) {
return null
}
const { specScope, activeTaskPackage, defaultPackage, packages } = config
if (specScope == null) return null
if (specScope === "active_task") {
if (activeTaskPackage && activeTaskPackage in packages) return new Set([activeTaskPackage])
if (defaultPackage && defaultPackage in packages) return new Set([defaultPackage])
return null
}
if (Array.isArray(specScope)) {
const valid = new Set()
for (const entry of specScope) {
if (entry in packages) {
valid.add(entry)
}
}
if (valid.size > 0) return valid
if (activeTaskPackage && activeTaskPackage in packages) return new Set([activeTaskPackage])
if (defaultPackage && defaultPackage in packages) return new Set([defaultPackage])
return null
}
return null
}
export function buildSessionContext(ctx, platformInput = null) {
const directory = ctx.directory
const trellisDir = join(directory, ".trellis")
const contextKey = typeof ctx.getContextKey === "function"
? ctx.getContextKey(platformInput)
: null
const config = loadTrellisConfig(directory, contextKey)
const allowedPkgs = resolveSpecScope(config)
const parts = []
parts.push(`<trellis-context>
You are starting a new session in a Trellis-managed project.
Read and follow all instructions below carefully.
</trellis-context>`)
parts.push(FIRST_REPLY_NOTICE)
const legacyWarning = checkLegacySpec(directory, config)
if (legacyWarning) {
parts.push(`<migration-warning>\n${legacyWarning}\n</migration-warning>`)
}
const contextScript = join(trellisDir, "scripts", "get_context.py")
if (existsSync(contextScript)) {
const output = ctx.runScript(contextScript, undefined, contextKey)
if (output) {
parts.push("<current-state>")
parts.push(output)
parts.push("</current-state>")
}
}
const workflowContent = ctx.readProjectFile(".trellis/workflow.md")
if (workflowContent) {
const allLines = workflowContent.split("\n")
const overviewLines = [
"# Development Workflow — Section Index",
"Full guide: .trellis/workflow.md (read on demand)",
"",
"## Table of Contents",
]
for (const line of allLines) {
if (line.startsWith("## ")) overviewLines.push(line)
}
overviewLines.push("", "---", "")
let rangeStart = -1
let rangeEnd = allLines.length
for (let i = 0; i < allLines.length; i++) {
const stripped = allLines[i].trim()
if (rangeStart === -1 && stripped === "## Phase Index") {
rangeStart = i
} else if (rangeStart !== -1 && stripped === "## Workflow State Breadcrumbs") {
rangeEnd = i
break
}
}
if (rangeStart !== -1) {
overviewLines.push(...allLines.slice(rangeStart, rangeEnd))
}
parts.push("<workflow>")
parts.push(overviewLines.join("\n").trimEnd())
parts.push("</workflow>")
}
parts.push("<guidelines>")
parts.push(
"Project spec indexes are listed by path below. Each index contains a " +
"**Pre-Development Checklist** listing the specific guideline files to " +
"read before coding.\n\n" +
"- If you're spawning an implement/check sub-agent, context is injected " +
"automatically via `{task}/implement.jsonl` / `check.jsonl`. You do NOT " +
"need to read these indexes yourself.\n" +
"- For agent-capable platforms, do NOT edit code directly in the main " +
"session; dispatch `trellis-implement` and `trellis-check` so JSONL " +
"context is loaded by the sub-agents.\n"
)
const specDir = join(directory, ".trellis", "spec")
const guidesIndex = join(specDir, "guides", "index.md")
if (existsSync(guidesIndex)) {
const content = ctx.readFile(guidesIndex)
if (content) {
parts.push(`## guides (inlined — cross-package thinking guides)\n${content}\n`)
}
}
const paths = []
if (existsSync(specDir)) {
try {
const subs = readdirSync(specDir).filter(name => {
if (name.startsWith(".")) return false
try {
return statSync(join(specDir, name)).isDirectory()
} catch {
return false
}
}).sort()
for (const sub of subs) {
if (sub === "guides") continue
const indexFile = join(specDir, sub, "index.md")
if (existsSync(indexFile)) {
paths.push(`.trellis/spec/${sub}/index.md`)
} else {
if (allowedPkgs !== null && !allowedPkgs.has(sub)) continue
try {
const nested = readdirSync(join(specDir, sub)).filter(name => {
try {
return statSync(join(specDir, sub, name)).isDirectory()
} catch {
return false
}
}).sort()
for (const layer of nested) {
const nestedIndex = join(specDir, sub, layer, "index.md")
if (existsSync(nestedIndex)) {
paths.push(`.trellis/spec/${sub}/${layer}/index.md`)
}
}
} catch {
// Ignore directory read errors
}
}
}
} catch {
// Ignore spec directory read errors
}
}
if (paths.length > 0) {
parts.push("## Available spec indexes (read on demand)")
for (const p of paths) {
parts.push(`- ${p}`)
}
parts.push("")
}
parts.push(
"Discover more via: " +
"`python3 ./.trellis/scripts/get_context.py --mode packages`"
)
parts.push("</guidelines>")
const taskStatus = getTaskStatus(ctx, platformInput)
parts.push(`<task-status>\n${taskStatus}\n</task-status>`)
parts.push(`<ready>
Context loaded. Workflow index, project state, and guidelines are already injected above — do NOT re-read them.
When the user sends the first message, follow <task-status> and the workflow guide.
If a task is READY, execute its Next required action without asking whether to continue.
</ready>`)
return parts.join("\n\n")
}
function getTrellisMetadata(metadata) {
if (!metadata || typeof metadata !== "object") {
return {}
}
const trellis = metadata.trellis
if (!trellis || typeof trellis !== "object") {
return {}
}
return trellis
}
function markPartAsSessionStart(part) {
const metadata = part.metadata && typeof part.metadata === "object"
? part.metadata
: {}
part.metadata = {
...metadata,
trellis: {
...getTrellisMetadata(metadata),
sessionStart: true,
},
}
}
function hasSessionStartMarker(part) {
if (!part || part.type !== "text" || typeof part.text !== "string") {
return false
}
return getTrellisMetadata(part.metadata).sessionStart === true
}
export function hasInjectedTrellisContext(messages) {
if (!Array.isArray(messages)) {
return false
}
return messages.some(message => {
if (!message?.info || message.info.role !== "user" || !Array.isArray(message.parts)) {
return false
}
return message.parts.some(hasSessionStartMarker)
})
}
export async function hasPersistedInjectedContext(client, directory, sessionID) {
try {
const response = await client.session.messages({
path: { id: sessionID },
query: { directory },
throwOnError: true,
})
return hasInjectedTrellisContext(response.data || [])
} catch (error) {
debugLog(
"session",
"Failed to read session history for dedupe:",
error instanceof Error ? error.message : String(error),
)
return false
}
}
export function markContextInjected(part) {
markPartAsSessionStart(part)
}

View File

@@ -0,0 +1,381 @@
/**
* Trellis Context Manager
*
* Utility class for OpenCode plugins providing file reading,
* JSONL parsing, and context building capabilities.
*/
import { existsSync, readFileSync, appendFileSync, readdirSync } from "fs"
import { isAbsolute, join } from "path"
import { platform } from "os"
import { execSync } from "child_process"
import { createHash } from "crypto"
import process from "process"
const PYTHON_CMD = platform() === "win32" ? "python" : "python3"
// Debug logging
const DEBUG_LOG = "/tmp/trellis-plugin-debug.log"
function debugLog(prefix, ...args) {
const timestamp = new Date().toISOString()
const msg = `[${timestamp}] [${prefix}] ${args.map(a => typeof a === "object" ? JSON.stringify(a) : a).join(" ")}\n`
try {
appendFileSync(DEBUG_LOG, msg)
} catch {
// ignore
}
}
function stringValue(value) {
return typeof value === "string" && value.trim() ? value.trim() : null
}
function sanitizeKey(raw) {
const safe = raw.trim().replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^[._-]+|[._-]+$/g, "")
return safe ? safe.slice(0, 160) : ""
}
function hashValue(raw) {
return createHash("sha256").update(raw).digest("hex").slice(0, 24)
}
function lookupString(data, keys) {
if (!data || typeof data !== "object") return null
for (const key of keys) {
const value = stringValue(data[key])
if (value) return value
}
for (const nestedKey of ["input", "properties", "event", "hook_input", "hookInput"]) {
const nested = data[nestedKey]
if (nested && typeof nested === "object") {
const value = lookupString(nested, keys)
if (value) return value
}
}
return null
}
function buildContextKey(platformName, kind, value) {
if (kind === "transcript") {
return `${platformName}_transcript_${hashValue(value)}`
}
const safeValue = sanitizeKey(value)
return safeValue ? `${platformName}_${safeValue}` : `${platformName}_${hashValue(value)}`
}
// Matches `trellis-implement`, `trellis-check`, `trellis-research` exactly.
// Used by chat.message plugins to skip injection inside Trellis sub-agent turns.
const TRELLIS_SUBAGENT_RE = /^trellis-(implement|check|research)$/
/**
* Return true when the OpenCode `chat.message` input represents a Trellis
* sub-agent turn. `input.agent` is set by OpenCode when a Task tool spawns a
* child session with a custom agent (see `packages/opencode/src/tool/task.ts`).
*/
export function isTrellisSubagent(input) {
if (!input || typeof input !== "object") return false
const agent = typeof input.agent === "string" ? input.agent.trim() : ""
return TRELLIS_SUBAGENT_RE.test(agent)
}
/**
* Trellis Context Manager
*/
export class TrellisContext {
constructor(directory) {
this.directory = directory
debugLog("context", "TrellisContext initialized", { directory })
}
// ============================================================
// Trellis Project Detection
// ============================================================
isTrellisProject() {
return existsSync(join(this.directory, ".trellis"))
}
getContextKey(platformInput = null) {
const override = stringValue(process.env.TRELLIS_CONTEXT_ID)
if (override) {
return sanitizeKey(override) || hashValue(override)
}
const runID = stringValue(process.env.OPENCODE_RUN_ID)
if (runID) return buildContextKey("opencode", "session", runID)
const input = platformInput && typeof platformInput === "object" ? platformInput : null
if (!input) return null
const sessionID = lookupString(input, ["session_id", "sessionId", "sessionID"])
if (sessionID) return buildContextKey("opencode", "session", sessionID)
const conversationID = lookupString(input, ["conversation_id", "conversationId", "conversationID"])
if (conversationID) return buildContextKey("opencode", "conversation", conversationID)
const transcriptPath = lookupString(input, ["transcript_path", "transcriptPath", "transcript"])
if (transcriptPath) return buildContextKey("opencode", "transcript", transcriptPath)
return null
}
readContext(contextKey) {
try {
const contextPath = join(this.directory, ".trellis", ".runtime", "sessions", `${contextKey}.json`)
if (!existsSync(contextPath)) return null
return JSON.parse(readFileSync(contextPath, "utf-8"))
} catch {
return null
}
}
/**
* Get active task from session runtime context.
*
* Resolution order (mirrors Python `active_task.resolve_active_task`):
* 1. Lookup the runtime file for the input-derived context key.
* 2. If that misses and exactly one session runtime file exists locally,
* use it (`_resolveSingleSessionFallback`). Refuses to guess when 0 or
* ≥2 files exist so multi-window isolation holds.
*/
getActiveTask(platformInput = null) {
const contextKey = this.getContextKey(platformInput)
if (contextKey) {
const context = this.readContext(contextKey)
const taskRef = this.normalizeTaskRef(context?.current_task || "")
if (taskRef) {
const taskDir = this.resolveTaskDir(taskRef)
return {
taskPath: taskRef,
source: `session:${contextKey}`,
stale: !taskDir || !existsSync(taskDir),
}
}
}
const fallback = this._resolveSingleSessionFallback()
if (fallback) {
return fallback
}
return { taskPath: null, source: "none", stale: false }
}
/**
* Mirror of Python `_resolve_single_session_fallback`. Returns the task
* pointed at by the sole session runtime file when exactly one exists,
* else null.
*/
_resolveSingleSessionFallback() {
const sessionsDir = join(this.directory, ".trellis", ".runtime", "sessions")
if (!existsSync(sessionsDir)) return null
let files
try {
files = readdirSync(sessionsDir)
.filter(name => name.endsWith(".json"))
.sort()
} catch {
return null
}
if (files.length !== 1) return null
const sessionFile = join(sessionsDir, files[0])
let context
try {
context = JSON.parse(readFileSync(sessionFile, "utf-8"))
} catch {
return null
}
const taskRef = this.normalizeTaskRef(context?.current_task || "")
if (!taskRef) return null
const taskDir = this.resolveTaskDir(taskRef)
const fallbackKey = files[0].replace(/\.json$/, "")
return {
taskPath: taskRef,
source: `session-fallback:${fallbackKey}`,
stale: !taskDir || !existsSync(taskDir),
}
}
getCurrentTask(platformInput = null) {
return this.getActiveTask(platformInput).taskPath
}
normalizeTaskRef(taskRef) {
if (!taskRef) {
return ""
}
if (isAbsolute(taskRef)) {
return taskRef.trim()
}
let normalized = taskRef.trim().replace(/\\/g, "/")
while (normalized.startsWith("./")) {
normalized = normalized.slice(2)
}
if (normalized.startsWith("tasks/")) {
return `.trellis/${normalized}`
}
return normalized
}
resolveTaskDir(taskRef) {
const normalized = this.normalizeTaskRef(taskRef)
if (!normalized) {
return null
}
if (isAbsolute(normalized)) {
return normalized
}
if (normalized.startsWith(".trellis/")) {
return join(this.directory, normalized)
}
return join(this.directory, ".trellis", "tasks", normalized)
}
// ============================================================
// File Reading Utilities
// ============================================================
readFile(filePath) {
try {
if (existsSync(filePath)) {
return readFileSync(filePath, "utf-8")
}
} catch {
// Ignore read errors
}
return null
}
readProjectFile(relativePath) {
return this.readFile(join(this.directory, relativePath))
}
runScript(scriptPath, cwd = null, contextKey = null) {
try {
const result = execSync(`${PYTHON_CMD} "${scriptPath}"`, {
cwd: cwd || this.directory,
timeout: 10000,
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
...(contextKey ? { TRELLIS_CONTEXT_ID: contextKey } : {}),
},
})
return result || ""
} catch {
return ""
}
}
// ============================================================
// JSONL Reading
// ============================================================
readDirectoryMdFiles(dirPath, maxFiles = 20) {
const results = []
const fullPath = join(this.directory, dirPath)
if (!existsSync(fullPath)) {
return results
}
try {
const files = readdirSync(fullPath)
.filter(f => f.endsWith(".md"))
.sort()
.slice(0, maxFiles)
for (const filename of files) {
const filePath = join(dirPath, filename)
const content = this.readProjectFile(filePath)
if (content) {
results.push({ path: filePath, content })
}
}
} catch {
// Ignore directory read errors
}
return results
}
/**
* Read a JSONL file and load referenced files/directories
* Supports:
* {"file": "path/to/file.md", "reason": "..."}
* {"file": "path/to/dir/", "type": "directory", "reason": "..."}
*/
readJsonlWithFiles(jsonlPath) {
const results = []
const content = this.readFile(jsonlPath)
if (!content) return results
for (const line of content.split("\n")) {
if (!line.trim()) continue
try {
const item = JSON.parse(line)
const file = item.file || item.path
const entryType = item.type || "file"
if (!file) continue
if (entryType === "directory") {
const dirEntries = this.readDirectoryMdFiles(file)
results.push(...dirEntries)
} else {
const fullPath = join(this.directory, file)
const fileContent = this.readFile(fullPath)
if (fileContent) {
results.push({ path: file, content: fileContent })
}
}
} catch {
// Ignore parse errors for individual lines
}
}
return results
}
buildContextFromEntries(entries) {
return entries.map(e => `=== ${e.path} ===\n${e.content}`).join("\n\n")
}
}
// ============================================================
// Context Collector (for session deduplication)
// ============================================================
class ContextCollector {
constructor() {
this.processed = new Set()
}
markProcessed(sessionID) {
this.processed.add(sessionID)
}
isProcessed(sessionID) {
return this.processed.has(sessionID)
}
clear(sessionID) {
this.processed.delete(sessionID)
}
}
// Singleton instance
export const contextCollector = new ContextCollector()
// Export debug log for plugins
export { debugLog }