index

package
v0.3.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 1, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var IndexCmd = &cobra.Command{
	Use:   "index [flags]",
	Short: "Build or rebuild the CANARY token database",
	Long: `Scan the codebase for CANARY tokens and store metadata in SQLite database.

This enables advanced features like priority ordering, keyword search, and checkpoints.
The database is stored at .canary/canary.db by default.

The rebuild is one transaction: either the new index fully replaces the old
one, or the old one is left exactly as it was. A token the scanner cannot
parse fails the run rather than being skipped with a warning.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		prompt, _ := cmd.Flags().GetString("prompt")
		if prompt != "" {
			if _, err := utils.LoadPrompt(prompt); err != nil {
				return err
			}
		}
		dbPath, _ := cmd.Flags().GetString("db")
		rootPath, _ := cmd.Flags().GetString("root")

		if cmd.Flags().Changed("db") {
			if !filepath.IsAbs(dbPath) {
				dbPath = filepath.Join(rootPath, dbPath)
			}
		} else {
			dbPath = filepath.Join(rootPath, ".canary", "canary.db")
		}
		if abs, err := filepath.Abs(dbPath); err == nil {
			dbPath = abs
		}

		projectID, err := utils.WriteProjectID(cmd, rootPath)
		if err != nil {
			return err
		}

		out := cmd.OutOrStdout()
		errOut := cmd.ErrOrStderr()
		fmt.Fprintf(out, "Indexing CANARY tokens from: %s\n", rootPath)

		reg, err := sources.LoadFromRoot(rootPath)
		if err != nil {
			return fmt.Errorf("load .canary/project.yaml: %w", err)
		}

		ignorePatterns, err := canaryscan.LoadCanaryIgnore(rootPath)
		if err != nil {
			return fmt.Errorf("load .canaryignore: %w", err)
		}

		records, files, issues, err := canaryscan.ScanTokenRecords(rootPath, nil, nil, ignorePatterns, reg)
		if err != nil {
			return fmt.Errorf("scan %s: %w", rootPath, err)
		}
		if err := reportIssues(errOut, "token", issues); err != nil {
			return err
		}

		scanDigest := canaryscan.ScanDigest(canaryscan.SnapshotSeed(rootPath), files)

		commitHash, branch := gitMetadata(rootPath)

		indexedAt := time.Now().UTC().Format(time.RFC3339)
		tokens := make([]*storage.Token, 0, len(records))
		for _, rec := range records {
			tokens = append(tokens, toToken(rec, projectID, commitHash, branch, indexedAt))
		}

		refs, err := collectRefs(errOut, rootPath, reg, ignorePatterns)
		if err != nil {
			return err
		}

		db, err := storage.OpenRW(dbPath)
		if err != nil {
			return fmt.Errorf("open database: %w", err)
		}
		defer func() { _ = db.Close() }()

		meta := storage.IndexMeta{
			Root:         rootPath,
			ProjectID:    projectID,
			CommitSHA:    commitHash,
			ParserSchema: canaryscan.ParserSchemaVersion,
			ScanDigest:   scanDigest,
			IndexedAt:    indexedAt,
		}

		if err := db.ReplaceIndex(projectID, tokens, refs, meta); err != nil {
			return fmt.Errorf("rebuild index: %w", err)
		}

		fmt.Fprintf(out, "Indexed %d diagram reference(s)\n", len(refs["diagram"]))
		fmt.Fprintf(out, "Indexed %d migration note(s)\n", len(refs["migrate"]))
		fmt.Fprintf(out, "\n✅ Indexed %d CANARY tokens\n", len(tokens))
		fmt.Fprintf(out, "Database: %s\n", dbPath)
		absRoot := rootPath
		if abs, err := filepath.Abs(rootPath); err == nil {
			absRoot = abs
		}
		fmt.Fprintf(out, "Root: %s\n", absRoot)
		fmt.Fprintf(out, "Project: %s\n", projectID)
		if commitHash != "" {
			fmt.Fprintf(out, "Commit: %s\n", commitHash[:8])
		}
		if branch != "" {
			fmt.Fprintf(out, "Branch: %s\n", branch)
		}

		return nil
	},
}

CANARY: REQ=ENG-4307; FEATURE="IndexCmd"; ASPECT=CLI; STATUS=TESTED; TEST=TestAuditF12,TestAuditF12CleanRunCommits,TestCANARY_CP_285_IndexRespectsCanaryIgnore,TestAuditR10_IndexingSecondProjectPreservesFirst,TestIndexRefusesUnreadableTokenFile,TestIndexRefusesOversizedTextFile,TestIndexAcceptsBinariesAsBenign,TestIndexRootsDefaultDB,TestIndexExplicitRelativeDBUnderRoot,TestIndexExplicitAbsoluteDBStaysPut; UPDATED=2026-09-01

Functions

func ComputeScanDigest added in v0.3.4

func ComputeScanDigest(root string) (string, error)

ComputeScanDigest returns the content digest of every token-bearing file under root, computed exactly as `canary index` records it in IndexMeta: the same .canary/project.yaml registry (sources.LoadFromRoot), the same .canaryignore (canaryscan.LoadCanaryIgnore), and the same (unrestricted, skip=nil) scan `canary index` passes to ScanTokenRecords.

`canary index` no longer calls this function for its own digest -- RunE above digests the `files` result of its own ScanTokenRecords call directly via canaryscan.ScanDigest, so the recorded digest describes exactly the snapshot the tokens were built from rather than a second, possibly different, scan of the tree. This function still exists for `canary next`'s index-freshness check (openFreshIndex) and for test fixtures, and both paths are required to use the identical scan inputs described above. If they ever diverge, freshness becomes fiction -- an index could describe a tree whose tokens changed and still read as current. CANARY: REQ=CBIN-132; FEATURE="ScanDigestHelper"; ASPECT=Engine; STATUS=TESTED; TEST=TestCANARY_CBIN_132_CLI_UncommittedEditInvalidatesIndex,TestCANARY_CBIN_132_CLI_ProjectYamlEditInvalidatesIndex; UPDATED=2026-08-31

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL