pi-crew 0.1.37 → 0.1.39

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.
Files changed (162) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +27 -0
  3. package/README.md +5 -0
  4. package/agents/analyst.md +11 -11
  5. package/agents/critic.md +11 -11
  6. package/agents/executor.md +11 -11
  7. package/agents/explorer.md +11 -11
  8. package/agents/planner.md +11 -11
  9. package/agents/reviewer.md +11 -11
  10. package/agents/security-reviewer.md +11 -11
  11. package/agents/test-engineer.md +11 -11
  12. package/agents/verifier.md +11 -11
  13. package/agents/writer.md +11 -11
  14. package/docs/refactor-tasks-phase3.md +394 -394
  15. package/docs/refactor-tasks-phase4.md +564 -564
  16. package/docs/refactor-tasks-phase5.md +402 -402
  17. package/docs/refactor-tasks-phase6.md +662 -662
  18. package/docs/research-extension-examples.md +297 -297
  19. package/docs/research-extension-system.md +324 -324
  20. package/docs/research-optimization-plan.md +548 -548
  21. package/docs/research-pi-coding-agent.md +357 -357
  22. package/docs/research-source-pi-crew-reference.md +174 -174
  23. package/docs/resource-formats.md +10 -8
  24. package/docs/runtime-flow.md +148 -148
  25. package/docs/source-runtime-refactor-map.md +83 -83
  26. package/docs/usage.md +6 -0
  27. package/index.ts +6 -6
  28. package/package.json +3 -3
  29. package/schema.json +2 -2
  30. package/src/agents/agent-serializer.ts +34 -34
  31. package/src/config/config.ts +8 -4
  32. package/src/extension/cross-extension-rpc.ts +82 -82
  33. package/src/extension/import-index.ts +18 -2
  34. package/src/extension/register.ts +11 -1
  35. package/src/extension/registration/compaction-guard.ts +125 -125
  36. package/src/extension/registration/subagent-helpers.ts +30 -6
  37. package/src/extension/registration/subagent-tools.ts +8 -3
  38. package/src/extension/result-watcher.ts +98 -98
  39. package/src/extension/run-import.ts +12 -2
  40. package/src/extension/run-index.ts +12 -2
  41. package/src/extension/run-maintenance.ts +24 -24
  42. package/src/extension/team-tool/api.ts +54 -14
  43. package/src/extension/team-tool/cancel.ts +31 -31
  44. package/src/extension/team-tool/doctor.ts +179 -179
  45. package/src/extension/team-tool/inspect.ts +41 -41
  46. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  47. package/src/extension/team-tool/plan.ts +19 -19
  48. package/src/extension/team-tool/status.ts +73 -73
  49. package/src/observability/correlation.ts +35 -35
  50. package/src/observability/event-to-metric.ts +54 -54
  51. package/src/observability/exporters/adapter.ts +24 -24
  52. package/src/observability/exporters/otlp-exporter.ts +65 -65
  53. package/src/observability/exporters/prometheus-exporter.ts +47 -47
  54. package/src/observability/metric-registry.ts +72 -72
  55. package/src/observability/metric-retention.ts +46 -46
  56. package/src/observability/metric-sink.ts +51 -51
  57. package/src/observability/metrics-primitives.ts +166 -166
  58. package/src/prompt/prompt-runtime.ts +68 -68
  59. package/src/runtime/agent-control.ts +64 -64
  60. package/src/runtime/agent-memory.ts +72 -72
  61. package/src/runtime/agent-observability.ts +114 -113
  62. package/src/runtime/async-marker.ts +26 -26
  63. package/src/runtime/background-runner.ts +53 -53
  64. package/src/runtime/crash-recovery.ts +56 -56
  65. package/src/runtime/crew-agent-records.ts +54 -9
  66. package/src/runtime/crew-agent-runtime.ts +58 -58
  67. package/src/runtime/deadletter.ts +36 -36
  68. package/src/runtime/direct-run.ts +35 -35
  69. package/src/runtime/foreground-control.ts +82 -82
  70. package/src/runtime/green-contract.ts +46 -46
  71. package/src/runtime/group-join.ts +88 -88
  72. package/src/runtime/heartbeat-gradient.ts +28 -28
  73. package/src/runtime/heartbeat-watcher.ts +80 -80
  74. package/src/runtime/live-agent-control.ts +87 -78
  75. package/src/runtime/live-agent-manager.ts +85 -85
  76. package/src/runtime/live-control-realtime.ts +36 -36
  77. package/src/runtime/live-session-runtime.ts +299 -299
  78. package/src/runtime/manifest-cache.ts +248 -212
  79. package/src/runtime/model-fallback.ts +261 -261
  80. package/src/runtime/parallel-research.ts +44 -44
  81. package/src/runtime/parallel-utils.ts +99 -99
  82. package/src/runtime/pi-json-output.ts +111 -111
  83. package/src/runtime/policy-engine.ts +78 -78
  84. package/src/runtime/post-exit-stdio-guard.ts +86 -86
  85. package/src/runtime/process-status.ts +56 -56
  86. package/src/runtime/progress-event-coalescer.ts +43 -43
  87. package/src/runtime/recovery-recipes.ts +74 -74
  88. package/src/runtime/retry-executor.ts +59 -59
  89. package/src/runtime/role-permission.ts +39 -39
  90. package/src/runtime/session-usage.ts +79 -79
  91. package/src/runtime/sidechain-output.ts +28 -28
  92. package/src/runtime/subagent-manager.ts +80 -12
  93. package/src/runtime/task-display.ts +38 -38
  94. package/src/runtime/task-output-context.ts +127 -106
  95. package/src/runtime/task-runner/live-executor.ts +98 -98
  96. package/src/runtime/task-runner/progress.ts +111 -111
  97. package/src/runtime/task-runner/result-utils.ts +14 -14
  98. package/src/runtime/task-runner/state-helpers.ts +22 -22
  99. package/src/runtime/team-runner.ts +1 -1
  100. package/src/runtime/worker-heartbeat.ts +21 -21
  101. package/src/runtime/worker-startup.ts +57 -57
  102. package/src/schema/config-schema.ts +21 -21
  103. package/src/schema/team-tool-schema.ts +100 -100
  104. package/src/state/artifact-store.ts +122 -108
  105. package/src/state/contracts.ts +105 -105
  106. package/src/state/jsonl-writer.ts +77 -77
  107. package/src/state/mailbox.ts +67 -22
  108. package/src/state/state-store.ts +36 -5
  109. package/src/state/task-claims.ts +42 -42
  110. package/src/state/usage.ts +29 -29
  111. package/src/subagents/async-entry.ts +1 -1
  112. package/src/subagents/index.ts +3 -3
  113. package/src/subagents/live/control.ts +1 -1
  114. package/src/subagents/live/manager.ts +1 -1
  115. package/src/subagents/live/realtime.ts +1 -1
  116. package/src/subagents/live/session-runtime.ts +1 -1
  117. package/src/subagents/manager.ts +1 -1
  118. package/src/subagents/spawn.ts +1 -1
  119. package/src/teams/discover-teams.ts +27 -5
  120. package/src/teams/team-serializer.ts +38 -36
  121. package/src/types/diff.d.ts +18 -18
  122. package/src/ui/crew-footer.ts +101 -101
  123. package/src/ui/crew-select-list.ts +111 -111
  124. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  125. package/src/ui/dynamic-border.ts +25 -25
  126. package/src/ui/layout-primitives.ts +106 -106
  127. package/src/ui/loaders.ts +158 -158
  128. package/src/ui/mascot.ts +441 -441
  129. package/src/ui/render-diff.ts +119 -119
  130. package/src/ui/run-dashboard.ts +5 -2
  131. package/src/ui/run-snapshot-cache.ts +19 -8
  132. package/src/ui/spinner.ts +17 -17
  133. package/src/ui/status-colors.ts +54 -54
  134. package/src/ui/syntax-highlight.ts +116 -116
  135. package/src/ui/transcript-viewer.ts +15 -1
  136. package/src/utils/completion-dedupe.ts +63 -63
  137. package/src/utils/file-coalescer.ts +84 -84
  138. package/src/utils/frontmatter.ts +36 -36
  139. package/src/utils/fs-watch.ts +31 -31
  140. package/src/utils/git.ts +262 -262
  141. package/src/utils/ids.ts +12 -12
  142. package/src/utils/names.ts +26 -26
  143. package/src/utils/paths.ts +3 -2
  144. package/src/utils/safe-paths.ts +34 -0
  145. package/src/utils/sleep.ts +32 -32
  146. package/src/utils/timings.ts +31 -31
  147. package/src/utils/visual.ts +159 -159
  148. package/src/workflows/discover-workflows.ts +30 -3
  149. package/src/workflows/validate-workflow.ts +40 -40
  150. package/src/worktree/branch-freshness.ts +45 -45
  151. package/teams/default.team.md +12 -12
  152. package/teams/fast-fix.team.md +11 -11
  153. package/teams/implementation.team.md +18 -18
  154. package/teams/parallel-research.team.md +14 -14
  155. package/teams/research.team.md +11 -11
  156. package/teams/review.team.md +12 -12
  157. package/workflows/default.workflow.md +29 -29
  158. package/workflows/fast-fix.workflow.md +22 -22
  159. package/workflows/implementation.workflow.md +38 -38
  160. package/workflows/parallel-research.workflow.md +46 -46
  161. package/workflows/research.workflow.md +22 -22
  162. package/workflows/review.workflow.md +30 -30
@@ -29,14 +29,15 @@ export function findRepoRoot(cwd: string): string | undefined {
29
29
  let current = path.resolve(cwd);
30
30
  const root = path.parse(current).root;
31
31
  const home = path.resolve(os.homedir());
32
+ const tempRoot = path.resolve(os.tmpdir());
32
33
  while (current !== root) {
33
- if (current === home) return undefined;
34
+ if (current === home || current === tempRoot) return undefined;
34
35
  if (hasProjectMarker(current)) return current;
35
36
  const parent = path.dirname(current);
36
37
  if (parent === current) break;
37
38
  current = parent;
38
39
  }
39
- if (current === home) return undefined;
40
+ if (current === home || current === tempRoot) return undefined;
40
41
  if (hasProjectMarker(root)) return root;
41
42
  return undefined;
42
43
  }
@@ -0,0 +1,34 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+
4
+ export function isSafePathId(value: string): boolean {
5
+ return /^[A-Za-z0-9_-]+$/.test(value);
6
+ }
7
+
8
+ export function assertSafePathId(kind: string, value: string): string {
9
+ if (!isSafePathId(value)) throw new Error(`Invalid ${kind}: ${value}`);
10
+ return value;
11
+ }
12
+
13
+ export function resolveContainedPath(baseDir: string, targetPath: string): string {
14
+ const base = path.resolve(baseDir);
15
+ const resolved = path.isAbsolute(targetPath) ? path.resolve(targetPath) : path.resolve(base, targetPath);
16
+ const relative = path.relative(base, resolved);
17
+ if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`Path is outside ${baseDir}: ${targetPath}`);
18
+ return resolved;
19
+ }
20
+
21
+ export function resolveRealContainedPath(baseDir: string, targetPath: string): string {
22
+ const resolved = resolveContainedPath(baseDir, targetPath);
23
+ const realBase = fs.realpathSync.native(baseDir);
24
+ const realTarget = fs.realpathSync.native(resolved);
25
+ const relative = path.relative(realBase, realTarget);
26
+ if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`Path is outside ${baseDir}: ${targetPath}`);
27
+ return realTarget;
28
+ }
29
+
30
+ export function resolveContainedRelativePath(baseDir: string, relativePath: string, kind = "path"): string {
31
+ const normalized = relativePath.replaceAll("\\", "/").replace(/^\.\/+/, "");
32
+ if (!normalized || normalized.split("/").some((segment) => segment === "..") || path.isAbsolute(normalized)) throw new Error(`Invalid ${kind}: ${relativePath}`);
33
+ return resolveContainedPath(baseDir, path.resolve(baseDir, normalized));
34
+ }
@@ -1,32 +1,32 @@
1
- /**
2
- * Sleep helper that respects abort signal.
3
- */
4
- export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
5
- return new Promise((resolve, reject) => {
6
- if (signal?.aborted) {
7
- reject(new Error("Aborted"));
8
- return;
9
- }
10
-
11
- let settled = false;
12
- const cleanup = (): void => {
13
- if (signal) signal.removeEventListener("abort", onAbort);
14
- };
15
- const timeout = setTimeout(() => {
16
- if (settled) return;
17
- settled = true;
18
- cleanup();
19
- resolve();
20
- }, ms);
21
-
22
- const onAbort = (): void => {
23
- if (settled) return;
24
- settled = true;
25
- clearTimeout(timeout);
26
- cleanup();
27
- reject(new Error("Aborted"));
28
- };
29
-
30
- signal?.addEventListener("abort", onAbort);
31
- });
32
- }
1
+ /**
2
+ * Sleep helper that respects abort signal.
3
+ */
4
+ export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
5
+ return new Promise((resolve, reject) => {
6
+ if (signal?.aborted) {
7
+ reject(new Error("Aborted"));
8
+ return;
9
+ }
10
+
11
+ let settled = false;
12
+ const cleanup = (): void => {
13
+ if (signal) signal.removeEventListener("abort", onAbort);
14
+ };
15
+ const timeout = setTimeout(() => {
16
+ if (settled) return;
17
+ settled = true;
18
+ cleanup();
19
+ resolve();
20
+ }, ms);
21
+
22
+ const onAbort = (): void => {
23
+ if (settled) return;
24
+ settled = true;
25
+ clearTimeout(timeout);
26
+ cleanup();
27
+ reject(new Error("Aborted"));
28
+ };
29
+
30
+ signal?.addEventListener("abort", onAbort);
31
+ });
32
+ }
@@ -1,31 +1,31 @@
1
- /**
2
- * Central timing instrumentation for startup profiling.
3
- * Enable with PI_TIMING=1 environment variable.
4
- */
5
-
6
- const ENABLED = process.env.PI_TIMING === "1";
7
- const timings: Array<{ label: string; ms: number }> = [];
8
- let lastTime = Date.now();
9
-
10
- export function resetTimings(): void {
11
- if (!ENABLED) return;
12
- timings.length = 0;
13
- lastTime = Date.now();
14
- }
15
-
16
- export function time(label: string): void {
17
- if (!ENABLED) return;
18
- const now = Date.now();
19
- timings.push({ label, ms: now - lastTime });
20
- lastTime = now;
21
- }
22
-
23
- export function printTimings(): void {
24
- if (!ENABLED || timings.length === 0) return;
25
- console.error("\n--- Startup Timings ---");
26
- for (const t of timings) {
27
- console.error(` ${t.label}: ${t.ms}ms`);
28
- }
29
- console.error(` TOTAL: ${timings.reduce((a, b) => a + b.ms, 0)}ms`);
30
- console.error("------------------------\n");
31
- }
1
+ /**
2
+ * Central timing instrumentation for startup profiling.
3
+ * Enable with PI_TIMING=1 environment variable.
4
+ */
5
+
6
+ const ENABLED = process.env.PI_TIMING === "1";
7
+ const timings: Array<{ label: string; ms: number }> = [];
8
+ let lastTime = Date.now();
9
+
10
+ export function resetTimings(): void {
11
+ if (!ENABLED) return;
12
+ timings.length = 0;
13
+ lastTime = Date.now();
14
+ }
15
+
16
+ export function time(label: string): void {
17
+ if (!ENABLED) return;
18
+ const now = Date.now();
19
+ timings.push({ label, ms: now - lastTime });
20
+ lastTime = now;
21
+ }
22
+
23
+ export function printTimings(): void {
24
+ if (!ENABLED || timings.length === 0) return;
25
+ console.error("\n--- Startup Timings ---");
26
+ for (const t of timings) {
27
+ console.error(` ${t.label}: ${t.ms}ms`);
28
+ }
29
+ console.error(` TOTAL: ${timings.reduce((a, b) => a + b.ms, 0)}ms`);
30
+ console.error("------------------------\n");
31
+ }
@@ -1,159 +1,159 @@
1
- export const ANSI_PATTERN = /\u001b\[[0-?]*[ -/]*[@-~]/g;
2
-
3
- const WIDTH_CACHE_LIMIT = 256;
4
- const widthCache = new Map<string, number>();
5
-
6
- export function visibleWidth(value: string): number {
7
- const cached = widthCache.get(value);
8
- if (cached !== undefined) return cached;
9
- let length = 0;
10
- for (const char of value.replace(ANSI_PATTERN, "")) {
11
- if (char !== "\n") length += 1;
12
- }
13
- if (widthCache.size >= WIDTH_CACHE_LIMIT) {
14
- const firstKey = widthCache.keys().next().value;
15
- if (firstKey !== undefined) widthCache.delete(firstKey);
16
- }
17
- widthCache.set(value, length);
18
- return length;
19
- }
20
-
21
- export function __test__clearVisibleWidthCache(): void {
22
- widthCache.clear();
23
- }
24
-
25
- export function __test__visibleWidthCacheSize(): number {
26
- return widthCache.size;
27
- }
28
-
29
- function consumeAnsi(input: string, index: number): number {
30
- const char = input[index];
31
- if (!char || char !== "\u001b") return 0;
32
- if (input[index + 1] !== "[") return 0;
33
- let i = index + 2;
34
- while (i < input.length) {
35
- const code = input.charCodeAt(i);
36
- if (code >= 0x40 && code <= 0x7e) return i - index + 1;
37
- i++;
38
- }
39
- return 0;
40
- }
41
-
42
- function splitGraphemes(value: string): string[] {
43
- return Array.from(value.replace(ANSI_PATTERN, ""));
44
- }
45
-
46
- export function truncateToWidth(value: string, width: number, ellipsis = "…"): string {
47
- if (width <= 0) return "";
48
- if (visibleWidth(value) <= width) return value;
49
- if (width <= ellipsis.length) return ellipsis.slice(0, width);
50
- let output = "";
51
- let renderedWidth = 0;
52
- for (let i = 0; i < value.length; i++) {
53
- const ansiLen = consumeAnsi(value, i);
54
- if (ansiLen) {
55
- output += value.slice(i, i + ansiLen);
56
- i += ansiLen - 1;
57
- continue;
58
- }
59
- const char = value[i] as string;
60
- const nextIndex = i + (char.codePointAt(0) ?? 0) > 0xFFFF ? i + 2 : i + 1;
61
- const segment = value.slice(i, nextIndex);
62
- const charWidth = visibleWidth(segment);
63
- if (renderedWidth + charWidth > width - ellipsis.length) {
64
- return `${output}${ellipsis}`;
65
- }
66
- output += segment;
67
- renderedWidth += charWidth;
68
- i = nextIndex - 1;
69
- }
70
- return output;
71
- }
72
-
73
- export const truncate = truncateToWidth;
74
-
75
- export function pad(value: string, width: number): string {
76
- const current = visibleWidth(value);
77
- if (current >= width) return value;
78
- return `${value}${" ".repeat(width - current)}`;
79
- }
80
-
81
- export function boxLine(text: string, innerWidth: number): string {
82
- return `│ ${truncate(text, innerWidth - 4)} │`;
83
- }
84
-
85
- function readAnsiCode(input: string, index: number): string | undefined {
86
- const ansiLength = consumeAnsi(input, index);
87
- if (ansiLength > 0) return input.slice(index, index + ansiLength);
88
- return undefined;
89
- }
90
-
91
- function takeCodePoint(input: string, index: number): { chunk: string; nextIndex: number } {
92
- const code = input.codePointAt(index);
93
- if (code === undefined) return { chunk: "", nextIndex: index + 1 };
94
- if (code >= 0xD800 && code <= 0xDBFF && index + 1 < input.length) {
95
- return { chunk: input.slice(index, index + 2), nextIndex: index + 2 };
96
- }
97
- return { chunk: input[index] ?? "", nextIndex: index + 1 };
98
- }
99
-
100
- export function wrapHard(value: string, width: number): string[] {
101
- if (width <= 0 || !value) return [];
102
- const lines: string[] = [];
103
- let current = "";
104
- let currentWidth = 0;
105
- let i = 0;
106
- while (i < value.length) {
107
- const ansi = readAnsiCode(value, i);
108
- if (ansi) {
109
- current += ansi;
110
- i += ansi.length;
111
- continue;
112
- }
113
- const { chunk, nextIndex } = takeCodePoint(value, i);
114
- const chunkWidth = visibleWidth(chunk);
115
- if (chunkWidth > width) {
116
- lines.push(current ? current + chunk : chunk);
117
- current = "";
118
- currentWidth = 0;
119
- i = nextIndex;
120
- continue;
121
- }
122
- if (currentWidth + chunkWidth > width) {
123
- if (current) lines.push(current);
124
- current = chunk;
125
- currentWidth = chunkWidth;
126
- i = nextIndex;
127
- continue;
128
- }
129
- current += chunk;
130
- currentWidth += chunkWidth;
131
- i = nextIndex;
132
- }
133
- if (current) lines.push(current);
134
- return lines.length > 0 ? lines : [""];
135
- }
136
-
137
- export interface VisualTruncateResult {
138
- visualLines: string[];
139
- skippedCount: number;
140
- }
141
-
142
- export function truncateToVisualLines(
143
- text: string,
144
- maxVisualLines: number,
145
- width: number,
146
- paddingX = 0,
147
- ): VisualTruncateResult {
148
- if (!text) {
149
- return { visualLines: [], skippedCount: 0 };
150
- }
151
- const effectiveWidth = Math.max(1, width - paddingX * 2);
152
- const limit = Math.max(1, maxVisualLines);
153
- const visualLines = text
154
- .split("\n")
155
- .flatMap((line) => wrapHard(pad(line, Math.max(0, effectiveWidth)).trimEnd(), effectiveWidth));
156
- if (visualLines.length <= limit) return { visualLines, skippedCount: 0 };
157
- const truncated = visualLines.slice(-limit);
158
- return { visualLines: truncated, skippedCount: visualLines.length - limit };
159
- }
1
+ export const ANSI_PATTERN = /\u001b\[[0-?]*[ -/]*[@-~]/g;
2
+
3
+ const WIDTH_CACHE_LIMIT = 256;
4
+ const widthCache = new Map<string, number>();
5
+
6
+ export function visibleWidth(value: string): number {
7
+ const cached = widthCache.get(value);
8
+ if (cached !== undefined) return cached;
9
+ let length = 0;
10
+ for (const char of value.replace(ANSI_PATTERN, "")) {
11
+ if (char !== "\n") length += 1;
12
+ }
13
+ if (widthCache.size >= WIDTH_CACHE_LIMIT) {
14
+ const firstKey = widthCache.keys().next().value;
15
+ if (firstKey !== undefined) widthCache.delete(firstKey);
16
+ }
17
+ widthCache.set(value, length);
18
+ return length;
19
+ }
20
+
21
+ export function __test__clearVisibleWidthCache(): void {
22
+ widthCache.clear();
23
+ }
24
+
25
+ export function __test__visibleWidthCacheSize(): number {
26
+ return widthCache.size;
27
+ }
28
+
29
+ function consumeAnsi(input: string, index: number): number {
30
+ const char = input[index];
31
+ if (!char || char !== "\u001b") return 0;
32
+ if (input[index + 1] !== "[") return 0;
33
+ let i = index + 2;
34
+ while (i < input.length) {
35
+ const code = input.charCodeAt(i);
36
+ if (code >= 0x40 && code <= 0x7e) return i - index + 1;
37
+ i++;
38
+ }
39
+ return 0;
40
+ }
41
+
42
+ function splitGraphemes(value: string): string[] {
43
+ return Array.from(value.replace(ANSI_PATTERN, ""));
44
+ }
45
+
46
+ export function truncateToWidth(value: string, width: number, ellipsis = "…"): string {
47
+ if (width <= 0) return "";
48
+ if (visibleWidth(value) <= width) return value;
49
+ if (width <= ellipsis.length) return ellipsis.slice(0, width);
50
+ let output = "";
51
+ let renderedWidth = 0;
52
+ for (let i = 0; i < value.length; i++) {
53
+ const ansiLen = consumeAnsi(value, i);
54
+ if (ansiLen) {
55
+ output += value.slice(i, i + ansiLen);
56
+ i += ansiLen - 1;
57
+ continue;
58
+ }
59
+ const char = value[i] as string;
60
+ const nextIndex = i + (char.codePointAt(0) ?? 0) > 0xFFFF ? i + 2 : i + 1;
61
+ const segment = value.slice(i, nextIndex);
62
+ const charWidth = visibleWidth(segment);
63
+ if (renderedWidth + charWidth > width - ellipsis.length) {
64
+ return `${output}${ellipsis}`;
65
+ }
66
+ output += segment;
67
+ renderedWidth += charWidth;
68
+ i = nextIndex - 1;
69
+ }
70
+ return output;
71
+ }
72
+
73
+ export const truncate = truncateToWidth;
74
+
75
+ export function pad(value: string, width: number): string {
76
+ const current = visibleWidth(value);
77
+ if (current >= width) return value;
78
+ return `${value}${" ".repeat(width - current)}`;
79
+ }
80
+
81
+ export function boxLine(text: string, innerWidth: number): string {
82
+ return `│ ${truncate(text, innerWidth - 4)} │`;
83
+ }
84
+
85
+ function readAnsiCode(input: string, index: number): string | undefined {
86
+ const ansiLength = consumeAnsi(input, index);
87
+ if (ansiLength > 0) return input.slice(index, index + ansiLength);
88
+ return undefined;
89
+ }
90
+
91
+ function takeCodePoint(input: string, index: number): { chunk: string; nextIndex: number } {
92
+ const code = input.codePointAt(index);
93
+ if (code === undefined) return { chunk: "", nextIndex: index + 1 };
94
+ if (code >= 0xD800 && code <= 0xDBFF && index + 1 < input.length) {
95
+ return { chunk: input.slice(index, index + 2), nextIndex: index + 2 };
96
+ }
97
+ return { chunk: input[index] ?? "", nextIndex: index + 1 };
98
+ }
99
+
100
+ export function wrapHard(value: string, width: number): string[] {
101
+ if (width <= 0 || !value) return [];
102
+ const lines: string[] = [];
103
+ let current = "";
104
+ let currentWidth = 0;
105
+ let i = 0;
106
+ while (i < value.length) {
107
+ const ansi = readAnsiCode(value, i);
108
+ if (ansi) {
109
+ current += ansi;
110
+ i += ansi.length;
111
+ continue;
112
+ }
113
+ const { chunk, nextIndex } = takeCodePoint(value, i);
114
+ const chunkWidth = visibleWidth(chunk);
115
+ if (chunkWidth > width) {
116
+ lines.push(current ? current + chunk : chunk);
117
+ current = "";
118
+ currentWidth = 0;
119
+ i = nextIndex;
120
+ continue;
121
+ }
122
+ if (currentWidth + chunkWidth > width) {
123
+ if (current) lines.push(current);
124
+ current = chunk;
125
+ currentWidth = chunkWidth;
126
+ i = nextIndex;
127
+ continue;
128
+ }
129
+ current += chunk;
130
+ currentWidth += chunkWidth;
131
+ i = nextIndex;
132
+ }
133
+ if (current) lines.push(current);
134
+ return lines.length > 0 ? lines : [""];
135
+ }
136
+
137
+ export interface VisualTruncateResult {
138
+ visualLines: string[];
139
+ skippedCount: number;
140
+ }
141
+
142
+ export function truncateToVisualLines(
143
+ text: string,
144
+ maxVisualLines: number,
145
+ width: number,
146
+ paddingX = 0,
147
+ ): VisualTruncateResult {
148
+ if (!text) {
149
+ return { visualLines: [], skippedCount: 0 };
150
+ }
151
+ const effectiveWidth = Math.max(1, width - paddingX * 2);
152
+ const limit = Math.max(1, maxVisualLines);
153
+ const visualLines = text
154
+ .split("\n")
155
+ .flatMap((line) => wrapHard(pad(line, Math.max(0, effectiveWidth)).trimEnd(), effectiveWidth));
156
+ if (visualLines.length <= limit) return { visualLines, skippedCount: 0 };
157
+ const truncated = visualLines.slice(-limit);
158
+ return { visualLines: truncated, skippedCount: visualLines.length - limit };
159
+ }
@@ -11,20 +11,25 @@ export interface WorkflowDiscoveryResult {
11
11
  project: WorkflowConfig[];
12
12
  }
13
13
 
14
+ const STEP_CONFIG_KEYS = new Set(["role", "dependsOn", "parallelGroup", "output", "reads", "model", "skills", "progress", "worktree", "verify", "task"]);
15
+
14
16
  function parseStepSection(id: string, body: string): WorkflowStep | undefined {
15
17
  const lines = body.trim().split("\n");
16
18
  const config: Record<string, string> = {};
17
19
  const taskLines: string[] = [];
18
20
  let inTask = false;
21
+ let sawConfig = false;
19
22
  for (const line of lines) {
20
23
  if (!inTask) {
21
24
  if (line.trim() === "") {
25
+ if (!sawConfig) continue;
22
26
  inTask = true;
23
27
  continue;
24
28
  }
25
29
  const match = line.match(/^([\w-]+):\s*(.*)$/);
26
30
  if (match) {
27
31
  config[match[1]!.trim()] = match[2]!.trim();
32
+ sawConfig = true;
28
33
  continue;
29
34
  }
30
35
  inTask = true;
@@ -55,18 +60,40 @@ const parseOptionalInteger = (value: string | undefined): number | undefined =>
55
60
  return Math.trunc(parsed);
56
61
  };
57
62
 
63
+ function hasSectionBoundary(body: string, match: RegExpMatchArray): boolean {
64
+ const index = match.index ?? 0;
65
+ return index === 0 || body.slice(0, index).trim() === "" || body.slice(Math.max(0, index - 2), index) === "\n\n";
66
+ }
67
+
68
+ function isStepHeading(body: string, match: RegExpMatchArray): boolean {
69
+ const sectionStart = match.index! + match[0].length + (body[match.index! + match[0].length] === "\n" ? 1 : 0);
70
+ const nextHeading = body.slice(sectionStart).search(/^##\s+.+[^\S\n]*$/m);
71
+ const section = body.slice(sectionStart, nextHeading >= 0 ? sectionStart + nextHeading : body.length);
72
+ for (const line of section.split("\n")) {
73
+ const trimmed = line.trim();
74
+ if (!trimmed) continue;
75
+ const config = trimmed.match(/^([\w-]+):\s*(.*)$/);
76
+ if (config && STEP_CONFIG_KEYS.has(config[1]!)) return true;
77
+ return false;
78
+ }
79
+ return false;
80
+ }
81
+
58
82
  function parseWorkflowFile(filePath: string, source: ResourceSource): WorkflowConfig | undefined {
59
83
  try {
60
84
  const content = fs.readFileSync(filePath, "utf-8");
61
85
  const { frontmatter, body } = parseFrontmatter(content);
62
86
  const name = frontmatter.name?.trim() || path.basename(filePath, ".workflow.md");
63
87
  const matches = [...body.matchAll(/^##\s+(.+)[^\S\n]*$/gm)];
88
+ const explicitStepIndexes = new Set(matches.map((match, index) => isStepHeading(body, match) ? index : undefined).filter((index): index is number => index !== undefined));
89
+ const effectiveMatches = matches.filter((match, index) => explicitStepIndexes.has(index) || (hasSectionBoundary(body, match) && /^[a-z][a-z0-9-]*$/.test(match[1]?.trim() ?? "")));
90
+ const parseMatches = explicitStepIndexes.size ? effectiveMatches : matches;
64
91
  const steps: WorkflowStep[] = [];
65
- for (let i = 0; i < matches.length; i++) {
66
- const match = matches[i]!;
92
+ for (let i = 0; i < parseMatches.length; i++) {
93
+ const match = parseMatches[i]!;
67
94
  const id = match[1]!.trim();
68
95
  const sectionStart = match.index! + match[0].length + (body[match.index! + match[0].length] === "\n" ? 1 : 0);
69
- const sectionEnd = i + 1 < matches.length ? matches[i + 1]!.index! : body.length;
96
+ const sectionEnd = i + 1 < parseMatches.length ? parseMatches[i + 1]!.index! : body.length;
70
97
  const step = parseStepSection(id, body.slice(sectionStart, sectionEnd));
71
98
  if (step) steps.push(step);
72
99
  }
@@ -1,40 +1,40 @@
1
- import type { TeamConfig } from "../teams/team-config.ts";
2
- import type { WorkflowConfig } from "./workflow-config.ts";
3
-
4
- export function validateWorkflowForTeam(workflow: WorkflowConfig, team: TeamConfig): string[] {
5
- const errors: string[] = [];
6
- const roles = new Set(team.roles.map((role) => role.name));
7
- const stepIds = new Set<string>();
8
-
9
- for (const step of workflow.steps) {
10
- if (stepIds.has(step.id)) errors.push(`Duplicate workflow step id '${step.id}'.`);
11
- stepIds.add(step.id);
12
- if (!roles.has(step.role)) errors.push(`Step '${step.id}' references unknown team role '${step.role}'.`);
13
- }
14
-
15
- for (const step of workflow.steps) {
16
- for (const dep of step.dependsOn ?? []) {
17
- if (!stepIds.has(dep)) errors.push(`Step '${step.id}' depends on unknown step '${dep}'.`);
18
- }
19
- }
20
-
21
- const visiting = new Set<string>();
22
- const visited = new Set<string>();
23
- const byId = new Map(workflow.steps.map((step) => [step.id, step]));
24
-
25
- function visit(id: string, trail: string[]): void {
26
- if (visited.has(id)) return;
27
- if (visiting.has(id)) {
28
- errors.push(`Workflow dependency cycle detected: ${[...trail, id].join(" -> ")}.`);
29
- return;
30
- }
31
- visiting.add(id);
32
- const step = byId.get(id);
33
- for (const dep of step?.dependsOn ?? []) visit(dep, [...trail, id]);
34
- visiting.delete(id);
35
- visited.add(id);
36
- }
37
-
38
- for (const step of workflow.steps) visit(step.id, []);
39
- return [...new Set(errors)];
40
- }
1
+ import type { TeamConfig } from "../teams/team-config.ts";
2
+ import type { WorkflowConfig } from "./workflow-config.ts";
3
+
4
+ export function validateWorkflowForTeam(workflow: WorkflowConfig, team: TeamConfig): string[] {
5
+ const errors: string[] = [];
6
+ const roles = new Set(team.roles.map((role) => role.name));
7
+ const stepIds = new Set<string>();
8
+
9
+ for (const step of workflow.steps) {
10
+ if (stepIds.has(step.id)) errors.push(`Duplicate workflow step id '${step.id}'.`);
11
+ stepIds.add(step.id);
12
+ if (!roles.has(step.role)) errors.push(`Step '${step.id}' references unknown team role '${step.role}'.`);
13
+ }
14
+
15
+ for (const step of workflow.steps) {
16
+ for (const dep of step.dependsOn ?? []) {
17
+ if (!stepIds.has(dep)) errors.push(`Step '${step.id}' depends on unknown step '${dep}'.`);
18
+ }
19
+ }
20
+
21
+ const visiting = new Set<string>();
22
+ const visited = new Set<string>();
23
+ const byId = new Map(workflow.steps.map((step) => [step.id, step]));
24
+
25
+ function visit(id: string, trail: string[]): void {
26
+ if (visited.has(id)) return;
27
+ if (visiting.has(id)) {
28
+ errors.push(`Workflow dependency cycle detected: ${[...trail, id].join(" -> ")}.`);
29
+ return;
30
+ }
31
+ visiting.add(id);
32
+ const step = byId.get(id);
33
+ for (const dep of step?.dependsOn ?? []) visit(dep, [...trail, id]);
34
+ visiting.delete(id);
35
+ visited.add(id);
36
+ }
37
+
38
+ for (const step of workflow.steps) visit(step.id, []);
39
+ return [...new Set(errors)];
40
+ }