Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -633,9 +633,19 @@ func cmdNote(args []string) int {
// in lessons/ with "custom" mangled into the filename. Prose titles that
// merely contain (or end with) a slash are NOT filing choices — see
// note.SplitPathTitle for the boundary.
if fold == "" {
// An explicit --kind is a stated filing choice too, so it now suppresses the
// inference rather than losing to it. Field use showed why: engineering
// titles routinely open with a bare directory token ("internal/cli test-gap
// audit", "README/SPEC drift", "CI/CD"), and the shorthand not only ignored
// --kind but STRIPPED that word from the title permanently — with no way to
// put it back, since the CLI had no --title. `nt note "custom/x"` with no
// flags still files under custom/, unchanged.
if fold == "" && kindFolder == "" {
if f, t := note.SplitPathTitle(title); f != "" {
fold, title = f, t
// Say so. The whole failure mode was that this happened silently:
// the only signal was the created path in the success line.
fmt.Fprintf(os.Stderr, "note: filed under %s/ and dropped %q from the title (path-style shorthand) — pass --folder to choose explicitly, or rephrase to keep the word\n", f, f)
}
}
// The kind's canonical folder is the default only when neither --folder nor a
Expand Down
27 changes: 27 additions & 0 deletions internal/cli/edit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,30 @@ func TestCmdEditWithoutExpectMtimeStillWorks(t *testing.T) {
t.Errorf("edit without --expect-mtime should still apply: %s", after)
}
}

// TestEditTitleRepairsAMangledTitle covers the gap that made a wrong title
// permanent from the CLI: `nt edit` had --desc but no --title, and `nt mv`
// pins the OLD title into frontmatter where it beats the body H1 — so there
// was no non-interactive way to fix one. This is also the recovery path for a
// title the path-style shorthand truncated.
func TestEditTitleRepairsAMangledTitle(t *testing.T) {
t.Setenv("NT_DIR", t.TempDir())
captureRun(t, "note", "cli test-gap audit", "--body", "# cli test-gap audit\n\nfindings here")

out := captureRun(t, "edit", "cli test-gap audit", "--title", "internal/cli test-gap audit")
if !strings.Contains(out, "retitled") && !strings.Contains(out, "edited") {
t.Errorf("edit --title should report what it did: %s", out)
}

shown := captureRun(t, "show", "internal/cli test-gap audit")
if !strings.Contains(shown, "internal/cli test-gap audit") {
t.Errorf("the new title should be resolvable and displayed:\n%s", shown)
}
// The stale H1 must not survive to contradict the frontmatter.
if strings.Contains(shown, "# cli test-gap audit\n") {
t.Errorf("the old H1 should have been rewritten with the title:\n%s", shown)
}
if !strings.Contains(shown, "findings here") {
t.Errorf("retitling must not disturb the body:\n%s", shown)
}
}
41 changes: 32 additions & 9 deletions internal/cli/fieldstudy4_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,27 +116,50 @@ func TestUndoStillWorksWithoutLaterNoteEdit(t *testing.T) {
}
}

// A path-style title is an explicit filing choice: it beats --kind's canonical
// folder (which remains only a default), while the kind's tag still applies.
func TestNotePathStyleTitleBeatsKindFolder(t *testing.T) {
// A path-style title is an explicit filing choice ONLY when nothing else states
// one. With no flags it still files under the given folder; with an explicit
// --kind (or --folder) the flag wins and the title is left intact — engineering
// titles routinely open with a bare directory token, and the shorthand used to
// strip that word permanently.
func TestNotePathStyleTitleFilesWhenNoFlagGiven(t *testing.T) {
dir := t.TempDir()
t.Setenv("NT_DIR", dir)
out := captureRun(t, "note", "custom/x", "--kind", "lesson")
out := captureRun(t, "note", "custom/x")
if !strings.Contains(out, "notes/custom/x.md") {
t.Fatalf("path-style title should file under custom/, got: %s", out)
}
if _, err := os.Stat(filepath.Join(dir, "notes", "custom", "x.md")); err != nil {
t.Fatalf("note not created at notes/custom/x.md: %v", err)
}
}

// An explicit --kind suppresses the path-style inference and keeps the title
// whole (regression guard: "internal/cli audit --kind ref" used to land in
// internal/ with "internal" deleted from the title, unrecoverably).
func TestNoteExplicitKindBeatsPathStyleAndKeepsTitle(t *testing.T) {
dir := t.TempDir()
t.Setenv("NT_DIR", dir)
out := captureRun(t, "note", "internal/cli test-gap audit", "--kind", "ref")
if !strings.Contains(out, "notes/ref/") {
t.Fatalf("--kind ref should file under ref/, got: %s", out)
}
var j struct {
Tags []string `json:"tags"`
Title string `json:"title"`
Tags []string `json:"tags"`
}
json.Unmarshal([]byte(captureRun(t, "show", "x", "--json")), &j)
if !contains(j.Tags, "lesson") {
t.Fatalf("--kind lesson should still tag the note, got %v", j.Tags)
json.Unmarshal([]byte(captureRun(t, "show", "internal/cli test-gap audit", "--json")), &j)
if !strings.Contains(j.Title, "internal") {
t.Fatalf("the leading path token must survive in the title, got %q", j.Title)
}
if !contains(j.Tags, "ref") {
t.Fatalf("--kind ref should tag the note, got %v", j.Tags)
}
}

func TestNoteKindFolderStillAppliesWithoutPath(t *testing.T) {
t.Setenv("NT_DIR", t.TempDir())
// Without a path or --folder, the kind's folder still applies (unchanged).
out = captureRun(t, "note", "plain lesson capture", "--kind", "lesson")
out := captureRun(t, "note", "plain lesson capture", "--kind", "lesson")
if !strings.Contains(out, "notes/lessons/plain-lesson-capture.md") {
t.Fatalf("kind folder should still be the default: %s", out)
}
Expand Down
48 changes: 48 additions & 0 deletions internal/cli/links_backlink_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package cli

import (
"strings"
"testing"
)

// TestShortIdWikilinkProducesBacklink guards a documented-but-broken promise:
// SKILL.md says "[[note-slug]] or [[<id>]] … backlinks are found automatically",
// and Resolve accepts the 6-char short id nt prints everywhere — but backlink
// discovery matched only the full ULID, so an id-form link resolved forward and
// left the target showing "linked from: (none)".
func TestShortIdWikilinkProducesBacklink(t *testing.T) {
t.Setenv("NT_DIR", t.TempDir())
captureRun(t, "note", "Target Note", "--body", "the thing being linked to")

// Grab the short id nt printed for the target.
out := captureRun(t, "notes")
var short string
for _, f := range strings.Fields(out) {
if len(f) == 6 {
short = f
break
}
}
if short == "" {
t.Fatalf("could not find a short id in: %s", out)
}

captureRun(t, "note", "Source Note", "--body", "see [["+short+"]] for detail")

if got := captureRun(t, "links", "Target Note"); !strings.Contains(strings.ToLower(got), "source-note") {
t.Errorf("an id-form [[%s]] link should register as a backlink, got:\n%s", short, got)
}
}

// TestSlugLikeWikilinkIsNotMistakenForAnId: the short-id match is restricted to
// Crockford base32 (no I/L/O/U) so an ordinary slug can't be read as an id
// suffix by backlink discovery, which has no note list to disambiguate with.
func TestSlugLikeWikilinkIsNotMistakenForAnId(t *testing.T) {
t.Setenv("NT_DIR", t.TempDir())
captureRun(t, "note", "Alpha", "--body", "target")
captureRun(t, "note", "Beta", "--body", "mentions [[quiz]] which is not an id")

if got := captureRun(t, "links", "Alpha"); strings.Contains(strings.ToLower(got), "beta") {
t.Errorf("a non-id slug link must not produce a spurious backlink:\n%s", got)
}
}
39 changes: 38 additions & 1 deletion internal/cli/maintenance.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ func cmdEdit(args []string) int {
bodyFile := fs.String("body-file", "", "replace the note body from a file ('-' = stdin); immune to shell quoting")
oldString := fs.String("old-string", "", "exact existing text in the body to replace — must match exactly once; pair with --new-string for a targeted fix without resending the whole body")
newString := fs.String("new-string", "", "replacement text for --old-string (empty deletes the matched text)")
title := fs.String("title", "", "set the note's title (frontmatter + body H1) without an editor")
desc := fs.String("desc", "", "set the note's one-line description (frontmatter) without an editor")
fs.StringVar(desc, "description", "", "alias for --desc")
validFrom := fs.String("valid-from", "", "set: this fact is only true from this date/time on (YYYY-MM-DD or RFC3339)")
Expand Down Expand Up @@ -270,7 +271,7 @@ func cmdEdit(args []string) int {
// be fixable only via $EDITOR or a whole-note supersede (which churns the id
// and every inbound link); this edits in place.
validitySet := strings.TrimSpace(*validFrom) != "" || strings.TrimSpace(*validUntil) != "" || *clearValidFrom || *clearValidUntil
if appendVal != "" || bodyVal != "" || replacing || strings.TrimSpace(*desc) != "" || validitySet {
if appendVal != "" || bodyVal != "" || replacing || strings.TrimSpace(*desc) != "" || strings.TrimSpace(*title) != "" || validitySet {
n, nerr := resolveNote(notes, strings.TrimPrefix(handle, "note:"))
if nerr != nil {
return fail(fmt.Errorf("edit: %w (non-interactive edits apply to notes; for tasks use `nt update`)", nerr))
Expand Down Expand Up @@ -302,6 +303,21 @@ func cmdEdit(args []string) int {
return fail(fmt.Errorf("edit: --old-string matches %d times in %s's body — make it longer/more specific so the match is unambiguous", count, shortID(n.ID)))
}
}
// --title was the missing repair path. Without it a wrong title was
// permanent from the CLI: `nt mv` renames the file but pins the OLD
// title into frontmatter, where it then beats the body H1, so editing
// the H1 changed nothing visible. Rewrite the H1 too when it still
// carries the previous title, so frontmatter, heading and filename
// don't drift apart.
if tt := strings.TrimSpace(*title); tt != "" {
if old := strings.TrimSpace(n.Title); old != "" {
n.Body = replaceLeadingHeading(n.Body, old, tt)
}
n.Title = tt
if verb == "" {
verb = "retitled"
}
}
if d := strings.TrimSpace(*desc); d != "" {
setNoteDescription(n, d)
if verb == "" {
Expand Down Expand Up @@ -999,3 +1015,24 @@ Full setup: docs/claude-integration.md. For typed agent tools (nt_add,
nt_index, nt_search, …) instead of the hook, see: nt mcp install.
`)
}

// replaceLeadingHeading rewrites a body's opening "# old" heading to "# new"
// when it still carries the previous title, so `nt edit --title` doesn't leave
// the H1 contradicting the frontmatter. Bodies whose H1 was already something
// else are left alone — that heading is the author's, not a mirror of the title.
func replaceLeadingHeading(body, old, new string) string {
trimmed := strings.TrimLeft(body, "\n")
lead := body[:len(body)-len(trimmed)]
if !strings.HasPrefix(trimmed, "# ") {
return body
}
line, rest, _ := strings.Cut(trimmed, "\n")
if strings.TrimSpace(strings.TrimPrefix(line, "# ")) != strings.TrimSpace(old) {
return body
}
out := lead + "# " + new
if rest != "" {
out += "\n" + rest
}
return out
}
38 changes: 36 additions & 2 deletions internal/links/links.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,9 @@ func Backlinks(s *store.Store, id, rel string) []search.Hit {
h, _ := search.Literal(id, s.TasksFile(), s.NotesDir())
add(h)
}
if rel != "" {
// Any wikilink is a candidate; references() does the precise suffix check.
// Any wikilink is a candidate; references() does the precise check. This
// runs for an id-only target too (a task), so a short-id link finds it.
if id != "" || rel != "" {
h, _ := search.Literal("[[", s.TasksFile(), s.NotesDir())
add(h)
}
Expand All @@ -277,6 +278,24 @@ func references(line, id, rel string) bool {
strings.Contains(line, "blocks:"+id) {
return true
}
// Short-id form: nt prints the 6-char id suffix everywhere (note
// creation, index, search, recall), Resolve accepts it, and the skill
// documents `[[<id>]]` as a supported link — but only the full ULID was
// matched here. So an id-form link resolved FORWARD while producing no
// backlink, and `nt links --orphans` called the target an orphan.
//
// Restricted to Crockford base32 (the ULID alphabet, which excludes
// I/L/O/U) so an ordinary slug can't be mistaken for an id suffix —
// Resolve gets to disambiguate against the real note list, and this
// function does not, so it errs narrow.
if idU := strings.ToUpper(id); idU != "" {
for _, raw := range wikilinks(line) {
key, _ := NormalizeTarget(raw)
if len(key) >= 4 && isCrockford(key) && strings.HasSuffix(idU, strings.ToUpper(key)) {
return true
}
}
}
}
if rel != "" {
for _, raw := range wikilinks(line) {
Expand Down Expand Up @@ -305,3 +324,18 @@ func itoa(n int) string {
}
return string(b[i:])
}

// isCrockford reports whether s is entirely Crockford base32 — the ULID
// alphabet (digits plus A-Z minus I, L, O and U). Used to tell a short-id
// wikilink from an ordinary slug without a note list to check against.
func isCrockford(s string) bool {
for _, r := range strings.ToUpper(s) {
switch {
case r >= '0' && r <= '9':
case r >= 'A' && r <= 'Z' && r != 'I' && r != 'L' && r != 'O' && r != 'U':
default:
return false
}
}
return s != ""
}
19 changes: 19 additions & 0 deletions internal/mutate/rename.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ func (e *Engine) RenameNote(src *note.Note, all []*note.Note, dest string) (newR
if !strings.Contains(newRel, "/") { // bare name → keep the note's folder
newRel = filepath.ToSlash(filepath.Join(filepath.Dir(oldRel), newRel))
}
// Slug each segment, the way `nt note` does when it derives a filename from
// a title. Without this, `nt mv <note> "ref/My Long Name"` wrote a file with
// literal spaces in it — the only file in the store nt hadn't slugged, and
// inconsistent with every other path it creates.
newRel = slugRel(newRel)
newBase := base(newRel)
if newBase == "" {
return "", 0, fmt.Errorf("rename: invalid destination %q", dest)
Expand Down Expand Up @@ -205,3 +210,17 @@ func trashDest(trash, rel string) (string, error) {
func base(rel string) string {
return strings.TrimSuffix(filepath.Base(rel), ".md")
}

// slugRel slugs every segment of a notes-relative path, preserving the folder
// structure and the .md suffix, so a destination typed in human form lands on
// the same shape of filename `nt note` would have produced from a title.
func slugRel(rel string) string {
stem := strings.TrimSuffix(rel, ".md")
parts := strings.Split(stem, "/")
for i, p := range parts {
if s := note.Slug(p); s != "" {
parts[i] = s
}
}
return strings.Join(parts, "/") + ".md"
}
26 changes: 26 additions & 0 deletions internal/mutate/rename_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,29 @@ func TestTrashNoteNeverClobbers(t *testing.T) {
}
}
}

// TestRenameNoteSlugsDestination: `nt mv` used to write the destination
// verbatim, so a human-readable name produced the one file in the store with
// literal spaces in it — unlike `nt note`, which always slugs.
func TestRenameNoteSlugsDestination(t *testing.T) {
e := newEngine(t)
p := filepath.Join(e.S.NotesDir(), "start.md")
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte("# Start\n\nbody\n"), 0o644); err != nil {
t.Fatal(err)
}
src := &note.Note{Path: p, Rel: "start.md", Title: "Start"}

newRel, _, err := e.RenameNote(src, []*note.Note{src}, "ref/My Long Name")
if err != nil {
t.Fatal(err)
}
if newRel != "ref/my-long-name.md" {
t.Errorf("destination should be slugged, got %q", newRel)
}
if _, err := os.Stat(filepath.Join(e.S.NotesDir(), "ref", "my-long-name.md")); err != nil {
t.Errorf("slugged file missing: %v", err)
}
}
Loading