| 1 | package knot |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "regexp" |
| 8 | "slices" |
| 9 | "strings" |
| 10 | "unicode/utf8" |
| 11 | ) |
| 12 | |
| 13 | // The canonical form of a knot's file. Go's standard library has no YAML |
| 14 | // parser, so the live graph is written in one form the Go code owns: a |
| 15 | // strict subset of YAML that is still YAML, so the CUE schema and the |
| 16 | // knowledge lint read the same file. The frontmatter is one line per key, |
| 17 | // in the order Fields lists them: |
| 18 | // |
| 19 | // --- |
| 20 | // type: outcome |
| 21 | // id: oc-1a2b3c4 |
| 22 | // status: open |
| 23 | // title: "Ship the plan graph" |
| 24 | // created: 2026-10-15 |
| 25 | // created_by: "operator" |
| 26 | // parent: oc-7654321 |
| 27 | // blocked_by: ["app:oc-0123456", bd-89abcde] |
| 28 | // --- |
| 29 | // |
| 30 | // The body, as markdown. |
| 31 | // |
| 32 | // type, id, status, created, parent and graduated_into are bare tokens. |
| 33 | // Every other value is a JSON string, so no title, name or link is read as |
| 34 | // anything else. A list is a flow list, sorted, of local IDs bare and of |
| 35 | // everything else as JSON strings. blocked_by is written on every outcome |
| 36 | // and bug, empty or not, and every other optional key only when it holds |
| 37 | // something. The body follows the closing --- after one blank line, with |
| 38 | // no blank line at its end, and a knot with no body ends at the ---. |
| 39 | // |
| 40 | // ParseKnot reads a file leniently enough to say which rule it breaks, |
| 41 | // and then refuses it unless rendering what it read gives back the same |
| 42 | // bytes. So there is exactly one way to write each knot. |
| 43 | |
| 44 | const fence = "---\n" |
| 45 | |
| 46 | // keyShape is a line's key, as YAML would read one from it. |
| 47 | var keyShape = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`) |
| 48 | |
| 49 | // checkText refuses content that is not valid UTF-8, or that holds a |
| 50 | // control character other than newline and tab. U+FFFE and U+FFFF are |
| 51 | // refused too: YAML does not allow them, so the CUE schema could not read |
| 52 | // a file holding one. |
| 53 | func checkText(path string, data []byte) *Error { |
| 54 | if !utf8.Valid(data) { |
| 55 | return refuse(RuleText, path, "is not valid UTF-8") |
| 56 | } |
| 57 | for i, r := range string(data) { |
| 58 | if (r < 0x20 && r != '\n' && r != '\t') || (r >= 0x7f && r <= 0x9f) || r == 0xfffe || r == 0xffff { |
| 59 | return refuse(RuleText, path, fmt.Sprintf("holds the control character %U at byte %d; a knot's text holds no control character but newline and tab", r, i)) |
| 60 | } |
| 61 | } |
| 62 | return nil |
| 63 | } |
| 64 | |
| 65 | // frontmatter splits a file into its frontmatter lines and its body. The |
| 66 | // file opens with a --- line, and the next --- line closes the |
| 67 | // frontmatter. |
| 68 | func frontmatter(path string, data []byte) (lines []string, body string, err *Error) { |
| 69 | text := string(data) |
| 70 | if !strings.HasPrefix(text, fence) { |
| 71 | return nil, "", refuse(RuleCanonical, path, "does not open with a --- line: the file opens with its frontmatter") |
| 72 | } |
| 73 | rest := text[len(fence):] |
| 74 | if strings.HasPrefix(rest, fence) { |
| 75 | return nil, rest[len(fence):], nil |
| 76 | } |
| 77 | end := strings.Index(rest, "\n"+fence) |
| 78 | if end < 0 { |
| 79 | return nil, "", refuse(RuleCanonical, path, "has no --- line closing its frontmatter") |
| 80 | } |
| 81 | return strings.Split(rest[:end], "\n"), rest[end+1+len(fence):], nil |
| 82 | } |
| 83 | |
| 84 | // readBody reads what follows the frontmatter leniently: one blank line |
| 85 | // and then the body. Whether it is written canonically is for the |
| 86 | // comparison with Render. |
| 87 | func readBody(rest string) string { |
| 88 | return strings.TrimPrefix(rest, "\n") |
| 89 | } |
| 90 | |
| 91 | // ParseKnot reads a knot's file. slug is the slug its filename carries, |
| 92 | // and path is named in a refusal. It refuses a file that breaks any rule |
| 93 | // about one knot alone; edges to other knots are the graph's to check. |
| 94 | func ParseKnot(path, slug string, data []byte) (*Knot, error) { |
| 95 | k, err := parseKnot(path, slug, data) |
| 96 | if err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | return k, nil |
| 100 | } |
| 101 | |
| 102 | func parseKnot(path, slug string, data []byte) (*Knot, *Error) { |
| 103 | if len(data) > MaxKnotSize { |
| 104 | return nil, refuse(RuleLimit, path, fmt.Sprintf("is %d bytes, more than the %d a knot may be", len(data), MaxKnotSize)) |
| 105 | } |
| 106 | if err := checkText(path, data); err != nil { |
| 107 | return nil, err |
| 108 | } |
| 109 | lines, rest, err := frontmatter(path, data) |
| 110 | if err != nil { |
| 111 | return nil, err |
| 112 | } |
| 113 | k := &Knot{Slug: slug, Body: readBody(rest)} |
| 114 | seen := map[string]bool{} |
| 115 | for _, line := range lines { |
| 116 | key, value, ok := strings.Cut(line, ": ") |
| 117 | if !ok { |
| 118 | key, value = strings.TrimSuffix(line, ":"), "" |
| 119 | } |
| 120 | f, known := FieldNamed(key) |
| 121 | switch { |
| 122 | case !known && keyShape.MatchString(key): |
| 123 | return nil, refuse(RuleFieldOnType, path, fmt.Sprintf("holds the key %s, and a knot's keys are %s", key, strings.Join(FieldNames(""), ", "))) |
| 124 | case !known: |
| 125 | return nil, refuse(RuleCanonical, path, fmt.Sprintf("holds the line %q, and each line of a knot's frontmatter is one key and its value", line)) |
| 126 | } |
| 127 | if seen[key] { |
| 128 | return nil, refuse(RuleCanonical, path, fmt.Sprintf("names %s twice", key)) |
| 129 | } |
| 130 | seen[key] = true |
| 131 | if err := k.read(path, f, value); err != nil { |
| 132 | return nil, err |
| 133 | } |
| 134 | } |
| 135 | if err := k.check(path); err != nil { |
| 136 | return nil, err |
| 137 | } |
| 138 | if k.Body != NormalBody(k.Body) { |
| 139 | return nil, refuse(RuleCanonical, path, "its body opens or ends with a blank line, or does not end with a newline") |
| 140 | } |
| 141 | if want := Render(k); !bytes.Equal(want, data) { |
| 142 | return nil, refuse(RuleCanonical, path, "is not in canonical form, which is:\n"+string(want)) |
| 143 | } |
| 144 | return k, nil |
| 145 | } |
| 146 | |
| 147 | // read sets one field from its written value. |
| 148 | func (k *Knot) read(path string, f Field, value string) *Error { |
| 149 | var s string |
| 150 | var list []string |
| 151 | var err error |
| 152 | switch f.Kind { |
| 153 | case "list": |
| 154 | list, err = readList(value) |
| 155 | default: |
| 156 | s, err = readScalar(value) |
| 157 | } |
| 158 | if err != nil { |
| 159 | return refuse(RuleCanonical, path, fmt.Sprintf("%s: %v", f.Name, err)) |
| 160 | } |
| 161 | switch f.Name { |
| 162 | case "type": |
| 163 | k.Type = s |
| 164 | case "id": |
| 165 | k.ID = s |
| 166 | case "status": |
| 167 | k.Status = s |
| 168 | case "title": |
| 169 | k.Title = s |
| 170 | case "created": |
| 171 | k.Created = s |
| 172 | case "created_by": |
| 173 | k.CreatedBy = s |
| 174 | case "source": |
| 175 | k.Source = s |
| 176 | case "parent": |
| 177 | k.Parent = s |
| 178 | case "owner": |
| 179 | k.Owner = s |
| 180 | case "blocked_by": |
| 181 | k.BlockedBy = list |
| 182 | case "claimed_by": |
| 183 | k.ClaimedBy = s |
| 184 | case "claimed_at": |
| 185 | k.ClaimedAt = s |
| 186 | case "changes": |
| 187 | k.Changes = list |
| 188 | case "target": |
| 189 | k.Target = s |
| 190 | case "graduated_into": |
| 191 | k.GraduatedInto = s |
| 192 | } |
| 193 | return nil |
| 194 | } |
| 195 | |
| 196 | // readScalar reads a bare token or a JSON string. |
| 197 | func readScalar(value string) (string, error) { |
| 198 | if strings.HasPrefix(value, `"`) { |
| 199 | var s string |
| 200 | if err := json.Unmarshal([]byte(value), &s); err != nil { |
| 201 | return "", fmt.Errorf("%s is not a JSON string", value) |
| 202 | } |
| 203 | return s, nil |
| 204 | } |
| 205 | if value == "" || strings.ContainsAny(value, " \t[]{},#&*!|>'%@`") { |
| 206 | return "", fmt.Errorf("%q is neither a bare token nor a JSON string", value) |
| 207 | } |
| 208 | return value, nil |
| 209 | } |
| 210 | |
| 211 | // readList reads a flow list of bare tokens and JSON strings. |
| 212 | func readList(value string) ([]string, error) { |
| 213 | if !strings.HasPrefix(value, "[") || !strings.HasSuffix(value, "]") { |
| 214 | return nil, fmt.Errorf("%q is not a flow list, [a, b]", value) |
| 215 | } |
| 216 | inner := value[1 : len(value)-1] |
| 217 | list := []string{} |
| 218 | for len(inner) > 0 { |
| 219 | var item string |
| 220 | if strings.HasPrefix(inner, `"`) { |
| 221 | end := 1 |
| 222 | for end < len(inner) && inner[end] != '"' { |
| 223 | if inner[end] == '\\' { |
| 224 | end++ |
| 225 | } |
| 226 | end++ |
| 227 | } |
| 228 | if end >= len(inner) { |
| 229 | return nil, fmt.Errorf("%s holds an unclosed string", value) |
| 230 | } |
| 231 | if err := json.Unmarshal([]byte(inner[:end+1]), &item); err != nil { |
| 232 | return nil, fmt.Errorf("%s holds a string that is not JSON", value) |
| 233 | } |
| 234 | inner = inner[end+1:] |
| 235 | } else { |
| 236 | cut := strings.Index(inner, ",") |
| 237 | if cut < 0 { |
| 238 | cut = len(inner) |
| 239 | } |
| 240 | item = strings.TrimSpace(inner[:cut]) |
| 241 | inner = inner[cut:] |
| 242 | if item == "" { |
| 243 | return nil, fmt.Errorf("%s holds an empty entry", value) |
| 244 | } |
| 245 | } |
| 246 | list = append(list, item) |
| 247 | inner = strings.TrimSpace(inner) |
| 248 | if inner == "" { |
| 249 | break |
| 250 | } |
| 251 | if !strings.HasPrefix(inner, ",") { |
| 252 | return nil, fmt.Errorf("%s does not separate its entries with commas", value) |
| 253 | } |
| 254 | inner = strings.TrimSpace(inner[1:]) |
| 255 | if inner == "" { |
| 256 | return nil, fmt.Errorf("%s ends with a comma", value) |
| 257 | } |
| 258 | } |
| 259 | return list, nil |
| 260 | } |
| 261 | |
| 262 | // Render writes a knot in its canonical form. |
| 263 | func Render(k *Knot) []byte { |
| 264 | var b bytes.Buffer |
| 265 | b.WriteString(fence) |
| 266 | line := func(key, value string) { b.WriteString(key + ": " + value + "\n") } |
| 267 | work := slices.Contains(workTypes, k.Type) |
| 268 | line("type", k.Type) |
| 269 | line("id", k.ID) |
| 270 | line("status", k.Status) |
| 271 | line("title", quote(k.Title)) |
| 272 | line("created", k.Created) |
| 273 | line("created_by", quote(k.CreatedBy)) |
| 274 | if k.Source != "" { |
| 275 | line("source", quote(k.Source)) |
| 276 | } |
| 277 | if k.Parent != "" { |
| 278 | line("parent", k.Parent) |
| 279 | } |
| 280 | if k.Owner != "" { |
| 281 | line("owner", quote(k.Owner)) |
| 282 | } |
| 283 | if work || len(k.BlockedBy) > 0 { |
| 284 | line("blocked_by", renderList(k.BlockedBy)) |
| 285 | } |
| 286 | if k.ClaimedBy != "" { |
| 287 | line("claimed_by", quote(k.ClaimedBy)) |
| 288 | } |
| 289 | if k.ClaimedAt != "" { |
| 290 | line("claimed_at", quote(k.ClaimedAt)) |
| 291 | } |
| 292 | if len(k.Changes) > 0 { |
| 293 | line("changes", renderList(k.Changes)) |
| 294 | } |
| 295 | if k.Target != "" { |
| 296 | line("target", quote(k.Target)) |
| 297 | } |
| 298 | if k.GraduatedInto != "" { |
| 299 | line("graduated_into", k.GraduatedInto) |
| 300 | } |
| 301 | b.WriteString(fence) |
| 302 | if k.Body != "" { |
| 303 | b.WriteString("\n" + k.Body) |
| 304 | } |
| 305 | return b.Bytes() |
| 306 | } |
| 307 | |
| 308 | // NormalBody is text as a knot's or a comment's body holds it: with no |
| 309 | // blank line at either end, no space at the end of the text, and one |
| 310 | // newline after its last line, or "" when it holds nothing. |
| 311 | func NormalBody(text string) string { |
| 312 | text = strings.ReplaceAll(text, "\r\n", "\n") |
| 313 | lines := strings.Split(text, "\n") |
| 314 | for len(lines) > 0 && strings.TrimSpace(lines[0]) == "" { |
| 315 | lines = lines[1:] |
| 316 | } |
| 317 | for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" { |
| 318 | lines = lines[:len(lines)-1] |
| 319 | } |
| 320 | if len(lines) == 0 { |
| 321 | return "" |
| 322 | } |
| 323 | return strings.Join(lines, "\n") + "\n" |
| 324 | } |
| 325 | |
| 326 | func renderList(list []string) string { |
| 327 | sorted := slices.Clone(list) |
| 328 | slices.Sort(sorted) |
| 329 | sorted = slices.Compact(sorted) |
| 330 | items := make([]string, len(sorted)) |
| 331 | for i, item := range sorted { |
| 332 | if IsLocalID(item) { |
| 333 | items[i] = item |
| 334 | } else { |
| 335 | items[i] = quote(item) |
| 336 | } |
| 337 | } |
| 338 | return "[" + strings.Join(items, ", ") + "]" |
| 339 | } |
| 340 | |
| 341 | // quote writes s as a JSON string, leaving <, > and & as they are. |
| 342 | func quote(s string) string { |
| 343 | var b bytes.Buffer |
| 344 | enc := json.NewEncoder(&b) |
| 345 | enc.SetEscapeHTML(false) |
| 346 | _ = enc.Encode(s) |
| 347 | return strings.TrimSuffix(b.String(), "\n") |
| 348 | } |
| 349 | |
| 350 | // ParseComment reads a comment's file: |
| 351 | // |
| 352 | // --- |
| 353 | // author: "alice" |
| 354 | // edited: "2026-10-25T15:00:00Z" |
| 355 | // edited_by: "operator" |
| 356 | // --- |
| 357 | // |
| 358 | // The comment, as markdown. |
| 359 | // |
| 360 | // author comes first. edited and edited_by follow it, in that order, on a |
| 361 | // comment that has been edited, and a comment holds both or neither. Each |
| 362 | // value is a JSON string. A comment that was never edited is the author |
| 363 | // line alone, so a comment written before edits existed reads as it |
| 364 | // always has. The body is required, and the form is as canonical as a |
| 365 | // knot's. |
| 366 | func ParseComment(path string, data []byte) (*Comment, error) { |
| 367 | c, err := parseComment(path, data) |
| 368 | if err != nil { |
| 369 | return nil, err |
| 370 | } |
| 371 | return c, nil |
| 372 | } |
| 373 | |
| 374 | func parseComment(path string, data []byte) (*Comment, *Error) { |
| 375 | if len(data) > MaxCommentSize { |
| 376 | return nil, refuse(RuleLimit, path, fmt.Sprintf("is %d bytes, more than the %d a comment may be", len(data), MaxCommentSize)) |
| 377 | } |
| 378 | if err := checkText(path, data); err != nil { |
| 379 | return nil, err |
| 380 | } |
| 381 | lines, rest, err := frontmatter(path, data) |
| 382 | if err != nil { |
| 383 | return nil, err |
| 384 | } |
| 385 | c := &Comment{Body: readBody(rest)} |
| 386 | fields := map[string]*string{"author": &c.Author, "edited": &c.Edited, "edited_by": &c.EditedBy} |
| 387 | seen := map[string]bool{} |
| 388 | for _, line := range lines { |
| 389 | key, value, _ := strings.Cut(line, ": ") |
| 390 | field := fields[key] |
| 391 | switch { |
| 392 | case field == nil: |
| 393 | return nil, refuse(RuleCanonical, path, fmt.Sprintf("holds the line %q, and a comment's frontmatter is author: \"<principal>\", and on an edited comment edited: \"<UTC time>\" and edited_by: \"<principal>\" after it", line)) |
| 394 | case seen[key]: |
| 395 | return nil, refuse(RuleCanonical, path, fmt.Sprintf("names %s twice", key)) |
| 396 | } |
| 397 | seen[key] = true |
| 398 | s, rerr := readScalar(value) |
| 399 | if rerr != nil { |
| 400 | return nil, refuse(RuleCanonical, path, key+": "+rerr.Error()) |
| 401 | } |
| 402 | *field = s |
| 403 | } |
| 404 | switch { |
| 405 | case !seen["author"]: |
| 406 | return nil, refuse(RuleCanonical, path, "a comment's frontmatter opens with author: \"<principal>\"") |
| 407 | case !IsName(c.Author): |
| 408 | return nil, refuse(RuleFieldShape, path, fmt.Sprintf("its author %q is not a principal's name", c.Author)) |
| 409 | case seen["edited"] && !IsTimestamp(c.Edited): |
| 410 | return nil, refuse(RuleFieldShape, path, fmt.Sprintf("edited is %q, and it is a UTC time, YYYY-MM-DDTHH:MM:SSZ", c.Edited)) |
| 411 | case seen["edited_by"] && !IsName(c.EditedBy): |
| 412 | return nil, refuse(RuleFieldShape, path, fmt.Sprintf("edited_by is %q, and it is a principal's name", c.EditedBy)) |
| 413 | case seen["edited"] != seen["edited_by"]: |
| 414 | return nil, refuse(RuleProvenance, path, "edited and edited_by come together: an edit names when it was made and who made it") |
| 415 | case c.Body == "": |
| 416 | return nil, refuse(RuleRequired, path, "a comment has a body") |
| 417 | case c.Body != NormalBody(c.Body): |
| 418 | return nil, refuse(RuleCanonical, path, "its body opens or ends with a blank line, or does not end with a newline") |
| 419 | } |
| 420 | if want := RenderComment(c); !bytes.Equal(want, data) { |
| 421 | return nil, refuse(RuleCanonical, path, "is not in canonical form, which is:\n"+string(want)) |
| 422 | } |
| 423 | return c, nil |
| 424 | } |
| 425 | |
| 426 | // RenderComment writes a comment in its canonical form. |
| 427 | func RenderComment(c *Comment) []byte { |
| 428 | front := "author: " + quote(c.Author) + "\n" |
| 429 | if c.Edited != "" { |
| 430 | front += "edited: " + quote(c.Edited) + "\n" |
| 431 | } |
| 432 | if c.EditedBy != "" { |
| 433 | front += "edited_by: " + quote(c.EditedBy) + "\n" |
| 434 | } |
| 435 | return []byte(fence + front + fence + "\n" + c.Body) |
| 436 | } |