agent-first-data 0.19.1

A naming convention that lets AI agents understand your data without being told what it means, plus a CLI and library for reading and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
package skill

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"unicode"
)

// ═══════════════════════════════════════════
// Public API: Skill Admin
// ═══════════════════════════════════════════
//
// Reusable Agent Skill installer for spore CLIs. A spore that embeds its SKILL.md
// describes itself with a SkillSpec and calls RunSkillAdmin to install, uninstall,
// or report status of that skill across supported coding agents (Codex, Claude
// Code, opencode, Hermes). The function performs the filesystem work and returns the
// protocol map (rendered by the caller with Render) or a *SkillError. It never
// writes to stdout/stderr itself.

const skillFileName = "SKILL.md"
const (
	skillFnv1a64Offset uint64 = 14695981039346656037
	skillFnv1a64Prime  uint64 = 1099511628211
)

// SkillSpec identifies the skill being managed and the tool that manages it.
//
// Name is both the skill directory name and the front-matter name field. Source is
// the bundled SKILL.md. Title is a human label for error messages. MarkerSlug seeds
// the managed-skill marker and the "Generated by <slug> skill install" comment, and
// is referenced in hints (e.g. afwidget).
type SkillSpec struct {
	// Name is the skill directory name and front-matter name (e.g. agent-first-widget).
	Name string
	// Source is the bundled SKILL.md contents.
	Source string
	// Title is a human-readable skill title for error messages (e.g. Agent-First Widget).
	Title string
	// MarkerSlug is the short tool slug used in the managed marker, generated-by
	// comment, and hints (e.g. afwidget).
	MarkerSlug string
}

// SkillAction is the skill action to perform.
type SkillAction string

const (
	// SkillActionStatus reports whether the skill is installed, valid, managed, and current.
	SkillActionStatus SkillAction = "status"
	// SkillActionInstall installs (or refreshes) the skill.
	SkillActionInstall SkillAction = "install"
	// SkillActionUninstall removes a managed skill.
	SkillActionUninstall SkillAction = "uninstall"
)

// SkillScope is where to install the skill.
type SkillScope string

const (
	// SkillScopePersonal is the user-level skills directory.
	SkillScopePersonal SkillScope = "personal"
	// SkillScopeWorkspace is the current workspace's skills directory.
	SkillScopeWorkspace SkillScope = "workspace"
)

// SkillAgentSelection selects which agent target(s) to manage.
type SkillAgentSelection string

const (
	// SkillAgentAll targets every agent that supports the requested scope.
	SkillAgentAll SkillAgentSelection = "all"
	// SkillAgentCodex targets Codex.
	SkillAgentCodex SkillAgentSelection = "codex"
	// SkillAgentClaudeCode targets Claude Code.
	SkillAgentClaudeCode SkillAgentSelection = "claude-code"
	// SkillAgentOpencode targets opencode.
	SkillAgentOpencode SkillAgentSelection = "opencode"
	// SkillAgentHermes targets Hermes Agent.
	SkillAgentHermes SkillAgentSelection = "hermes"
)

// SkillOptions are the options shared by every skill action.
type SkillOptions struct {
	// Agent is the agent target selection.
	Agent SkillAgentSelection
	// Scope is the skill scope.
	Scope SkillScope
	// SkillsDir is an explicit skills directory; requires a single concrete Agent.
	// Empty means use the default for each target.
	SkillsDir string
	// Force overwrites or removes a skill that this tool did not manage.
	Force bool
}

// SkillError is a skill admin failure with an operator-facing message and optional hint.
type SkillError struct {
	// Message is what went wrong.
	Message string
	// Hint is an optional remediation hint (empty when absent).
	Hint string
}

func (e *SkillError) Error() string { return e.Message }

// skillAgent is a concrete agent a skill is installed for (no "all").
type skillAgent string

const (
	agentCodex      skillAgent = "codex"
	agentClaudeCode skillAgent = "claude-code"
	agentOpencode   skillAgent = "opencode"
	agentHermes     skillAgent = "hermes"
)

// SkillTargetStatus is the per-target outcome of status / install.
type SkillTargetStatus struct {
	Agent           string  `json:"agent"`
	Scope           string  `json:"scope"`
	SkillsDir       string  `json:"skills_dir"`
	SkillPath       string  `json:"skill_path"`
	Installed       bool    `json:"installed"`
	Managed         bool    `json:"managed"`
	Valid           bool    `json:"valid"`
	Current         bool    `json:"current"`
	ValidationError *string `json:"validation_error"`
}

// SkillUninstallStatus is the per-target outcome of uninstall.
type SkillUninstallStatus struct {
	Agent     string `json:"agent"`
	Scope     string `json:"scope"`
	SkillsDir string `json:"skills_dir"`
	SkillPath string `json:"skill_path"`
	Removed   bool   `json:"removed"`
}

// SkillReport is the result of a skill action: one of *SkillStatusReport,
// *SkillInstallReport, or *SkillUninstallReport. Callers can type-switch to read
// fields, or serialize it with Render; the JSON shape carries a "code"
// discriminator.
type SkillReport interface {
	isSkillReport()
}

// SkillStatusReport is the result of a status action.
type SkillStatusReport struct {
	Code         string              `json:"code"`
	Skill        string              `json:"skill"`
	InstalledAll bool                `json:"installed_all"`
	ValidAll     bool                `json:"valid_all"`
	CurrentAll   bool                `json:"current_all"`
	Targets      []SkillTargetStatus `json:"targets"`
}

// SkillInstallReport is the result of an install action.
type SkillInstallReport struct {
	Code      string              `json:"code"`
	Skill     string              `json:"skill"`
	Installed bool                `json:"installed"`
	Targets   []SkillTargetStatus `json:"targets"`
	Hint      string              `json:"hint"`
}

// SkillUninstallReport is the result of an uninstall action.
type SkillUninstallReport struct {
	Code       string                 `json:"code"`
	Skill      string                 `json:"skill"`
	RemovedAny bool                   `json:"removed_any"`
	Targets    []SkillUninstallStatus `json:"targets"`
}

func (*SkillStatusReport) isSkillReport()    {}
func (*SkillInstallReport) isSkillReport()   {}
func (*SkillUninstallReport) isSkillReport() {}

// RunSkillAdmin installs, uninstalls, or reports status of spec's skill across the
// selected agent target(s). Returns a typed SkillReport (caller reads fields or
// serializes it with Render) or a *SkillError. Does not touch stdout/stderr.
func RunSkillAdmin(spec SkillSpec, action SkillAction, opts SkillOptions) (SkillReport, *SkillError) {
	if err := skillValidateSpec(spec); err != nil {
		return nil, err
	}
	switch action {
	case SkillActionStatus:
		return skillStatus(spec, opts)
	case SkillActionInstall:
		return skillInstall(spec, opts)
	case SkillActionUninstall:
		return skillUninstall(spec, opts)
	default:
		return nil, &SkillError{Message: fmt.Sprintf("unknown skill action %q", action)}
	}
}

func skillStatus(spec SkillSpec, opts SkillOptions) (SkillReport, *SkillError) {
	targets, err := skillResolveTargets(spec, opts)
	if err != nil {
		return nil, err
	}
	statuses := make([]SkillTargetStatus, 0, len(targets))
	installedAll, validAll, currentAll := true, true, true
	for _, target := range targets {
		st, e := skillTargetStatus(spec, target)
		if e != nil {
			return nil, e
		}
		if !st.Installed {
			installedAll = false
		}
		if !st.Valid {
			validAll = false
		}
		if !st.Current {
			currentAll = false
		}
		statuses = append(statuses, st)
	}
	return &SkillStatusReport{
		Code:         "skill_status",
		Skill:        spec.Name,
		InstalledAll: installedAll,
		ValidAll:     validAll,
		CurrentAll:   currentAll,
		Targets:      statuses,
	}, nil
}

func skillInstall(spec SkillSpec, opts SkillOptions) (SkillReport, *SkillError) {
	if e := skillValidateText(spec, spec.Source); e != nil {
		return nil, e
	}
	targets, err := skillResolveTargets(spec, opts)
	if err != nil {
		return nil, err
	}
	content := skillManagedContents(spec)
	installed := make([]SkillTargetStatus, 0, len(targets))
	for _, target := range targets {
		if e := os.MkdirAll(target.skillDir, 0o755); e != nil {
			return nil, &SkillError{Message: fmt.Sprintf("create skill dir failed: %v", e)}
		}
		info, exists, e := skillLstat(target.skillPath)
		if e != nil {
			return nil, e
		}
		if exists {
			if skillIsSymlink(info) && !opts.Force {
				return nil, &SkillError{
					Message: fmt.Sprintf("refusing to overwrite symlinked skill at %s", target.skillPath),
					Hint:    "pass --force to replace the symlink itself, or choose another --skills-dir",
				}
			}
			if !skillIsSymlink(info) {
				managed, e := skillIsManagedOrBundled(spec, target.skillPath)
				if e != nil {
					return nil, e
				}
				if !managed && !opts.Force {
					return nil, &SkillError{
						Message: fmt.Sprintf("refusing to overwrite unmanaged skill at %s", target.skillPath),
						Hint:    "pass --force to replace it, or choose another --skills-dir",
					}
				}
			}
		}
		if e := skillWriteFileAtomic(target.skillDir, target.skillPath, content); e != nil {
			return nil, e
		}
		if e := skillValidateInstalled(spec, target.skillPath); e != nil {
			return nil, e
		}
		st, e := skillTargetStatus(spec, target)
		if e != nil {
			return nil, e
		}
		installed = append(installed, st)
	}
	return &SkillInstallReport{
		Code:      "skill_install",
		Skill:     spec.Name,
		Installed: true,
		Targets:   installed,
		Hint:      "restart the agent so it reloads installed skills",
	}, nil
}

func skillUninstall(spec SkillSpec, opts SkillOptions) (SkillReport, *SkillError) {
	targets, err := skillResolveTargets(spec, opts)
	if err != nil {
		return nil, err
	}
	removed := make([]SkillUninstallStatus, 0, len(targets))
	removedAny := false
	for _, target := range targets {
		info, exists, e := skillLstat(target.skillPath)
		if e != nil {
			return nil, e
		}
		if !exists {
			removed = append(removed, skillTargetUninstallStatus(target, false))
			continue
		}
		if skillIsSymlink(info) && !opts.Force {
			return nil, &SkillError{
				Message: fmt.Sprintf("refusing to remove symlinked skill at %s", target.skillPath),
				Hint:    "pass --force to remove the symlink itself",
			}
		}
		if !skillIsSymlink(info) {
			managed, e := skillIsManagedOrBundled(spec, target.skillPath)
			if e != nil {
				return nil, e
			}
			if !managed && !opts.Force {
				return nil, &SkillError{
					Message: fmt.Sprintf("refusing to remove unmanaged skill at %s", target.skillPath),
					Hint:    fmt.Sprintf("only skills generated by %s skill install can be removed without --force", spec.MarkerSlug),
				}
			}
		}
		if e := os.Remove(target.skillPath); e != nil {
			return nil, &SkillError{Message: fmt.Sprintf("remove skill failed: %v", e)}
		}
		_ = os.Remove(target.skillDir) // prune the now-empty skill dir; ignore error
		removed = append(removed, skillTargetUninstallStatus(target, true))
		removedAny = true
	}
	return &SkillUninstallReport{
		Code:       "skill_uninstall",
		Skill:      spec.Name,
		RemovedAny: removedAny,
		Targets:    removed,
	}, nil
}

type skillTarget struct {
	agent     skillAgent
	scope     SkillScope
	skillsDir string
	skillDir  string
	skillPath string
}

func skillResolveTargets(spec SkillSpec, opts SkillOptions) ([]skillTarget, *SkillError) {
	if opts.SkillsDir != "" && opts.Agent == SkillAgentAll {
		return nil, &SkillError{
			Message: "--skills-dir requires a single --agent",
			Hint:    "custom skills directories are ambiguous when --agent all is used",
		}
	}
	switch {
	case opts.Agent == SkillAgentAll && opts.Scope == SkillScopePersonal:
		return skillResolveMany(spec, SkillScopePersonal, agentCodex, agentClaudeCode, agentOpencode, agentHermes)
	case opts.Agent == SkillAgentAll && opts.Scope == SkillScopeWorkspace:
		return skillResolveMany(spec, SkillScopeWorkspace, agentCodex, agentClaudeCode, agentOpencode, agentHermes)
	case opts.Agent == SkillAgentCodex:
		t, e := skillResolveTarget(spec, agentCodex, opts.Scope, opts.SkillsDir)
		if e != nil {
			return nil, e
		}
		return []skillTarget{t}, nil
	case opts.Agent == SkillAgentClaudeCode:
		t, e := skillResolveTarget(spec, agentClaudeCode, opts.Scope, opts.SkillsDir)
		if e != nil {
			return nil, e
		}
		return []skillTarget{t}, nil
	case opts.Agent == SkillAgentOpencode:
		t, e := skillResolveTarget(spec, agentOpencode, opts.Scope, opts.SkillsDir)
		if e != nil {
			return nil, e
		}
		return []skillTarget{t}, nil
	case opts.Agent == SkillAgentHermes:
		t, e := skillResolveTarget(spec, agentHermes, opts.Scope, opts.SkillsDir)
		if e != nil {
			return nil, e
		}
		return []skillTarget{t}, nil
	default:
		return nil, &SkillError{Message: fmt.Sprintf("invalid --agent %q", opts.Agent)}
	}
}

func skillResolveMany(spec SkillSpec, scope SkillScope, agents ...skillAgent) ([]skillTarget, *SkillError) {
	targets := make([]skillTarget, 0, len(agents))
	for _, agent := range agents {
		t, e := skillResolveTarget(spec, agent, scope, "")
		if e != nil {
			return nil, e
		}
		targets = append(targets, t)
	}
	return targets, nil
}

func skillResolveTarget(spec SkillSpec, agent skillAgent, scope SkillScope, skillsDir string) (skillTarget, *SkillError) {
	var dir string
	if skillsDir != "" {
		d, e := skillExpandTilde(skillsDir)
		if e != nil {
			return skillTarget{}, e
		}
		dir = d
	} else {
		d, e := skillDefaultDir(agent, scope)
		if e != nil {
			return skillTarget{}, e
		}
		dir = d
	}
	skillDir := filepath.Join(dir, spec.Name)
	return skillTarget{
		agent:     agent,
		scope:     scope,
		skillsDir: dir,
		skillDir:  skillDir,
		skillPath: filepath.Join(skillDir, skillFileName),
	}, nil
}

func skillDefaultDir(agent skillAgent, scope SkillScope) (string, *SkillError) {
	switch agent {
	case agentCodex:
		if scope != SkillScopePersonal {
			return skillWorkspaceDir(".codex")
		}
		if ch, ok := os.LookupEnv("CODEX_HOME"); ok {
			return filepath.Join(ch, "skills"), nil
		}
		h, e := skillHomeDir()
		if e != nil {
			return "", e
		}
		return filepath.Join(h, ".codex", "skills"), nil
	case agentClaudeCode:
		if scope != SkillScopePersonal {
			return skillWorkspaceDir(".claude")
		}
		h, e := skillHomeDir()
		if e != nil {
			return "", e
		}
		return filepath.Join(h, ".claude", "skills"), nil
	case agentOpencode:
		if scope != SkillScopePersonal {
			return skillWorkspaceDir(".opencode")
		}
		if xdg, ok := os.LookupEnv("XDG_CONFIG_HOME"); ok {
			return filepath.Join(xdg, "opencode", "skills"), nil
		}
		h, e := skillHomeDir()
		if e != nil {
			return "", e
		}
		return filepath.Join(h, ".config", "opencode", "skills"), nil
	case agentHermes:
		if scope != SkillScopePersonal {
			return skillWorkspaceDir(".hermes")
		}
		if hh, ok := os.LookupEnv("HERMES_HOME"); ok {
			return filepath.Join(hh, "skills"), nil
		}
		h, e := skillHomeDir()
		if e != nil {
			return "", e
		}
		return filepath.Join(h, ".hermes", "skills"), nil
	default:
		return "", &SkillError{Message: fmt.Sprintf("unknown agent %q", agent)}
	}
}

func skillWorkspaceDir(agentDir string) (string, *SkillError) {
	cwd, err := os.Getwd()
	if err != nil {
		return "", &SkillError{Message: fmt.Sprintf("resolve current directory failed: %v", err)}
	}
	return filepath.Join(cwd, agentDir, "skills"), nil
}

func skillTargetStatus(spec SkillSpec, target skillTarget) (SkillTargetStatus, *SkillError) {
	info, exists, err := skillLstat(target.skillPath)
	if err != nil {
		return SkillTargetStatus{}, err
	}
	installed := exists
	valid, current, managed := false, false, false
	var validationError *string
	if installed && skillIsSymlink(info) {
		msg := "target SKILL.md is a symlink; refusing to follow it"
		validationError = &msg
	} else if installed && info.Mode().IsRegular() {
		data, err := os.ReadFile(target.skillPath)
		if err != nil {
			return SkillTargetStatus{}, &SkillError{Message: fmt.Sprintf("read skill failed: %v", err)}
		}
		text := string(data)
		managed = skillTextIsManagedOrBundled(spec, text)
		current = !skillTextHasLegacyMarker(spec, text) && skillNormalizeText(spec, text) == skillNormalizeText(spec, spec.Source)
		if e := skillValidateText(spec, text); e != nil {
			msg := e.Message
			validationError = &msg
		} else {
			valid = true
		}
	} else if installed {
		msg := "target SKILL.md is not a regular file"
		validationError = &msg
	}
	return SkillTargetStatus{
		Agent:           string(target.agent),
		Scope:           string(target.scope),
		SkillsDir:       target.skillsDir,
		SkillPath:       target.skillPath,
		Installed:       installed,
		Managed:         managed,
		Valid:           valid,
		Current:         current,
		ValidationError: validationError,
	}, nil
}

func skillTargetUninstallStatus(target skillTarget, removed bool) SkillUninstallStatus {
	return SkillUninstallStatus{
		Agent:     string(target.agent),
		Scope:     string(target.scope),
		SkillsDir: target.skillsDir,
		SkillPath: target.skillPath,
		Removed:   removed,
	}
}

func skillGeneratedBy(spec SkillSpec) string {
	return fmt.Sprintf("Generated by %s skill install", spec.MarkerSlug)
}

func skillMarker(spec SkillSpec) string {
	return fmt.Sprintf("%s-managed-skill: true", spec.MarkerSlug)
}

func skillSourceHash(spec SkillSpec) string {
	hash := skillFnv1a64Offset
	for _, b := range []byte(spec.Source) {
		hash ^= uint64(b)
		hash *= skillFnv1a64Prime
	}
	return fmt.Sprintf("%016x", hash)
}

func skillManagedMarkerBlock(spec SkillSpec) string {
	slug := spec.MarkerSlug
	return fmt.Sprintf(
		"<!--\n%s\n%s-managed-skill: true\n%s-managed-skill-name: %s\n%s-managed-skill-source-hash-fnv1a64: %s\n-->",
		skillGeneratedBy(spec),
		slug,
		slug,
		spec.Name,
		slug,
		skillSourceHash(spec),
	)
}

func skillLegacyMarkerBlock(spec SkillSpec) string {
	return fmt.Sprintf("<!-- %s -->\n<!-- %s -->", skillGeneratedBy(spec), skillMarker(spec))
}

func skillManagedContents(spec SkillSpec) string {
	block := skillManagedMarkerBlock(spec)
	lines := skillSplitLines(spec.Source)
	var b strings.Builder
	inserted := false
	for i, line := range lines {
		b.WriteString(line)
		b.WriteByte('\n')
		if i == 0 {
			continue
		}
		if !inserted && strings.TrimSpace(line) == "---" {
			b.WriteString(block + "\n\n")
			inserted = true
		}
	}
	if !inserted {
		b.WriteString(block + "\n")
	}
	return b.String()
}

func skillValidateInstalled(spec SkillSpec, path string) *SkillError {
	data, err := os.ReadFile(path)
	if err != nil {
		return &SkillError{Message: fmt.Sprintf("read installed skill failed: %v", err)}
	}
	return skillValidateText(spec, string(data))
}

func skillValidateText(spec SkillSpec, text string) *SkillError {
	frontmatter, err := skillParseFrontmatter(text)
	if err != nil {
		return &SkillError{
			Message: fmt.Sprintf("invalid %s skill front matter: %v", spec.Title, err),
			Hint:    "quote scalar values that contain ': ', especially description",
		}
	}
	if frontmatter.name != spec.Name {
		return &SkillError{
			Message: fmt.Sprintf("invalid %s skill front matter: name %q does not match expected %q", spec.Title, frontmatter.name, spec.Name),
			Hint:    fmt.Sprintf("set front matter name to %s", spec.Name),
		}
	}
	return nil
}

func skillValidateFrontmatter(text string) error {
	_, err := skillParseFrontmatter(text)
	return err
}

type skillFrontmatter struct {
	name string
}

func skillParseFrontmatter(text string) (skillFrontmatter, error) {
	lines := skillSplitLines(text)
	if len(lines) == 0 {
		return skillFrontmatter{}, errors.New("missing YAML front matter")
	}
	if strings.TrimSpace(lines[0]) != "---" {
		return skillFrontmatter{}, errors.New("missing opening --- YAML front matter delimiter")
	}
	foundEnd, hasDescription := false, false
	var name *string
	for idx := 1; idx < len(lines); idx++ {
		line := lines[idx]
		lineNo := idx + 1
		trimmed := strings.TrimSpace(line)
		if trimmed == "---" {
			foundEnd = true
			break
		}
		if trimmed == "" || strings.HasPrefix(trimmed, "#") {
			continue
		}
		if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
			return skillFrontmatter{}, fmt.Errorf("line %d: nested YAML is not supported here", lineNo)
		}
		key, value, ok := strings.Cut(line, ":")
		if !ok {
			return skillFrontmatter{}, fmt.Errorf("line %d: expected key: value", lineNo)
		}
		key = strings.TrimSpace(key)
		if key == "" {
			return skillFrontmatter{}, fmt.Errorf("line %d: empty key", lineNo)
		}
		value = strings.TrimLeftFunc(value, unicode.IsSpace)
		if key == "name" {
			parsed := skillParseFrontmatterScalar(value)
			name = &parsed
		}
		if key == "description" {
			hasDescription = true
		}
		if strings.HasPrefix(value, "\"") || strings.HasPrefix(value, "'") {
			continue
		}
		if strings.Contains(value, ": ") {
			return skillFrontmatter{}, fmt.Errorf("line %d: unquoted scalar contains ': '; quote the value", lineNo)
		}
	}
	if !foundEnd {
		return skillFrontmatter{}, errors.New("missing closing --- YAML front matter delimiter")
	}
	if name == nil {
		return skillFrontmatter{}, errors.New("missing required name field")
	}
	if !hasDescription {
		return skillFrontmatter{}, errors.New("missing required description field")
	}
	return skillFrontmatter{name: *name}, nil
}

func skillParseFrontmatterScalar(value string) string {
	value = strings.TrimSpace(value)
	if len(value) >= 2 {
		first, last := value[0], value[len(value)-1]
		if (first == '"' && last == '"') || (first == '\'' && last == '\'') {
			return value[1 : len(value)-1]
		}
	}
	return value
}

func skillIsManagedOrBundled(spec SkillSpec, path string) (bool, *SkillError) {
	info, exists, err := skillLstat(path)
	if err != nil {
		return false, err
	}
	if !exists {
		return false, nil
	}
	if skillIsSymlink(info) {
		return false, &SkillError{
			Message: fmt.Sprintf("refusing to inspect symlinked skill at %s", path),
			Hint:    "pass --force to replace or remove the symlink itself",
		}
	}
	data, readErr := os.ReadFile(path)
	if readErr != nil {
		return false, &SkillError{Message: fmt.Sprintf("read skill failed: %v", readErr)}
	}
	return skillTextIsManagedOrBundled(spec, string(data)), nil
}

func skillTextIsManagedOrBundled(spec SkillSpec, text string) bool {
	if skillTextHasCurrentMarker(spec, text) || skillTextHasLegacyMarker(spec, text) {
		return true
	}
	return skillNormalizeText(spec, text) == skillNormalizeText(spec, spec.Source)
}

func skillTextHasCurrentMarker(spec SkillSpec, text string) bool {
	return strings.Contains(strings.ReplaceAll(text, "\r\n", "\n"), skillManagedMarkerBlock(spec))
}

func skillTextHasLegacyMarker(spec SkillSpec, text string) bool {
	return strings.Contains(strings.ReplaceAll(text, "\r\n", "\n"), skillLegacyMarkerBlock(spec))
}

// skillNormalizeText drops the managed-marker lines, then collapses runs of blank
// lines to one so that the blank line skillManagedContents inserts after the marker
// block does not make a managed install compare unequal to the bundled source.
func skillNormalizeText(spec SkillSpec, text string) string {
	text = strings.ReplaceAll(text, "\r\n", "\n")
	text = strings.ReplaceAll(text, skillManagedMarkerBlock(spec), "")
	text = strings.ReplaceAll(text, skillLegacyMarkerBlock(spec), "")
	out := make([]string, 0)
	for _, line := range skillSplitLines(text) {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" && len(out) > 0 && strings.TrimSpace(out[len(out)-1]) == "" {
			continue
		}
		out = append(out, line)
	}
	return strings.TrimSpace(strings.Join(out, "\n"))
}

func skillHomeDir() (string, *SkillError) {
	if h, ok := os.LookupEnv("HOME"); ok {
		return h, nil
	}
	if h, ok := os.LookupEnv("USERPROFILE"); ok {
		return h, nil
	}
	return "", &SkillError{
		Message: "cannot determine home directory",
		Hint:    "pass --skills-dir explicitly",
	}
}

func skillExpandTilde(input string) (string, *SkillError) {
	if input == "~" {
		return skillHomeDir()
	}
	if rest, ok := strings.CutPrefix(input, "~/"); ok {
		h, e := skillHomeDir()
		if e != nil {
			return "", e
		}
		return filepath.Join(h, rest), nil
	}
	return input, nil
}

func skillValidateSpec(spec SkillSpec) *SkillError {
	if err := skillValidateSlug("skill name", spec.Name); err != nil {
		return err
	}
	if err := skillValidateSlug("marker slug", spec.MarkerSlug); err != nil {
		return err
	}
	return skillValidateText(spec, spec.Source)
}

func skillValidateSlug(field, value string) *SkillError {
	if skillSlugIsValid(value) {
		return nil
	}
	return &SkillError{
		Message: fmt.Sprintf("invalid %s %q: expected a lowercase slug matching [a-z0-9][a-z0-9-]*[a-z0-9]", field, value),
		Hint:    "use lowercase ASCII letters, digits, and single hyphen-separated words",
	}
}

func skillSlugIsValid(value string) bool {
	if value == "" {
		return false
	}
	isLowerAlnum := func(r byte) bool {
		return (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
	}
	if !isLowerAlnum(value[0]) || !isLowerAlnum(value[len(value)-1]) {
		return false
	}
	for i := 0; i < len(value); i++ {
		if !isLowerAlnum(value[i]) && value[i] != '-' {
			return false
		}
	}
	return true
}

func skillLstat(path string) (os.FileInfo, bool, *SkillError) {
	info, err := os.Lstat(path)
	if err == nil {
		return info, true, nil
	}
	if os.IsNotExist(err) {
		return nil, false, nil
	}
	return nil, false, &SkillError{Message: fmt.Sprintf("inspect skill path failed: %v", err)}
}

func skillIsSymlink(info os.FileInfo) bool {
	return info != nil && info.Mode()&os.ModeSymlink != 0
}

func skillWriteFileAtomic(dir, path, content string) *SkillError {
	tmp, err := os.CreateTemp(dir, ".SKILL.md.*.tmp")
	if err != nil {
		return &SkillError{Message: fmt.Sprintf("create temporary skill failed: %v", err)}
	}
	tmpName := tmp.Name()
	cleanup := true
	defer func() {
		if cleanup {
			_ = os.Remove(tmpName)
		}
	}()
	if _, err := tmp.WriteString(content); err != nil {
		_ = tmp.Close()
		return &SkillError{Message: fmt.Sprintf("write temporary skill failed: %v", err)}
	}
	if err := tmp.Chmod(0o644); err != nil {
		_ = tmp.Close()
		return &SkillError{Message: fmt.Sprintf("chmod temporary skill failed: %v", err)}
	}
	if err := tmp.Close(); err != nil {
		return &SkillError{Message: fmt.Sprintf("close temporary skill failed: %v", err)}
	}
	if err := os.Rename(tmpName, path); err != nil {
		return &SkillError{Message: fmt.Sprintf("replace skill failed: %v", err)}
	}
	cleanup = false
	return nil
}

// skillSplitLines mirrors Rust's str::lines: split on '\n' (normalizing '\r\n'),
// dropping a single trailing empty element from a final newline.
func skillSplitLines(s string) []string {
	s = strings.ReplaceAll(s, "\r\n", "\n")
	lines := strings.Split(s, "\n")
	if n := len(lines); n > 0 && lines[n-1] == "" {
		lines = lines[:n-1]
	}
	return lines
}

func skillIsFile(p string) bool {
	info, err := os.Stat(p)
	return err == nil && !info.IsDir()
}

func skillPathExists(p string) bool {
	_, err := os.Stat(p)
	return err == nil
}