///|
let max_openspec_files : Int32 = 256
///|
let max_openspec_depth : Int32 = 6
///|
/// Built-in canonical intent adapter for OpenSpec workspaces (`openspec/`).
pub struct OpenSpecIntentAdapter {}
///|
/// Constructs an `OpenSpecIntentAdapter`.
pub fn OpenSpecIntentAdapter::OpenSpecIntentAdapter() -> OpenSpecIntentAdapter {
OpenSpecIntentAdapter::{ }
}
///|
/// Returns the default registered intent adapters (`OpenSpecIntentAdapter`).
pub fn default_intent_adapters() -> Array[&@intent.IntentAdapter] {
[OpenSpecIntentAdapter() as &@intent.IntentAdapter]
}
///|
fn sanitize_title_text(raw : String, fallback : String) -> @intent.IntentTitle {
let buf = StringBuilder()
let mut count = 0
for c in raw.trim() {
let code = c.to_int()
if code >= 0x20 && code != 0x7f && count < 180 {
buf.write_char(c)
count += 1
}
}
let candidate = buf.to_string().trim().to_owned()
let chosen = if candidate.is_empty() { fallback } else { candidate }
@intent.IntentTitle(chosen) catch {
_ =>
@intent.IntentTitle(fallback) catch {
_ =>
@intent.IntentTitle("Untitled") catch {
_ => abort("Untitled is a valid IntentTitle")
}
}
}
}
///|
fn humanize_slug(slug : String) -> String {
let parts : Array[String] = []
for seg in slug.split("-") {
let word = seg.to_owned()
if !word.is_empty() {
let buf = StringBuilder()
let mut first = true
for c in word {
if first && c is ('a'..<='z') {
buf.write_char((c.to_int() - 32).unsafe_to_char())
} else {
buf.write_char(c)
}
first = false
}
parts.push(buf.to_string())
}
}
if parts.is_empty() {
slug
} else {
parts.join(" ")
}
}
///|
fn split_markdown_lines(content : String) -> Array[String] {
let out : Array[String] = []
for raw in content.split("\n") {
let line = raw.to_owned()
if line.has_suffix("\r") {
out.push(line[0:line.length() - 1].to_owned())
} else {
out.push(line)
}
}
out
}
///|
fn strip_known_title_prefix(title : String) -> String {
let prefixes : ReadOnlyArray[String] = [
"Change Proposal: ", "Proposal: ", "Design: ", "Tasks: ",
]
for prefix in prefixes {
if title.strip_prefix(prefix) is Some(rest) {
let trimmed = rest.trim().to_owned()
if !trimmed.is_empty() {
return trimmed
}
}
}
title
}
///|
fn extract_heading_title(
lines : Array[String],
fallback : String,
) -> @intent.IntentTitle {
for line in lines {
let trimmed = line.trim().to_owned()
if trimmed.strip_prefix("# ") is Some(rest) {
let cleaned = strip_known_title_prefix(rest.trim().to_owned())
return sanitize_title_text(cleaned, fallback)
}
}
sanitize_title_text(fallback, "Untitled")
}
///|
fn extract_summary(lines : Array[String]) -> String {
let buf = StringBuilder()
let mut in_code = false
let mut collecting = false
for line in lines {
let trimmed = line.trim().to_owned()
if trimmed.has_prefix("```") {
in_code = !in_code
if collecting {
break
}
continue
}
if in_code {
continue
}
if trimmed.is_empty() {
if collecting {
break
}
continue
}
if trimmed.has_prefix("#") ||
trimmed.has_prefix("- ") ||
trimmed.has_prefix("* ") ||
trimmed.has_prefix(">") ||
trimmed.has_prefix("|") {
if collecting {
break
}
continue
}
if collecting {
buf.write_char(' ')
}
buf.write_string(trimmed)
collecting = true
if buf.to_string().length() >= 220 {
break
}
}
let text = buf.to_string()
truncate_chars(text, 240)
}
///|
fn strip_scenario_marker(line : String, keyword : String) -> String? {
let trimmed = line.trim().to_owned()
let body = if trimmed.strip_prefix("- ") is Some(r) {
r.trim().to_owned()
} else if trimmed.strip_prefix("* ") is Some(r) {
r.trim().to_owned()
} else {
return None
}
let bold = "**\{keyword}**"
if body.strip_prefix(bold) is Some(r) {
return Some(r.trim().to_owned())
}
let plain = "\{keyword} "
if body.strip_prefix(plain) is Some(r) {
return Some(r.trim().to_owned())
}
None
}
///|
fn extract_requirements(
lines : Array[String],
) -> Array[@intent.RequirementDelta] {
let out : Array[@intent.RequirementDelta] = []
let mut current_kind : @intent.RequirementDeltaKind? = None
let mut req_title : @intent.IntentTitle? = None
let mut req_body : Array[String] = []
let mut req_scenarios : Array[@intent.ScenarioEntry] = []
let mut scen_title : @intent.IntentTitle? = None
let mut scen_when : Array[String] = []
let mut scen_then : Array[String] = []
let mut scen_phase = 0 // 0=none, 1=when, 2=then
fn flush_scenario() {
match scen_title {
Some(title) => {
req_scenarios.push(
@intent.ScenarioEntry(
title~,
when_text=scen_when.join(" "),
then_text=scen_then.join(" "),
),
)
scen_title = None
scen_when = []
scen_then = []
scen_phase = 0
}
None => ()
}
}
fn flush_requirement() {
flush_scenario()
match (current_kind, req_title) {
(Some(kind), Some(title)) => {
out.push(
@intent.RequirementDelta(
kind~,
title~,
text=req_body.join(" ").trim().to_owned(),
scenarios=req_scenarios,
),
)
req_title = None
req_body = []
req_scenarios = []
}
_ => {
req_title = None
req_body = []
req_scenarios = []
}
}
}
for line in lines {
let trimmed = line.trim().to_owned()
if trimmed.strip_prefix("## ") is Some(heading) {
flush_requirement()
let h = heading.trim().to_owned()
current_kind = match h {
"ADDED Requirements" | "Requirements" => Some(Added)
"MODIFIED Requirements" => Some(Modified)
"REMOVED Requirements" => Some(Removed)
"RENAMED Requirements" => Some(Renamed)
_ => None
}
continue
}
if current_kind is None {
continue
}
if trimmed.strip_prefix("### Requirement:") is Some(rest) {
flush_requirement()
req_title = Some(
sanitize_title_text(rest.trim().to_owned(), "Requirement"),
)
continue
}
if trimmed.strip_prefix("#### Scenario:") is Some(rest) {
flush_scenario()
scen_title = Some(sanitize_title_text(rest.trim().to_owned(), "Scenario"))
continue
}
if scen_title is Some(_) {
if strip_scenario_marker(trimmed, "WHEN") is Some(w) {
scen_when.push(w)
scen_phase = 1
} else if strip_scenario_marker(trimmed, "THEN") is Some(t) {
scen_then.push(t)
scen_phase = 2
} else if strip_scenario_marker(trimmed, "AND") is Some(a) {
if scen_phase == 1 {
scen_when.push("AND " + a)
} else if scen_phase == 2 {
scen_then.push("AND " + a)
}
}
continue
}
if req_title is Some(_) && !trimmed.is_empty() && !trimmed.has_prefix("#") {
req_body.push(trimmed)
}
}
flush_requirement()
out
}
///|
fn is_task_code(token : String) -> Bool {
if token.is_empty() {
return false
}
let mut has_digit = false
for c in token {
if c is ('0'..<='9') {
has_digit = true
} else if c != '.' {
return false
}
}
has_digit
}
///|
fn extract_tasks(lines : Array[String]) -> Array[@intent.TaskItem] {
let out : Array[@intent.TaskItem] = []
for line in lines {
let trimmed = line.trim().to_owned()
let (completed, rest) : (Bool, String) = if trimmed.strip_prefix("- [x] ")
is Some(r) {
(true, r.trim().to_owned())
} else if trimmed.strip_prefix("- [X] ") is Some(r) {
(true, r.trim().to_owned())
} else if trimmed.strip_prefix("- [ ] ") is Some(r) {
(false, r.trim().to_owned())
} else {
continue
}
if rest.is_empty() {
continue
}
let (code, label_text) = match rest.split_once(" ") {
Some((first, tail)) => {
let tok = first.to_owned()
if is_task_code(tok) {
(tok, tail.trim().to_owned())
} else {
("", rest)
}
}
None => ("", rest)
}
let label = sanitize_title_text(label_text, "Task")
out.push(@intent.TaskItem(code~, label~, completed~))
}
out
}
///|
fn infer_change_stage_and_status(
has_design : Bool,
has_spec : Bool,
progress : @intent.TaskProgress,
) -> (@intent.StageId, @intent.IntentStatus) {
if progress.total() > 0 && progress.all_done() {
(@intent.StageId::verify(), ReadyToVerify)
} else if progress.total() > 0 {
(@intent.StageId::implement(), Active)
} else if has_design || has_spec {
(@intent.StageId::propose(), Active)
} else {
(@intent.StageId::explore(), Active)
}
}
///|
pub impl @intent.IntentAdapter for OpenSpecIntentAdapter with fn adapter_id(
_self,
) {
@intent.AdapterId::openspec()
}
///|
pub impl @intent.IntentAdapter for OpenSpecIntentAdapter with fn project(
_self,
workspace_urn~,
docs,
) {
let adapter = @intent.AdapterId::openspec()
let change_inputs : Map[String, Array[@intent.DocumentInput]] = Map([])
let change_titles : Map[String, @intent.IntentTitle] = Map([])
let change_flags : Map[String, (Bool, Bool)] = Map([]) // (has_design, has_spec)
let main_specs : Array[@intent.PacketDocument] = []
let diagnostics : Array[@intent.IntentDiagnostic] = []
for pair in docs {
let (doc_path, content) = pair
let path_str = doc_path.as_str()
if !path_str.has_suffix(".md") {
continue
}
let lines = split_markdown_lines(content)
if path_str.strip_prefix("openspec/changes/") is Some(rel_view) {
let rel = rel_view.to_owned()
let (slug, inner) = match rel.split_once("/") {
Some((s, r)) => (s.to_owned(), r.to_owned())
None => continue
}
if slug == "archive" || slug.is_empty() {
continue
}
let role : @intent.ArtifactRole = if inner == "proposal.md" {
Proposal
} else if inner == "design.md" {
Design
} else if inner == "tasks.md" {
Tasks
} else if inner.has_prefix("specs/") && inner.has_suffix("/spec.md") {
SpecDelta
} else {
continue
}
let fallback_title = match role {
Proposal => humanize_slug(slug)
Design => "Design: " + humanize_slug(slug)
Tasks => "Tasks: " + humanize_slug(slug)
SpecDelta => "Spec Delta: " + inner
_ => inner
}
let title = extract_heading_title(lines, fallback_title)
let requirements = match role {
SpecDelta => extract_requirements(lines)
_ => []
}
let tasks = match role {
Tasks => extract_tasks(lines)
_ => []
}
let summary = match role {
Tasks => {
let prog = @intent.TaskProgress::from_tasks(tasks)
if prog.total() > 0 {
"\{prog.completed()}/\{prog.total()} tasks completed"
} else {
extract_summary(lines)
}
}
_ => extract_summary(lines)
}
let input = @intent.DocumentInput(
role~,
title~,
path=doc_path,
summary~,
source_lines=lines,
requirements~,
tasks~,
)
match change_inputs.get(slug) {
Some(list) => list.push(input)
None => change_inputs[slug] = [input]
}
if role is Proposal {
change_titles[slug] = title
}
let (prev_design, prev_spec) = match change_flags.get(slug) {
Some(flags) => flags
None => (false, false)
}
change_flags[slug] = (
prev_design || role is Design,
prev_spec || role is SpecDelta,
)
if role is SpecDelta && requirements.is_empty() {
diagnostics.push(
@intent.IntentDiagnostic(
kind=EmptySpec,
path=Some(doc_path),
message="Spec delta contains no parsed requirements",
),
)
}
} else if path_str.strip_prefix("openspec/specs/") is Some(rel_view) {
let rel = rel_view.to_owned()
let title = extract_heading_title(lines, rel)
let requirements = extract_requirements(lines)
let summary = extract_summary(lines)
let doc = @intent.PacketDocument::standalone(
@intent.DocumentInput(
role=MainSpec,
title~,
path=doc_path,
summary~,
source_lines=lines,
requirements~,
),
)
main_specs.push(doc)
}
}
let slugs : Array[String] = []
for pair in change_inputs {
slugs.push(pair.0)
}
slugs.sort_by((a, b) => a.lexical_compare(b))
let items : Array[@intent.IntentItem] = []
for slug in slugs {
let inputs = match change_inputs.get(slug) {
Some(list) => list
None => continue
}
let packet = @intent.ReadingPacket(inputs)
let (has_design, has_spec) = match change_flags.get(slug) {
Some(flags) => flags
None => (false, false)
}
let (stage, status) = infer_change_stage_and_status(
has_design,
has_spec,
packet.task_progress(),
)
let title = match change_titles.get(slug) {
Some(t) => t
None => sanitize_title_text(humanize_slug(slug), slug)
}
let origin_str = "openspec/changes/\{slug}"
let origin_path = @intent.DocumentPath(origin_str) catch {
_ =>
@intent.DocumentPath("openspec/changes") catch {
_ => abort("openspec/changes is a valid DocumentPath")
}
}
let id = @intent.IntentId::for_origin(
workspace_urn~,
adapter~,
label=slug,
origin_key=origin_str,
)
items.push(
@intent.IntentItem(
id~,
slug~,
title~,
adapter~,
stage~,
status~,
origin_path~,
packet~,
),
)
}
@intent.IntentProjection(items~, specs=main_specs, diagnostics~)
}
///|
pub extend OpenSpecIntentAdapter with @intent.IntentAdapter::{
adapter_id,
project,
}
///|
fn walk_openspec_dir(
dir_path : FolderPath,
rel_prefix : String,
real_root : FolderPath,
depth : Int32,
skip_archive : Bool,
collected : Array[(@intent.DocumentPath, String)],
diagnostics : Array[@intent.IntentDiagnostic],
) -> Inquiry[Unit] {
if depth > max_openspec_depth || collected.length() >= max_openspec_files {
return Done(())
}
RealPath(dir_path, dir_real => {
match dir_real {
Resolved(real_dir) =>
if !real_root.contains(real_dir) {
let maybe_doc = Some(@intent.DocumentPath(rel_prefix)) catch {
_ => None
}
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem("symlink_escape"),
path=maybe_doc,
message="Skipped directory whose real path escapes the workspace root",
),
)
Done(())
} else {
Names(dir_path, listing => {
match listing {
Entries(raw_entries) => {
let entries : Array[String] = []
for e in raw_entries {
if !e.has_prefix(".") && !(skip_archive && e == "archive") {
entries.push(e)
}
}
entries.sort()
walk_openspec_entries(
dir_path, rel_prefix, real_root, depth, entries, 0, collected,
diagnostics,
)
}
Missing | Failed(_) => Done(())
}
})
}
Missing => Done(())
TimedOut => {
let maybe_doc = Some(@intent.DocumentPath(rel_prefix)) catch {
_ => None
}
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem("timeout"),
path=maybe_doc,
message="Timed out resolving canonical directory path",
),
)
Done(())
}
Failed(reason) => {
let maybe_doc = Some(@intent.DocumentPath(rel_prefix)) catch {
_ => None
}
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem(reason),
path=maybe_doc,
message="Failed to inspect directory: \{reason}",
),
)
Done(())
}
}
})
}
///|
fn walk_openspec_entries(
dir_path : FolderPath,
rel_prefix : String,
real_root : FolderPath,
depth : Int32,
entries : Array[String],
idx : Int32,
collected : Array[(@intent.DocumentPath, String)],
diagnostics : Array[@intent.IntentDiagnostic],
) -> Inquiry[Unit] {
if idx >= entries.length() || collected.length() >= max_openspec_files {
return Done(())
}
let name = entries[idx]
let child_path = dir_path.join([name])
let child_rel = "\{rel_prefix}/\{name}"
let next = () => {
walk_openspec_entries(
dir_path,
rel_prefix,
real_root,
depth,
entries,
idx + 1,
collected,
diagnostics,
)
}
Look(child_path, looked => {
match looked {
Folder =>
walk_openspec_dir(
child_path,
child_rel,
real_root,
depth + 1,
false,
collected,
diagnostics,
).then(_ => next())
File =>
if !name.has_suffix(".md") {
next()
} else {
let maybe_doc = Some(@intent.DocumentPath(child_rel)) catch {
_ => None
}
match maybe_doc {
None => next()
Some(doc_path) =>
RealPath(child_path, file_real => {
match file_real {
Resolved(real_file) =>
if !real_root.contains(real_file) {
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem("symlink_escape"),
path=Some(doc_path),
message="Skipped file whose real path escapes the workspace root",
),
)
next()
} else {
ReadFile(child_path, text => {
match text {
Found(content) => collected.push((doc_path, content))
TooLarge =>
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem("too_large"),
path=Some(doc_path),
message="Skipped file exceeding 1 MiB read cap",
),
)
TimedOut =>
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem("timeout"),
path=Some(doc_path),
message="Timed out reading file",
),
)
Failed(reason) =>
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem(reason),
path=Some(doc_path),
message="Failed reading file: \{reason}",
),
)
Missing => ()
}
next()
})
}
Missing => next()
TimedOut | Failed(_) => {
diagnostics.push(
@intent.IntentDiagnostic(
kind=ParseProblem("real_path_failed"),
path=Some(doc_path),
message="Failed resolving real path of file",
),
)
next()
}
}
})
}
}
Missing | TimedOut | Failed(_) => next()
}
})
}
///|
fn role_to_wire(role : @intent.ArtifactRole) -> @app.WireArtifactRole {
match role {
Proposal => Proposal
Design => Design
SpecDelta => SpecDelta
Tasks => Tasks
MainSpec => MainSpec
Custom(id) => Custom(id.as_str())
}
}
///|
fn delta_kind_to_wire(
kind : @intent.RequirementDeltaKind,
) -> @app.WireRequirementDeltaKind {
match kind {
Added => Added
Modified => Modified
Removed => Removed
Renamed => Renamed
}
}
///|
fn document_to_wire(doc : @intent.PacketDocument) -> @app.WirePacketDocument {
let reqs : Array[@app.WireRequirementDelta] = []
for r in doc.requirements() {
let scens : Array[@app.WireScenario] = []
for s in r.scenarios() {
scens.push({
title: s.title().as_str(),
when_text: s.when_text(),
then_text: s.then_text(),
})
}
reqs.push({
kind: delta_kind_to_wire(r.kind()),
title: r.title().as_str(),
text: r.text(),
scenarios: ReadOnlyArray::from_array(scens),
})
}
let tasks : Array[@app.WireTaskItem] = []
for t in doc.tasks() {
tasks.push({
code: t.code(),
label: t.label().as_str(),
completed: t.completed(),
})
}
{
step: doc.step(),
role: role_to_wire(doc.role()),
title: doc.title().as_str(),
path: doc.path().as_str(),
summary: doc.summary(),
source_lines: doc.source_lines(),
requirements: ReadOnlyArray::from_array(reqs),
tasks: ReadOnlyArray::from_array(tasks),
}
}
///|
fn status_to_wire(status : @intent.IntentStatus) -> @app.WireIntentStatus {
match status {
Active => Active
ReadyToVerify => ReadyToVerify
Archived => Archived
Blocked(reason) => Blocked(reason)
}
}
///|
fn diagnostic_to_wire(
diag : @intent.IntentDiagnostic,
) -> @app.WireIntentDiagnostic {
let kind = match diag.kind() {
MissingArtifact(role) => "missing_artifact:\{role.label()}"
ParseProblem(code) => "parse_problem:\{code}"
EmptySpec => "empty_spec"
DuplicateId(id) => "duplicate_id:\{id.as_str()}"
}
{ kind, path: diag.path().map(p => p.as_str()), message: diag.message(), }
}
///|
/// Projects a pure domain `@intent.IntentProjection` into the wire DTO reply
/// `@app.WorkspaceIntent`.
pub fn intent_projection_to_wire(
workspace : @app.WorkspaceId,
projection : @intent.IntentProjection,
) -> @app.WorkspaceIntent {
let items : Array[@app.WireIntentItem] = []
for item in projection.items() {
let adapter = @app.AdapterId(item.adapter().as_str()) catch {
_ => @app.AdapterId::openspec()
}
let docs : Array[@app.WirePacketDocument] = []
for d in item.packet().documents() {
docs.push(document_to_wire(d))
}
let prog = item.task_progress()
items.push({
id: item.id().as_str(),
slug: item.slug(),
title: item.title().as_str(),
adapter,
stage: item.stage().as_str(),
status: status_to_wire(item.status()),
origin_path: item.origin_path().as_str(),
task_progress: { completed: prog.completed(), total: prog.total(), },
packet: { documents: ReadOnlyArray::from_array(docs), },
})
}
let specs : Array[@app.WirePacketDocument] = []
for spec in projection.specs() {
specs.push(document_to_wire(spec))
}
let diagnostics : Array[@app.WireIntentDiagnostic] = []
for d in projection.diagnostics() {
diagnostics.push(diagnostic_to_wire(d))
}
{
workspace,
items: ReadOnlyArray::from_array(items),
specs: ReadOnlyArray::from_array(specs),
diagnostics: ReadOnlyArray::from_array(diagnostics),
}
}
///|
/// Pure `Inquiry` inspecting a workspace root's `openspec/` directory under
/// strict symlink confinement and running registered `@intent.IntentAdapter`s.
pub fn inspect_workspace_intent(
workspace_id : @app.WorkspaceId,
workspace_root : FolderPath,
adapters~ : Array[&@intent.IntentAdapter] = default_intent_adapters(),
) -> Inquiry[@app.WorkspaceIntent] {
RealPath(workspace_root, root_real => {
match root_real {
Missing =>
Done({ workspace: workspace_id, items: [], specs: [], diagnostics: [], })
TimedOut =>
Done({
workspace: workspace_id,
items: [],
specs: [],
diagnostics: [
{
kind: "parse_problem:timeout",
path: None,
message: "Timed out resolving workspace root",
},
],
})
Failed(reason) =>
Done({
workspace: workspace_id,
items: [],
specs: [],
diagnostics: [
{
kind: "parse_problem:root_unavailable",
path: None,
message: "Failed resolving workspace root: \{reason}",
},
],
})
Resolved(real_root) => {
let openspec_dir = workspace_root.join(["openspec"])
Look(openspec_dir, looked => {
match looked {
Folder => {
let collected : Array[(@intent.DocumentPath, String)] = []
let extra_diags : Array[@intent.IntentDiagnostic] = []
let changes_dir = openspec_dir.join(["changes"])
let specs_dir = openspec_dir.join(["specs"])
walk_openspec_dir(
changes_dir, "openspec/changes", real_root, 0, true, collected, extra_diags,
).then(_ => {
walk_openspec_dir(
specs_dir, "openspec/specs", real_root, 0, false, collected, extra_diags,
).map(_ => {
let base = @intent.run_adapters(
adapters,
workspace_urn=workspace_id.to_string(),
ReadOnlyArray::from_array(collected),
)
let combined = if extra_diags.is_empty() {
base
} else {
@intent.compose_projections([
base,
@intent.IntentProjection(diagnostics=extra_diags),
])
}
intent_projection_to_wire(workspace_id, combined)
})
})
}
File | Missing | TimedOut | Failed(_) =>
Done({
workspace: workspace_id,
items: [],
specs: [],
diagnostics: [],
})
}
})
}
}
})
}