@backlog-md/core 0.3.8 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core/Core.js CHANGED
@@ -535,43 +535,76 @@ export class Core {
535
535
  * @returns Created milestone
536
536
  */
537
537
  async createMilestone(input) {
538
- const milestonesDir = this.getMilestonesDir();
539
- // Ensure milestones directory exists
540
- await this.fs.createDir(milestonesDir, { recursive: true });
541
- // Find next available milestone ID
542
- const entries = await this.fs.readDir(milestonesDir).catch(() => []);
543
- const existingIds = entries
544
- .map((f) => {
545
- const match = f.match(/^m-(\d+)/);
546
- return match?.[1] ? parseInt(match[1], 10) : -1;
547
- })
548
- .filter((id) => id >= 0);
549
- const nextId = existingIds.length > 0 ? Math.max(...existingIds) + 1 : 0;
550
- const id = `m-${nextId}`;
551
- const description = input.description || `Milestone: ${input.title}`;
552
- // Create a temporary milestone to generate content
553
- const tempMilestone = {
554
- id,
555
- title: input.title,
556
- description,
557
- rawContent: "",
558
- tasks: [],
559
- };
560
- // Generate content
561
- const content = serializeMilestoneMarkdown(tempMilestone);
562
- // Create the final milestone with correct rawContent
563
- const milestone = {
564
- id,
565
- title: input.title,
566
- description,
567
- rawContent: content,
568
- tasks: [],
569
- };
570
- // Write file
571
- const filename = getMilestoneFilename(id, input.title);
572
- const filepath = this.fs.join(milestonesDir, filename);
573
- await this.fs.writeFile(filepath, content);
574
- return milestone;
538
+ const startTime = Date.now();
539
+ const span = this.tracer.startSpan("milestone.create", {
540
+ attributes: {
541
+ "input.title": input.title,
542
+ "input.hasDescription": input.description !== undefined,
543
+ },
544
+ });
545
+ return await context.with(trace.setSpan(context.active(), span), async () => {
546
+ try {
547
+ span.addEvent("milestone.create.started", {
548
+ "input.title": input.title,
549
+ "input.hasDescription": input.description !== undefined,
550
+ });
551
+ const milestonesDir = this.getMilestonesDir();
552
+ // Ensure milestones directory exists
553
+ await this.fs.createDir(milestonesDir, { recursive: true });
554
+ // Find next available milestone ID
555
+ const entries = await this.fs.readDir(milestonesDir).catch(() => []);
556
+ const existingIds = entries
557
+ .map((f) => {
558
+ const match = f.match(/^m-(\d+)/);
559
+ return match?.[1] ? parseInt(match[1], 10) : -1;
560
+ })
561
+ .filter((id) => id >= 0);
562
+ const nextId = existingIds.length > 0 ? Math.max(...existingIds) + 1 : 0;
563
+ const id = `m-${nextId}`;
564
+ const description = input.description || `Milestone: ${input.title}`;
565
+ // Create a temporary milestone to generate content
566
+ const tempMilestone = {
567
+ id,
568
+ title: input.title,
569
+ description,
570
+ rawContent: "",
571
+ tasks: [],
572
+ };
573
+ // Generate content
574
+ const content = serializeMilestoneMarkdown(tempMilestone);
575
+ // Create the final milestone with correct rawContent
576
+ const milestone = {
577
+ id,
578
+ title: input.title,
579
+ description,
580
+ rawContent: content,
581
+ tasks: [],
582
+ };
583
+ // Write file
584
+ const filename = getMilestoneFilename(id, input.title);
585
+ const filepath = this.fs.join(milestonesDir, filename);
586
+ await this.fs.writeFile(filepath, content);
587
+ span.addEvent("milestone.create.complete", {
588
+ "output.milestoneId": id,
589
+ "duration.ms": Date.now() - startTime,
590
+ });
591
+ span.setStatus({ code: SpanStatusCode.OK });
592
+ span.end();
593
+ return milestone;
594
+ }
595
+ catch (error) {
596
+ span.addEvent("milestone.create.error", {
597
+ "error.type": error instanceof Error ? error.name : "UnknownError",
598
+ "error.message": error instanceof Error ? error.message : String(error),
599
+ });
600
+ span.setStatus({
601
+ code: SpanStatusCode.ERROR,
602
+ message: error instanceof Error ? error.message : String(error),
603
+ });
604
+ span.end();
605
+ throw error;
606
+ }
607
+ });
575
608
  }
576
609
  /**
577
610
  * Update an existing milestone
@@ -581,49 +614,101 @@ export class Core {
581
614
  * @returns Updated milestone or null if not found
582
615
  */
583
616
  async updateMilestone(id, input) {
584
- const existing = await this.loadMilestone(id);
585
- if (!existing) {
586
- return null;
587
- }
588
- const milestonesDir = this.getMilestonesDir();
589
- const entries = await this.fs.readDir(milestonesDir);
590
- // Find the current file
591
- const currentFile = entries.find((entry) => {
592
- const fileId = extractMilestoneIdFromFilename(entry);
593
- return fileId === id;
617
+ const startTime = Date.now();
618
+ const span = this.tracer.startSpan("milestone.update", {
619
+ attributes: {
620
+ "input.milestoneId": id,
621
+ "input.hasTitle": input.title !== undefined,
622
+ "input.hasDescription": input.description !== undefined,
623
+ },
624
+ });
625
+ return await context.with(trace.setSpan(context.active(), span), async () => {
626
+ try {
627
+ span.addEvent("milestone.update.started", {
628
+ "input.milestoneId": id,
629
+ "input.hasTitle": input.title !== undefined,
630
+ "input.hasDescription": input.description !== undefined,
631
+ });
632
+ const existing = await this.loadMilestone(id);
633
+ if (!existing) {
634
+ span.addEvent("milestone.update.error", {
635
+ "error.type": "NotFoundError",
636
+ "error.message": "Milestone not found",
637
+ "input.milestoneId": id,
638
+ });
639
+ span.setStatus({ code: SpanStatusCode.OK });
640
+ span.end();
641
+ return null;
642
+ }
643
+ const milestonesDir = this.getMilestonesDir();
644
+ const entries = await this.fs.readDir(milestonesDir);
645
+ // Find the current file
646
+ const currentFile = entries.find((entry) => {
647
+ const fileId = extractMilestoneIdFromFilename(entry);
648
+ return fileId === id;
649
+ });
650
+ if (!currentFile) {
651
+ span.addEvent("milestone.update.error", {
652
+ "error.type": "NotFoundError",
653
+ "error.message": "Milestone file not found",
654
+ "input.milestoneId": id,
655
+ });
656
+ span.setStatus({ code: SpanStatusCode.OK });
657
+ span.end();
658
+ return null;
659
+ }
660
+ // Build updated values
661
+ const newTitle = input.title ?? existing.title;
662
+ const newDescription = input.description ?? existing.description;
663
+ const titleChanged = input.title !== undefined && input.title !== existing.title;
664
+ // Create a temporary milestone to generate content
665
+ const tempMilestone = {
666
+ id: existing.id,
667
+ title: newTitle,
668
+ description: newDescription,
669
+ rawContent: "",
670
+ tasks: existing.tasks,
671
+ };
672
+ // Generate new content
673
+ const content = serializeMilestoneMarkdown(tempMilestone);
674
+ // Create the final updated milestone
675
+ const updated = {
676
+ id: existing.id,
677
+ title: newTitle,
678
+ description: newDescription,
679
+ rawContent: content,
680
+ tasks: existing.tasks,
681
+ };
682
+ // Delete old file
683
+ const oldPath = this.fs.join(milestonesDir, currentFile);
684
+ await this.fs.deleteFile(oldPath);
685
+ // Write new file (with potentially new filename if title changed)
686
+ const newFilename = getMilestoneFilename(id, updated.title);
687
+ const newPath = this.fs.join(milestonesDir, newFilename);
688
+ await this.fs.writeFile(newPath, content);
689
+ span.addEvent("milestone.update.complete", {
690
+ "output.milestoneId": id,
691
+ "output.titleChanged": titleChanged,
692
+ "duration.ms": Date.now() - startTime,
693
+ });
694
+ span.setStatus({ code: SpanStatusCode.OK });
695
+ span.end();
696
+ return updated;
697
+ }
698
+ catch (error) {
699
+ span.addEvent("milestone.update.error", {
700
+ "error.type": error instanceof Error ? error.name : "UnknownError",
701
+ "error.message": error instanceof Error ? error.message : String(error),
702
+ "input.milestoneId": id,
703
+ });
704
+ span.setStatus({
705
+ code: SpanStatusCode.ERROR,
706
+ message: error instanceof Error ? error.message : String(error),
707
+ });
708
+ span.end();
709
+ throw error;
710
+ }
594
711
  });
595
- if (!currentFile) {
596
- return null;
597
- }
598
- // Build updated values
599
- const newTitle = input.title ?? existing.title;
600
- const newDescription = input.description ?? existing.description;
601
- // Create a temporary milestone to generate content
602
- const tempMilestone = {
603
- id: existing.id,
604
- title: newTitle,
605
- description: newDescription,
606
- rawContent: "",
607
- tasks: existing.tasks,
608
- };
609
- // Generate new content
610
- const content = serializeMilestoneMarkdown(tempMilestone);
611
- // Create the final updated milestone
612
- const updated = {
613
- id: existing.id,
614
- title: newTitle,
615
- description: newDescription,
616
- rawContent: content,
617
- tasks: existing.tasks,
618
- };
619
- // Delete old file
620
- const oldPath = this.fs.join(milestonesDir, currentFile);
621
- await this.fs.deleteFile(oldPath);
622
- // Write new file (with potentially new filename if title changed)
623
- const newFilename = getMilestoneFilename(id, updated.title);
624
- const newPath = this.fs.join(milestonesDir, newFilename);
625
- await this.fs.writeFile(newPath, content);
626
- return updated;
627
712
  }
628
713
  /**
629
714
  * Delete a milestone
@@ -632,27 +717,69 @@ export class Core {
632
717
  * @returns true if deleted, false if not found
633
718
  */
634
719
  async deleteMilestone(id) {
635
- const milestonesDir = this.getMilestonesDir();
636
- if (!(await this.fs.exists(milestonesDir))) {
637
- return false;
638
- }
639
- const entries = await this.fs.readDir(milestonesDir);
640
- // Find file matching the ID
641
- const milestoneFile = entries.find((entry) => {
642
- const fileId = extractMilestoneIdFromFilename(entry);
643
- return fileId === id;
720
+ const startTime = Date.now();
721
+ const span = this.tracer.startSpan("milestone.delete", {
722
+ attributes: {
723
+ "input.milestoneId": id,
724
+ },
725
+ });
726
+ return await context.with(trace.setSpan(context.active(), span), async () => {
727
+ try {
728
+ span.addEvent("milestone.delete.started", {
729
+ "input.milestoneId": id,
730
+ });
731
+ const milestonesDir = this.getMilestonesDir();
732
+ if (!(await this.fs.exists(milestonesDir))) {
733
+ span.addEvent("milestone.delete.error", {
734
+ "error.type": "NotFoundError",
735
+ "error.message": "Milestones directory not found",
736
+ "input.milestoneId": id,
737
+ });
738
+ span.setStatus({ code: SpanStatusCode.OK });
739
+ span.end();
740
+ return false;
741
+ }
742
+ const entries = await this.fs.readDir(milestonesDir);
743
+ // Find file matching the ID
744
+ const milestoneFile = entries.find((entry) => {
745
+ const fileId = extractMilestoneIdFromFilename(entry);
746
+ return fileId === id;
747
+ });
748
+ if (!milestoneFile) {
749
+ span.addEvent("milestone.delete.error", {
750
+ "error.type": "NotFoundError",
751
+ "error.message": "Milestone not found",
752
+ "input.milestoneId": id,
753
+ });
754
+ span.setStatus({ code: SpanStatusCode.OK });
755
+ span.end();
756
+ return false;
757
+ }
758
+ const filepath = this.fs.join(milestonesDir, milestoneFile);
759
+ await this.fs.deleteFile(filepath);
760
+ span.addEvent("milestone.delete.complete", {
761
+ "output.milestoneId": id,
762
+ "output.deleted": true,
763
+ "duration.ms": Date.now() - startTime,
764
+ });
765
+ span.setStatus({ code: SpanStatusCode.OK });
766
+ span.end();
767
+ return true;
768
+ }
769
+ catch (error) {
770
+ span.addEvent("milestone.delete.error", {
771
+ "error.type": error instanceof Error ? error.name : "UnknownError",
772
+ "error.message": error instanceof Error ? error.message : String(error),
773
+ "input.milestoneId": id,
774
+ });
775
+ span.setStatus({
776
+ code: SpanStatusCode.ERROR,
777
+ message: error instanceof Error ? error.message : String(error),
778
+ });
779
+ span.end();
780
+ throw error;
781
+ }
644
782
  });
645
- if (!milestoneFile) {
646
- return false;
647
- }
648
- const filepath = this.fs.join(milestonesDir, milestoneFile);
649
- try {
650
- await this.fs.deleteFile(filepath);
651
- return true;
652
- }
653
- catch {
654
- return false;
655
- }
656
783
  }
657
784
  /**
658
785
  * Get a single task by ID
@@ -928,81 +1055,117 @@ export class Core {
928
1055
  */
929
1056
  async createTask(input) {
930
1057
  this.ensureInitialized();
931
- const tasksDir = this.getTasksDir();
932
- // Ensure tasks directory exists
933
- await this.fs.createDir(tasksDir, { recursive: true });
934
- // Generate next task ID
935
- // Use taskIndex as source of truth (works for both lazy and full initialization)
936
- const existingIds = Array.from(this.lazyInitialized ? this.taskIndex.keys() : this.tasks.keys())
937
- .map((id) => parseInt(id.replace(/\D/g, ""), 10))
938
- .filter((n) => !Number.isNaN(n));
939
- const nextId = existingIds.length > 0 ? Math.max(...existingIds) + 1 : 1;
940
- const taskId = String(nextId);
941
- // Validate and normalize status
942
- const configStatuses = this.config?.statuses || [
943
- DEFAULT_TASK_STATUSES.TODO,
944
- DEFAULT_TASK_STATUSES.IN_PROGRESS,
945
- DEFAULT_TASK_STATUSES.DONE,
946
- ];
947
- let status = input.status || this.config?.defaultStatus || DEFAULT_TASK_STATUSES.TODO;
948
- // Validate status against configured statuses
949
- if (!configStatuses.includes(status)) {
950
- console.warn(`Warning: Status "${status}" is not in configured statuses [${configStatuses.join(", ")}]. ` +
951
- `Using default status "${this.config?.defaultStatus || DEFAULT_TASK_STATUSES.TODO}" instead.`);
952
- status = this.config?.defaultStatus || DEFAULT_TASK_STATUSES.TODO;
953
- }
954
- // Build task object
955
- const now = new Date().toISOString().split("T")[0];
956
- const task = {
957
- id: taskId,
958
- title: input.title,
959
- status,
960
- priority: input.priority,
961
- assignee: input.assignee || [],
962
- createdDate: now,
963
- labels: input.labels || [],
964
- milestone: input.milestone,
965
- dependencies: input.dependencies || [],
966
- references: input.references || [],
967
- parentTaskId: input.parentTaskId,
968
- description: input.description,
969
- implementationPlan: input.implementationPlan,
970
- implementationNotes: input.implementationNotes,
971
- acceptanceCriteriaItems: input.acceptanceCriteria?.map((ac, i) => ({
972
- index: i + 1,
973
- text: ac.text,
974
- checked: ac.checked || false,
975
- })),
976
- rawContent: input.rawContent,
977
- source: "local",
978
- };
979
- // Serialize and write file
980
- const content = serializeTaskMarkdown(task);
981
- const safeTitle = input.title
982
- .replace(/[<>:"/\\|?*]/g, "")
983
- .replace(/\s+/g, " ")
984
- .slice(0, 50);
985
- const filename = `${taskId} - ${safeTitle}.md`;
986
- const filepath = this.fs.join(tasksDir, filename);
987
- await this.fs.writeFile(filepath, content);
988
- // Update in-memory cache
989
- task.filePath = filepath;
990
- this.tasks.set(taskId, task);
991
- // Also update taskIndex if in lazy mode
992
- if (this.lazyInitialized) {
993
- const relativePath = filepath.replace(`${this.projectRoot}/`, "");
994
- this.taskIndex.set(taskId, {
995
- id: taskId,
996
- filePath: relativePath,
997
- title: task.title,
998
- source: "tasks",
999
- });
1000
- }
1001
- // Sync milestone if specified
1002
- if (input.milestone) {
1003
- await this.addTaskToMilestone(taskId, input.milestone);
1004
- }
1005
- return task;
1058
+ const startTime = Date.now();
1059
+ const span = this.tracer.startSpan("task.create", {
1060
+ attributes: {
1061
+ "input.title": input.title,
1062
+ "input.status": input.status,
1063
+ "input.milestoneId": input.milestone,
1064
+ },
1065
+ });
1066
+ return await context.with(trace.setSpan(context.active(), span), async () => {
1067
+ try {
1068
+ span.addEvent("task.create.started", {
1069
+ "input.title": input.title,
1070
+ "input.status": input.status,
1071
+ "input.milestoneId": input.milestone,
1072
+ });
1073
+ const tasksDir = this.getTasksDir();
1074
+ // Ensure tasks directory exists
1075
+ await this.fs.createDir(tasksDir, { recursive: true });
1076
+ // Generate next task ID
1077
+ // Use taskIndex as source of truth (works for both lazy and full initialization)
1078
+ const existingIds = Array.from(this.lazyInitialized ? this.taskIndex.keys() : this.tasks.keys())
1079
+ .map((id) => parseInt(id.replace(/\D/g, ""), 10))
1080
+ .filter((n) => !Number.isNaN(n));
1081
+ const nextId = existingIds.length > 0 ? Math.max(...existingIds) + 1 : 1;
1082
+ const taskId = String(nextId);
1083
+ // Validate and normalize status
1084
+ const configStatuses = this.config?.statuses || [
1085
+ DEFAULT_TASK_STATUSES.TODO,
1086
+ DEFAULT_TASK_STATUSES.IN_PROGRESS,
1087
+ DEFAULT_TASK_STATUSES.DONE,
1088
+ ];
1089
+ let status = input.status || this.config?.defaultStatus || DEFAULT_TASK_STATUSES.TODO;
1090
+ // Validate status against configured statuses
1091
+ if (!configStatuses.includes(status)) {
1092
+ console.warn(`Warning: Status "${status}" is not in configured statuses [${configStatuses.join(", ")}]. ` +
1093
+ `Using default status "${this.config?.defaultStatus || DEFAULT_TASK_STATUSES.TODO}" instead.`);
1094
+ status = this.config?.defaultStatus || DEFAULT_TASK_STATUSES.TODO;
1095
+ }
1096
+ // Build task object
1097
+ const now = new Date().toISOString().split("T")[0];
1098
+ const task = {
1099
+ id: taskId,
1100
+ title: input.title,
1101
+ status,
1102
+ priority: input.priority,
1103
+ assignee: input.assignee || [],
1104
+ createdDate: now,
1105
+ labels: input.labels || [],
1106
+ milestone: input.milestone,
1107
+ dependencies: input.dependencies || [],
1108
+ references: input.references || [],
1109
+ parentTaskId: input.parentTaskId,
1110
+ description: input.description,
1111
+ implementationPlan: input.implementationPlan,
1112
+ implementationNotes: input.implementationNotes,
1113
+ acceptanceCriteriaItems: input.acceptanceCriteria?.map((ac, i) => ({
1114
+ index: i + 1,
1115
+ text: ac.text,
1116
+ checked: ac.checked || false,
1117
+ })),
1118
+ rawContent: input.rawContent,
1119
+ source: "local",
1120
+ };
1121
+ // Serialize and write file
1122
+ const content = serializeTaskMarkdown(task);
1123
+ const safeTitle = input.title
1124
+ .replace(/[<>:"/\\|?*]/g, "")
1125
+ .replace(/\s+/g, " ")
1126
+ .slice(0, 50);
1127
+ const filename = `${taskId} - ${safeTitle}.md`;
1128
+ const filepath = this.fs.join(tasksDir, filename);
1129
+ await this.fs.writeFile(filepath, content);
1130
+ // Update in-memory cache
1131
+ task.filePath = filepath;
1132
+ this.tasks.set(taskId, task);
1133
+ // Also update taskIndex if in lazy mode
1134
+ if (this.lazyInitialized) {
1135
+ const relativePath = filepath.replace(`${this.projectRoot}/`, "");
1136
+ this.taskIndex.set(taskId, {
1137
+ id: taskId,
1138
+ filePath: relativePath,
1139
+ title: task.title,
1140
+ source: "tasks",
1141
+ });
1142
+ }
1143
+ // Sync milestone if specified
1144
+ if (input.milestone) {
1145
+ await this.addTaskToMilestone(taskId, input.milestone);
1146
+ }
1147
+ span.addEvent("task.create.complete", {
1148
+ "output.taskId": taskId,
1149
+ "output.taskIndex": nextId,
1150
+ "duration.ms": Date.now() - startTime,
1151
+ });
1152
+ span.setStatus({ code: SpanStatusCode.OK });
1153
+ span.end();
1154
+ return task;
1155
+ }
1156
+ catch (error) {
1157
+ span.addEvent("task.create.error", {
1158
+ "error.type": error instanceof Error ? error.name : "UnknownError",
1159
+ "error.message": error instanceof Error ? error.message : String(error),
1160
+ });
1161
+ span.setStatus({
1162
+ code: SpanStatusCode.ERROR,
1163
+ message: error instanceof Error ? error.message : String(error),
1164
+ });
1165
+ span.end();
1166
+ throw error;
1167
+ }
1168
+ });
1006
1169
  }
1007
1170
  /**
1008
1171
  * Update an existing task
@@ -1013,105 +1176,153 @@ export class Core {
1013
1176
  */
1014
1177
  async updateTask(id, input) {
1015
1178
  this.ensureInitialized();
1016
- const existing = this.tasks.get(id);
1017
- if (!existing) {
1018
- return null;
1019
- }
1020
- const oldMilestone = existing.milestone;
1021
- const newMilestone = input.milestone === null
1022
- ? undefined
1023
- : input.milestone !== undefined
1024
- ? input.milestone
1025
- : oldMilestone;
1026
- // Build updated task
1027
- const now = new Date().toISOString().split("T")[0];
1028
- const updated = {
1029
- ...existing,
1030
- title: input.title ?? existing.title,
1031
- status: input.status ?? existing.status,
1032
- priority: input.priority ?? existing.priority,
1033
- milestone: newMilestone,
1034
- updatedDate: now,
1035
- description: input.description ?? existing.description,
1036
- implementationPlan: input.clearImplementationPlan
1037
- ? undefined
1038
- : (input.implementationPlan ?? existing.implementationPlan),
1039
- implementationNotes: input.clearImplementationNotes
1040
- ? undefined
1041
- : (input.implementationNotes ?? existing.implementationNotes),
1042
- ordinal: input.ordinal ?? existing.ordinal,
1043
- dependencies: input.dependencies ?? existing.dependencies,
1044
- references: input.references ?? existing.references ?? [],
1045
- };
1046
- // Handle label operations
1047
- if (input.labels) {
1048
- updated.labels = input.labels;
1049
- }
1050
- else {
1051
- if (input.addLabels) {
1052
- updated.labels = [...new Set([...updated.labels, ...input.addLabels])];
1053
- }
1054
- if (input.removeLabels) {
1055
- updated.labels = updated.labels.filter((l) => !input.removeLabels?.includes(l));
1056
- }
1057
- }
1058
- // Handle assignee
1059
- if (input.assignee) {
1060
- updated.assignee = input.assignee;
1061
- }
1062
- // Handle dependency operations
1063
- if (input.addDependencies) {
1064
- updated.dependencies = [...new Set([...updated.dependencies, ...input.addDependencies])];
1065
- }
1066
- if (input.removeDependencies) {
1067
- updated.dependencies = updated.dependencies.filter((d) => !input.removeDependencies?.includes(d));
1068
- }
1069
- // Handle references operations
1070
- if (input.addReferences) {
1071
- updated.references = [...new Set([...(updated.references || []), ...input.addReferences])];
1072
- }
1073
- if (input.removeReferences) {
1074
- updated.references = (updated.references || []).filter((r) => !input.removeReferences?.includes(r));
1075
- }
1076
- // Handle acceptance criteria
1077
- if (input.acceptanceCriteria) {
1078
- updated.acceptanceCriteriaItems = input.acceptanceCriteria.map((ac, i) => ({
1079
- index: i + 1,
1080
- text: ac.text,
1081
- checked: ac.checked || false,
1082
- }));
1083
- }
1084
- // Serialize and write file
1085
- const content = serializeTaskMarkdown(updated);
1086
- // Delete old file if exists
1087
- if (existing.filePath) {
1088
- await this.fs.deleteFile(existing.filePath).catch(() => { });
1089
- }
1090
- // Write new file
1091
- const tasksDir = this.getTasksDir();
1092
- const safeTitle = updated.title
1093
- .replace(/[<>:"/\\|?*]/g, "")
1094
- .replace(/\s+/g, " ")
1095
- .slice(0, 50);
1096
- const filename = `${id} - ${safeTitle}.md`;
1097
- const filepath = this.fs.join(tasksDir, filename);
1098
- await this.fs.writeFile(filepath, content);
1099
- // Update in-memory cache
1100
- updated.filePath = filepath;
1101
- this.tasks.set(id, updated);
1102
- // Handle milestone sync
1103
- const milestoneChanged = milestoneKey(oldMilestone) !== milestoneKey(newMilestone);
1104
- if (milestoneChanged) {
1105
- // Remove from old milestone
1106
- if (oldMilestone) {
1107
- await this.removeTaskFromMilestone(id, oldMilestone);
1179
+ const startTime = Date.now();
1180
+ const span = this.tracer.startSpan("task.update", {
1181
+ attributes: {
1182
+ "input.taskId": id,
1183
+ "input.hasTitle": input.title !== undefined,
1184
+ "input.hasStatus": input.status !== undefined,
1185
+ "input.hasMilestone": input.milestone !== undefined,
1186
+ },
1187
+ });
1188
+ return await context.with(trace.setSpan(context.active(), span), async () => {
1189
+ try {
1190
+ span.addEvent("task.update.started", {
1191
+ "input.taskId": id,
1192
+ "input.hasTitle": input.title !== undefined,
1193
+ "input.hasStatus": input.status !== undefined,
1194
+ "input.hasMilestone": input.milestone !== undefined,
1195
+ });
1196
+ const existing = this.tasks.get(id);
1197
+ if (!existing) {
1198
+ span.addEvent("task.update.error", {
1199
+ "error.type": "NotFoundError",
1200
+ "error.message": "Task not found",
1201
+ "input.taskId": id,
1202
+ });
1203
+ span.setStatus({ code: SpanStatusCode.OK }); // Not found is not an error
1204
+ span.end();
1205
+ return null;
1206
+ }
1207
+ const oldMilestone = existing.milestone;
1208
+ const newMilestone = input.milestone === null
1209
+ ? undefined
1210
+ : input.milestone !== undefined
1211
+ ? input.milestone
1212
+ : oldMilestone;
1213
+ // Build updated task
1214
+ const now = new Date().toISOString().split("T")[0];
1215
+ const updated = {
1216
+ ...existing,
1217
+ title: input.title ?? existing.title,
1218
+ status: input.status ?? existing.status,
1219
+ priority: input.priority ?? existing.priority,
1220
+ milestone: newMilestone,
1221
+ updatedDate: now,
1222
+ description: input.description ?? existing.description,
1223
+ implementationPlan: input.clearImplementationPlan
1224
+ ? undefined
1225
+ : (input.implementationPlan ?? existing.implementationPlan),
1226
+ implementationNotes: input.clearImplementationNotes
1227
+ ? undefined
1228
+ : (input.implementationNotes ?? existing.implementationNotes),
1229
+ ordinal: input.ordinal ?? existing.ordinal,
1230
+ dependencies: input.dependencies ?? existing.dependencies,
1231
+ references: input.references ?? existing.references ?? [],
1232
+ };
1233
+ // Handle label operations
1234
+ if (input.labels) {
1235
+ updated.labels = input.labels;
1236
+ }
1237
+ else {
1238
+ if (input.addLabels) {
1239
+ updated.labels = [...new Set([...updated.labels, ...input.addLabels])];
1240
+ }
1241
+ if (input.removeLabels) {
1242
+ updated.labels = updated.labels.filter((l) => !input.removeLabels?.includes(l));
1243
+ }
1244
+ }
1245
+ // Handle assignee
1246
+ if (input.assignee) {
1247
+ updated.assignee = input.assignee;
1248
+ }
1249
+ // Handle dependency operations
1250
+ if (input.addDependencies) {
1251
+ updated.dependencies = [...new Set([...updated.dependencies, ...input.addDependencies])];
1252
+ }
1253
+ if (input.removeDependencies) {
1254
+ updated.dependencies = updated.dependencies.filter((d) => !input.removeDependencies?.includes(d));
1255
+ }
1256
+ // Handle references operations
1257
+ if (input.addReferences) {
1258
+ updated.references = [
1259
+ ...new Set([...(updated.references || []), ...input.addReferences]),
1260
+ ];
1261
+ }
1262
+ if (input.removeReferences) {
1263
+ updated.references = (updated.references || []).filter((r) => !input.removeReferences?.includes(r));
1264
+ }
1265
+ // Handle acceptance criteria
1266
+ if (input.acceptanceCriteria) {
1267
+ updated.acceptanceCriteriaItems = input.acceptanceCriteria.map((ac, i) => ({
1268
+ index: i + 1,
1269
+ text: ac.text,
1270
+ checked: ac.checked || false,
1271
+ }));
1272
+ }
1273
+ // Serialize and write file
1274
+ const content = serializeTaskMarkdown(updated);
1275
+ // Delete old file if exists
1276
+ if (existing.filePath) {
1277
+ await this.fs.deleteFile(existing.filePath).catch(() => { });
1278
+ }
1279
+ // Write new file
1280
+ const tasksDir = this.getTasksDir();
1281
+ const safeTitle = updated.title
1282
+ .replace(/[<>:"/\\|?*]/g, "")
1283
+ .replace(/\s+/g, " ")
1284
+ .slice(0, 50);
1285
+ const filename = `${id} - ${safeTitle}.md`;
1286
+ const filepath = this.fs.join(tasksDir, filename);
1287
+ await this.fs.writeFile(filepath, content);
1288
+ // Update in-memory cache
1289
+ updated.filePath = filepath;
1290
+ this.tasks.set(id, updated);
1291
+ // Handle milestone sync
1292
+ const milestoneChanged = milestoneKey(oldMilestone) !== milestoneKey(newMilestone);
1293
+ if (milestoneChanged) {
1294
+ // Remove from old milestone
1295
+ if (oldMilestone) {
1296
+ await this.removeTaskFromMilestone(id, oldMilestone);
1297
+ }
1298
+ // Add to new milestone
1299
+ if (newMilestone) {
1300
+ await this.addTaskToMilestone(id, newMilestone);
1301
+ }
1302
+ }
1303
+ span.addEvent("task.update.complete", {
1304
+ "output.taskId": id,
1305
+ "output.statusChanged": input.status !== undefined,
1306
+ "duration.ms": Date.now() - startTime,
1307
+ });
1308
+ span.setStatus({ code: SpanStatusCode.OK });
1309
+ span.end();
1310
+ return updated;
1108
1311
  }
1109
- // Add to new milestone
1110
- if (newMilestone) {
1111
- await this.addTaskToMilestone(id, newMilestone);
1312
+ catch (error) {
1313
+ span.addEvent("task.update.error", {
1314
+ "error.type": error instanceof Error ? error.name : "UnknownError",
1315
+ "error.message": error instanceof Error ? error.message : String(error),
1316
+ "input.taskId": id,
1317
+ });
1318
+ span.setStatus({
1319
+ code: SpanStatusCode.ERROR,
1320
+ message: error instanceof Error ? error.message : String(error),
1321
+ });
1322
+ span.end();
1323
+ throw error;
1112
1324
  }
1113
- }
1114
- return updated;
1325
+ });
1115
1326
  }
1116
1327
  /**
1117
1328
  * Delete a task
@@ -1121,26 +1332,62 @@ export class Core {
1121
1332
  */
1122
1333
  async deleteTask(id) {
1123
1334
  this.ensureInitialized();
1124
- const task = this.tasks.get(id);
1125
- if (!task) {
1126
- return false;
1127
- }
1128
- // Remove from milestone if assigned
1129
- if (task.milestone) {
1130
- await this.removeTaskFromMilestone(id, task.milestone);
1131
- }
1132
- // Delete file
1133
- if (task.filePath) {
1335
+ const startTime = Date.now();
1336
+ const span = this.tracer.startSpan("task.delete", {
1337
+ attributes: { "input.taskId": id },
1338
+ });
1339
+ return await context.with(trace.setSpan(context.active(), span), async () => {
1134
1340
  try {
1135
- await this.fs.deleteFile(task.filePath);
1341
+ span.addEvent("task.delete.started", { "input.taskId": id });
1342
+ const task = this.tasks.get(id);
1343
+ if (!task) {
1344
+ span.addEvent("task.delete.error", {
1345
+ "error.type": "NotFoundError",
1346
+ "error.message": "Task not found",
1347
+ "input.taskId": id,
1348
+ });
1349
+ span.setStatus({ code: SpanStatusCode.OK });
1350
+ span.end();
1351
+ return false;
1352
+ }
1353
+ // Remove from milestone if assigned
1354
+ if (task.milestone) {
1355
+ await this.removeTaskFromMilestone(id, task.milestone);
1356
+ }
1357
+ // Delete file
1358
+ if (task.filePath) {
1359
+ try {
1360
+ await this.fs.deleteFile(task.filePath);
1361
+ }
1362
+ catch {
1363
+ // File may already be deleted
1364
+ }
1365
+ }
1366
+ // Remove from in-memory cache
1367
+ this.tasks.delete(id);
1368
+ span.addEvent("task.delete.complete", {
1369
+ "output.taskId": id,
1370
+ "output.deleted": true,
1371
+ "duration.ms": Date.now() - startTime,
1372
+ });
1373
+ span.setStatus({ code: SpanStatusCode.OK });
1374
+ span.end();
1375
+ return true;
1136
1376
  }
1137
- catch {
1138
- // File may already be deleted
1377
+ catch (error) {
1378
+ span.addEvent("task.delete.error", {
1379
+ "error.type": error instanceof Error ? error.name : "UnknownError",
1380
+ "error.message": error instanceof Error ? error.message : String(error),
1381
+ "input.taskId": id,
1382
+ });
1383
+ span.setStatus({
1384
+ code: SpanStatusCode.ERROR,
1385
+ message: error instanceof Error ? error.message : String(error),
1386
+ });
1387
+ span.end();
1388
+ throw error;
1139
1389
  }
1140
- }
1141
- // Remove from in-memory cache
1142
- this.tasks.delete(id);
1143
- return true;
1390
+ });
1144
1391
  }
1145
1392
  /**
1146
1393
  * Archive a task (move from tasks/ to completed/)
@@ -1150,53 +1397,96 @@ export class Core {
1150
1397
  */
1151
1398
  async archiveTask(id) {
1152
1399
  this.ensureInitialized();
1153
- const task = this.tasks.get(id);
1154
- if (!task) {
1155
- return null;
1156
- }
1157
- // Check if already in completed
1158
- if (task.source === "completed") {
1159
- return null;
1160
- }
1161
- const completedDir = this.getCompletedDir();
1162
- // Ensure completed directory exists
1163
- await this.fs.createDir(completedDir, { recursive: true });
1164
- // Build new filepath in completed/
1165
- const safeTitle = task.title
1166
- .replace(/[<>:"/\\|?*]/g, "")
1167
- .replace(/\s+/g, " ")
1168
- .slice(0, 50);
1169
- const filename = `${id} - ${safeTitle}.md`;
1170
- const newFilepath = this.fs.join(completedDir, filename);
1171
- // Delete old file
1172
- if (task.filePath) {
1400
+ const startTime = Date.now();
1401
+ const span = this.tracer.startSpan("task.archive", {
1402
+ attributes: { "input.taskId": id },
1403
+ });
1404
+ return await context.with(trace.setSpan(context.active(), span), async () => {
1173
1405
  try {
1174
- await this.fs.deleteFile(task.filePath);
1175
- }
1176
- catch {
1177
- // File may not exist
1406
+ span.addEvent("task.archive.started", { "input.taskId": id });
1407
+ const task = this.tasks.get(id);
1408
+ if (!task) {
1409
+ span.addEvent("task.archive.error", {
1410
+ "error.type": "NotFoundError",
1411
+ "error.message": "Task not found",
1412
+ "input.taskId": id,
1413
+ });
1414
+ span.setStatus({ code: SpanStatusCode.OK }); // Not found is not an error
1415
+ span.end();
1416
+ return null;
1417
+ }
1418
+ // Check if already in completed
1419
+ if (task.source === "completed") {
1420
+ span.addEvent("task.archive.error", {
1421
+ "error.type": "InvalidStateError",
1422
+ "error.message": "Task already archived",
1423
+ "input.taskId": id,
1424
+ });
1425
+ span.setStatus({ code: SpanStatusCode.OK });
1426
+ span.end();
1427
+ return null;
1428
+ }
1429
+ const completedDir = this.getCompletedDir();
1430
+ // Ensure completed directory exists
1431
+ await this.fs.createDir(completedDir, { recursive: true });
1432
+ // Build new filepath in completed/
1433
+ const safeTitle = task.title
1434
+ .replace(/[<>:"/\\|?*]/g, "")
1435
+ .replace(/\s+/g, " ")
1436
+ .slice(0, 50);
1437
+ const filename = `${id} - ${safeTitle}.md`;
1438
+ const newFilepath = this.fs.join(completedDir, filename);
1439
+ // Delete old file
1440
+ if (task.filePath) {
1441
+ try {
1442
+ await this.fs.deleteFile(task.filePath);
1443
+ }
1444
+ catch {
1445
+ // File may not exist
1446
+ }
1447
+ }
1448
+ // Update task
1449
+ const archived = {
1450
+ ...task,
1451
+ source: "completed",
1452
+ filePath: newFilepath,
1453
+ };
1454
+ // Write to new location
1455
+ const content = serializeTaskMarkdown(archived);
1456
+ await this.fs.writeFile(newFilepath, content);
1457
+ // Update in-memory cache
1458
+ this.tasks.set(id, archived);
1459
+ // Update task index if lazy initialized
1460
+ if (this.lazyInitialized) {
1461
+ const entry = this.taskIndex.get(id);
1462
+ if (entry) {
1463
+ entry.source = "completed";
1464
+ entry.filePath = newFilepath;
1465
+ }
1466
+ }
1467
+ span.addEvent("task.archive.complete", {
1468
+ "output.taskId": id,
1469
+ "output.newPath": newFilepath,
1470
+ "duration.ms": Date.now() - startTime,
1471
+ });
1472
+ span.setStatus({ code: SpanStatusCode.OK });
1473
+ span.end();
1474
+ return archived;
1178
1475
  }
1179
- }
1180
- // Update task
1181
- const archived = {
1182
- ...task,
1183
- source: "completed",
1184
- filePath: newFilepath,
1185
- };
1186
- // Write to new location
1187
- const content = serializeTaskMarkdown(archived);
1188
- await this.fs.writeFile(newFilepath, content);
1189
- // Update in-memory cache
1190
- this.tasks.set(id, archived);
1191
- // Update task index if lazy initialized
1192
- if (this.lazyInitialized) {
1193
- const entry = this.taskIndex.get(id);
1194
- if (entry) {
1195
- entry.source = "completed";
1196
- entry.filePath = newFilepath;
1476
+ catch (error) {
1477
+ span.addEvent("task.archive.error", {
1478
+ "error.type": error instanceof Error ? error.name : "UnknownError",
1479
+ "error.message": error instanceof Error ? error.message : String(error),
1480
+ "input.taskId": id,
1481
+ });
1482
+ span.setStatus({
1483
+ code: SpanStatusCode.ERROR,
1484
+ message: error instanceof Error ? error.message : String(error),
1485
+ });
1486
+ span.end();
1487
+ throw error;
1197
1488
  }
1198
- }
1199
- return archived;
1489
+ });
1200
1490
  }
1201
1491
  /**
1202
1492
  * Restore a task (move from completed/ to tasks/)
@@ -1206,53 +1496,96 @@ export class Core {
1206
1496
  */
1207
1497
  async restoreTask(id) {
1208
1498
  this.ensureInitialized();
1209
- const task = this.tasks.get(id);
1210
- if (!task) {
1211
- return null;
1212
- }
1213
- // Check if in completed
1214
- if (task.source !== "completed") {
1215
- return null;
1216
- }
1217
- const tasksDir = this.getTasksDir();
1218
- // Ensure tasks directory exists
1219
- await this.fs.createDir(tasksDir, { recursive: true });
1220
- // Build new filepath in tasks/
1221
- const safeTitle = task.title
1222
- .replace(/[<>:"/\\|?*]/g, "")
1223
- .replace(/\s+/g, " ")
1224
- .slice(0, 50);
1225
- const filename = `${id} - ${safeTitle}.md`;
1226
- const newFilepath = this.fs.join(tasksDir, filename);
1227
- // Delete old file
1228
- if (task.filePath) {
1499
+ const startTime = Date.now();
1500
+ const span = this.tracer.startSpan("task.restore", {
1501
+ attributes: { "input.taskId": id },
1502
+ });
1503
+ return await context.with(trace.setSpan(context.active(), span), async () => {
1229
1504
  try {
1230
- await this.fs.deleteFile(task.filePath);
1231
- }
1232
- catch {
1233
- // File may not exist
1505
+ span.addEvent("task.restore.started", { "input.taskId": id });
1506
+ const task = this.tasks.get(id);
1507
+ if (!task) {
1508
+ span.addEvent("task.restore.error", {
1509
+ "error.type": "NotFoundError",
1510
+ "error.message": "Task not found",
1511
+ "input.taskId": id,
1512
+ });
1513
+ span.setStatus({ code: SpanStatusCode.OK }); // Not found is not an error
1514
+ span.end();
1515
+ return null;
1516
+ }
1517
+ // Check if in completed
1518
+ if (task.source !== "completed") {
1519
+ span.addEvent("task.restore.error", {
1520
+ "error.type": "InvalidStateError",
1521
+ "error.message": "Task not in completed",
1522
+ "input.taskId": id,
1523
+ });
1524
+ span.setStatus({ code: SpanStatusCode.OK });
1525
+ span.end();
1526
+ return null;
1527
+ }
1528
+ const tasksDir = this.getTasksDir();
1529
+ // Ensure tasks directory exists
1530
+ await this.fs.createDir(tasksDir, { recursive: true });
1531
+ // Build new filepath in tasks/
1532
+ const safeTitle = task.title
1533
+ .replace(/[<>:"/\\|?*]/g, "")
1534
+ .replace(/\s+/g, " ")
1535
+ .slice(0, 50);
1536
+ const filename = `${id} - ${safeTitle}.md`;
1537
+ const newFilepath = this.fs.join(tasksDir, filename);
1538
+ // Delete old file
1539
+ if (task.filePath) {
1540
+ try {
1541
+ await this.fs.deleteFile(task.filePath);
1542
+ }
1543
+ catch {
1544
+ // File may not exist
1545
+ }
1546
+ }
1547
+ // Update task
1548
+ const restored = {
1549
+ ...task,
1550
+ source: "local",
1551
+ filePath: newFilepath,
1552
+ };
1553
+ // Write to new location
1554
+ const content = serializeTaskMarkdown(restored);
1555
+ await this.fs.writeFile(newFilepath, content);
1556
+ // Update in-memory cache
1557
+ this.tasks.set(id, restored);
1558
+ // Update task index if lazy initialized
1559
+ if (this.lazyInitialized) {
1560
+ const entry = this.taskIndex.get(id);
1561
+ if (entry) {
1562
+ entry.source = "tasks";
1563
+ entry.filePath = newFilepath;
1564
+ }
1565
+ }
1566
+ span.addEvent("task.restore.complete", {
1567
+ "output.taskId": id,
1568
+ "output.newPath": newFilepath,
1569
+ "duration.ms": Date.now() - startTime,
1570
+ });
1571
+ span.setStatus({ code: SpanStatusCode.OK });
1572
+ span.end();
1573
+ return restored;
1234
1574
  }
1235
- }
1236
- // Update task
1237
- const restored = {
1238
- ...task,
1239
- source: "local",
1240
- filePath: newFilepath,
1241
- };
1242
- // Write to new location
1243
- const content = serializeTaskMarkdown(restored);
1244
- await this.fs.writeFile(newFilepath, content);
1245
- // Update in-memory cache
1246
- this.tasks.set(id, restored);
1247
- // Update task index if lazy initialized
1248
- if (this.lazyInitialized) {
1249
- const entry = this.taskIndex.get(id);
1250
- if (entry) {
1251
- entry.source = "tasks";
1252
- entry.filePath = newFilepath;
1575
+ catch (error) {
1576
+ span.addEvent("task.restore.error", {
1577
+ "error.type": error instanceof Error ? error.name : "UnknownError",
1578
+ "error.message": error instanceof Error ? error.message : String(error),
1579
+ "input.taskId": id,
1580
+ });
1581
+ span.setStatus({
1582
+ code: SpanStatusCode.ERROR,
1583
+ message: error instanceof Error ? error.message : String(error),
1584
+ });
1585
+ span.end();
1586
+ throw error;
1253
1587
  }
1254
- }
1255
- return restored;
1588
+ });
1256
1589
  }
1257
1590
  /**
1258
1591
  * Load specific tasks by their IDs (for lazy loading milestone tasks)