Repository navigation
Expand file tree
/
Copy pathvalidate_workshop.py
More file actions
2493 lines (2341 loc) · 110 KB
/
Copy pathvalidate_workshop.py
File metadata and controls
2493 lines (2341 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
from html.parser import HTMLParser
import json
from pathlib import Path
import re
import sys
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parents[1]
WORKSHOP = ROOT / "workshop"
DOCS = ROOT / "docs"
LANGUAGES = ("dotnet", "go", "java", "nodejs", "python", "rust")
SDLC_LESSONS = (
"00-preflight.md",
"01-first-session.md",
"02-streaming.md",
"03-local-tool.md",
"04-mcp-safety.md",
"05-combine-tools.md",
"06-structured-report.md",
"07-run-explain.md",
"08-model-selection.md",
"09-interactive-html-report.md",
)
MUSEUM_LESSONS = (
"museum-00-preflight.md",
"museum-01-first-curator-session.md",
"museum-02-stream-the-curator.md",
"museum-03-curator-voice.md",
"museum-04-approved-facts.md",
"museum-06-prove-the-structure.md",
"museum-07-wikipedia-research.md",
"museum-08-interactive-exhibit-page.md",
)
INSTRUCTIONAL_LESSONS = SDLC_LESSONS + MUSEUM_LESSONS
COMPLETION_LESSONS = ("10-complete.md", "museum-09-complete.md")
LESSONS = INSTRUCTIONAL_LESSONS + COMPLETION_LESSONS
OFFICIAL_SDK_URLS = {
"dotnet": "https://github.com/github/copilot-sdk/tree/main/dotnet",
"nodejs": "https://github.com/github/copilot-sdk/tree/main/nodejs",
"python": "https://github.com/github/copilot-sdk/tree/main/python",
"go": "https://github.com/github/copilot-sdk/tree/main/go",
"rust": "https://github.com/github/copilot-sdk/tree/main/rust",
"java": "https://github.com/github/copilot-sdk/tree/main/java",
}
MANIFESTS = {
"dotnet": "*.csproj",
"nodejs": "package.json",
"python": "requirements.txt",
"go": "go.mod",
"rust": "Cargo.toml",
"java": "pom.xml",
}
ENTRYPOINTS = {
"dotnet": "Program.cs",
"nodejs": "src/index.ts",
"python": "main.py",
"go": "main.go",
"rust": "src/main.rs",
"java": "src/main/java/workshop/AccessibilityReport.java",
}
LESSON_TRACK_MARKERS = {
"dotnet": (
"Program.cs",
"Helpers/",
"dotnet run",
"```csharp",
"finished/dotnet/",
),
"nodejs": (
"src/index.ts",
"src/workshop.ts",
"npm start",
"```typescript",
"finished/nodejs/",
),
"python": (
"main.py",
"workshop.py",
"python main.py",
"```python",
"finished/python/",
),
"go": (
"main.go",
"go run .",
"```go",
"finished/go/",
),
"rust": (
"src/main.rs",
"cargo run",
"```rust",
"finished/rust/",
),
"java": (
"src/main/java/",
"./mvnw compile",
"```java",
"finished/java/",
),
}
STEP_3_TRACK_MARKERS = {
"dotnet": ("AccessibilityRuleCatalog.cs", "CopilotTool.DefineTool", "dotnet run"),
"nodejs": ("src/workshop.ts", 'defineTool("accessibility_rule_lookup"', "npm start"),
"python": ("workshop.py", '@define_tool(', "python main.py"),
"go": ("main.go", "copilot.DefineTool(", "go run ."),
"rust": ("src/main.rs", 'Tool::new("accessibility_rule_lookup")', "cargo run"),
"java": ("AccessibilityReport.java", "ToolDefinition.from(", "./mvnw compile exec:java"),
}
# Every command runs from inside the starter directory the learner already sits in.
# No lesson may reintroduce a copied sibling project.
RUN_COMMAND_MARKERS = {
"dotnet": "dotnet run",
"nodejs": "npm start",
"python": "python main.py",
"go": "go run .",
"rust": "cargo run",
"java": "./mvnw compile exec:java",
}
STEP_9_RUN_COMMAND_MARKERS = {
"dotnet": "dotnet run",
"nodejs": "npm start",
"python": "python main.py",
"go": "go run .",
"rust": "cargo run --",
"java": "./mvnw compile exec:java",
}
MUSEUM_COMMAND_MARKERS = {
"dotnet": (
"dotnet run",
),
"nodejs": (
"npm start",
),
"python": (
".venv/bin/python main.py",
),
"go": (
"go run .",
),
"rust": (
"cargo run",
),
"java": (
"./mvnw compile exec:java",
),
}
MUSEUM_ENTRYPOINTS = {
"dotnet": "Program.cs",
"nodejs": "src/index.ts",
"python": "main.py",
"go": "main.go",
"rust": "src/main.rs",
"java": "src/main/java/workshop/MuseumExhibitStudio.java",
}
# The learner grows one project in place. Nothing may scaffold or copy a second one.
SECOND_PROJECT_MARKERS = (
"cp -R start-",
"Copy-Item -Recurse start-",
"dotnet new console",
"cargo new ",
"go mod init",
"npm init ",
"mvn archetype:generate",
"./mvnw archetype:generate",
)
IN_PLACE_FORBIDDEN_MARKERS = (
"workshop-app",
"museum-workshop-app",
)
MUSEUM_FORBIDDEN_LESSON_MARKERS = (
"museum-07-guides",
"dotnet test",
"npm test",
"go test",
"cargo test",
"mvn test",
"./mvnw test",
"python -m unittest",
"unittest",
"mock-wikipedia",
"tests/",
"src/test/java",
"checkpoints/",
"samples/",
"ICuratorClient",
"ICuratorSession",
"CopilotCuratorClient",
"createCopilotCuratorClient",
"MuseumExhibitService",
"CuratorRuntime",
"ExhibitValidator",
"selectApprovedFacts",
"parseResearchResult",
"ProposedAddition",
)
PROCEDURE_MARKERS = {
"01-first-session.md": {
"dotnet": "SendAndWaitAsync",
"nodejs": "sendAndWait",
"python": "create_session",
"go": "copilot.NewClient",
"rust": "Client::start",
"java": "new CopilotClient",
},
"02-streaming.md": {
"dotnet": "ResponseStreamer.SendAndPrintAsync",
"nodejs": "streamResponse",
"python": "AssistantMessageDeltaData",
"go": "session.On",
"rust": "session.subscribe()",
"java": "setStreaming(true)",
},
"03-local-tool.md": {
language: markers[1] for language, markers in STEP_3_TRACK_MARKERS.items()
},
"04-mcp-safety.md": {
"dotnet": "McpStdioServerConfig",
"nodejs": "src/index.ts",
"python": "main.py",
"go": "MCPStdioServerConfig",
"rust": 'tools: Some(vec!["browser_navigate"',
"java": '.setTools(List.of("browser_navigate"))',
},
"05-combine-tools.md": {
"dotnet": "For each issue, call accessibility_rule_lookup",
"nodejs": "src/index.ts",
"python": "main.py",
"go": "AvailableTools",
"rust": "config.available_tools",
"java": "setAvailableTools",
},
"06-structured-report.md": {
"dotnet": "Prompts.CreateReportPrompt",
"nodejs": 'import "./report.js"',
"python": "from report import main",
"go": "reportPrompt(target)",
"rust": "report_prompt(&target)",
"java": "reportPrompt(target)",
},
"08-model-selection.md": {
"dotnet": "ModelSelector.SelectAsync",
"nodejs": "client.listModels()",
"python": "client.list_models()",
"go": "client.ListModels",
"rust": "models().list()",
"java": "SessionConfig.setModel",
},
"09-interactive-html-report.md": {
"dotnet": "builtin:apply_patch",
"nodejs": "builtin:apply_patch",
"python": "builtin:apply_patch",
"go": "builtin:apply_patch",
"rust": "builtin:apply_patch",
"java": "builtin:apply_patch",
},
"museum-01-first-curator-session.md": {
"dotnet": "SendAndWaitAsync",
"nodejs": "sendAndWait",
"python": "create_session",
"go": "copilot.NewClient",
"rust": "Client::start",
"java": "new CopilotClient",
},
"museum-02-stream-the-curator.md": {
"dotnet": "CuratorStreamer.StreamExhibitAsync",
"nodejs": "streamExhibit(",
"python": "stream_exhibit(",
"go": "StreamExhibit(",
"rust": "stream_exhibit(",
"java": "CuratorStreamer.streamExhibit",
},
"museum-03-curator-voice.md": {
"dotnet": "const string SystemMessage",
"nodejs": "const systemMessage",
"python": "SYSTEM_MESSAGE =",
"go": "const systemMessage",
"rust": "const SYSTEM_MESSAGE",
"java": "public static final String SYSTEM_MESSAGE",
},
"museum-04-approved-facts.md": {
"dotnet": "BuildExhibitPrompt",
"nodejs": "buildExhibitPrompt",
"python": "build_exhibit_prompt",
"go": "buildExhibitPrompt",
"rust": "build_exhibit_prompt",
"java": "buildExhibitPrompt",
},
"museum-06-prove-the-structure.md": {
"dotnet": "CuratorValidation.FormatValidation",
"nodejs": "formatValidation(validateExhibit(",
"python": "format_validation(validate_exhibit(",
"go": "FormatValidation(ValidateExhibit(",
"rust": "format_validation(&validate_exhibit(",
"java": "CuratorValidation.formatValidation",
},
"museum-07-wikipedia-research.md": {
"dotnet": "CuratorSafety.WikipediaPermissionHandler()",
"nodejs": "wikipediaPermissionHandler()",
"python": "wikipedia_permission_handler()",
"go": "WikipediaPermissionHandler()",
"rust": "wikipedia_permission_handler()",
"java": "CuratorSafety.wikipediaPermissionHandler()",
},
"museum-08-interactive-exhibit-page.md": {
"dotnet": "builtin:apply_patch",
"nodejs": "builtin:apply_patch",
"python": "builtin:apply_patch",
"go": "builtin:apply_patch",
"rust": "builtin:apply_patch",
"java": "builtin:apply_patch",
},
}
UNSCOPED_TRACK_MARKERS = (
"Program.cs",
"Helpers/",
"src/index.ts",
"src/workshop.ts",
"main.py",
"workshop.py",
"main.go",
"src/main.rs",
"src/main/java/",
"```csharp",
"```typescript",
"```python",
"```go",
"```rust",
"```java",
"PingAsync",
"SendAndWaitAsync",
"AssistantMessageDeltaEvent",
"AssistantMessageEvent",
"SessionIdleEvent",
"SessionErrorEvent",
"ToolExecutionStartEvent",
"ToolExecutionCompleteEvent",
"ListModelsAsync",
)
errors: list[str] = []
def require(condition: bool, message: str) -> None:
if not condition:
errors.append(message)
class LocalAssetParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.references: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
attribute = "href" if tag in {"a", "link"} else "src" if tag in {"script", "img"} else None
if attribute:
value = dict(attrs).get(attribute)
if value:
self.references.append(value)
def read(path: Path) -> str:
return path.read_text(encoding="utf-8")
def has_manifest(directory: Path, language: str) -> bool:
manifest = MANIFESTS[language]
return bool(list(directory.glob(manifest))) if "*" in manifest else (directory / manifest).exists()
def entrypoint_path(directory: Path, language: str) -> Path:
if language == "java" and directory.name == "hello-copilot-sdk":
return Path("src/main/java/workshop/AccessibilityGuidance.java")
if language == "java" and directory.name == "museum-exhibit-studio":
return Path("src/main/java/workshop/MuseumExhibitStudio.java")
if language == "java" and directory.parent.name == "start-museum":
return Path("src/main/java/workshop/MuseumExhibitStudio.java")
return Path(ENTRYPOINTS[language])
def project_source(directory: Path) -> str:
source_suffixes = {
".cs", ".ts", ".py", ".go", ".rs", ".java"
}
return "\n".join(
read(path) for path in directory.rglob("*")
if path.is_file()
and path.suffix in source_suffixes
and not set(path.relative_to(directory).parts).intersection(
{"node_modules", "bin", "obj", "target", "__pycache__"}
)
)
def executable_source(directory: Path, language: str) -> str:
"""Read the launched entrypoint and any directly launched report module, not dormant helpers."""
entrypoint = directory / entrypoint_path(directory, language)
text = read(entrypoint)
if language == "nodejs" and re.search(r'import\s+["\']\./report\.js["\']', text):
text += "\n" + read(directory / "src" / "report.ts") + "\n" + read(directory / "src" / "workshop.ts")
if language == "python" and re.search(r"from\s+report\s+import\s+main", text):
text += "\n" + read(directory / "report.py") + "\n" + read(directory / "workshop.py")
if language == "dotnet" and "Prompts.CreateReportPrompt" in text:
text += "\n" + read(directory / "Helpers" / "Prompts.cs")
return text
def contains_any(text: str, markers: tuple[str, ...]) -> bool:
folded = text.casefold()
return any(marker.casefold() in folded for marker in markers)
LANGUAGE_APIS = {
"dotnet": {
"client": ("new CopilotClient",),
"session": ("CreateSessionAsync",),
"send": ("SendAndWaitAsync", "ResponseStreamer.SendAndPrintAsync"),
"stream": ("Streaming = true",),
"tool": ("CreateLookupTool",),
},
"nodejs": {
"client": ("new CopilotClient",),
"session": ("createSession",),
"send": ("sendAndWait", "streamResponse"),
"stream": ("streaming: true",),
"tool": ("accessibilityRuleLookup", "tools: ["),
},
"python": {
"client": ("CopilotClient",),
"session": ("create_session",),
"send": ("session.send",),
"stream": ("streaming=True",),
"tool": ("accessibility_rule_lookup", "tools=["),
},
"go": {
"client": ("copilot.NewClient",),
"session": ("CreateSession",),
"send": ("SendAndWait",),
"stream": ("Streaming: copilot.Bool(true)",),
"tool": ('DefineTool("accessibility_rule_lookup"',),
},
"rust": {
"client": ("Client::start",),
"session": ("create_session",),
"send": ("send_and_wait", "$session.send("),
"stream": ("config.streaming = Some(true)",),
"tool": ('Tool::new("accessibility_rule_lookup")',),
},
"java": {
"client": ("new CopilotClient",),
"session": ("createSession",),
"send": ("sendAndWait",),
"stream": ("setStreaming(true)",),
"tool": ('ToolDefinition.from(', '"accessibility_rule_lookup"'),
},
}
def contains_all(text: str, markers: tuple[str, ...]) -> bool:
folded = text.casefold()
return all(marker.casefold() in folded for marker in markers)
def runtime_source(directory: Path, language: str, text: str) -> str:
"""Include the directly imported Node response helper for runtime-flow validation."""
if language == "nodejs":
if re.search(r'from\s+["\']\./local-tool\.js["\']', text):
return text + "\n" + read(directory / "src" / "local-tool.ts")
if re.search(r'from\s+["\']\./workshop\.js["\']', text):
return text + "\n" + read(directory / "src" / "workshop.ts")
if language == "dotnet" and "ResponseStreamer.SendAndPrintAsync" in text:
return text + "\n" + read(directory / "Helpers" / "ResponseStreamer.cs")
return text
def validate_runtime_flow(language: str, stage: str, text: str, label: Path) -> None:
"""Require a visible response and a completion/error path, not just a send call."""
streaming = stage != "01-first-session"
if language == "dotnet":
markers = (
("SendAndWaitAsync", 'Console.WriteLine($"\\nCopilot: {response.Data.Content}")', "await")
if not streaming
else ("await ResponseStreamer.SendAndPrintAsync", "AssistantMessageDeltaEvent",
"AssistantMessageEvent", "SessionIdleEvent", "SessionErrorEvent", "receivedDelta")
)
require(contains_all(text, markers),
f"{label} does not print a completed Copilot response")
elif language == "nodejs":
markers = (
("const response = await session.sendAndWait", "console.log(response")
if not streaming
else ("await streamResponse(", "session.on(", "process.stdout.write", "session.error", "session.idle")
)
require(contains_all(text, markers),
f"{label} does not print and complete the Copilot response")
elif language == "python":
markers = (
("AssistantMessageData", "print(content)", "SessionErrorData", "SessionIdleData",
"await done.wait()", "if error is not None", "done.set()")
if not streaming
else ("AssistantMessageDeltaData", "AssistantMessageData", "received_delta = False",
"received_delta = True", "not received_delta", "print(delta", "print(content)",
"SessionErrorData", "SessionIdleData",
"await done.wait()", "if error is not None", "done.set()")
)
require(contains_all(text, markers),
f"{label} does not print streamed output or a final-message fallback before propagating session errors")
if stage == "05-combine-tools":
tool_event_markers = (
"ToolExecutionStartData",
"[tool:start]",
"ToolExecutionCompleteData",
"[tool:done]",
)
require(
contains_all(text, tool_event_markers),
f"{label} does not print local and MCP tool lifecycle events",
)
elif language == "go":
if streaming:
event_output = contains_all(text, ("session.On(", "AssistantMessageDeltaData", "AssistantMessageData", "receivedDelta", "fmt.Print"))
blocking_output = contains_all(text, ("AssistantMessageData", "fmt.Println(message.Content)"))
require(event_output or blocking_output,
f"{label} does not print streamed or final assistant output")
else:
require(contains_all(text, ("AssistantMessageData", "fmt.Println(message.Content)")),
f"{label} does not print the final assistant response")
require(contains_all(text, ("SendAndWait",)) and
("return err" in text or "if err != nil" in text),
f"{label} does not wait for or propagate the send result")
elif language == "rust":
markers = (
("send_and_wait", 'message.data.get("content")', "println!")
if not streaming
else ("$session.send(", "session.subscribe", "assistant.message_delta", "assistant.message",
"session.error", "session.idle", "tokio::select!", "print!")
)
require(contains_all(text, markers),
f"{label} does not subscribe, print, and await completion or errors")
elif language == "java":
markers = (
("sendAndWait", "response == null", "response.getData().content()", ".get()")
if not streaming or label != Path("finished/java/hello-copilot-sdk")
else ("AssistantMessageDeltaEvent", "AssistantMessageEvent", "receivedDelta",
"System.out.print", "sendAndWait", ".get()")
)
require(contains_all(text, markers),
f"{label} does not print streamed output or a final-message fallback before awaiting completion")
LATER_CAPABILITIES = {
"stream": ("streaming", "Streaming", "setStreaming"),
"local": ("accessibility_rule_lookup",),
"mcp": ("mcpServers", "mcp_servers", "MCPServers", "McpStdioServerConfig", "McpServerConfig"),
"browser": ("browser_navigate", "playwright-browser_navigate"),
"snapshot": ("read_latest_accessibility_snapshot",),
"permission": ("permissionForTarget", "permission_for_target", "OnPermissionRequest", "with_permission_handler", "setOnPermissionRequest"),
"report": ("Review limits", "review limits", "reportPrompt", "report_prompt"),
}
DEFAULT_PERMISSION_HANDLERS = {
"dotnet": "OnPermissionRequest = PermissionHandler.ApproveAll",
"nodejs": "onPermissionRequest: approveAll",
"python": "on_permission_request=PermissionHandler.approve_all",
"go": "OnPermissionRequest: copilot.PermissionHandler.ApproveAll",
"rust": "with_permission_handler(permission::approve_all())",
"java": "setOnPermissionRequest(PermissionHandler.APPROVE_ALL)",
}
PLAYWRIGHT_MCP_PACKAGE = "@playwright/mcp@0.0.78"
PLAYWRIGHT_OUTPUT_DIRECTORY = re.compile(
r'--output-dir(?:(?!--[a-z]).){0,80}["\']\.playwright-mcp["\']',
re.DOTALL,
)
PLAYWRIGHT_OUTPUT_MODE = re.compile(
r'--output-mode(?:(?!--[a-z]).){0,80}["\']file["\']',
re.DOTALL,
)
def validate_executable_stage(language: str, stage: str, directory: Path) -> str:
text = executable_source(directory, language)
apis = LANGUAGE_APIS[language]
label = directory.relative_to(ROOT)
if stage == "starter":
for capability in ("client", "session", "stream", "local", "mcp", "browser", "snapshot", "permission", "report"):
markers = apis.get(capability, ()) + LATER_CAPABILITIES.get(capability, ())
require(not contains_any(text, markers),
f"{label} starter wires {capability} instead of remaining a scaffold")
return text
for capability in ("client", "session", "send"):
require(contains_any(text, apis[capability]),
f"{label} executable entrypoint does not create, use, and send through a Copilot session")
required_capabilities = {
"01-first-session": (),
"02-streaming": ("stream",),
"03-local-tool": ("stream", "local"),
"04-mcp-safety": ("stream", "local", "mcp", "browser", "snapshot", "permission"),
"05-combine-tools": ("stream", "local", "mcp", "browser", "snapshot", "permission"),
"06-structured-report": ("stream", "local", "mcp", "browser", "snapshot", "permission", "report"),
}[stage]
for capability in required_capabilities:
markers = apis.get(capability, ()) + LATER_CAPABILITIES.get(capability, ())
require(contains_any(text, markers),
f"{label} executable entrypoint does not wire {capability} for {stage}")
if stage == "01-first-session" or (
language == "java" and stage in {"02-streaming", "03-local-tool"}):
require(DEFAULT_PERMISSION_HANDLERS[language] in text,
f"{label} does not configure the required baseline permission handler")
validate_runtime_flow(language, stage, runtime_source(directory, language, text), label)
if stage == "04-mcp-safety":
require("evidence-backed" not in text and "Review limits" not in text,
f"{label} combines report behavior before Step 5 or Step 6")
if stage == "05-combine-tools":
combined_marker = {
"dotnet": "For each issue, call accessibility_rule_lookup",
"nodejs": "evidence-backed",
"python": "evidence-backed",
"go": "evidence-backed",
"rust": "evidence-backed",
"java": "evidence-backed",
}[language]
require(combined_marker in text and "Review limits" not in text,
f"{label} does not combine browser evidence with local guidance before Step 6")
if stage == "06-structured-report":
require("Review limits" in text,
f"{label} executable entrypoint does not request the structured report limits")
forbidden_capabilities = {
"01-first-session": ("stream", "local", "mcp", "browser", "snapshot", "report"),
"02-streaming": ("local", "mcp", "browser", "snapshot", "report"),
"03-local-tool": ("mcp", "browser", "snapshot", "report"),
}.get(stage, ())
for capability in forbidden_capabilities:
markers = apis.get(capability, ()) + LATER_CAPABILITIES.get(capability, ())
require(not contains_any(text, markers),
f"{label} executable entrypoint wires later-stage {capability} capability")
if language == "nodejs" and stage in {"04-mcp-safety", "05-combine-tools"}:
require('["http:", "https:"].includes(target.protocol)' in text,
f"{label} accepts a non-HTTP(S) URL")
return text
def validate_hello_manifest_entrypoint(language: str, directory: Path) -> None:
"""Ensure the sample's launch manifest reaches the entrypoint being inspected."""
label = directory.relative_to(ROOT)
entrypoint = directory / entrypoint_path(directory, language)
require(has_manifest(directory, language), f"{label} is missing its {language} manifest")
require(entrypoint.exists(), f"{label} manifest cannot reach {entrypoint_path(directory, language)}")
manifest = read(next(directory.glob(MANIFESTS[language]))) if "*" in MANIFESTS[language] else read(directory / MANIFESTS[language])
if language == "dotnet":
require("<OutputType>Exe</OutputType>" in manifest,
f"{label} project manifest does not define an executable")
elif language == "nodejs":
package = json.loads(manifest)
require(package.get("scripts", {}).get("start") == "tsx src/index.ts",
f"{label} package start script does not launch src/index.ts")
elif language == "python":
require("github-copilot-sdk==" in manifest
and "[project]" in read(directory / "pyproject.toml")
and 'if __name__ == "__main__":' in read(entrypoint),
f"{label} Python manifest and main.py do not define a runnable entrypoint")
elif language == "go":
require("module " in manifest and "package main" in read(entrypoint) and "func main()" in read(entrypoint),
f"{label} Go manifest does not reach package main")
elif language == "rust":
require("[package]" in manifest and "async fn main()" in read(entrypoint),
f"{label} Cargo manifest does not reach src/main.rs")
elif language == "java":
require("<mainClass>workshop.AccessibilityGuidance</mainClass>" in manifest
and "public static void main" in read(entrypoint),
f"{label} Maven manifest does not launch AccessibilityGuidance")
def validate_hello_sample(language: str, directory: Path) -> None:
stage = "03-local-tool"
validate_hello_manifest_entrypoint(language, directory)
text = validate_executable_stage(language, stage, directory)
source = project_source(directory)
label = directory.relative_to(ROOT)
forbidden_capabilities = ("mcp", "browser", "snapshot", "permission", "report")
if language == "java":
forbidden_capabilities = tuple(
capability for capability in forbidden_capabilities if capability != "permission")
for capability in forbidden_capabilities:
markers = LANGUAGE_APIS[language].get(capability, ()) + LATER_CAPABILITIES[capability]
require(not contains_any(source, markers),
f"{label} includes later-stage {capability} behavior")
tool_config = {
"dotnet": ("Tools = [AccessibilityRuleCatalog.CreateLookupTool()]", 'AvailableTools = ["accessibility_rule_lookup"]'),
"nodejs": ("tools: [accessibilityRuleLookup]", 'availableTools: ["accessibility_rule_lookup"]'),
"python": ("tools=[accessibility_rule_lookup]", 'available_tools=["accessibility_rule_lookup"]'),
"go": ("Tools: []copilot.Tool{lookup}", 'AvailableTools: []string{"accessibility_rule_lookup"}'),
"rust": ("config.tools = Some(vec![lookup])", 'config.available_tools = Some(vec!["accessibility_rule_lookup".to_owned()])'),
"java": (".setTools(List.of(lookup))", '.setAvailableTools(List.of("accessibility_rule_lookup"))'),
}[language]
require(contains_all(text, tool_config),
f"{label} does not register only accessibility_rule_lookup")
question_markers = {
"dotnet": ("Console.ReadLine()", "Accessibility question:", "Use accessibility_rule_lookup to answer this question:"),
"nodejs": ("readQuestion", "Accessibility question:", "Use accessibility_rule_lookup to answer this question:"),
"python": ("read_question", "Accessibility question:", "Use accessibility_rule_lookup to answer this question:"),
"go": ("readQuestion", "Accessibility question:", "Use accessibility_rule_lookup to answer this question:"),
"rust": ("read_question", "Accessibility question:", "Use accessibility_rule_lookup to answer this question:"),
"java": ("readQuestion", "Accessibility question:", "Use accessibility_rule_lookup to answer this question:"),
}[language]
require(contains_all(text, question_markers),
f"{label} does not accept an accessibility question and direct the lookup tool")
def validate_html_assets(html_file: Path) -> None:
parser = LocalAssetParser()
parser.feed(read(html_file))
for reference in parser.references:
parsed = urlsplit(reference)
if parsed.scheme or reference.startswith(("#", "?", "//", "data:")):
continue
target = (html_file.parent / parsed.path).resolve()
if parsed.path.endswith("/"):
target /= "index.html"
require(target.exists(), f"{html_file.relative_to(ROOT)} links to missing local asset {reference}")
def validate_markdown_links(markdown_file: Path) -> None:
for target_text in re.findall(r"!?\[[^\]]*\]\(([^)]+)\)", read(markdown_file)):
target_value = target_text.split(maxsplit=1)[0].strip("<>")
prefixes = (
"https://github.com/github/copilot-sdk-workshop/tree/main/",
"https://github.com/github/copilot-sdk-workshop/blob/main/",
)
prefix = next((candidate for candidate in prefixes if target_value.startswith(candidate)), None)
if prefix:
require(
(ROOT / target_value.removeprefix(prefix)).exists(),
f"{markdown_file.relative_to(ROOT)} links to missing repository path {target_value}",
)
continue
parsed = urlsplit(target_value)
if parsed.scheme or target_value.startswith(("#", "mailto:")):
continue
require(
(markdown_file.parent / parsed.path).resolve().exists(),
f"{markdown_file.relative_to(ROOT)} links to missing file {target_value}",
)
def validate_language_directives(markdown_file: Path) -> None:
active_language: str | None = None
blocks: set[str] = set()
for line_number, line in enumerate(read(markdown_file).splitlines(), start=1):
opening = re.fullmatch(r":::language ([a-z0-9]+)", line)
if opening:
require(active_language is None, f"{markdown_file.relative_to(ROOT)}:{line_number} nests a language directive")
active_language = opening.group(1)
require(active_language in LANGUAGES, f"{markdown_file.relative_to(ROOT)}:{line_number} uses unknown language {active_language}")
blocks.add(active_language)
elif line == ":::":
require(active_language is not None, f"{markdown_file.relative_to(ROOT)}:{line_number} closes no language directive")
active_language = None
elif line.startswith(":::"):
require(False, f"{markdown_file.relative_to(ROOT)}:{line_number} has invalid language directive syntax")
require(active_language is None, f"{markdown_file.relative_to(ROOT)} has an unclosed language directive")
require(blocks == set(LANGUAGES), f"{markdown_file.relative_to(ROOT)} must contain exactly one or more blocks for all six languages")
def validate_shared_language_content(markdown_file: Path) -> None:
active_language: str | None = None
for line_number, line in enumerate(read(markdown_file).splitlines(), start=1):
opening = re.fullmatch(r":::language ([a-z0-9]+)", line)
if opening:
active_language = opening.group(1)
elif line == ":::":
active_language = None
elif active_language is None:
require(
not line.startswith("### "),
f"{markdown_file.relative_to(ROOT)}:{line_number} exposes a "
"language-specific procedure heading outside a language block",
)
for marker in UNSCOPED_TRACK_MARKERS:
require(
marker.casefold() not in line.casefold(),
f"{markdown_file.relative_to(ROOT)}:{line_number} exposes "
f"language-specific content outside a language block: {marker}",
)
def render_language_markdown(markdown_file: Path, selected_language: str) -> str:
rendered: list[str] = []
active_language: str | None = None
for line in read(markdown_file).splitlines():
opening = re.fullmatch(r":::language ([a-z0-9]+)", line)
if opening:
active_language = opening.group(1)
elif line == ":::":
active_language = None
elif active_language is None or active_language == selected_language:
rendered.append(line)
return "\n".join(rendered)
def markdown_section(markdown: str, heading: str) -> str:
lines = markdown.splitlines()
try:
start = lines.index(heading)
except ValueError:
return ""
end = next(
(index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")),
len(lines),
)
return "\n".join(lines[start:end])
def validate_rendered_language_content(markdown_file: Path) -> None:
for selected_language in LANGUAGES:
rendered = render_language_markdown(markdown_file, selected_language)
rendered_folded = rendered.casefold()
for other_language, markers in LESSON_TRACK_MARKERS.items():
if other_language == selected_language:
continue
for marker in markers:
require(
marker.casefold() not in rendered_folded,
f"{markdown_file.relative_to(ROOT)} shows {other_language} content "
f"for the {selected_language} track: {marker}",
)
if markdown_file.name == "03-local-tool.md":
for marker in (
*STEP_3_TRACK_MARKERS[selected_language],
"## Run it",
"Troubleshooting this run",
):
require(
marker.casefold() in rendered_folded,
f"{markdown_file.relative_to(ROOT)} is missing {selected_language} "
f"Step 3 guidance: {marker}",
)
if markdown_file.name not in {"00-preflight.md", "museum-00-preflight.md", *COMPLETION_LESSONS}:
run_section = markdown_section(rendered, "## Run it")
if markdown_file.name == "09-interactive-html-report.md":
run_markers = STEP_9_RUN_COMMAND_MARKERS
elif markdown_file.name.startswith("museum-"):
run_markers = MUSEUM_COMMAND_MARKERS
else:
run_markers = RUN_COMMAND_MARKERS
run_marker = run_markers[selected_language]
require(
contains_any(run_section, run_marker)
if isinstance(run_marker, tuple)
else run_marker.casefold() in run_section.casefold(),
f"{markdown_file.relative_to(ROOT)} has no {selected_language} "
f"run command in its Run it section: {run_marker}",
)
if markdown_file.name in PROCEDURE_MARKERS:
procedure_marker = PROCEDURE_MARKERS[markdown_file.name][selected_language]
run_position = rendered.find("## Run it")
procedure_position = rendered.casefold().find(procedure_marker.casefold())
require(
0 <= procedure_position < run_position,
f"{markdown_file.relative_to(ROOT)} does not show the {selected_language} "
f"procedure before Run it: {procedure_marker}",
)
if markdown_file.name == "05-combine-tools.md" and selected_language == "java":
for marker in ("private record Rule", "Rule.RULES", "\"1.1.1\"", "\"4.1.2\""):
require(
marker.casefold() in rendered_folded,
f"{markdown_file.relative_to(ROOT)} does not teach the Java expanded rule catalog: {marker}",
)
if markdown_file.name == "05-combine-tools.md" and selected_language == "python":
for marker in (
"ToolExecutionStartData",
"[tool:start]",
"ToolExecutionCompleteData",
"[tool:done]",
):
require(
marker.casefold() in rendered_folded,
f"{markdown_file.relative_to(ROOT)} does not teach Python tool lifecycle events: {marker}",
)
if markdown_file.name == "09-interactive-html-report.md":
for marker in (
"accessibility-report.html",
"builtin:apply_patch",
"exact target navigation",
"accessible text filter",
):
require(
marker.casefold() in rendered_folded,
f"{markdown_file.relative_to(ROOT)} is missing {selected_language} "
f"interactive HTML report guidance: {marker}",
)
if markdown_file.name == "08-model-selection.md":
require(
"Enter the workshop target URL, then choose a model" in rendered,
f"{markdown_file.relative_to(ROOT)} does not preserve target URL input before model selection",
)
def validate_language_registry() -> None:
registry = read(DOCS / "language-registry.js")
ids = re.findall(r"\bid: '([a-z0-9]+)'", registry)
require(ids == list(LANGUAGES), "docs/language-registry.js must be the ordered six-language registry")
for language, url in OFFICIAL_SDK_URLS.items():
require(url in registry, f"Language registry has no official {language} SDK link")
require("Object.freeze" in registry and "getLanguage" in registry, "Language registry must expose immutable language lookup")
def validate_layout() -> None:
for language in LANGUAGES:
directories = [
ROOT / "start-accessibility" / language,
ROOT / "start-museum" / language,
*(ROOT / "finished" / language / project for project in (
"hello-copilot-sdk",
"accessibility-report",
"museum-exhibit-studio",
)),
]
for directory in directories:
require(directory.is_dir(), f"Missing {language} project directory {directory.relative_to(ROOT)}")
require(has_manifest(directory, language), f"Missing {language} manifest in {directory.relative_to(ROOT)}")
require((directory / entrypoint_path(directory, language)).exists(),
f"Missing {language} executable entrypoint in {directory.relative_to(ROOT)}")
for language in ("nodejs", "go", "rust"):
for directory in [
ROOT / "start-accessibility" / language,
ROOT / "start-museum" / language,
*(ROOT / "finished" / language / project for project in (
"hello-copilot-sdk",
"accessibility-report",
"museum-exhibit-studio",
)),
]:
lock = {"nodejs": "package-lock.json", "go": "go.sum", "rust": "Cargo.lock"}[language]
require((directory / lock).exists(), f"Missing deterministic {language} lock file in {directory.relative_to(ROOT)}")
require(
(ROOT / "start-museum" / "dotnet" / "packages.lock.json").exists(),
"Missing deterministic .NET package lock in start-museum/dotnet",
)
MUSEUM_HELPER_PATTERNS = {
"dotnet": ("Helpers/Curator*.cs",),
"nodejs": ("src/curator.ts",),
"python": ("curator.py",),
"go": ("curator.go",),
"rust": ("src/lib.rs",),
"java": ("src/main/java/workshop/Curator*.java",),
}
MUSEUM_HELPER_SYMBOLS = (
"apollo11facts",
"greatbarrierreeffacts",
"terracottaarmyfacts",
"factsets",
"maximumfactcount",
"maximumfactlength",
"boundfacts",
"approvedfactlookup",
"approvedwikipediafactlookup",
"streamexhibit",
"validateexhibit",
"formatvalidation",
"wikipediaserver",
"wikipediapermission",
"extractsources",
"exhibitwrite",
"askyesno",
"readfacts",
)
MUSEUM_HELPER_LESSON_REFERENCES = {
"dotnet": re.compile(r"Helpers/Curator[A-Za-z]+\.cs"),
"nodejs": re.compile(r"src/curator\.ts"),
"python": re.compile(r"(?<![\w/])curator\.py"),
"go": re.compile(r"(?<![\w/])curator\.go"),
"rust": re.compile(r"src/lib\.rs"),
"java": re.compile(r"(?<![\w/])Curator[A-Za-z]+\.java"),
}
MUSEUM_ABSTRACTION_MARKERS = (
"icuratorclient",