Documentation
¶
Overview ¶
Package knowledge implements the knowledge layer's page contract and the bookkeeping that keeps the layer honest about which code it describes (方案 §12): the front matter every page carries, located validation, and the scan/freshness machinery the later milestones build on.
The layer has two halves (方案 §12.6). The index layer is ours: it is scanned from the project and can be rebuilt at will. The page layer is written by an external generator — RepoWiki is the preferred optional one — so pages are an interop surface: unknown front matter keys are warnings, not errors, and `sources` may live in the generator's state mapping instead of the page.
Index ¶
- Constants
- Variables
- func AheadBehind(root string) (ahead, behind int, err error)
- func Changes(root, commit string) ([]string, error)
- func ClearCheckpoint(root string) error
- func ExistingRoots(root string, candidates []string) []string
- func GeneratorCommand(command string, scopePath, projectRoot string) ([]string, error)
- func HashBytes(data []byte) string
- func HashFile(path string) (string, error)
- func Head(root string) (commit, branch string, err error)
- func LockRefresh(root string) (func() error, error)
- func Match(pattern, path string) bool
- func MergeHeads(root string) ([]string, error)
- func MissingCheckpoint(err error) bool
- func MissingState(err error) bool
- func ResumePending(root string, pages []*Page, state *State, pending []string) ([]string, error)
- func TriggerHit(triggers []string, lowerText string) (string, bool)
- func Upstream(root string) (string, error)
- func WorkItemText(item *domain.WorkItem) string
- func WriteCheckpoint(root string, checkpoint *Checkpoint) (string, error)
- func WriteScope(root string, scope Scope) (string, error)
- func WriteSnapshot(root string, snapshot *Snapshot) (string, error)
- func WriteState(root string, state *State) (string, error)
- type Adapter
- type Availability
- type Baseline
- type Checkpoint
- type Exclusion
- type FileEntry
- type Freshness
- type GenerateRequest
- type GenerateResult
- type IgnoreFile
- type Page
- type PageFreshness
- type PageState
- type PorcelainEntry
- type Report
- type ScanOptions
- type Scope
- type Skip
- type Snapshot
- type SnapshotExcluded
- type SnapshotStats
- type State
Constants ¶
const ( ScopeFull = "full" ScopeAffected = "affected" )
ScopeModes a refresh can ask for.
const ( // Dir is the knowledge layer's home under .devsys/ (index layer and // bookkeeping). Dir = ".devsys/knowledge" // DefaultRepowikiRoot is the RepoWiki bundle's knowledge cards: the // preferred optional generator's page layer (方案 §12.6). DefaultRepowikiRoot = "docs/repowiki/knowledge" // DefaultPagesRoot is where a generator that follows the contract writes // pages directly. DefaultPagesRoot = ".devsys/knowledge/pages" // SnapshotFile is the index-layer snapshot (M5.2). SnapshotFile = ".devsys/knowledge/snapshot.json" // StateFile holds the freshness baseline and the page mapping (M5.3). StateFile = ".devsys/knowledge/state.json" // RunFile is the generator checkpoint that makes a refresh resumable // (M5.5). RunFile = ".devsys/knowledge/run.json" )
Layout constants. The page layer is wherever a generator writes it; these are the locations this system knows by name.
const ( PhaseGenerating = "generating" PhaseFinished = "finished" PhaseFailed = "failed" )
Checkpoint phases.
const CustomIgnoreFile = Dir + "/ignore"
CustomIgnoreFile is the project's own ignore list for the index.
const DefaultMaxFileSize = 1 << 20
DefaultMaxFileSize is the index's size ceiling: a file larger than this is listed as excluded rather than hashed (方案 §12.2 keeps the index to what a reader or an agent could actually load).
const FormatVersion = 1
FormatVersion is the page format contract version this build speaks; a generator is told which one it must produce (方案 §12.6).
const ProbeTimeout = 10 * time.Second
ProbeTimeout bounds a probe: a generator that hangs on startup must not hang the status command that asked whether it is there.
const RunLockFile = Dir + "/run.lock"
RunLockFile is the refresh mutex: an OS-level exclusive lock, released when the process dies, so a killed refresh never blocks the next one.
const RunSchemaVersion = 1
RunSchemaVersion is the only checkpoint version this build reads or writes.
const ScopeFile = Dir + "/refresh-scope.json"
ScopeFile is the generation scope handed to a generator. It is written on every refresh so the request is inspectable after the fact, and so a long page list does not have to survive a command line.
const SnapshotSchemaVersion = 1
SnapshotSchemaVersion is the only snapshot version this build writes.
const StateSchemaVersion = 1
StateSchemaVersion is the only state version this build reads or writes.
Variables ¶
var AuthoredStatuses = []string{"current", "stable", "draft", "unverified", "conflicted", "deprecated", "archived"}
AuthoredStatuses are the statuses a page may declare. `stale` and `invalid` are deliberately absent: the freshness check (方案 §12.5) and this validator compute them, and a hand-written claim about a computed state is a lie the layer cannot check.
var DefaultExcludedDirectories = []string{".git", ".devsys", ".repowiki", "vendor", "node_modules"}
DefaultExcludedDirectories are directory names the index never descends into: version control, the layer's own state, tooling state, and vendored dependencies.
var DefaultRoots = []string{DefaultRepowikiRoot, DefaultPagesRoot}
DefaultRoots are the page roots a command reads when the project does not configure `knowledge_pages`. RepoWiki comes first because it is the preferred optional generator; a root that does not exist is skipped by the caller rather than reported.
var ErrNoGit = errors.New("git is required to apply .gitignore")
ErrNoGit reports that .gitignore matching could not be applied because git is unavailable or failed. 方案 §12.5 forbids degrading to "no ignores": silently indexing files the project excluded would make every downstream claim about coverage untrue.
var ErrNoUpstream = errors.New("no upstream configured for the current branch")
ErrNoUpstream reports that the current branch tracks no upstream branch. Callers treat it as a handoff blocker (there is nothing to push to or pull from), not as a command failure (方案 §14.4).
var KnownKeys = []string{
"status", "type", "dimension", "triggers", "description", "generated",
"generator", "source_commit", "sources", "content_hash", "protected",
}
KnownKeys is the front matter this contract defines. Anything else is a warning: pages come from external generators, so unknown keys are an interop fact, not a defect.
var KnownTypes = []string{"module", "overview", "architecture", "api", "data_model", "config", "test", "process", "guide", "reference", "note"}
KnownTypes carry a defined meaning here. Other lowercase tokens are accepted with a warning: generators have their own vocabulary (RepoWiki's dimensions, for one) and the contract must not pretend to be closed.
var RequiredKeys = []string{"status", "type", "triggers", "description", "source_commit"}
RequiredKeys must be present (their values are checked separately).
var SecretPatterns = []string{
".env", ".env.*", "*.env",
"*.pem", "*.key", "*.p12", "*.pfx", "*.keystore", "*.jks",
"id_rsa*", "id_dsa*", "id_ecdsa*", "id_ed25519*",
"credentials", "credentials.*", "secrets", "secrets.*",
"*.npmrc", ".netrc", ".htpasswd",
}
SecretPatterns are the name patterns whose content is never fingerprinted. The list is deliberately conservative: a false positive hides a file that a human can whitelist by renaming, while a false negative would put a credential into a file that agents are encouraged to read.
Functions ¶
func AheadBehind ¶
AheadBehind counts how far HEAD and its upstream have diverged, using only locally recorded refs (no fetch, no network). ahead counts local-only commits, behind counts upstream-only commits.
func Changes ¶
Changes lists the paths that differ between a commit and the working tree: committed changes, uncommitted modifications and deletions, and untracked files. Comparing against the working tree rather than HEAD is deliberate — a page that describes committed code is stale the moment the tree changes, whether or not anyone has committed yet.
func ClearCheckpoint ¶
ClearCheckpoint removes the checkpoint after a run finished cleanly. A missing file is not an error: the run may have been the one that created it.
func ExistingRoots ¶
ExistingRoots keeps the candidates that exist under root, in order. It backs the default page roots: a candidate that is not there is a project that does not use that generator, not a problem to report.
func GeneratorCommand ¶
GeneratorCommand builds the argv for one generator run from the configured command. The command is split on whitespace and never handed to a shell: a configured generator is a program with arguments, and a shell would add a second, platform-specific parsing layer to the contract.
func HashFile ¶
HashFile returns the content hash the layer records and compares: the sha256 of the file's bytes, lowercase hex. This is deliberately the whole file, front matter included, and the reference generator records the same value — a bundle's recorded hashes can therefore be compared as they are.
func Head ¶
Head returns the working tree's commit and branch. A detached HEAD reports the literal "HEAD" as the branch: the identity of the tree is the commit, and inventing a branch name would be a claim the repository does not make.
func LockRefresh ¶
LockRefresh takes the refresh mutex. A held lock means another refresh is running; releasing is the caller's job. The lock file's directory is created when needed: a project that has never refreshed has no .devsys/knowledge yet, and a mutex that cannot exist would make the first refresh fail.
func Match ¶
Match reports whether a slash-separated project-relative path matches a pattern. Patterns follow the ignore-file conventions the layer documents:
- `*` matches inside one path segment, `?` matches one character inside a segment, `**` crosses segments;
- a pattern without `/` matches at any depth (`*.key` matches `a/b/secret.key`);
- a pattern with `/` is anchored at the project root;
- a trailing `/` makes the pattern cover the directory's whole subtree.
The same shape is used for the custom ignore file, for page `sources` patterns, and for the file index, so one implementation defines it.
func MergeHeads ¶
MergeHeads names the in-progress merge machinery git currently holds (MERGE_HEAD, CHERRY_PICK_HEAD, REBASE_HEAD, REVERT_HEAD, rebase-merge/, rebase-apply/): any of them means a merge the operator started and never finished. Read-only: existence checks only.
func MissingCheckpoint ¶
MissingCheckpoint reports whether the error means "there is no checkpoint".
func MissingState ¶
MissingState reports whether the error means "there is no state file".
func ResumePending ¶
ResumePending reduces an interrupted run's page list to the pages that still need regenerating. A page whose recorded content hash already matches the file on disk was finished before the interruption, and the generator contract makes re-running it harmless but pointless (方案 §12.6: 幂等); this is what keeps a resumed run from rewriting work that is done.
func TriggerHit ¶
TriggerHit reports the first trigger that occurs in lowerText, the relevance rule the context assembly and the workspace view share (M5.6, 方案 §10.2): the trimmed trigger, lowercased, must appear as a substring, and the first match in trigger order wins. Callers pass text they have lowercased once, so a scan over many pages pays for the lowercasing once, not per page.
func Upstream ¶
Upstream returns the full name (remote/branch) of the current branch's upstream. Read-only: it resolves the locally recorded @{u}, never fetching.
func WorkItemText ¶
WorkItemText is the text knowledge triggers are matched against (M5.6): the work item's title, description and type plus its workflow instance's id and step, newline-joined so one field cannot fake another, then lowercased once.
func WriteCheckpoint ¶
func WriteCheckpoint(root string, checkpoint *Checkpoint) (string, error)
WriteCheckpoint stores the checkpoint atomically.
func WriteScope ¶
WriteScope stores the scope atomically and returns its project-relative path.
func WriteSnapshot ¶
WriteSnapshot stores the snapshot atomically at .devsys/knowledge/ snapshot.json.
Types ¶
type Adapter ¶
type Adapter interface {
// Name is the identifier a project writes in `knowledge_generator`.
Name() string
// Probe reports whether the generator is installed.
Probe(ctx context.Context) Availability
// Import maps the generator's own state onto the layer's State. A generator
// that has not run yet returns (nil, nil): there is nothing to import, and
// that is not a failure.
Import(root string) (*State, error)
// Generate runs the generator's mechanical steps for one scope.
Generate(ctx context.Context, req GenerateRequest) (GenerateResult, error)
}
Adapter bridges one external page generator.
func AdapterByName ¶
AdapterByName resolves a `knowledge_generator` value to a built-in adapter.
type Availability ¶
type Availability struct {
Installed bool `json:"installed"`
Detail string `json:"detail,omitempty"`
}
Availability is what a probe learned about one generator.
type Checkpoint ¶
type Checkpoint struct {
SchemaVersion int `json:"schema_version"`
PID int `json:"pid"`
Host string `json:"host,omitempty"`
Phase string `json:"phase"`
Mode string `json:"mode"`
Generator string `json:"generator,omitempty"`
ScopeFile string `json:"scope_file,omitempty"`
StartedAt time.Time `json:"started_at"`
UpdatedAt time.Time `json:"updated_at"`
// Pages is the set this run asked the generator for; Completed is what the
// run had confirmed when it last wrote the checkpoint.
Pages []string `json:"pages"`
Completed []string `json:"completed,omitempty"`
Error string `json:"error,omitempty"`
}
Checkpoint is the refresh's progress record (.devsys/knowledge/run.json, 方案 §12.5). It exists to make an interrupted refresh resumable instead of restartable: a killed run leaves it behind, and the next run reduces its page list to the pages that still do not match their record.
func LoadCheckpoint ¶
func LoadCheckpoint(root string) (*Checkpoint, error)
LoadCheckpoint reads the checkpoint; a missing file reports fs.ErrNotExist.
type FileEntry ¶
type FileEntry struct {
Path string `json:"path"`
Size int64 `json:"size"`
Hash string `json:"hash"`
Language string `json:"language"`
}
FileEntry is one fingerprinted file.
type Freshness ¶
type Freshness struct {
Pages []PageFreshness `json:"pages"`
// ChangedFiles counts the working-tree changes the verdict considered.
ChangedFiles int `json:"changed_files"`
}
Freshness is the layer-level verdict.
func Evaluate ¶
Evaluate compares every page against the working tree. Sources come from the page first and from the generator's mapping otherwise (方案 §12.5); the baseline is the page's own `source_commit` when it has one, else the mapping's, else the layer baseline. Git failures are errors: §12.5 forbids degrading to an "unknown baseline".
func (Freshness) Unverifiable ¶
Unverifiable lists the pages the layer cannot claim anything about: no sources to attribute changes to, or no baseline to compare with. They are the reason a run reports stale even when nothing matches — "cannot tell" is not "fresh".
type GenerateRequest ¶
type GenerateRequest struct {
// Root is the project root.
Root string
// ScopeFile is the scope this layer wrote (Scope), project-relative.
ScopeFile string
// Pages is the scope's page list, resolved for the adapter's own
// bookkeeping.
Pages []string
}
GenerateRequest is one adapter run.
type GenerateResult ¶
type GenerateResult struct {
// Output is the combined output of the steps that ran.
Output string `json:"output,omitempty"`
// Finalized reports whether the generator recorded a new baseline.
Finalized bool `json:"finalized,omitempty"`
// AwaitingGeneration lists pages the generator cannot write by itself.
// RepoWiki is agent-driven: its CLI scans and bookkeeps, while the pages are
// written through its skill. Saying so is the honest outcome.
AwaitingGeneration []string `json:"awaiting_generation,omitempty"`
// Note explains the run in one line.
Note string `json:"note,omitempty"`
}
GenerateResult reports what an adapter run did.
type IgnoreFile ¶
type IgnoreFile struct {
// Path is where the file came from, relative to the project root; empty
// for an inline rule set.
Path string
// contains filtered or unexported fields
}
IgnoreFile holds the compiled patterns of one ignore file.
func ParseIgnoreFile ¶
func ParseIgnoreFile(rel string, data []byte) (*IgnoreFile, []string)
ParseIgnoreFile reads a custom ignore file: one pattern per line, `#` comments and blank lines skipped. Negation is not supported — an ignore file that cannot express `!` is easier to reason about, and the project's `.gitignore` already covers the cases that need it.
func (*IgnoreFile) Match ¶
func (f *IgnoreFile) Match(path string) bool
Match reports whether the path is ignored by this file.
func (*IgnoreFile) Patterns ¶
func (f *IgnoreFile) Patterns() []string
Patterns returns the patterns in file order.
type Page ¶
type Page struct {
// Path is the page's location, slash separated and relative to the
// project root.
Path string
Status string
Type string
Dimension string
Triggers []string
Description string
SourceCommit string
Sources []string
ContentHash string
Generator string
Generated bool
Protected bool
// Keys lists every top-level front matter key in file order.
Keys []string
// Body is the Markdown body; BodyLine is the 1-based line where it starts
// (the line after the closing fence).
Body string
BodyLine int
}
Page is one Markdown knowledge page: front matter plus body. Fields that failed to parse keep their zero value and the matching problem is reported.
type PageFreshness ¶
type PageFreshness struct {
Path string `json:"path"`
// Stale is true when a change since the page's baseline touches a pattern
// the page covers.
Stale bool `json:"stale"`
// Baseline is the commit the verdict compared against; empty when the page
// has no baseline at all and therefore cannot be called fresh.
Baseline string `json:"baseline,omitempty"`
// Reason explains a stale or unverifiable verdict.
Reason string `json:"reason,omitempty"`
// AffectedBy lists the changed paths that made the page stale (bounded by
// the caller's patience: every matching path is recorded).
AffectedBy []string `json:"affected_by,omitempty"`
}
PageFreshness is one page's verdict.
type PageState ¶
type PageState struct {
Sources []string `json:"sources,omitempty"`
ContentHash string `json:"content_hash,omitempty"`
SourceCommit string `json:"source_commit,omitempty"`
}
PageState is the mapping entry for one page: the patterns it covers and the hash of what the generator last wrote (方案 §12.5). Pages may declare `sources` themselves; this mapping is the other half of the contract — a generator that keeps its own state (RepoWiki does) supplies them here.
type PorcelainEntry ¶
type PorcelainEntry struct {
// XY is the two-letter index/worktree status (e.g. "M ", "??", "UU").
XY string
// Path is the worktree-relative path (the new name for renames).
Path string
// Orig holds the source path for renames/copies, else "".
Orig string
// Unmerged is true for the seven unmerged XY codes (DD AU UD UA DU AA UU):
// a merge both devices touched and git could not reconcile.
Unmerged bool
}
PorcelainEntry is one `git status --porcelain` record.
func PorcelainStatus ¶
func PorcelainStatus(root string) ([]PorcelainEntry, error)
PorcelainStatus lists the working tree's uncommitted changes without touching them. With -z, a rename/copies entry is "XY new\0orig\0": the source path is a separate NUL-terminated field the parser must consume.
type Report ¶
type Report struct {
// Roots are the roots that were scanned, slash separated and relative to
// the project root, in scan order.
Roots []string
// Missing is true when no roots were given: the page layer has not been
// generated (方案 §12.6), which is a degradation and not a defect.
Missing bool
// Pages are the parsed pages, in path order.
Pages []*Page
// Problems are all located problems, both severities.
Problems []config.Problem
}
Report is the outcome of validating a set of page roots.
func Scan ¶
Scan parses and validates every page under roots. A root is a project-relative directory (scanned recursively for .md files, dot directories skipped) or a single page file. Results are deterministic: files are visited in sorted order.
type ScanOptions ¶
type ScanOptions struct {
// MaxFileSize overrides DefaultMaxFileSize when positive.
MaxFileSize int64
// Now overrides the clock (tests).
Now func() time.Time
// SkipGitIgnore leaves .gitignore matching to the caller: without a git
// repository the scan cannot honour it, and §12.5 forbids pretending
// otherwise, so the caller decides whether that is an error.
SkipGitIgnore bool
}
ScanOptions configures a scan.
type Scope ¶
type Scope struct {
FormatVersion int `json:"format_version"`
Project string `json:"project"`
Mode string `json:"mode"`
Baseline string `json:"baseline,omitempty"`
Head string `json:"head,omitempty"`
Pages []string `json:"pages"`
}
Scope is the generator contract's input (方案 §12.6): project root, the generation range, and the page format version.
type Skip ¶
type Skip struct {
Path string `json:"path"`
Reason string `json:"reason"`
// Recorded is the hash the generator wrote down; Actual is what is on disk
// now. They differ exactly when a page was edited by hand.
Recorded string `json:"recorded_hash,omitempty"`
Actual string `json:"actual_hash,omitempty"`
// Overridden is true when --force regenerated the page anyway: the skip is
// then a report, not an outcome.
Overridden bool `json:"overridden,omitempty"`
}
Skip is one page a refresh leaves alone, and why (方案 §12.5).
func Skips ¶
Skips lists the pages a refresh must not regenerate:
- `protected: true` is a permanent lock;
- a page whose recorded `content_hash` differs from the file on disk was edited by hand — its content is not the generator's to replace.
Both are overridden only by `--force`, and an override is still reported. A page with no recorded hash is not a skip: nothing was recorded, so there is nothing to compare and no claim to protect.
type Snapshot ¶
type Snapshot struct {
SchemaVersion int `json:"schema_version"`
GeneratedAt time.Time `json:"generated_at"`
Files []FileEntry `json:"files"`
Stats SnapshotStats `json:"stats"`
Excluded SnapshotExcluded `json:"excluded"`
}
Snapshot is the index layer's fingerprint of the working tree (.devsys/knowledge/snapshot.json). It is derived state: deleting it costs one rescan.
func BuildSnapshot ¶
func BuildSnapshot(root string, opts ScanOptions) (*Snapshot, error)
BuildSnapshot walks the project and fingerprints every file that survives the exclusion rules. Errors are explicit: a missing git repository or a failing git command is reported, never silently treated as "no ignores".
func LoadSnapshot ¶
LoadSnapshot reads a snapshot, refusing a version this build does not know.
type SnapshotExcluded ¶
type SnapshotExcluded struct {
Directories []string `json:"directories"`
Files []Exclusion `json:"files"`
IgnoreFiles []string `json:"ignore_files"`
Rules []string `json:"rules"`
}
SnapshotExcluded records what was left out; the reasons are part of the snapshot because "the index is smaller than the tree" must always be explainable (实施计划 M5.2 acceptance).
type SnapshotStats ¶
type SnapshotStats struct {
TotalFiles int `json:"total_files"`
TotalSize int64 `json:"total_size"`
Languages map[string]int `json:"languages"`
}
SnapshotStats summarizes a scan.
type State ¶
type State struct {
SchemaVersion int `json:"schema_version"`
Baseline Baseline `json:"baseline"`
Pages map[string]PageState `json:"pages,omitempty"`
Generator string `json:"generator,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
State is the page layer's bookkeeping: the overall baseline and the page mapping (.devsys/knowledge/state.json). It is written by whatever generates pages — the generator contract (方案 §12.6) — never by the index scan: a baseline that moved with every scan would make stale pages look fresh.
func LoadState ¶
LoadState reads the state file. A missing file is reported as fs.ErrNotExist so a caller can distinguish "no page layer yet" from "state is unreadable".
func MergeStates ¶
MergeStates layers an imported mapping under the project's own state: the page layer's own bookkeeping wins where both know a page, and the imported one fills the gaps (the reference generator keeps `sources` in its state, so without this merge its pages cannot be attributed at all).